From cf64c0cc417616c18741404c1dfe01da966b6929 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Wed, 25 Nov 2026 13:54:17 +0800 Subject: [PATCH 1/5] Harden wire/zlib parsing, fix delivery/storage bugs, and share DB pool --- cmd/fmsgd/dns.go | 97 +++++-- cmd/fmsgd/host.go | 472 ++++++++++++++++++++++------------- cmd/fmsgd/host_test.go | 269 ++++++++++++++++++++ cmd/fmsgd/id.go | 30 ++- cmd/fmsgd/indicators.go | 130 ++++++---- cmd/fmsgd/indicators_test.go | 59 ++++- cmd/fmsgd/sender.go | 284 +++++++++++++++------ cmd/fmsgd/store.go | 220 +++++++++------- cmd/fmsgd/usage_test.go | 43 ++++ pkg/fmsg/deflate.go | 72 +++++- pkg/fmsg/fmsg.go | 174 ++++++++----- pkg/fmsg/fmsg_test.go | 28 +++ pkg/fmsg/prepare.go | 37 ++- pkg/fmsg/prepare_test.go | 35 +++ pkg/message/store.go | 24 +- 15 files changed, 1439 insertions(+), 535 deletions(-) diff --git a/cmd/fmsgd/dns.go b/cmd/fmsgd/dns.go index 4e1a6a3..3b21622 100644 --- a/cmd/fmsgd/dns.go +++ b/cmd/fmsgd/dns.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "io" "log" @@ -14,25 +15,35 @@ import ( "github.com/miekg/dns" ) +const dnsLookupTimeout = 5 * time.Second + +var ( + dnsClient = &dns.Client{Timeout: dnsLookupTimeout} + dnsTCPClient = &dns.Client{Net: "tcp", Timeout: dnsLookupTimeout} +) + func dnssecRequired() bool { return os.Getenv("FMSG_REQUIRE_DNSSEC") == "true" } -func resolverAuthenticatedData(name string, qtype uint16) (bool, error) { - cfg, err := dns.ClientConfigFromFile("/etc/resolv.conf") - if err != nil { - return false, err - } +type dnssecQueryResult struct { + ips []net.IP + ad bool + err error +} +func queryDNSSEC(cfg *dns.ClientConfig, name string, qtype uint16) dnssecQueryResult { msg := new(dns.Msg) msg.SetQuestion(dns.Fqdn(name), qtype) msg.SetEdns0(4096, true) - client := &dns.Client{Timeout: 5 * time.Second} var lastErr error for _, server := range cfg.Servers { addr := net.JoinHostPort(server, cfg.Port) - resp, _, err := client.Exchange(msg, addr) + resp, _, err := dnsClient.Exchange(msg, addr) + if err == nil && resp != nil && resp.Truncated { + resp, _, err = dnsTCPClient.Exchange(msg, addr) + } if err != nil { lastErr = err continue @@ -45,19 +56,74 @@ func resolverAuthenticatedData(name string, qtype uint16) (bool, error) { lastErr = fmt.Errorf("dns rcode %d from %s", resp.Rcode, addr) continue } - return resp.AuthenticatedData, nil + var ips []net.IP + for _, rr := range resp.Answer { + switch r := rr.(type) { + case *dns.A: + if qtype == dns.TypeA && r.A != nil { + ips = append(ips, r.A) + } + case *dns.AAAA: + if qtype == dns.TypeAAAA && r.AAAA != nil { + ips = append(ips, r.AAAA) + } + } + } + return dnssecQueryResult{ips: ips, ad: resp.AuthenticatedData} } if lastErr == nil { lastErr = fmt.Errorf("no DNS resolvers configured") } - return false, lastErr + return dnssecQueryResult{err: lastErr} +} + +func validateDNSSECResults(fmsgDomain string, resA, resAAAA dnssecQueryResult) ([]net.IP, error) { + if resA.err != nil && resAAAA.err != nil { + return nil, fmt.Errorf("dnssec validation failed for %s: A=%v AAAA=%v", fmsgDomain, resA.err, resAAAA.err) + } + if resA.err == nil && len(resA.ips) > 0 && !resA.ad { + return nil, fmt.Errorf("dnssec validation failed for %s: A response missing AD bit", fmsgDomain) + } + if resAAAA.err == nil && len(resAAAA.ips) > 0 && !resAAAA.ad { + return nil, fmt.Errorf("dnssec validation failed for %s: AAAA response missing AD bit", fmsgDomain) + } + + var verified []net.IP + if resA.err == nil && resA.ad { + verified = append(verified, resA.ips...) + } + if resAAAA.err == nil && resAAAA.ad { + verified = append(verified, resAAAA.ips...) + } + if len(verified) == 0 { + if resA.err != nil { + return nil, fmt.Errorf("dnssec validation failed for %s: A=%v", fmsgDomain, resA.err) + } + if resAAAA.err != nil { + return nil, fmt.Errorf("dnssec validation failed for %s: AAAA=%v", fmsgDomain, resAAAA.err) + } + return nil, fmt.Errorf("no DNSSEC-verified A/AAAA records found for %s", fmsgDomain) + } + return verified, nil } // lookupAuthorisedIPs resolves fmsg. for A and AAAA records func lookupAuthorisedIPs(domain string) ([]net.IP, error) { fmsgDomain := "fmsg." + domain - ips, err := net.LookupIP(fmsgDomain) + if dnssecRequired() { + cfg, err := dns.ClientConfigFromFile("/etc/resolv.conf") + if err != nil { + return nil, fmt.Errorf("dnssec validation failed for %s: %w", fmsgDomain, err) + } + resA := queryDNSSEC(cfg, fmsgDomain, dns.TypeA) + resAAAA := queryDNSSEC(cfg, fmsgDomain, dns.TypeAAAA) + return validateDNSSECResults(fmsgDomain, resA, resAAAA) + } + + ctx, cancel := context.WithTimeout(context.Background(), dnsLookupTimeout) + defer cancel() + ips, err := net.DefaultResolver.LookupIP(ctx, "ip", fmsgDomain) if err != nil { return nil, fmt.Errorf("DNS lookup for %s failed: %w", fmsgDomain, err) } @@ -65,17 +131,6 @@ func lookupAuthorisedIPs(domain string) ([]net.IP, error) { return nil, fmt.Errorf("no A/AAAA records found for %s", fmsgDomain) } - if dnssecRequired() { - adA, errA := resolverAuthenticatedData(fmsgDomain, dns.TypeA) - adAAAA, errAAAA := resolverAuthenticatedData(fmsgDomain, dns.TypeAAAA) - if !adA && !adAAAA { - if errA != nil && errAAAA != nil { - return nil, fmt.Errorf("dnssec validation failed for %s: A=%v AAAA=%v", fmsgDomain, errA, errAAAA) - } - return nil, fmt.Errorf("dnssec validation failed for %s: resolver did not set AD bit", fmsgDomain) - } - } - return ips, nil } diff --git a/cmd/fmsgd/host.go b/cmd/fmsgd/host.go index 7f50971..2c44f72 100644 --- a/cmd/fmsgd/host.go +++ b/cmd/fmsgd/host.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "compress/zlib" + "context" "crypto/tls" "encoding/binary" "encoding/hex" @@ -16,8 +17,10 @@ import ( "net" "net/url" "os" + "os/signal" "path/filepath" "slices" + "strconv" "strings" "syscall" "time" @@ -257,7 +260,7 @@ func setIDURL() { log.Printf("INFO: ID URL: %s", IDURI) } -func calcNetIODuration(sizeInBytes int, bytesPerSecond float64) time.Duration { +func calcNetIODuration(sizeInBytes int64, bytesPerSecond float64) time.Duration { rate := float64(sizeInBytes) / bytesPerSecond d := time.Duration(rate * float64(time.Second)) if d < MinNetIODeadline { @@ -266,6 +269,18 @@ func calcNetIODuration(sizeInBytes int, bytesPerSecond float64) time.Duration { return d } +func totalWirePayloadSize(h *FMsgHeader) int64 { + total := int64(h.Size) + for _, att := range h.Attachments { + total += int64(att.Size) + } + return total +} + +func addrEqualFold(a, b FMsgAddress) bool { + return strings.EqualFold(a.User, b.User) && strings.EqualFold(a.Domain, b.Domain) +} + func isValidUser(s string) bool { if !utf8.ValidString(s) || len(s) == 0 || len(s) > 64 { return false @@ -339,30 +354,33 @@ func isValidAttachmentFilename(name string) bool { } func isMessageRetrievable(msg *FMsgHeader) bool { - if msg == nil { - return false - } - if msg.Filepath != "" { - st, err := os.Stat(msg.Filepath) - if err == nil && !st.IsDir() { - return true + visited := make(map[string]struct{}) + for depth := 0; msg != nil && depth < maxThreadWalkDepth; depth++ { + if msg.Filepath != "" { + st, err := os.Stat(msg.Filepath) + if err == nil && !st.IsDir() { + return true + } } + if len(msg.Pid) == 0 { + return false + } + pidKey := string(msg.Pid) + if _, seen := visited[pidKey]; seen { + return false + } + visited[pidKey] = struct{}{} + parentID, err := lookupMsgIdByHashFn(msg.Pid) + if err != nil || parentID == 0 { + return false + } + parentMsg, err := getMsgByIDFn(parentID) + if err != nil { + return false + } + msg = parentMsg } - if len(msg.Pid) == 0 { - return false - } - parentID, err := lookupMsgIdByHashFn(msg.Pid) - if err != nil || parentID == 0 { - return false - } - parentMsg, err := getMsgByIDFn(parentID) - if err != nil { - return false - } - if parentMsg == nil { - return false - } - return isMessageRetrievable(parentMsg) + return false } // isOriginalParticipant reports whether addr is in the stored message's own @@ -373,12 +391,11 @@ func isOriginalParticipant(msg *FMsgHeader, addr *FMsgAddress) bool { if msg == nil || addr == nil { return false } - target := strings.ToLower(addr.ToString()) - if strings.ToLower(msg.From.ToString()) == target { + if addrEqualFold(msg.From, *addr) { return true } for i := range msg.To { - if strings.ToLower(msg.To[i].ToString()) == target { + if addrEqualFold(msg.To[i], *addr) { return true } } @@ -389,20 +406,19 @@ func isParentParticipant(parent *FMsgHeader, addr *FMsgAddress) bool { if parent == nil || addr == nil { return false } - target := strings.ToLower(addr.ToString()) - if strings.ToLower(parent.From.ToString()) == target { + if addrEqualFold(parent.From, *addr) { return true } for i := range parent.To { - if strings.ToLower(parent.To[i].ToString()) == target { + if addrEqualFold(parent.To[i], *addr) { return true } } - if parent.AddToFrom != nil && strings.ToLower(parent.AddToFrom.ToString()) == target { + if parent.AddToFrom != nil && addrEqualFold(*parent.AddToFrom, *addr) { return true } for i := range parent.AddTo { - if strings.ToLower(parent.AddTo[i].ToString()) == target { + if addrEqualFold(parent.AddTo[i], *addr) { return true } } @@ -463,12 +479,15 @@ func parseAddress(b []byte) (*FMsgAddress, error) { // Reads byte slice prefixed with uint8 size from reader supplied func ReadUInt8Slice(r io.Reader) ([]byte, error) { - var size byte - err := binary.Read(r, binary.LittleEndian, &size) - if err != nil { + var size [1]byte + if _, err := io.ReadFull(r, size[:]); err != nil { return nil, err } - return io.ReadAll(io.LimitReader(r, int64(size))) + buf := make([]byte, size[0]) + if _, err := io.ReadFull(r, buf); err != nil { + return nil, err + } + return buf, nil } func readAddress(r io.Reader) (*FMsgAddress, error) { @@ -480,19 +499,18 @@ func readAddress(r io.Reader) (*FMsgAddress, error) { } func handleChallenge(c net.Conn, r *bufio.Reader) error { - hashSlice, err := io.ReadAll(io.LimitReader(r, 32)) - if err != nil { + var hash [32]byte + if _, err := io.ReadFull(r, hash[:]); err != nil { return err } - hash := *(*[32]byte)(hashSlice) - log.Printf("INFO: CHALLENGE <-- %s", hex.EncodeToString(hashSlice)) + log.Printf("INFO: CHALLENGE <-- %s", hex.EncodeToString(hash[:])) // Verify the challenger's IP is the Host-B IP registered for this message // (§10.5 step 2). An unrecognised hash OR a mismatched IP both → TERMINATE. remoteIP, _, _ := net.SplitHostPort(c.RemoteAddr().String()) header, exists := lookupOutgoing(hash, remoteIP) if !exists { - return fmt.Errorf("challenge for unknown message: %s, from: %s", hex.EncodeToString(hashSlice), c.RemoteAddr().String()) + return fmt.Errorf("challenge for unknown message: %s, from: %s", hex.EncodeToString(hash[:]), c.RemoteAddr().String()) } msgHash, err := header.GetMessageHash() if err != nil { @@ -666,11 +684,15 @@ func handleAddToPath(c net.Conn, h *FMsgHeader) (*FMsgHeader, error) { // Batch identity is the batch message hash — this add-to header combined // with the stored parent's payload (SPEC §11) — so map the parent's data // in and compute it before the duplicate check. + if len(h.Attachments) != len(parentMsg.Attachments) { + if err := sendCode(c, RejectCodeInvalid); err != nil { + return h, err + } + return h, fmt.Errorf("add-to: attachment count %d does not match parent msg %d (%d)", len(h.Attachments), parentID, len(parentMsg.Attachments)) + } h.Filepath = parentMsg.Filepath for i := range h.Attachments { - if i < len(parentMsg.Attachments) { - h.Attachments[i].Filepath = parentMsg.Attachments[i].Filepath - } + h.Attachments[i].Filepath = parentMsg.Attachments[i].Filepath } batchHash, err := h.GetMessageHash() if err != nil { @@ -808,6 +830,9 @@ func readToRecipients(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { } key := strings.ToLower(addr.ToString()) if seen[key] { + if err := sendCode(c, RejectCodeInvalid); err != nil { + return err + } return fmt.Errorf("duplicate recipient address: %s", addr.ToString()) } seen[key] = true @@ -836,12 +861,10 @@ func readAddToRecipients(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { return fmt.Errorf("reading add-to-from address: %w", err) } - addToFromKey := strings.ToLower(addToFrom.ToString()) - fromKey := strings.ToLower(h.From.ToString()) - inFromOrTo := fromKey == addToFromKey + inFromOrTo := addrEqualFold(h.From, *addToFrom) if !inFromOrTo { - for _, toAddr := range h.To { - if strings.ToLower(toAddr.ToString()) == addToFromKey { + for i := range h.To { + if addrEqualFold(h.To[i], *addToFrom) { inFromOrTo = true break } @@ -911,40 +934,8 @@ func readAndValidateTimestamp(c net.Conn, r *bufio.Reader, h *FMsgHeader) error return nil } -func readMessageType(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { - if h.Flags&FlagCommonType != 0 { - typeID, err := r.ReadByte() - if err != nil { - return err - } - mtype, ok := fmsg.GetCommonMediaType(typeID) - if !ok { - if err := sendCode(c, RejectCodeInvalid); err != nil { - return err - } - return fmt.Errorf("unmapped common type ID: %d", typeID) - } - h.TypeID = typeID - h.Type = mtype - return nil - } - - mime, err := ReadUInt8Slice(r) - if err != nil { - return err - } - if !isASCIIBytes(mime) { - if err := sendCode(c, RejectCodeInvalid); err != nil { - return err - } - return fmt.Errorf("message media type must be US-ASCII") - } - h.Type = string(mime) - return nil -} - -func readAttachmentType(c net.Conn, r *bufio.Reader, flags uint8) (string, uint8, error) { - if flags&(1<<0) != 0 { +func readMediaType(c net.Conn, r *bufio.Reader, isCommon bool, label string) (string, uint8, error) { + if isCommon { typeID, err := r.ReadByte() if err != nil { return "", 0, err @@ -954,7 +945,7 @@ func readAttachmentType(c net.Conn, r *bufio.Reader, flags uint8) (string, uint8 if err := sendCode(c, RejectCodeInvalid); err != nil { return "", 0, err } - return "", 0, fmt.Errorf("unmapped attachment common type ID: %d", typeID) + return "", 0, fmt.Errorf("unmapped %scommon type ID: %d", label, typeID) } return mtype, typeID, nil } @@ -967,25 +958,39 @@ func readAttachmentType(c net.Conn, r *bufio.Reader, flags uint8) (string, uint8 if err := sendCode(c, RejectCodeInvalid); err != nil { return "", 0, err } - return "", 0, fmt.Errorf("attachment media type must be US-ASCII") + return "", 0, fmt.Errorf("%smedia type must be US-ASCII", label) } return string(typeBytes), 0, nil } +func readMessageType(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { + mtype, typeID, err := readMediaType(c, r, h.Flags&FlagCommonType != 0, "message ") + if err != nil { + return err + } + h.TypeID = typeID + h.Type = mtype + return nil +} + +func readAttachmentType(c net.Conn, r *bufio.Reader, flags uint8) (string, uint8, error) { + return readMediaType(c, r, flags&(1<<0) != 0, "attachment ") +} + func readAttachmentHeaders(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { var attachCount uint8 if err := binary.Read(r, binary.LittleEndian, &attachCount); err != nil { return err } - totalSize := h.Size + totalSize := uint64(h.Size) // When message is compressed, expanded size comes from the header field. // When uncompressed, the wire size IS the expanded size. - var totalExpandedSize uint32 + var totalExpandedSize uint64 if h.Flags&FlagDeflate != 0 { - totalExpandedSize = h.ExpandedSize + totalExpandedSize = uint64(h.ExpandedSize) } else { - totalExpandedSize = h.Size + totalExpandedSize = uint64(h.Size) } filenameSeen := make(map[string]bool) for i := uint8(0); i < attachCount; i++ { @@ -1033,10 +1038,24 @@ func readAttachmentHeaders(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { if err := binary.Read(r, binary.LittleEndian, &attExpandedSize); err != nil { return err } - totalExpandedSize += attExpandedSize + totalExpandedSize += uint64(attExpandedSize) } else { // uncompressed: expanded size equals wire size - totalExpandedSize += attSize + totalExpandedSize += uint64(attSize) + } + totalSize += uint64(attSize) + + if totalSize > uint64(MaxMessageSize) { + if err := sendCode(c, RejectCodeTooBig); err != nil { + return err + } + return fmt.Errorf("total message size %d exceeds max %d", totalSize, MaxMessageSize) + } + if totalExpandedSize > uint64(MaxExpandedSize) { + if err := sendCode(c, RejectCodeTooBig); err != nil { + return err + } + return fmt.Errorf("total expanded size %d exceeds MAX_EXPANDED_SIZE %d", totalExpandedSize, MaxExpandedSize) } h.Attachments = append(h.Attachments, FMsgAttachmentHeader{ @@ -1047,17 +1066,16 @@ func readAttachmentHeaders(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { Size: attSize, ExpandedSize: attExpandedSize, }) - totalSize += attSize } - if totalSize > MaxMessageSize { + if totalSize > uint64(MaxMessageSize) { if err := sendCode(c, RejectCodeTooBig); err != nil { return err } return fmt.Errorf("total message size %d exceeds max %d", totalSize, MaxMessageSize) } - if totalExpandedSize > MaxExpandedSize { + if totalExpandedSize > uint64(MaxExpandedSize) { if err := sendCode(c, RejectCodeTooBig); err != nil { return err } @@ -1097,12 +1115,10 @@ func readHeader(c net.Conn) (*FMsgHeader, *bufio.Reader, error) { // read pid if any if flags&FlagHasPid != 0 { - pid, err := io.ReadAll(io.LimitReader(r, 32)) - if err != nil { + h.Pid = make([]byte, 32) + if _, err := io.ReadFull(r, h.Pid); err != nil { return h, r, err } - h.Pid = make([]byte, 32) - copy(h.Pid, pid) } // read from address @@ -1232,45 +1248,41 @@ func challenge(conn net.Conn, h *FMsgHeader, senderDomain string) error { if err != nil { return fmt.Errorf("failed to parse remote address for challenge: %w", err) } - conn2, err := tls.Dial("tcp", net.JoinHostPort(remoteHost, fmt.Sprintf("%d", RemotePort)), buildClientTLSConfig("fmsg."+senderDomain)) + dialer := &net.Dialer{Timeout: 10 * time.Second} + conn2, err := tls.DialWithDialer(dialer, "tcp", net.JoinHostPort(remoteHost, strconv.Itoa(RemotePort)), buildClientTLSConfig("fmsg."+senderDomain)) if err != nil { return err } - version := uint8(255) - if err := binary.Write(conn2, binary.LittleEndian, version); err != nil { + defer conn2.Close() + + if err := conn2.SetWriteDeadline(time.Now().Add(10 * time.Second)); err != nil { return err } hash := h.GetHeaderHash() log.Printf("INFO: --> CHALLENGE\t%s\n", hex.EncodeToString(hash)) - if _, err := conn2.Write(hash); err != nil { + var challengeBuf [33]byte + challengeBuf[0] = 255 + copy(challengeBuf[1:], hash) + if _, err := conn2.Write(challengeBuf[:]); err != nil { return err } // read challenge response - resp, err := io.ReadAll(io.LimitReader(conn2, 32)) - if err != nil { + if err := conn2.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil { return err } - if len(resp) != 32 { - return fmt.Errorf("challenge response size %d, expected 32", len(resp)) - } - copy(h.ChallengeHash[:], resp) - h.ChallengeCompleted = true - log.Printf("INFO: <-- CHALLENGE RESP\t%s\n", hex.EncodeToString(resp)) - - // gracefully close 2nd connection - if err := conn2.Close(); err != nil { + var resp [32]byte + if _, err := io.ReadFull(conn2, resp[:]); err != nil { return err } + h.ChallengeHash = resp + h.ChallengeCompleted = true + log.Printf("INFO: <-- CHALLENGE RESP\t%s\n", hex.EncodeToString(resp[:])) return nil } -func validateMsgRecvForAddr(h *FMsgHeader, addr *FMsgAddress, msgHash []byte) (code uint8, err error) { - duplicate, err := hasAddrReceivedMsgHash(msgHash, addr) - if err != nil { - return RejectCodeUserUndisclosed, err - } +func validateMsgRecvForAddr(h *FMsgHeader, addr *FMsgAddress, duplicate bool) (code uint8, err error) { if duplicate { return RejectCodeUserDuplicate, nil } @@ -1332,22 +1344,35 @@ func recvLimitExceeded(detail *AddressDetail, size int64) string { return "" } -// uniqueFilepath generates a unique file path in the given directory, -// appending a counter suffix if the base name already exists. -func uniqueFilepath(dir string, timestamp uint32, ext string) string { - base := fmt.Sprintf("%d", timestamp) +// createUniqueFile atomically creates a new file in dir using O_CREATE|O_EXCL, +// appending a numeric suffix if base+ext already exists. +func createUniqueFile(dir, base, ext string) (*os.File, string, error) { fp := filepath.Join(dir, base+ext) - if _, err := os.Stat(fp); os.IsNotExist(err) { - return fp + f, err := os.OpenFile(fp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0640) + if err == nil { + return f, fp, nil + } + if !errors.Is(err, os.ErrExist) { + return nil, "", err } for i := 1; ; i++ { fp = filepath.Join(dir, fmt.Sprintf("%s_%d%s", base, i, ext)) - if _, err := os.Stat(fp); os.IsNotExist(err) { - return fp + f, err = os.OpenFile(fp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0640) + if err == nil { + return f, fp, nil + } + if !errors.Is(err, os.ErrExist) { + return nil, "", err } } } +// uniqueFilepath atomically creates a unique file in the given directory, +// appending a counter suffix if the base name already exists. +func uniqueFilepath(dir string, timestamp uint32, ext string) (*os.File, string, error) { + return createUniqueFile(dir, strconv.FormatUint(uint64(timestamp), 10), ext) +} + // localRecipients returns this host's recipients in wire order: every _to_ // entry for this domain, then every _add to_ entry for this domain. Addresses // are distinct within each list but MAY appear in both (SPEC Terms), in which @@ -1374,12 +1399,12 @@ func allLocalRecipientsHaveMessageHash(msgHash []byte, addrs []FMsgAddress) (boo if len(addrs) == 0 { return false, nil } + received, err := receivedAddrsForMsgHash(msgHash, addrs) + if err != nil { + return false, err + } for i := range addrs { - duplicate, err := hasAddrReceivedMsgHash(msgHash, &addrs[i]) - if err != nil { - return false, err - } - if !duplicate { + if !received[strings.ToLower(addrs[i].ToString())] { return false, nil } } @@ -1484,13 +1509,11 @@ func cleanupFiles(paths []string) { } } -func copyMessagePayload(src *os.File, dstPath string, compressed bool, wireSize uint32) error { +func copyMessagePayload(src *os.File, dst *os.File, compressed bool, wireSize, expandedSize uint32) error { + dstPath := dst.Name() if _, err := src.Seek(0, io.SeekStart); err != nil { - return err - } - - fd2, err := os.Create(dstPath) - if err != nil { + _ = dst.Close() + _ = os.Remove(dstPath) return err } @@ -1499,60 +1522,86 @@ func copyMessagePayload(src *os.File, dstPath string, compressed bool, wireSize lr := io.LimitReader(src, int64(wireSize)) zr, err := zlib.NewReader(lr) if err != nil { - fd2.Close() + _ = dst.Close() _ = os.Remove(dstPath) return err } - _, copyErr = io.Copy(fd2, zr) - _ = zr.Close() + written, err := io.Copy(dst, io.LimitReader(zr, int64(expandedSize)+1)) + zrCloseErr := zr.Close() + if err != nil { + copyErr = err + } else if written != int64(expandedSize) { + copyErr = fmt.Errorf("decompressed size %d does not match declared expanded size %d", written, expandedSize) + } else if zrCloseErr != nil { + copyErr = zrCloseErr + } } else { - _, copyErr = io.CopyN(fd2, src, int64(wireSize)) - } - if err := fd2.Close(); err != nil { - return err + _, copyErr = io.CopyN(dst, src, int64(wireSize)) } - + closeErr := dst.Close() if copyErr != nil { _ = os.Remove(dstPath) return copyErr } + if closeErr != nil { + _ = os.Remove(dstPath) + return closeErr + } return nil } -func uniqueAttachmentPath(dir string, timestamp uint32, idx int, filename string) string { +func uniqueAttachmentPath(dir string, timestamp uint32, idx int, filename string) (*os.File, string, error) { ext := filepath.Ext(filename) base := fmt.Sprintf("%d_att_%d", timestamp, idx) - p := filepath.Join(dir, base+ext) - if _, err := os.Stat(p); os.IsNotExist(err) { - return p - } - for n := 1; ; n++ { - p = filepath.Join(dir, fmt.Sprintf("%s_%d%s", base, n, ext)) - if _, err := os.Stat(p); os.IsNotExist(err) { - return p - } - } + return createUniqueFile(dir, base, ext) } func persistAttachmentPayloads(h *FMsgHeader, dirpath string) error { + dstPaths := make([]string, len(h.Attachments)) for i := range h.Attachments { a := &h.Attachments[i] src, err := os.Open(a.Filepath) if err != nil { + cleanupFiles(dstPaths[:i]) + return err + } + dstFile, dstPath, err := uniqueAttachmentPath(dirpath, uint32(h.Timestamp), i, a.Filename) + if err != nil { + src.Close() + cleanupFiles(dstPaths[:i]) return err } - dstPath := uniqueAttachmentPath(dirpath, uint32(h.Timestamp), i, a.Filename) compressed := a.Flags&(1<<1) != 0 - err = copyMessagePayload(src, dstPath, compressed, a.Size) + err = copyMessagePayload(src, dstFile, compressed, a.Size, a.ExpandedSize) src.Close() if err != nil { + cleanupFiles(dstPaths[:i]) return err } - a.Filepath = dstPath + dstPaths[i] = dstPath + } + for i, p := range dstPaths { + h.Attachments[i].Filepath = p } return nil } +func dedupeAddresses(lists ...[]FMsgAddress) []FMsgAddress { + seen := make(map[string]struct{}) + var out []FMsgAddress + for _, list := range lists { + for _, addr := range list { + key := strings.ToLower(addr.ToString()) + if _, ok := seen[key]; ok { + continue + } + seen[key] = struct{}{} + out = append(out, addr) + } + } + return out +} + // storeAcceptedMessage stores a received message once at least one local // recipient accepted it. The header is stored with its COMPLETE wire // recipient lists (never truncated to this host's recipients — §10.3 @@ -1577,7 +1626,7 @@ func storeAcceptedMessage(h *FMsgHeader, codes []byte, acceptedTo []FMsgAddress, return false } - recordRecvUsage(h, append(acceptedTo, acceptedAddTo...), timeutil.TimestampNow().Float64()) + recordRecvUsage(h, dedupeAddresses(acceptedTo, acceptedAddTo), timeutil.TimestampNow().Float64()) return true } @@ -1649,9 +1698,16 @@ func downloadMessage(c net.Conn, r io.Reader, h *FMsgHeader, skipData bool) erro } defer src.Close() + // Batch duplicate check across all local recipients in a single DB query. + receivedSet, err := receivedAddrsForMsgHash(dupHash, addrs) + if err != nil { + return err + } + // validate each recipient and copy message for accepted ones acceptedTo := []FMsgAddress{} acceptedAddTo := []FMsgAddress{} + addrCodes := make(map[string]uint8, len(addrs)) var primaryFilepath string var wireDir string wireStored := false @@ -1661,13 +1717,27 @@ func downloadMessage(c net.Conn, r io.Reader, h *FMsgHeader, skipData bool) erro } }() for i, addr := range addrs { - code, err := validateMsgRecvForAddr(h, &addr, dupHash) + addrKey := strings.ToLower(addr.ToString()) + if prevCode, seen := addrCodes[addrKey]; seen { + codes[i] = prevCode + if prevCode == RejectCodeAccept { + if i < numLocalTo { + acceptedTo = append(acceptedTo, addr) + } else { + acceptedAddTo = append(acceptedAddTo, addr) + } + } + continue + } + + code, err := validateMsgRecvForAddr(h, &addr, receivedSet[addrKey]) if err != nil { return err } if code != RejectCodeAccept { log.Printf("WARN: Rejected message to: %s: %s (%d)", addr.ToString(), responseCodeName(code), code) codes[i] = code + addrCodes[addrKey] = code continue } @@ -1677,14 +1747,22 @@ func downloadMessage(c net.Conn, r io.Reader, h *FMsgHeader, skipData bool) erro return err } - fp := uniqueFilepath(dirpath, uint32(h.Timestamp), ext) - if err := copyMessagePayload(src, fp, h.Flags&FlagDeflate != 0, h.Size); err != nil { - log.Printf("ERROR: copying downloaded message from: %s, to: %s", h.Filepath, fp) + dstFile, fp, err := uniqueFilepath(dirpath, uint32(h.Timestamp), ext) + if err != nil { + log.Printf("ERROR: creating destination file in %s: %s", dirpath, err) codes[i] = RejectCodeUserUndisclosed + addrCodes[addrKey] = RejectCodeUserUndisclosed + continue + } + if err := copyMessagePayload(src, dstFile, h.Flags&FlagDeflate != 0, h.Size, h.ExpandedSize); err != nil { + log.Printf("ERROR: copying downloaded message from: %s, to: %s: %s", h.Filepath, fp, err) + codes[i] = RejectCodeUserUndisclosed + addrCodes[addrKey] = RejectCodeUserUndisclosed continue } codes[i] = RejectCodeAccept + addrCodes[addrKey] = RejectCodeAccept // Entries before numLocalTo came from _to_, the rest from _add to_. An // address in both lists appears once in each range and is recorded in // both, rather than being classified exclusively as add-to. @@ -1706,13 +1784,16 @@ func downloadMessage(c net.Conn, r io.Reader, h *FMsgHeader, skipData bool) erro return err } } - if err := persistAttachmentPayloads(h, filepath.Dir(primaryFilepath)); err != nil { - log.Printf("ERROR: copying attachment payloads for message storage: %s", err) - codes[i] = RejectCodeUserUndisclosed - primaryFilepath = "" - acceptedTo = acceptedTo[:0] - acceptedAddTo = acceptedAddTo[:0] - continue + if !skipData { + if err := persistAttachmentPayloads(h, filepath.Dir(primaryFilepath)); err != nil { + log.Printf("ERROR: copying attachment payloads for message storage: %s", err) + codes[i] = RejectCodeUserUndisclosed + addrCodes[addrKey] = RejectCodeUserUndisclosed + primaryFilepath = "" + acceptedTo = acceptedTo[:0] + acceptedAddTo = acceptedAddTo[:0] + continue + } } } } @@ -1753,8 +1834,12 @@ func resolvePostChallengeCode(initialCode uint8, challengeCompleted bool, allLoc } func abortConn(c net.Conn) { - if tcp, ok := c.(*net.TCPConn); ok { - tcp.SetLinger(0) + raw := c + if tc, ok := raw.(*tls.Conn); ok { + raw = tc.NetConn() + } + if tcp, ok := raw.(*net.TCPConn); ok { + _ = tcp.SetLinger(0) } _ = c.Close() } @@ -1795,6 +1880,7 @@ func handleConn(c net.Conn) { defer func() { if r := recover(); r != nil { log.Printf("ERROR: Recovered in handleConn: %v", r) + abortConn(c) } }() @@ -1913,7 +1999,7 @@ func handleConn(c net.Conn) { } // store message - deadlineBytes := int(header.Size) + deadlineBytes := totalWirePayloadSize(header) if skipData { deadlineBytes = 1 } @@ -1933,6 +2019,8 @@ func handleConn(c net.Conn) { } func main() { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() initOutgoing() @@ -1951,11 +2039,12 @@ func main() { listenAddress = arg } - // initalize database + // initialize database err := testDb() if err != nil { log.Fatalf("ERROR: connecting to database: %s\n", err) } + defer closeDB() // set DataDir, Domain and IDURL from env setDataDir() @@ -1966,12 +2055,16 @@ func main() { serverTLSConfig = buildServerTLSConfig() // FMSG-006 indicators on UDP, same address and port as TCP - startIndicators(listenAddress, Port) + startIndicators(ctx, listenAddress, Port) // start sender in background (small delay so listener is ready first) go func() { - time.Sleep(1 * time.Second) - startSender() + select { + case <-ctx.Done(): + return + case <-time.After(1 * time.Second): + } + startSender(ctx) }() // start listening @@ -1980,14 +2073,35 @@ func main() { if err != nil { log.Fatal(err) } + go func() { + <-ctx.Done() + _ = ln.Close() + }() log.Printf("INFO: Ready to receive on %s\n", addr) + + var acceptBackoff time.Duration for { conn, err := ln.Accept() if err != nil { + if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { + log.Println("INFO: Shutting down") + return + } log.Printf("ERROR: Accept connection from %s returned: %s\n", ln.Addr().String(), err) - } else { - go handleConn(conn) + if acceptBackoff == 0 { + acceptBackoff = 5 * time.Millisecond + } else { + acceptBackoff = min(acceptBackoff*2, time.Second) + } + select { + case <-ctx.Done(): + return + case <-time.After(acceptBackoff): + } + continue } + acceptBackoff = 0 + go handleConn(conn) } } diff --git a/cmd/fmsgd/host_test.go b/cmd/fmsgd/host_test.go index ab39f23..ce5544e 100644 --- a/cmd/fmsgd/host_test.go +++ b/cmd/fmsgd/host_test.go @@ -3,9 +3,15 @@ package main import ( "bufio" "bytes" + "compress/zlib" "encoding/binary" + "errors" "fmt" + "io" "net" + "os" + "path/filepath" + "sync" "testing" "time" ) @@ -817,3 +823,266 @@ func TestHandleAddToParentNotStoredParticipantOnly(t *testing.T) { t.Fatalf("wrote %v, want single code %d (parent not found)", got, RejectCodeParentNotFound) } } + +func TestReadAttachmentHeadersRejectsUint32SizeOverflow(t *testing.T) { + origMax := MaxMessageSize + origExpanded := MaxExpandedSize + MaxMessageSize = 1024 + MaxExpandedSize = 1024 + t.Cleanup(func() { + MaxMessageSize = origMax + MaxExpandedSize = origExpanded + }) + + // Two attachments of size 0x80000001 each would wrap uint32 to 2 (<= 1024). + h := &FMsgHeader{Size: 0} + c := &testConn{} + b := []byte{2} // 2 attachments + for _, name := range []string{"a.bin", "b.bin"} { + b = append(b, 0) + b = append(b, encodeUInt8String(t, "application/octet-stream")...) + b = append(b, encodeUInt8String(t, name)...) + var sz [4]byte + binary.LittleEndian.PutUint32(sz[:], 0x80000001) + b = append(b, sz[:]...) + } + + err := readAttachmentHeaders(c, bufio.NewReader(bytes.NewReader(b)), h) + if err == nil { + t.Fatal("expected error for uint32 size overflow") + } + if got := c.Bytes(); len(got) != 1 || got[0] != RejectCodeTooBig { + t.Fatalf("wrote %v, want single code %d (too big)", got, RejectCodeTooBig) + } +} + +func TestHandleChallengeTruncatedNoPanic(t *testing.T) { + initOutgoing() + c := &testConn{} + // Only 5 bytes instead of 32: must return an error without panicking. + err := handleChallenge(c, bufio.NewReader(bytes.NewReader([]byte{1, 2, 3, 4, 5}))) + if !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("handleChallenge truncated err = %v, want io.ErrUnexpectedEOF", err) + } +} + +func TestReadUInt8SliceTruncatedErrors(t *testing.T) { + var buf bytes.Buffer + buf.WriteByte(10) + buf.WriteString("short") + if _, err := ReadUInt8Slice(&buf); !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("ReadUInt8Slice truncated err = %v, want io.ErrUnexpectedEOF", err) + } +} + +func TestReadToRecipientsDuplicateSendsRejectCodeInvalid(t *testing.T) { + b := []byte{2} + b = append(b, encodeUInt8String(t, "@alice@example.com")...) + b = append(b, encodeUInt8String(t, "@ALICE@example.com")...) + + c := &testConn{} + h := &FMsgHeader{} + err := readToRecipients(c, bufio.NewReader(bytes.NewReader(b)), h) + if err == nil { + t.Fatal("expected duplicate recipient error") + } + if got := c.Bytes(); len(got) != 1 || got[0] != RejectCodeInvalid { + t.Fatalf("wrote %v, want single code %d (invalid)", got, RejectCodeInvalid) + } +} + +func TestHandleAddToPathAttachmentCountMismatch(t *testing.T) { + stubStoredParent(t, storedParentForTest(t, 0)) + h := addToForTest() + h.Attachments = []FMsgAttachmentHeader{{Filename: "extra.txt", Type: "text/plain", Size: 1}} + c := &testConn{} + if _, err := handleAddToPath(c, h); err == nil { + t.Fatal("expected error for add-to attachment count mismatch") + } + if got := c.Bytes(); len(got) != 1 || got[0] != RejectCodeInvalid { + t.Fatalf("wrote %v, want single code %d (invalid)", got, RejectCodeInvalid) + } +} + +func TestIsMessageRetrievableCycleGuard(t *testing.T) { + origLookup, origGet := lookupMsgIdByHashFn, getMsgByIDFn + t.Cleanup(func() { + lookupMsgIdByHashFn, getMsgByIDFn = origLookup, origGet + }) + + pidA := bytes.Repeat([]byte{0xAA}, 32) + pidB := bytes.Repeat([]byte{0xBB}, 32) + msgA := &FMsgHeader{Pid: pidB} + msgB := &FMsgHeader{Pid: pidA} + lookupMsgIdByHashFn = func(hash []byte) (int64, error) { + if bytes.Equal(hash, pidB) { + return 2, nil + } + if bytes.Equal(hash, pidA) { + return 1, nil + } + return 0, nil + } + getMsgByIDFn = func(id int64) (*FMsgHeader, error) { + if id == 1 { + return msgA, nil + } + if id == 2 { + return msgB, nil + } + return nil, nil + } + + if isMessageRetrievable(msgA) { + t.Fatal("expected cyclic missing messages to be non-retrievable") + } +} + +func TestCopyMessagePayloadRejectsZlibBomb(t *testing.T) { + dir := t.TempDir() + bomb := make([]byte, 1<<20) + srcPath := filepath.Join(dir, "bomb.z") + sf, err := os.Create(srcPath) + if err != nil { + t.Fatal(err) + } + zw := zlib.NewWriter(sf) + if _, err := zw.Write(bomb); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + wireSize, _ := sf.Seek(0, io.SeekCurrent) + + dstFile, dstPath, err := uniqueFilepath(dir, 12345, ".txt") + if err != nil { + sf.Close() + t.Fatal(err) + } + + err = copyMessagePayload(sf, dstFile, true, uint32(wireSize), 128) + sf.Close() + if err == nil { + t.Fatal("copyMessagePayload accepted zlib bomb") + } + if _, statErr := os.Stat(dstPath); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("expected failed dst file %s to be removed, stat err=%v", dstPath, statErr) + } +} + +func TestUniqueFilepathAtomicCreation(t *testing.T) { + dir := t.TempDir() + + // Concurrent creation with the same timestamp must produce distinct files. + const n = 16 + paths := make(chan string, n) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + f, p, err := uniqueFilepath(dir, 1700000000, ".txt") + if err != nil { + t.Errorf("uniqueFilepath error: %v", err) + return + } + _ = f.Close() + paths <- p + }() + } + wg.Wait() + close(paths) + + seen := make(map[string]bool) + for p := range paths { + if seen[p] { + t.Fatalf("duplicate path created: %s", p) + } + seen[p] = true + } + if len(seen) != n { + t.Fatalf("created %d unique files, want %d", len(seen), n) + } + + // Non-existent directory must return an error immediately (not loop). + if _, _, err := uniqueFilepath(filepath.Join(dir, "does-not-exist"), 1, ".txt"); err == nil { + t.Fatal("expected error for missing directory") + } +} + +func TestBuildDomainRecipsToIntersectAddToLocking(t *testing.T) { + bob := FMsgAddress{User: "bob", Domain: "remote.example"} + carol := FMsgAddress{User: "carol", Domain: "remote.example"} + h := &FMsgHeader{ + Flags: FlagHasPid | FlagHasAddTo, + To: []FMsgAddress{bob, {User: "other", Domain: "other.example"}}, + AddTo: []FMsgAddress{bob, carol}, + } + + // Delivering msg_add_to where bob is in both To and AddTo: + // only the AddTo entry for bob should be marked isLocked. + recips := buildDomainRecips(h, "remote.example", "msg_add_to", []string{"@bob@remote.example", "@carol@remote.example"}) + if len(recips) != 3 { + t.Fatalf("len(recips) = %d, want 3 (bob from To, bob & carol from AddTo)", len(recips)) + } + if recips[0].addr != "@bob@remote.example" || recips[0].isLocked { + t.Fatalf("To entry recips[0] = %+v, want isLocked=false", recips[0]) + } + if recips[1].addr != "@bob@remote.example" || !recips[1].isLocked { + t.Fatalf("AddTo entry recips[1] = %+v, want isLocked=true", recips[1]) + } + if recips[2].addr != "@carol@remote.example" || !recips[2].isLocked { + t.Fatalf("AddTo entry recips[2] = %+v, want isLocked=true", recips[2]) + } + + // Delivering msg_to: only the To entry for bob should be marked isLocked. + recipsTo := buildDomainRecips(h, "remote.example", "msg_to", []string{"@bob@remote.example"}) + if len(recipsTo) != 3 { + t.Fatalf("len(recipsTo) = %d, want 3", len(recipsTo)) + } + if !recipsTo[0].isLocked || recipsTo[1].isLocked || recipsTo[2].isLocked { + t.Fatalf("msg_to locking mismatch: %+v", recipsTo) + } +} + +func TestValidateDNSSECResults(t *testing.T) { + v4 := net.ParseIP("192.0.2.1") + v6 := net.ParseIP("2001:db8::1") + + // Unsigned A + signed AAAA NODATA must fail (regression check). + _, err := validateDNSSECResults("fmsg.example.com", + dnssecQueryResult{ips: []net.IP{v4}, ad: false}, + dnssecQueryResult{ips: nil, ad: true}, + ) + if err == nil { + t.Fatal("accepted unsigned A record because AAAA had signed NODATA") + } + + // Signed A + unsigned AAAA must fail. + _, err = validateDNSSECResults("fmsg.example.com", + dnssecQueryResult{ips: []net.IP{v4}, ad: true}, + dnssecQueryResult{ips: []net.IP{v6}, ad: false}, + ) + if err == nil { + t.Fatal("accepted unsigned AAAA record alongside signed A") + } + + // Signed A + signed AAAA NODATA succeeds and returns verified A IP. + ips, err := validateDNSSECResults("fmsg.example.com", + dnssecQueryResult{ips: []net.IP{v4}, ad: true}, + dnssecQueryResult{ips: nil, ad: true}, + ) + if err != nil || len(ips) != 1 || !ips[0].Equal(v4) { + t.Fatalf("signed A + signed NODATA AAAA = (%v, %v), want [%s]", ips, err, v4) + } + + // Signed A + signed AAAA returns both verified IPs. + ips, err = validateDNSSECResults("fmsg.example.com", + dnssecQueryResult{ips: []net.IP{v4}, ad: true}, + dnssecQueryResult{ips: []net.IP{v6}, ad: true}, + ) + if err != nil || len(ips) != 2 || !ips[0].Equal(v4) || !ips[1].Equal(v6) { + t.Fatalf("signed A + signed AAAA = (%v, %v), want [%s %s]", ips, err, v4, v6) + } +} diff --git a/cmd/fmsgd/id.go b/cmd/fmsgd/id.go index d4c8ca9..fb7643e 100644 --- a/cmd/fmsgd/id.go +++ b/cmd/fmsgd/id.go @@ -4,10 +4,23 @@ import ( "bytes" "encoding/json" "fmt" + "io" "net/http" "net/url" + "time" ) +var idHTTPClient = newIDHTTPClient() + +func newIDHTTPClient() *http.Client { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.MaxIdleConnsPerHost = 32 + return &http.Client{ + Timeout: 10 * time.Second, + Transport: transport, + } +} + type AddressDetail struct { Address string `json:"address"` DisplayName string `json:"displayName"` @@ -33,15 +46,21 @@ type AddressDetail struct { // address supplied. If the address is not found returns nil, nil. func getAddressDetail(addr *FMsgAddress) (*AddressDetail, error) { uri := IDURI + "/fmsgid/" + url.PathEscape(addr.ToString()) - resp, err := http.Get(uri) + resp, err := idHTTPClient.Get(uri) if err != nil { return nil, err } - defer resp.Body.Close() + defer func() { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024)) + _ = resp.Body.Close() + }() if resp.StatusCode == http.StatusNotFound { return nil, nil } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("GET %s returned %d", uri, resp.StatusCode) + } var detail AddressDetail err = json.NewDecoder(resp.Body).Decode(&detail) @@ -78,11 +97,14 @@ func postMsgStat(addr *FMsgAddress, timestamp float64, size int64, isSending boo return err } - resp, err := http.Post(uri, "application/json", bytes.NewBuffer(jsonPayload)) + resp, err := idHTTPClient.Post(uri, "application/json", bytes.NewReader(jsonPayload)) if err != nil { return err } - defer resp.Body.Close() + defer func() { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024)) + _ = resp.Body.Close() + }() if resp.StatusCode != http.StatusOK { return fmt.Errorf("POST %s returned %d", uri, resp.StatusCode) diff --git a/cmd/fmsgd/indicators.go b/cmd/fmsgd/indicators.go index 2792db3..e67bb1c 100644 --- a/cmd/fmsgd/indicators.go +++ b/cmd/fmsgd/indicators.go @@ -35,6 +35,7 @@ import ( "github.com/lib/pq" "github.com/markmnl/fmsgd/internal/emoji" + "github.com/markmnl/fmsgd/pkg/fmsg" ) const ( @@ -158,24 +159,6 @@ func indicatorParticipants(h *FMsgHeader) []FMsgAddress { return parts } -// preparedHeader decodes a stored prepared message (msg.wire_message, -// msg_add_to_batch.wire_message) for its header fields only. Unlike -// fmsg.UnmarshalPrepared it does not re-hash the payload from disk: the row -// was found by its hash, and a datagram must not cost a read of the message. -func preparedHeader(data []byte) (*FMsgHeader, error) { - var s struct { - Version int - Header *FMsgHeader - } - if err := json.Unmarshal(data, &s); err != nil { - return nil, err - } - if s.Version != 1 || s.Header == nil { - return nil, fmt.Errorf("unsupported prepared message") - } - return s.Header, nil -} - // indicatorSubject is a message an indicator can refer to: the original // message or one of its add-to batch messages, with its participants. type indicatorSubject struct { @@ -187,7 +170,7 @@ type indicatorSubject struct { // or -1. func (s *indicatorSubject) participantIndex(addr FMsgAddress) int { for i, p := range s.Participants { - if strings.EqualFold(p.ToString(), addr.ToString()) { + if addrEqualFold(p, addr) { return i } } @@ -296,7 +279,7 @@ func (s sqlIndicatorStore) originalFromBatch(ctx context.Context, msgID int64) ( if err != nil { return nil, false, err } - h, err := preparedHeader(prepared) + h, err := fmsg.UnmarshalPreparedHeader(prepared) if err != nil { return nil, false, err } @@ -312,7 +295,7 @@ func (s sqlIndicatorStore) subjectByHash(ctx context.Context, hash []byte) (int6 parts, ok, err := s.originalFromBatch(ctx, id) return id, parts, ok, err } - h, err := preparedHeader(prepared) + h, err := fmsg.UnmarshalPreparedHeader(prepared) if err != nil { return 0, nil, false, err } @@ -328,7 +311,7 @@ func (s sqlIndicatorStore) subjectByHash(ctx context.Context, hash []byte) (int6 if err != nil { return 0, nil, false, err } - h, err := preparedHeader(prepared) + h, err := fmsg.UnmarshalPreparedHeader(prepared) if err != nil { return 0, nil, false, err } @@ -352,15 +335,21 @@ func (s sqlIndicatorStore) subjectsOf(ctx context.Context, msgID int64) (*indica } defer rows.Close() var batches []indicatorSubject + var firstBatchOrigParts []FMsgAddress for rows.Next() { var bHash, bPrepared []byte if err := rows.Scan(&bHash, &bPrepared); err != nil { return nil, nil, err } - h, err := preparedHeader(bPrepared) + h, err := fmsg.UnmarshalPreparedHeader(bPrepared) if err != nil { return nil, nil, err } + if firstBatchOrigParts == nil { + firstBatchOrigParts = make([]FMsgAddress, 0, 1+len(h.To)) + firstBatchOrigParts = append(firstBatchOrigParts, h.From) + firstBatchOrigParts = append(firstBatchOrigParts, h.To...) + } batches = append(batches, indicatorSubject{Hash: bHash, Participants: indicatorParticipants(h)}) } if err := rows.Err(); err != nil { @@ -370,15 +359,13 @@ func (s sqlIndicatorStore) subjectsOf(ctx context.Context, msgID int64) (*indica var original *indicatorSubject if len(hash) == 32 { if len(prepared) > 0 { - h, err := preparedHeader(prepared) + h, err := fmsg.UnmarshalPreparedHeader(prepared) if err != nil { return nil, nil, err } original = &indicatorSubject{Hash: hash, Participants: indicatorParticipants(h)} - } else if parts, ok, err := s.originalFromBatch(ctx, msgID); err != nil { - return nil, nil, err - } else if ok { - original = &indicatorSubject{Hash: hash, Participants: parts} + } else if firstBatchOrigParts != nil { + original = &indicatorSubject{Hash: hash, Participants: firstBatchOrigParts} } } return original, batches, nil @@ -432,13 +419,20 @@ func newSourceLimiter(rate, burst float64, max int) *sourceLimiter { return &sourceLimiter{rate: rate, burst: burst, max: max, buckets: map[string]*tokenBucket{}} } +const sourceLimiterMinPruneInterval = time.Second + func (l *sourceLimiter) allow(src string, now time.Time) bool { l.mu.Lock() defer l.mu.Unlock() b, ok := l.buckets[src] if !ok { - if len(l.buckets) >= l.max || now.Sub(l.lastPrune) >= 10*time.Second { - l.prune(now) + if l.lastPrune.IsZero() { + l.lastPrune = now + } else { + sincePrune := now.Sub(l.lastPrune) + if (len(l.buckets) >= l.max && sincePrune >= sourceLimiterMinPruneInterval) || sincePrune >= 10*time.Second { + l.prune(now) + } } if len(l.buckets) >= l.max { return false @@ -514,13 +508,14 @@ func (l *windowLimiter) prune(now time.Time) { // ipCache caches fmsg. resolutions for indicators: positive results // for ttl, failures for negTTL. The TCP exchange keeps resolving afresh. type ipCache struct { - mu sync.Mutex - lookup func(domain string) ([]net.IP, error) - now func() time.Time - ttl time.Duration - negTTL time.Duration - max int - entries map[string]ipCacheEntry + mu sync.Mutex + lookup func(domain string) ([]net.IP, error) + now func() time.Time + ttl time.Duration + negTTL time.Duration + max int + entries map[string]ipCacheEntry + lastPrune time.Time } type ipCacheEntry struct { @@ -534,29 +529,33 @@ func newIPCache(lookup func(string) ([]net.IP, error), now func() time.Time) *ip max: indicatorDNSCacheMax, entries: map[string]ipCacheEntry{}} } +const ipCacheMinPruneInterval = time.Second + func (c *ipCache) get(domain string) ([]net.IP, error) { domain = strings.ToLower(domain) + now := c.now() c.mu.Lock() e, ok := c.entries[domain] c.mu.Unlock() - now := c.now() if ok && now.Before(e.expires) { return e.ips, e.err } ips, err := c.lookup(domain) - e = ipCacheEntry{ips: ips, err: err, expires: now.Add(c.ttl)} + after := c.now() + e = ipCacheEntry{ips: ips, err: err, expires: after.Add(c.ttl)} if err != nil { - e.expires = now.Add(c.negTTL) + e.expires = after.Add(c.negTTL) } c.mu.Lock() - if len(c.entries) >= c.max { + if len(c.entries) >= c.max && (c.lastPrune.IsZero() || after.Sub(c.lastPrune) >= ipCacheMinPruneInterval) { for k, old := range c.entries { - if !now.Before(old.expires) { + if !after.Before(old.expires) { delete(c.entries, k) } } + c.lastPrune = after } - if len(c.entries) < c.max { + if _, exists := c.entries[domain]; exists || len(c.entries) < c.max { c.entries[domain] = e } c.mu.Unlock() @@ -841,7 +840,7 @@ func (s *indicatorService) sendTo(domain string, b []byte) { // listen LISTENs on the indicator channel and sends each local participant's // indicator, in the order published so the latest state wins. -func (s *indicatorService) listen(dsn string) { +func (s *indicatorService) listen(ctx context.Context, dsn string) { listener := pq.NewListener(dsn, 10*time.Second, time.Minute, func(ev pq.ListenerEventType, err error) { if err != nil { log.Printf("ERROR: indicators: pg listener: %s", err) @@ -852,18 +851,31 @@ func (s *indicatorService) listen(dsn string) { return } defer listener.Close() + + pingTimer := time.NewTimer(32 * time.Second) + defer pingTimer.Stop() for { select { + case <-ctx.Done(): + return case n := <-listener.Notify: + if !pingTimer.Stop() { + select { + case <-pingTimer.C: + default: + } + } + pingTimer.Reset(32 * time.Second) if n == nil { continue } - ctx, cancel := context.WithTimeout(context.Background(), indicatorQueryTimeout) - if err := s.handleNotice(ctx, n.Extra); err != nil { + qctx, cancel := context.WithTimeout(ctx, indicatorQueryTimeout) + if err := s.handleNotice(qctx, n.Extra); err != nil { log.Printf("WARN: indicators: notice %q: %s", n.Extra, err) } cancel() - case <-time.After(32 * time.Second): + case <-pingTimer.C: + pingTimer.Reset(32 * time.Second) if err := listener.Ping(); err != nil { log.Printf("ERROR: indicators: pg listener ping: %s", err) } @@ -871,11 +883,16 @@ func (s *indicatorService) listen(dsn string) { } } -func (s *indicatorService) runFlusher() { +func (s *indicatorService) runFlusher(ctx context.Context) { t := time.NewTicker(indicatorFlushInterval) defer t.Stop() - for range t.C { - s.flush() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + s.flush() + } } } @@ -883,7 +900,7 @@ func (s *indicatorService) runFlusher() { // address and port, and sends local participants' indicators from the same // socket, so they leave from an address in this host's fmsg. set. // Failing to start is logged; message exchange is unaffected. -func startIndicators(listenAddress string, port int) { +func startIndicators(ctx context.Context, listenAddress string, port int) { if !indicatorsEnabled() { log.Println("INFO: indicators: disabled (FMSG_INDICATORS)") return @@ -899,16 +916,19 @@ func startIndicators(listenAddress string, port int) { log.Printf("ERROR: indicators: listening on UDP %s: %s", addr, err) return } - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { log.Printf("ERROR: indicators: opening database: %s", err) conn.Close() return } - db.SetMaxOpenConns(indicatorRecvWorkers + 2) s := newIndicatorService(sqlIndicatorStore{db}, conn, lookupAuthorisedIPs, time.Now) + go func() { + <-ctx.Done() + _ = conn.Close() + }() go s.serve() - go s.listen("") - go s.runFlusher() + go s.listen(ctx, "") + go s.runFlusher(ctx) log.Printf("INFO: indicators: ready on UDP %s", addr) } diff --git a/cmd/fmsgd/indicators_test.go b/cmd/fmsgd/indicators_test.go index 7251aba..1d4d470 100644 --- a/cmd/fmsgd/indicators_test.go +++ b/cmd/fmsgd/indicators_test.go @@ -171,14 +171,14 @@ func TestPreparedHeaderParticipants(t *testing.T) { if err != nil { t.Fatal(err) } - got, err := preparedHeader(data) + got, err := fmsg.UnmarshalPreparedHeader(data) if err != nil { t.Fatal(err) } if s := strings.Join(addrStrings(indicatorParticipants(got)), ","); s != "@alice@a.test,@bob@b.test,@bob@b.test,@erin@e.test" { t.Fatalf("participants = %s", s) } - if _, err := preparedHeader([]byte(`{"Version":2,"Header":{}}`)); err == nil { + if _, err := fmsg.UnmarshalPreparedHeader([]byte(`{"Version":2,"Header":{}}`)); err == nil { t.Fatal("unsupported prepared version accepted") } } @@ -326,6 +326,61 @@ func TestSourceLimiter(t *testing.T) { } } +func TestSourceLimiterPruneGatingUnderFlood(t *testing.T) { + l := newSourceLimiter(50, 100, 2) + now := time.Unix(2000, 0) + if !l.allow("192.0.2.1", now) || !l.allow("192.0.2.2", now) { + t.Fatal("initial sources should be allowed") + } + initialPrune := l.lastPrune + // Flood with new sources within < 1s: must drop without re-pruning. + for i := 0; i < 50; i++ { + if l.allow(fmt.Sprintf("198.51.100.%d", i), now.Add(500*time.Millisecond)) { + t.Fatalf("source %d allowed while table full", i) + } + if !l.lastPrune.Equal(initialPrune) { + t.Fatalf("pruned within 1s gate: lastPrune=%v, want %v", l.lastPrune, initialPrune) + } + } + // After 1s, prune runs once and updates lastPrune. + t1 := now.Add(time.Second) + if l.allow("198.51.100.200", t1) { + t.Fatal("new source allowed while existing buckets not yet refilled") + } + if !l.lastPrune.Equal(t1) { + t.Fatalf("expected prune at %v, got lastPrune=%v", t1, l.lastPrune) + } + // Another flood right after t1 must not re-prune. + if l.allow("198.51.100.201", t1.Add(100*time.Millisecond)) { + t.Fatal("new source allowed while full") + } + if !l.lastPrune.Equal(t1) { + t.Fatalf("pruned again within 1s: lastPrune=%v, want %v", l.lastPrune, t1) + } +} + +func TestIPCacheExpiryUsesTimeAfterLookup(t *testing.T) { + now := time.Unix(3000, 0) + calls := 0 + c := newIPCache(func(d string) ([]net.IP, error) { + calls++ + now = now.Add(30 * time.Second) // simulate slow DNS lookup + return []net.IP{net.ParseIP("192.0.2.1")}, nil + }, func() time.Time { return now }) + + if _, err := c.get("slow.test"); err != nil { + t.Fatal(err) + } + // 45s after lookup completed (75s after start) must still be cached (TTL=60s). + now = now.Add(45 * time.Second) + if _, err := c.get("slow.test"); err != nil { + t.Fatal(err) + } + if calls != 1 { + t.Fatalf("lookups = %d, want 1 (expiry should be based on post-lookup time)", calls) + } +} + func TestWindowLimiter(t *testing.T) { l := newWindowLimiter(20, time.Second) now := time.Unix(1000, 0) diff --git a/cmd/fmsgd/sender.go b/cmd/fmsgd/sender.go index 092f14d..0190b78 100644 --- a/cmd/fmsgd/sender.go +++ b/cmd/fmsgd/sender.go @@ -1,21 +1,23 @@ package main import ( + "context" "crypto/tls" "database/sql" "encoding/hex" "fmt" - "github.com/markmnl/fmsgd/pkg/fmsg" "io" "log" "net" "os" "strings" + "sync" "time" env "github.com/caitlinelfring/go-env-default" "github.com/levenlabs/golib/timeutil" "github.com/lib/pq" + "github.com/markmnl/fmsgd/pkg/fmsg" ) var RetryInterval float64 = 20 @@ -60,11 +62,10 @@ type pendingTarget struct { // retryable recipients. This is a lightweight read-only query — row-level // locks are acquired per-delivery in deliverMessage. func findPendingTargets() ([]pendingTarget, error) { - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return nil, err } - defer db.Close() now := timeutil.TimestampNow().Float64() @@ -166,7 +167,7 @@ func sendMsgData(conn net.Conn, h *FMsgHeader) error { } defer fd.Close() - conn.SetWriteDeadline(time.Now().Add(calcNetIODuration(int(h.Size), MinUploadRate))) + conn.SetWriteDeadline(time.Now().Add(calcNetIODuration(totalWirePayloadSize(h), MinUploadRate))) if _, err := io.CopyN(conn, fd, int64(h.Size)); err != nil { return fmt.Errorf("sending data: %w", err) } @@ -187,30 +188,51 @@ func sendMsgData(conn net.Conn, h *FMsgHeader) error { // updateRecipient records a delivery outcome for one address in table. // Deliveries set time_delivered; failures set time_last_attempt and increment // attempt_count to drive exponential back-off on subsequent retries. -func updateRecipient(tx *sql.Tx, table, addr string, msgID int64, now float64, code int, delivered bool) { +// For msg_add_to, rows are scoped by batch_id so independent batches sharing +// the same recipient address do not overwrite each other. +func updateRecipient(tx *sql.Tx, table, addr string, msgID, batchID int64, now float64, code int, delivered bool) error { var err error - if delivered { - _, err = tx.Exec(fmt.Sprintf(` - UPDATE %s SET time_delivered = $1, response_code = $2 - WHERE msg_id = $3 AND addr = $4 - `, table), now, code, msgID, addr) + if table == "msg_add_to" { + if delivered { + _, err = tx.Exec(` + UPDATE msg_add_to SET time_delivered = $1, response_code = $2 + WHERE batch_id = $3 AND addr = $4 + `, now, code, batchID, addr) + } else { + _, err = tx.Exec(` + UPDATE msg_add_to SET time_last_attempt = $1, response_code = $2, + attempt_count = attempt_count + 1 + WHERE batch_id = $3 AND addr = $4 + `, now, code, batchID, addr) + } } else { - _, err = tx.Exec(fmt.Sprintf(` - UPDATE %s SET time_last_attempt = $1, response_code = $2, - attempt_count = attempt_count + 1 - WHERE msg_id = $3 AND addr = $4 - `, table), now, code, msgID, addr) + if delivered { + _, err = tx.Exec(` + UPDATE msg_to SET time_delivered = $1, response_code = $2 + WHERE msg_id = $3 AND addr = $4 + `, now, code, msgID, addr) + } else { + _, err = tx.Exec(` + UPDATE msg_to SET time_last_attempt = $1, response_code = $2, + attempt_count = attempt_count + 1 + WHERE msg_id = $3 AND addr = $4 + `, now, code, msgID, addr) + } } if err != nil { log.Printf("ERROR: sender: update recipient %s: %s", addr, err) } + return err } // updateLocked applies the same outcome to every locked address in one table. -func updateLocked(tx *sql.Tx, table string, addrs []string, msgID int64, now float64, code int, delivered bool) { +func updateLocked(tx *sql.Tx, table string, addrs []string, msgID, batchID int64, now float64, code int, delivered bool) error { for _, a := range addrs { - updateRecipient(tx, table, a, msgID, now, code, delivered) + if err := updateRecipient(tx, table, a, msgID, batchID, now, code, delivered); err != nil { + return err + } } + return nil } // commitOrLog commits the transaction and marks it as committed. @@ -224,10 +246,14 @@ func commitOrLog(tx *sql.Tx, committed *bool, msgID int64) { // recordRetryableFailure marks one delivery unit's locked recipients and // locked notify row (if any) for retry. -func recordRetryableFailure(tx *sql.Tx, committed *bool, table string, locked []string, msgID int64, notifyID int64) { +func recordRetryableFailure(tx *sql.Tx, committed *bool, table string, locked []string, msgID, batchID, notifyID int64) { now := timeutil.TimestampNow().Float64() - updateLocked(tx, table, locked, msgID, now, localResponseCodeNoResponse, false) - updateNotify(tx, notifyID, now, localResponseCodeNoResponse, false) + if err := updateLocked(tx, table, locked, msgID, batchID, now, localResponseCodeNoResponse, false); err != nil { + return + } + if err := updateNotify(tx, notifyID, now, localResponseCodeNoResponse, false); err != nil { + return + } commitOrLog(tx, committed, msgID) } @@ -264,9 +290,9 @@ func lockPendingNotify(tx *sql.Tx, batchID int64, domain string, now float64) (i // updateNotify records a notification outcome for one msg_add_to_notify row. // notifyID 0 is a no-op so callers need not branch on whether the unit // carried a notify row. -func updateNotify(tx *sql.Tx, notifyID int64, now float64, code int, notified bool) { +func updateNotify(tx *sql.Tx, notifyID int64, now float64, code int, notified bool) error { if notifyID == 0 { - return + return nil } var err error if notified { @@ -284,6 +310,7 @@ func updateNotify(tx *sql.Tx, notifyID int64, now float64, code int, notified bo if err != nil { log.Printf("ERROR: sender: update notify row %d: %s", notifyID, err) } + return err } // lockPendingRecipients locks (FOR UPDATE SKIP LOCKED) the undelivered, @@ -347,12 +374,11 @@ func deliverMessage(target pendingTarget) { return } - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { log.Printf("ERROR: sender: db open: %s", err) return } - defer db.Close() // Load the message fields and its add-to batches (read-only). rtx, err := db.Begin() @@ -374,10 +400,6 @@ func deliverMessage(target pendingTarget) { } rtx.Rollback() - // Sending never changes an identity or its representation. Messages that - // first arrived through add-to have batch snapshots but no original header. - orig := m.wire - // SPEC §10.2: a host must not transmit a reply to a terminal message, nor // an add-to batch of one. dd.sql refuses to create such rows, so this is // defensive; matching units are recorded as code 1 (invalid, not @@ -397,8 +419,8 @@ func deliverMessage(target pendingTarget) { if parentTerminal { log.Printf("ERROR: sender: msg %d references a terminal parent; not sending (SPEC §10.2)", target.MsgID) recordUnitInvalid(db, target, "msg_to", 0) - } else if orig != nil && !parentPending { - deliverUnit(db, target, orig, "msg_to", 0) + } else if len(m.prepared) > 0 && !parentPending { + deliverUnit(db, target, m.prepared, m.storedHash, "msg_to", 0) } // Deliver each add-to batch as its own add-to message (one sender each). @@ -411,12 +433,7 @@ func deliverMessage(target pendingTarget) { recordUnitInvalid(db, target, "msg_add_to", b.ID) continue } - h, err := fmsg.UnmarshalPrepared(b.Prepared, b.Hash) - if err != nil { - log.Printf("ERROR: sender: load finalized batch %d of msg %d: %s", b.ID, target.MsgID, err) - continue - } - deliverUnit(db, target, h, "msg_add_to", b.ID) + deliverUnit(db, target, b.Prepared, b.Hash, "msg_add_to", b.ID) } } @@ -483,8 +500,12 @@ func recordUnitInvalid(db *sql.DB, target pendingTarget, table string, batchID i if len(locked) == 0 && notifyID == 0 { return } - updateLocked(tx, table, locked, target.MsgID, now, int(RejectCodeInvalid), false) - updateNotify(tx, notifyID, now, int(RejectCodeInvalid), false) + if err := updateLocked(tx, table, locked, target.MsgID, batchID, now, int(RejectCodeInvalid), false); err != nil { + return + } + if err := updateNotify(tx, notifyID, now, int(RejectCodeInvalid), false); err != nil { + return + } commitOrLog(tx, &committed, target.MsgID) } @@ -492,12 +513,11 @@ func recordUnitInvalid(db *sql.DB, target pendingTarget, table string, batchID i // rather than sending over the network. (findPendingTargets skips the local // domain, so this is a defensive path.) func markLocalDelivered(target pendingTarget) { - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { log.Printf("ERROR: sender: db open for local delivery: %s", err) return } - defer db.Close() now := timeutil.TimestampNow().Float64() if _, err := db.Exec(` UPDATE msg_to SET time_delivered = $1, response_code = 200 @@ -523,12 +543,46 @@ func dialTargetIPs(targetIPs []net.IP, port int, tlsConf *tls.Config) net.Conn { return nil } +type domainRecip struct { + addr string + isLocked bool +} + +// buildDomainRecips builds the per-recipient wire-order list for targetDomain +// (to-field order, then add-to order per SPEC §10.2 step 6). Only entries +// belonging to table (msg_to vs msg_add_to) are marked isLocked so an address +// present in both To and AddTo is never double-updated against the wrong table. +func buildDomainRecips(h *FMsgHeader, targetDomain, table string, locked []string) []domainRecip { + lockedSet := make(map[string]bool, len(locked)) + for _, a := range locked { + lockedSet[strings.ToLower(a)] = true + } + var domainRecips []domainRecip + appendDomain := func(addrs []FMsgAddress, matchTable bool) { + for _, addr := range addrs { + if !strings.EqualFold(addr.Domain, targetDomain) { + continue + } + s := addr.ToString() + domainRecips = append(domainRecips, domainRecip{ + addr: s, + isLocked: matchTable && lockedSet[strings.ToLower(s)], + }) + } + } + appendDomain(h.To, table == "msg_to") + if h.Flags&FlagHasAddTo != 0 { + appendDomain(h.AddTo, table == "msg_add_to") + } + return domainRecips +} + // deliverUnit sends one wire message — the original message or a single add-to // batch — to target.Domain over its own connection, recording per-recipient // outcomes. It owns its transaction: it locks this unit's pending recipients in // `table` (msg_add_to rows restricted to batchID; batchID is 0 for the original // message) and marks them for retry on early failure. -func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, batchID int64) { +func deliverUnit(db *sql.DB, target pendingTarget, prepared, expectedHash []byte, table string, batchID int64) { tx, err := db.Begin() if err != nil { log.Printf("ERROR: sender: begin tx: %s", err) @@ -561,10 +615,16 @@ func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, return // nothing pending for this unit (or locked by another sender) } + h, err := fmsg.UnmarshalPrepared(prepared, expectedHash) + if err != nil { + log.Printf("ERROR: sender: load finalized %s (batch %d) of msg %d: %s", table, batchID, target.MsgID, err) + return + } + deferRetry := true defer func() { if deferRetry && !committed { - recordRetryableFailure(tx, &committed, table, locked, target.MsgID, notifyID) + recordRetryableFailure(tx, &committed, table, locked, target.MsgID, batchID, notifyID) } }() @@ -573,28 +633,7 @@ func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, // recipient of each and so is counted, and answered, twice. Only this // unit's locked recipients are recorded; the recipients carried only to // reconstruct that ordering stay unlocked. - lockedSet := make(map[string]bool, len(locked)) - for _, a := range locked { - lockedSet[strings.ToLower(a)] = true - } - type domainRecip struct { - addr string - isLocked bool - } - var domainRecips []domainRecip - appendDomain := func(addrs []FMsgAddress) { - for _, addr := range addrs { - if !strings.EqualFold(addr.Domain, target.Domain) { - continue - } - s := addr.ToString() - domainRecips = append(domainRecips, domainRecip{addr: s, isLocked: lockedSet[strings.ToLower(s)]}) - } - } - appendDomain(h.To) - if h.Flags&FlagHasAddTo != 0 { - appendDomain(h.AddTo) - } + domainRecips := buildDomainRecips(h, target.Domain, table, locked) // --- network delivery --- @@ -623,7 +662,9 @@ func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, defer removeOutgoingIP(hashArr, connectedIP) // Step 3: Transmit message header. - if _, err := conn.Write(h.Encode()); err != nil { + encodedHeader := h.Encode() + conn.SetWriteDeadline(time.Now().Add(calcNetIODuration(int64(len(encodedHeader)), MinUploadRate))) + if _, err := conn.Write(encodedHeader); err != nil { log.Printf("ERROR: sender: writing header for msg %d: %s", target.MsgID, err) return } @@ -659,9 +700,13 @@ func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, return } log.Printf("INFO: sender: msg %d add-to accepted by %s (code 11)", target.MsgID, target.Domain) - updateLocked(tx, table, locked, target.MsgID, now, int(initCode[0]), true) - updateNotify(tx, notifyID, now, int(initCode[0]), true) deferRetry = false + if err := updateLocked(tx, table, locked, target.MsgID, batchID, now, int(initCode[0]), true); err != nil { + return + } + if err := updateNotify(tx, notifyID, now, int(initCode[0]), true); err != nil { + return + } commitOrLog(tx, &committed, target.MsgID) return default: @@ -669,9 +714,13 @@ func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, // global rejection log.Printf("WARN: sender: msg %d rejected by %s: %s (%d)", target.MsgID, target.Domain, responseCodeName(initCode[0]), initCode[0]) - updateLocked(tx, table, locked, target.MsgID, now, int(initCode[0]), false) - updateNotify(tx, notifyID, now, int(initCode[0]), false) deferRetry = false + if err := updateLocked(tx, table, locked, target.MsgID, batchID, now, int(initCode[0]), false); err != nil { + return + } + if err := updateNotify(tx, notifyID, now, int(initCode[0]), false); err != nil { + return + } commitOrLog(tx, &committed, target.MsgID) } else { // unexpected code — TERMINATE @@ -691,6 +740,7 @@ func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, } now = timeutil.TimestampNow().Float64() + deferRetry = false for i, dr := range domainRecips { if !dr.isLocked { continue @@ -702,20 +752,51 @@ func deliverUnit(db *sql.DB, target pendingTarget, h *FMsgHeader, table string, } else { log.Printf("WARN: sender: msg %d to %s: %s (%d)", target.MsgID, dr.addr, responseCodeName(c), c) } - updateRecipient(tx, table, dr.addr, target.MsgID, now, int(c), delivered) + if err := updateRecipient(tx, table, dr.addr, target.MsgID, batchID, now, int(c), delivered); err != nil { + return + } } // The exchange completed, so a locked notify row is satisfied too: the // domain was informed of the batch through this delivery. - updateNotify(tx, notifyID, now, int(initCode[0]), true) + if err := updateNotify(tx, notifyID, now, int(initCode[0]), true); err != nil { + return + } - deferRetry = false commitOrLog(tx, &committed, target.MsgID) } +type inFlightTracker struct { + mu sync.Mutex + active map[pendingTarget]struct{} +} + +func newInFlightTracker() *inFlightTracker { + return &inFlightTracker{active: make(map[pendingTarget]struct{})} +} + +func (f *inFlightTracker) acquire(t pendingTarget) bool { + k := pendingTarget{MsgID: t.MsgID, Domain: strings.ToLower(t.Domain)} + f.mu.Lock() + defer f.mu.Unlock() + if _, exists := f.active[k]; exists { + return false + } + f.active[k] = struct{}{} + return true +} + +func (f *inFlightTracker) release(t pendingTarget) { + k := pendingTarget{MsgID: t.MsgID, Domain: strings.ToLower(t.Domain)} + f.mu.Lock() + delete(f.active, k) + f.mu.Unlock() +} + // processPendingMessages finds messages needing delivery and dispatches a -// goroutine per (message, domain) pair, bounded by the semaphore. -func processPendingMessages(sem chan struct{}) { +// goroutine per (message, domain) pair, bounded by the semaphore and +// deduplicated against currently in-flight targets. +func processPendingMessages(ctx context.Context, sem chan struct{}, inFlight *inFlightTracker) { targets, err := findPendingTargets() if err != nil { log.Printf("ERROR: sender: finding pending targets: %s", err) @@ -727,9 +808,20 @@ func processPendingMessages(sem chan struct{}) { log.Printf("INFO: sender: found %d pending target(s)", len(targets)) for _, t := range targets { - sem <- struct{}{} // acquire + if !inFlight.acquire(t) { + continue + } + select { + case <-ctx.Done(): + inFlight.release(t) + return + case sem <- struct{}{}: + } go func(t pendingTarget) { - defer func() { <-sem }() + defer func() { + <-sem + inFlight.release(t) + }() deliverMessage(t) }(t) } @@ -737,12 +829,13 @@ func processPendingMessages(sem chan struct{}) { // startSender runs the sender loop: polls the database periodically and also // listens for PostgreSQL notifications for immediate pickup of new messages. -func startSender() { +func startSender(ctx context.Context) { loadSenderEnvConfig() log.Printf("INFO: sender: started (poll=%ds, retry=%.0fs, max_concurrent=%d)", PollInterval, RetryInterval, MaxConcurrentSend) sem := make(chan struct{}, MaxConcurrentSend) + inFlight := newInFlightTracker() // set up PostgreSQL LISTEN for immediate notification notifyCh := make(chan struct{}, 1) @@ -758,9 +851,20 @@ func startSender() { } defer listener.Close() log.Println("INFO: sender: listening for new_msg_to notifications") + pingTimer := time.NewTimer(32 * time.Second) + defer pingTimer.Stop() for { select { + case <-ctx.Done(): + return case n := <-listener.Notify: + if !pingTimer.Stop() { + select { + case <-pingTimer.C: + default: + } + } + pingTimer.Reset(32 * time.Second) if n != nil { log.Printf("INFO: sender: notification received: %s", n.Extra) select { @@ -768,7 +872,8 @@ func startSender() { default: } } - case <-time.After(32 * time.Second): + case <-pingTimer.C: + pingTimer.Reset(32 * time.Second) // ping to keep connection alive if err := listener.Ping(); err != nil { log.Printf("ERROR: sender: pg listener ping: %s", err) @@ -778,19 +883,34 @@ func startSender() { }() // initial poll on startup - processPendingMessages(sem) + processPendingMessages(ctx, sem, inFlight) ticker := time.NewTicker(time.Duration(PollInterval) * time.Second) defer ticker.Stop() + batchTimer := time.NewTimer(0) + if !batchTimer.Stop() { + select { + case <-batchTimer.C: + default: + } + } + defer batchTimer.Stop() for { select { + case <-ctx.Done(): + return case <-ticker.C: - processPendingMessages(sem) + processPendingMessages(ctx, sem, inFlight) case <-notifyCh: // small delay to batch rapid inserts - time.Sleep(256 * time.Millisecond) - processPendingMessages(sem) + batchTimer.Reset(256 * time.Millisecond) + select { + case <-ctx.Done(): + return + case <-batchTimer.C: + } + processPendingMessages(ctx, sem, inFlight) } } } diff --git a/cmd/fmsgd/store.go b/cmd/fmsgd/store.go index 12249fd..00eb720 100644 --- a/cmd/fmsgd/store.go +++ b/cmd/fmsgd/store.go @@ -2,22 +2,58 @@ package main import ( "database/sql" - "fmt" - "github.com/markmnl/fmsgd/pkg/fmsg" "log" "strings" + "sync" + "time" "github.com/levenlabs/golib/timeutil" - _ "github.com/lib/pq" + "github.com/lib/pq" + "github.com/markmnl/fmsgd/pkg/fmsg" ) -func testDb() error { +var ( + dbMu sync.Mutex + sharedDB *sql.DB +) + +// getDB returns the process-wide shared *sql.DB connection pool, initializing +// it lazily on first use. +func getDB() (*sql.DB, error) { + dbMu.Lock() + defer dbMu.Unlock() + if sharedDB != nil { + return sharedDB, nil + } db, err := sql.Open("postgres", "") + if err != nil { + return nil, err + } + db.SetMaxOpenConns(48) + db.SetMaxIdleConns(16) + db.SetConnMaxLifetime(30 * time.Minute) + db.SetConnMaxIdleTime(5 * time.Minute) + sharedDB = db + return sharedDB, nil +} + +// closeDB closes the shared *sql.DB connection pool if initialized. +func closeDB() { + dbMu.Lock() + db := sharedDB + sharedDB = nil + dbMu.Unlock() + if db != nil { + _ = db.Close() + } +} + +func testDb() error { + db, err := getDB() if err != nil { return err } - defer db.Close() err = db.Ping() if err != nil { return err @@ -50,11 +86,10 @@ func testDb() error { // lookupMsgIdByHash returns the msg id for a message with the given SHA256 hash, // or 0 if no such message exists. func lookupMsgIdByHash(hash []byte) (int64, error) { - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return 0, err } - defer db.Close() var id int64 err = db.QueryRow("SELECT id FROM msg WHERE sha256 = $1", hash).Scan(&id) @@ -74,11 +109,10 @@ func threadHasFromDomain(hash []byte, domain string) (bool, error) { return false, nil } - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return false, err } - defer db.Close() // from_addr is @user@domain; split_part(..., 3) is the domain. // Depth cap and cycle guard limit pathological chains. @@ -107,44 +141,61 @@ func threadHasFromDomain(hash []byte, domain string) (bool, error) { return found, nil } -// hasAddrReceivedMsgHash reports whether addr has already received a stored -// message identified by hash. -func hasAddrReceivedMsgHash(hash []byte, addr *FMsgAddress) (bool, error) { - if addr == nil || len(hash) == 0 { - return false, nil +// receivedAddrsForMsgHash returns the set of lower-cased addresses from addrs +// that have already received a stored message identified by hash. +func receivedAddrsForMsgHash(hash []byte, addrs []FMsgAddress) (map[string]bool, error) { + result := make(map[string]bool) + if len(hash) == 0 || len(addrs) == 0 { + return result, nil } - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { - return false, err + return nil, err } - defer db.Close() - addrStr := strings.ToLower(addr.ToString()) + lowerAddrs := make([]string, 0, len(addrs)) + seen := make(map[string]struct{}, len(addrs)) + for i := range addrs { + k := strings.ToLower(addrs[i].ToString()) + if _, ok := seen[k]; !ok { + seen[k] = struct{}{} + lowerAddrs = append(lowerAddrs, k) + } + } - var exists bool - err = db.QueryRow(` - SELECT EXISTS ( - SELECT 1 - FROM msg m - JOIN msg_to mt ON mt.msg_id = m.id - WHERE m.sha256 = $1 - AND lower(mt.addr) = $2 - AND mt.time_delivered IS NOT NULL - UNION ALL - SELECT 1 - FROM msg m - JOIN msg_add_to mat ON mat.msg_id = m.id - WHERE m.sha256 = $1 - AND lower(mat.addr) = $2 - AND mat.time_delivered IS NOT NULL - ) - `, hash, addrStr).Scan(&exists) + rows, err := db.Query(` + SELECT DISTINCT lower(mt.addr) + FROM msg m + JOIN msg_to mt ON mt.msg_id = m.id + WHERE m.sha256 = $1 + AND lower(mt.addr) = ANY($2) + AND mt.time_delivered IS NOT NULL + UNION + SELECT DISTINCT lower(mat.addr) + FROM msg m + JOIN msg_add_to mat ON mat.msg_id = m.id + WHERE m.sha256 = $1 + AND lower(mat.addr) = ANY($2) + AND mat.time_delivered IS NOT NULL + `, hash, pq.Array(lowerAddrs)) if err != nil { - return false, err + return nil, err } + defer rows.Close() - return exists, nil + for rows.Next() { + var addr string + if err := rows.Scan(&addr); err != nil { + return nil, err + } + result[addr] = true + } + if err := rows.Err(); err != nil { + return nil, err + } + + return result, nil } type parentLinkStore interface { @@ -254,11 +305,10 @@ func relationalParentHash(msg *FMsgHeader) []byte { // getMsgByID loads a message and all its recipients from the database by msg ID. // Returns the full FMsgHeader or nil if the message doesn't exist. func getMsgByID(msgID int64) (*FMsgHeader, error) { - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return nil, err } - defer db.Close() tx, err := db.Begin() if err != nil { @@ -289,27 +339,20 @@ func getMsgByBatchHash(batchHash []byte) (*FMsgHeader, error) { if len(batchHash) == 0 { return nil, nil } - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return nil, err } - defer db.Close() - - tx, err := db.Begin() - if err != nil { - return nil, err - } - defer tx.Rollback() var prepared []byte - err = tx.QueryRow(`SELECT wire_message FROM msg_add_to_batch WHERE sha256 = $1`, batchHash).Scan(&prepared) + err = db.QueryRow(`SELECT wire_message FROM msg_add_to_batch WHERE sha256 = $1`, batchHash).Scan(&prepared) if err == sql.ErrNoRows { return nil, nil } if err != nil { return nil, err } - return fmsg.UnmarshalPrepared(prepared, batchHash) + return fmsg.UnmarshalPreparedHeader(prepared) } // existingMsgIDForAddTo returns the id of an already-stored message row whose @@ -338,11 +381,10 @@ func addToBatchRecorded(msgID int64, batchHash []byte) (bool, error) { if len(batchHash) == 0 { return false, nil } - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return false, err } - defer db.Close() var exists bool err = db.QueryRow(`SELECT EXISTS ( @@ -364,27 +406,34 @@ values ($1, $2, $3, NULL) returning id`, msgID, addToFrom, now).Scan(&batchID) } // attachAddToRecipients extends an already-stored message with the recipients -// carried by an add-to delivery, marking those on our domain delivered. It is -// the add-to counterpart of an INSERT: when a host already holds the shared -// message, an add-to delivery must grow its recipient list rather than insert -// a second row under the same unique canonical sha256 (SPEC §12). Each call is -// one batch, recorded so its sender and timing are not lost. -func attachAddToRecipients(tx *sql.Tx, msgID int64, msg *FMsgHeader) error { +// carried by an add-to delivery. When localOutcome is non-nil (code 65 path), +// each recipient's row state reflects its actual per-recipient outcome; when +// nil (code 11 notification path), local recipients are marked delivered and +// remote recipients are marked not-our-delivery. It is the add-to counterpart +// of an INSERT: when a host already holds the shared message, an add-to +// delivery must grow its recipient list rather than insert a second row under +// the same unique canonical sha256 (SPEC §12). Each call is one batch, +// recorded so its sender and timing are not lost. +func attachAddToRecipients(tx *sql.Tx, msgID int64, msg *FMsgHeader, localOutcome map[string]uint8) error { now := timeutil.TimestampNow().Float64() + rowOutcome := func(addr FMsgAddress) (delivered any, code any) { + if localOutcome != nil { + return inboundRecipientRow(addr, localOutcome, now) + } + if strings.EqualFold(addr.Domain, Domain) { + return now, nil + } + return nil, int16(localResponseCodeNotOurDelivery) + } + // This host is recording a batch it RECEIVED: delivering the batch to // other domains is the batch sender's job, not ours (SPEC §10.2 — a host // delivers iff from or add to from belongs to its domain). Rows for other // domains are recorded with localResponseCodeNotOurDelivery so the // sender's pending queries never treat them as our delivery work. for _, addr := range msg.To { - var delivered any - var code any - if addr.Domain == Domain { - delivered = now - } else { - code = int16(localResponseCodeNotOurDelivery) - } + delivered, code := rowOutcome(addr) if _, err := tx.Exec(`insert into msg_to (msg_id, addr, time_delivered, response_code) values ($1, $2, $3, $4) on conflict (msg_id, addr) do nothing`, msgID, addr.ToString(), delivered, code); err != nil { @@ -416,13 +465,7 @@ on conflict (msg_id, addr) do nothing`, msgID, addr.ToString(), delivered, code) } for _, addr := range msg.AddTo { - var delivered any - var code any - if addr.Domain == Domain { - delivered = now - } else { - code = int16(localResponseCodeNotOurDelivery) - } + delivered, code := rowOutcome(addr) if _, err := tx.Exec(`insert into msg_add_to (msg_id, batch_id, addr, time_delivered, response_code) values ($1, $2, $3, $4, $5) on conflict (batch_id, addr) do nothing`, msgID, batchID, addr.ToString(), delivered, code); err != nil { @@ -468,11 +511,10 @@ func inboundRecipientRow(addr FMsgAddress, localOutcome map[string]uint8, now fl // local recipient address to the per-recipient code this host responded. func storeMsgDetail(msg *FMsgHeader, localOutcome map[string]uint8) error { - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return err } - defer db.Close() tx, err := db.Begin() if err != nil { @@ -492,7 +534,7 @@ func storeMsgDetail(msg *FMsgHeader, localOutcome map[string]uint8) error { if existingID, err := existingMsgIDForAddTo(tx, msg, msgHash); err != nil { return err } else if existingID != 0 { - if err := attachAddToRecipients(tx, existingID, msg); err != nil { + if err := attachAddToRecipients(tx, existingID, msg, localOutcome); err != nil { return err } return tx.Commit() @@ -620,11 +662,10 @@ values ($1, $2, $3, $4, $5, $6, $7)`) // (spec code 11). Only the header is recorded so the header hash can be // faithfully computed for subsequent messages referencing this one via pid. func storeMsgHeaderOnly(msg *FMsgHeader) error { - db, err := sql.Open("postgres", "") + db, err := getDB() if err != nil { return err } - defer db.Close() tx, err := db.Begin() if err != nil { @@ -647,7 +688,7 @@ func storeMsgHeaderOnly(msg *FMsgHeader) error { if existingID == 0 { return fmt.Errorf("add-to header for unstored message %x", msgHash) } - if err := attachAddToRecipients(tx, existingID, msg); err != nil { + if err := attachAddToRecipients(tx, existingID, msg, nil); err != nil { return err } return tx.Commit() @@ -658,26 +699,18 @@ func storeMsgHeaderOnly(msg *FMsgHeader) error { type msgFields struct { parentPid []byte storedHash []byte - wire *FMsgHeader + prepared []byte isTerminal bool } func loadMsgFields(tx *sql.Tx, msgID int64) (*msgFields, error) { var m msgFields - var prepared []byte - if err := tx.QueryRow(`SELECT psha256,sha256,is_terminal,wire_message FROM msg WHERE id=$1 AND time_sent IS NOT NULL`, msgID).Scan(&m.parentPid, &m.storedHash, &m.isTerminal, &prepared); err != nil { + if err := tx.QueryRow(`SELECT psha256,sha256,is_terminal,wire_message FROM msg WHERE id=$1 AND time_sent IS NOT NULL`, msgID).Scan(&m.parentPid, &m.storedHash, &m.isTerminal, &m.prepared); err != nil { return nil, err } if len(m.storedHash) != 32 { return nil, fmt.Errorf("message %d has no finalized identity", msgID) } - if len(prepared) > 0 { - var err error - m.wire, err = fmsg.UnmarshalPrepared(prepared, m.storedHash) - if err != nil { - return nil, fmt.Errorf("load prepared msg %d: %w", msgID, err) - } - } return &m, nil } @@ -802,10 +835,13 @@ func loadMsg(tx *sql.Tx, msgID int64) (*FMsgHeader, error) { } var h *FMsgHeader - if m.wire != nil { - h = m.wire.Clone() + if len(m.prepared) > 0 { + h, err = fmsg.UnmarshalPreparedHeader(m.prepared) + if err != nil { + return nil, fmt.Errorf("load prepared msg %d: %w", msgID, err) + } } - if m.wire == nil { + if h == nil { // When the original arrived through add-to, its batch retains the // exact wire payloads; the API files have already been expanded. batches, err := loadAddToBatches(tx, msgID) @@ -814,7 +850,7 @@ func loadMsg(tx *sql.Tx, msgID int64) (*FMsgHeader, error) { } for _, b := range batches { if len(b.Prepared) > 0 { - h, err = fmsg.UnmarshalPrepared(b.Prepared, b.Hash) + h, err = fmsg.UnmarshalPreparedHeader(b.Prepared) if err != nil { return nil, err } diff --git a/cmd/fmsgd/usage_test.go b/cmd/fmsgd/usage_test.go index 623758d..3d3e2bd 100644 --- a/cmd/fmsgd/usage_test.go +++ b/cmd/fmsgd/usage_test.go @@ -128,3 +128,46 @@ func TestRecordRecvUsage(t *testing.T) { } } } + +func TestGetAddressDetailStatusCodes(t *testing.T) { + status := http.StatusOK + body := `{"address":"@alice@example.com","acceptingNew":true}` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + defer srv.Close() + + origURI := IDURI + IDURI = srv.URL + defer func() { IDURI = origURI }() + + addr := &FMsgAddress{User: "alice", Domain: "example.com"} + + // 200 OK decodes detail + detail, err := getAddressDetail(addr) + if err != nil || detail == nil || !detail.AcceptingNew { + t.Fatalf("200 OK: got (%+v, %v), want AcceptingNew=true", detail, err) + } + + // 404 Not Found returns nil, nil + status = http.StatusNotFound + body = `{"error":"not found"}` + detail, err = getAddressDetail(addr) + if err != nil || detail != nil { + t.Fatalf("404: got (%+v, %v), want (nil, nil)", detail, err) + } + + // 500/503 returns an error rather than decoding into a zero AddressDetail + for _, code := range []int{http.StatusInternalServerError, http.StatusServiceUnavailable} { + status = code + body = `{"error":"upstream failed"}` + detail, err = getAddressDetail(addr) + if err == nil { + t.Fatalf("status %d: expected error, got detail=%+v", code, detail) + } + if detail != nil { + t.Fatalf("status %d: expected nil detail on error, got %+v", code, detail) + } + } +} diff --git a/pkg/fmsg/deflate.go b/pkg/fmsg/deflate.go index 4a3b5ce..dc94f75 100644 --- a/pkg/fmsg/deflate.go +++ b/pkg/fmsg/deflate.go @@ -1,13 +1,32 @@ package fmsg import ( + "bufio" "bytes" "compress/zlib" "io" "os" "strings" + "sync" ) +var zlibWriterPool = sync.Pool{ + New: func() any { + return zlib.NewWriter(io.Discard) + }, +} + +func getZlibWriter(w io.Writer) *zlib.Writer { + zw := zlibWriterPool.Get().(*zlib.Writer) + zw.Reset(w) + return zw +} + +func putZlibWriter(zw *zlib.Writer) { + zw.Reset(io.Discard) + zlibWriterPool.Put(zw) +} + // minDeflateSize is the minimum payload size in bytes before compression is // attempted. const minDeflateSize uint32 = 512 @@ -74,14 +93,17 @@ func probeSample(src *os.File, srcSize uint32) (bool, error) { sampleLen := min(int64(srcSize), int64(deflateSampleSize)) var buf bytes.Buffer - zw := zlib.NewWriter(&buf) + zw := getZlibWriter(&buf) if _, err := io.CopyN(zw, src, sampleLen); err != nil { _ = zw.Close() + putZlibWriter(zw) return false, err } if err := zw.Close(); err != nil { + putZlibWriter(zw) return false, err } + putZlibWriter(zw) if _, err := src.Seek(0, io.SeekStart); err != nil { return false, err @@ -90,7 +112,7 @@ func probeSample(src *os.File, srcSize uint32) (bool, error) { return int64(buf.Len()) < sampleLen*8/10, nil } -// tryCompress compresses the file at srcPath using zlib-deflate and writes the +// TryCompress compresses the file at srcPath using zlib-deflate and writes the // result to a temporary file. For files larger than deflateSampleSize it first // compresses a prefix sample to estimate compressibility, avoiding a full pass // over files that won't compress well. It returns worthwhile=true only when @@ -98,6 +120,10 @@ func probeSample(src *os.File, srcSize uint32) (bool, error) { // reduction). When not worthwhile the temporary file is removed. When // worthwhile the caller is responsible for removing the file at dstPath. func TryCompress(srcPath string, srcSize uint32) (dstPath string, compressedSize uint32, worthwhile bool, err error) { + return tryCompressInDir(srcPath, srcSize, "", false) +} + +func tryCompressInDir(srcPath string, srcSize uint32, dir string, durable bool) (dstPath string, compressedSize uint32, worthwhile bool, err error) { src, err := os.Open(srcPath) if err != nil { return "", 0, false, err @@ -115,40 +141,66 @@ func TryCompress(srcPath string, srcSize uint32) (dstPath string, compressedSize } } - dst, err := os.CreateTemp("", "fmsg-deflate-*") + pattern := "fmsg-deflate-*" + if durable { + pattern = ".fmsg-deflate-*" + } + dst, err := os.CreateTemp(dir, pattern) if err != nil { return "", 0, false, err } dstName := dst.Name() - zw := zlib.NewWriter(dst) + bw := bufio.NewWriterSize(dst, 32*1024) + zw := getZlibWriter(bw) if _, err := io.Copy(zw, src); err != nil { _ = zw.Close() + putZlibWriter(zw) _ = dst.Close() _ = os.Remove(dstName) return "", 0, false, err } if err := zw.Close(); err != nil { + putZlibWriter(zw) _ = dst.Close() _ = os.Remove(dstName) return "", 0, false, err } - if err := dst.Close(); err != nil { + putZlibWriter(zw) + if err := bw.Flush(); err != nil { + _ = dst.Close() _ = os.Remove(dstName) return "", 0, false, err } - fi, err := os.Stat(dstName) + cSize, err := dst.Seek(0, io.SeekCurrent) if err != nil { + _ = dst.Close() _ = os.Remove(dstName) return "", 0, false, err } - - cSize := uint32(fi.Size()) - if cSize >= srcSize*8/10 { + if cSize >= int64(srcSize)*8/10 { + _ = dst.Close() _ = os.Remove(dstName) return "", 0, false, nil } - return dstName, cSize, true, nil + if durable { + if err := dst.Chmod(0640); err != nil { + _ = dst.Close() + _ = os.Remove(dstName) + return "", 0, false, err + } + if err := dst.Sync(); err != nil { + _ = dst.Close() + _ = os.Remove(dstName) + return "", 0, false, err + } + } + if err := dst.Close(); err != nil { + _ = os.Remove(dstName) + return "", 0, false, err + } + + return dstName, uint32(cSize), true, nil } diff --git a/pkg/fmsg/fmsg.go b/pkg/fmsg/fmsg.go index 6508b3b..cbbf2cc 100644 --- a/pkg/fmsg/fmsg.go +++ b/pkg/fmsg/fmsg.go @@ -7,13 +7,13 @@ package fmsg import ( - "bytes" "compress/zlib" "crypto/sha256" "encoding/binary" "encoding/hex" "fmt" "io" + "math" "os" "strings" ) @@ -38,7 +38,7 @@ type Address struct { // ToString returns the address in @user@domain form. func (addr *Address) ToString() string { - return fmt.Sprintf("@%s@%s", addr.User, addr.Domain) + return "@" + addr.User + "@" + addr.Domain } // AttachmentHeader holds the wire-level metadata for a single attachment. @@ -86,48 +86,86 @@ type Header struct { // Encode serialises the message header to wire format as defined in SPEC.md. // The returned bytes cover all fields up to and including the attachment -// headers (fields 1–12 per spec). This method panics on internal buffer errors -// rather than returning an error. +// headers (fields 1–13 per spec). func (h *Header) Encode() []byte { - var b bytes.Buffer - b.WriteByte(h.Version) - b.WriteByte(h.Flags) + addToFrom := h.AddToFrom + if h.Flags&FlagHasAddTo != 0 && addToFrom == nil { + addToFrom = &h.From + } + + // Pre-size output buffer to avoid repeated reallocations. + size := 2 + // version + flags + 1 + 2 + len(h.From.User) + len(h.From.Domain) + // from + 1 + // to count + 8 + // timestamp + 4 + // size + 1 // attachment count if h.Flags&FlagHasPid != 0 { - b.Write(h.Pid[:]) + size += len(h.Pid) + } else { + size += 1 + len(h.Topic) } - str := h.From.ToString() - b.WriteByte(byte(len(str))) - b.WriteString(str) - b.WriteByte(byte(len(h.To))) - for _, addr := range h.To { - str = addr.ToString() - b.WriteByte(byte(len(str))) - b.WriteString(str) + for i := range h.To { + size += 3 + len(h.To[i].User) + len(h.To[i].Domain) } if h.Flags&FlagHasAddTo != 0 { - // add-to-from address (field 6) - addToFrom := h.AddToFrom - if addToFrom == nil { - addToFrom = &h.From + size += 3 + len(addToFrom.User) + len(addToFrom.Domain) + 1 + for i := range h.AddTo { + size += 3 + len(h.AddTo[i].User) + len(h.AddTo[i].Domain) } - str := addToFrom.ToString() - b.WriteByte(byte(len(str))) - b.WriteString(str) - // add-to addresses (field 7) - b.WriteByte(byte(len(h.AddTo))) - for _, addr := range h.AddTo { - str = addr.ToString() - b.WriteByte(byte(len(str))) - b.WriteString(str) + } + if h.Flags&FlagCommonType != 0 { + size++ + } else { + size += 1 + len(h.Type) + } + if h.Flags&FlagDeflate != 0 { + size += 4 + } + for i := range h.Attachments { + att := &h.Attachments[i] + size += 1 + 1 + len(att.Filename) + 4 + if att.Flags&1 != 0 { + size++ + } else { + size += 1 + len(att.Type) + } + if att.Flags&(1<<1) != 0 { + size += 4 } } - if err := binary.Write(&b, binary.LittleEndian, h.Timestamp); err != nil { - panic(err) + + appendAddr := func(b []byte, a *Address) []byte { + b = append(b, byte(2+len(a.User)+len(a.Domain)), '@') + b = append(b, a.User...) + b = append(b, '@') + return append(b, a.Domain...) + } + + b := make([]byte, 0, size) + b = append(b, h.Version, h.Flags) + if h.Flags&FlagHasPid != 0 { + b = append(b, h.Pid...) + } + b = appendAddr(b, &h.From) + b = append(b, byte(len(h.To))) + for i := range h.To { + b = appendAddr(b, &h.To[i]) + } + if h.Flags&FlagHasAddTo != 0 { + // add-to-from address (field 6) + b = appendAddr(b, addToFrom) + // add-to addresses (field 7) + b = append(b, byte(len(h.AddTo))) + for i := range h.AddTo { + b = appendAddr(b, &h.AddTo[i]) + } } + b = binary.LittleEndian.AppendUint64(b, math.Float64bits(h.Timestamp)) // topic is only present when pid is NOT set if h.Flags&FlagHasPid == 0 { - b.WriteByte(byte(len(h.Topic))) - b.WriteString(h.Topic) + b = append(b, byte(len(h.Topic))) + b = append(b, h.Topic...) } if h.Flags&FlagCommonType != 0 { typeID := h.TypeID @@ -136,25 +174,22 @@ func (h *Header) Encode() []byte { typeID = id } } - b.WriteByte(typeID) + b = append(b, typeID) } else { - b.WriteByte(byte(len(h.Type))) - b.WriteString(h.Type) + b = append(b, byte(len(h.Type))) + b = append(b, h.Type...) } // size (uint32 LE) - if err := binary.Write(&b, binary.LittleEndian, h.Size); err != nil { - panic(err) - } + b = binary.LittleEndian.AppendUint32(b, h.Size) // expanded size (uint32 LE) — present iff zlib-deflate flag set if h.Flags&FlagDeflate != 0 { - if err := binary.Write(&b, binary.LittleEndian, h.ExpandedSize); err != nil { - panic(err) - } + b = binary.LittleEndian.AppendUint32(b, h.ExpandedSize) } // attachment headers - b.WriteByte(byte(len(h.Attachments))) - for _, att := range h.Attachments { - b.WriteByte(att.Flags) + b = append(b, byte(len(h.Attachments))) + for i := range h.Attachments { + att := &h.Attachments[i] + b = append(b, att.Flags) if att.Flags&1 != 0 { typeID := att.TypeID if typeID == 0 { @@ -162,24 +197,20 @@ func (h *Header) Encode() []byte { typeID = id } } - b.WriteByte(typeID) + b = append(b, typeID) } else { - b.WriteByte(byte(len(att.Type))) - b.WriteString(att.Type) - } - b.WriteByte(byte(len(att.Filename))) - b.WriteString(att.Filename) - if err := binary.Write(&b, binary.LittleEndian, att.Size); err != nil { - panic(err) + b = append(b, byte(len(att.Type))) + b = append(b, att.Type...) } + b = append(b, byte(len(att.Filename))) + b = append(b, att.Filename...) + b = binary.LittleEndian.AppendUint32(b, att.Size) // attachment expanded size — present iff attachment zlib-deflate flag set if att.Flags&(1<<1) != 0 { - if err := binary.Write(&b, binary.LittleEndian, att.ExpandedSize); err != nil { - panic(err) - } + b = binary.LittleEndian.AppendUint32(b, att.ExpandedSize) } } - return b.Bytes() + return b } // String returns a human-readable summary of the header fields. @@ -228,9 +259,7 @@ func (h *Header) GetMessageHash() ([]byte, error) { hash := sha256.New() headerBytes := h.Encode() - if _, err := io.Copy(hash, bytes.NewBuffer(headerBytes)); err != nil { - return nil, err - } + hash.Write(headerBytes) if err := hashPayload(hash, h.Filepath, int64(h.Size), h.Flags&FlagDeflate != 0, h.ExpandedSize); err != nil { return nil, err @@ -266,14 +295,17 @@ func HashPayload(dst io.Writer, filepath string, wireSize int64, deflated bool, if err != nil { return err } - written, err := io.Copy(dst, zr) - _ = zr.Close() + written, err := io.Copy(dst, io.LimitReader(zr, int64(expandedSize)+1)) + closeErr := zr.Close() if err != nil { return err } - if uint32(written) != expandedSize { + if written != int64(expandedSize) { return fmt.Errorf("decompressed size %d does not match declared expanded size %d", written, expandedSize) } + if closeErr != nil { + return closeErr + } return nil } @@ -303,6 +335,14 @@ var commonMediaTypes = map[uint8]string{ 58: "video/H264", 59: "video/H265", 60: "video/H266", 61: "video/ogg", 62: "video/VP8", 63: "video/VP9", 64: "video/webm", } +var commonMediaTypeIDs = func() map[string]uint8 { + m := make(map[string]uint8, len(commonMediaTypes)) + for id, mime := range commonMediaTypes { + m[mime] = id + } + return m +}() + // GetCommonMediaType returns the MIME type string for a common type ID, or // ("", false) if the ID is not in the mapping (should be rejected per spec). func GetCommonMediaType(id uint8) (string, bool) { @@ -313,12 +353,8 @@ func GetCommonMediaType(id uint8) (string, bool) { // GetCommonMediaTypeID returns the common type ID for a MIME string, or // (0, false) if the string has no assigned ID. func GetCommonMediaTypeID(mediaType string) (uint8, bool) { - for id, mime := range commonMediaTypes { - if mime == mediaType { - return id, true - } - } - return 0, false + id, ok := commonMediaTypeIDs[mediaType] + return id, ok } // getCommonMediaTypeID is the unexported alias used internally by Encode. diff --git a/pkg/fmsg/fmsg_test.go b/pkg/fmsg/fmsg_test.go index d263392..9eadf29 100644 --- a/pkg/fmsg/fmsg_test.go +++ b/pkg/fmsg/fmsg_test.go @@ -461,6 +461,34 @@ func TestHashPayloadDeflatedSizeMismatch(t *testing.T) { } } +func TestHashPayloadDeflatedRejectsZlibBomb(t *testing.T) { + // 1 MiB of zeros compresses to ~1 KiB; declare expandedSize = 100. + bomb := make([]byte, 1<<20) + f, err := os.CreateTemp(t.TempDir(), "fmsg-bomb-*") + if err != nil { + t.Fatal(err) + } + zw := zlib.NewWriter(f) + if _, err := zw.Write(bomb); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + wireSize, _ := f.Seek(0, 1) + f.Close() + + var dst bytes.Buffer + const declared uint32 = 100 + err = fmsg.HashPayload(&dst, f.Name(), wireSize, true, declared) + if err == nil { + t.Fatal("HashPayload() accepted zlib bomb exceeding declared expanded size") + } + if dst.Len() > int(declared)+1 { + t.Fatalf("HashPayload() wrote %d bytes before stopping, want <= %d", dst.Len(), declared+1) + } +} + // ── Common media types ──────────────────────────────────────────────────────── func TestGetCommonMediaType(t *testing.T) { diff --git a/pkg/fmsg/prepare.go b/pkg/fmsg/prepare.go index a545b51..ecdf4dc 100644 --- a/pkg/fmsg/prepare.go +++ b/pkg/fmsg/prepare.go @@ -9,13 +9,18 @@ import ( "path/filepath" ) -// Clone returns a header with independent slices and no cached hashes. +// Clone returns a header with independent slices/pointers and no cached hashes. func (h *Header) Clone() *Header { c := *h c.Pid = append([]byte(nil), h.Pid...) c.To = append([]Address(nil), h.To...) + if h.AddToFrom != nil { + addr := *h.AddToFrom + c.AddToFrom = &addr + } c.AddTo = append([]Address(nil), h.AddTo...) c.Attachments = append([]AttachmentHeader(nil), h.Attachments...) + c.StoredWire = append([]byte(nil), h.StoredWire...) c.HeaderHash, c.messageHash = nil, nil return &c } @@ -175,15 +180,17 @@ func preparePart(src string, size uint32, typ, dst string) (string, uint32, uint if !info.Mode().IsRegular() || info.Size() != int64(size) { return "", 0, 0, fmt.Errorf("payload length differs from metadata: %s", src) } - expanded := uint32(0) if ShouldCompress(typ, size) { - path, compressed, useful, err := TryCompress(src, size) + path, compressed, useful, err := tryCompressInDir(src, size, filepath.Dir(dst), true) if err != nil { return "", 0, 0, err } if useful { - defer os.Remove(path) - src, size, expanded = path, compressed, size + if err := os.Rename(path, dst); err != nil { + _ = os.Remove(path) + return "", 0, 0, err + } + return dst, compressed, size, nil } } in, err := os.Open(src) @@ -203,7 +210,7 @@ func preparePart(src string, size uint32, typ, dst string) (string, uint32, uint if err == nil { err = closeErr } - return dst, size, expanded, err + return dst, size, 0, err } // MarshalPrepared stores an internal, versioned snapshot, including durable @@ -215,9 +222,10 @@ func MarshalPrepared(h *Header) ([]byte, error) { }{1, h.Clone()}) } -// UnmarshalPrepared verifies the snapshot against the persisted protocol hash. -// A missing or corrupt payload is an error, never a reason to re-encode it. -func UnmarshalPrepared(data, expected []byte) (*Header, error) { +// UnmarshalPreparedHeader decodes a stored prepared message snapshot for its +// header fields only without re-hashing payload files from disk. Use +// UnmarshalPrepared when full payload integrity verification is required. +func UnmarshalPreparedHeader(data []byte) (*Header, error) { var s struct { Version int Header *Header @@ -228,7 +236,16 @@ func UnmarshalPrepared(data, expected []byte) (*Header, error) { if s.Version != 1 || s.Header == nil { return nil, fmt.Errorf("unsupported prepared message") } - h := s.Header.Clone() + return s.Header.Clone(), nil +} + +// UnmarshalPrepared verifies the snapshot against the persisted protocol hash. +// A missing or corrupt payload is an error, never a reason to re-encode it. +func UnmarshalPrepared(data, expected []byte) (*Header, error) { + h, err := UnmarshalPreparedHeader(data) + if err != nil { + return nil, err + } hash, err := h.GetMessageHash() if err != nil { return nil, err diff --git a/pkg/fmsg/prepare_test.go b/pkg/fmsg/prepare_test.go index 56b386e..75ad210 100644 --- a/pkg/fmsg/prepare_test.go +++ b/pkg/fmsg/prepare_test.go @@ -64,6 +64,41 @@ func TestPreparedHashAndDurableRepresentation(t *testing.T) { if _, err = UnmarshalPrepared(snapshot, got); err == nil { t.Fatal("missing immutable content accepted") } + // UnmarshalPreparedHeader decodes metadata without reading payload files. + metaOnly, err := UnmarshalPreparedHeader(snapshot) + if err != nil { + t.Fatalf("UnmarshalPreparedHeader failed with missing payload file: %v", err) + } + if !bytes.Equal(metaOnly.Encode(), h.Encode()) { + t.Fatal("UnmarshalPreparedHeader changed wire header") + } }) } } + +func TestHeaderCloneDeepCopiesAddToFromAndStoredWire(t *testing.T) { + orig := &Header{ + Version: 1, + Flags: FlagHasPid | FlagHasAddTo, + Pid: []byte{1, 2, 3}, + From: Address{User: "alice", Domain: "example.com"}, + To: []Address{{User: "bob", Domain: "example.com"}}, + AddToFrom: &Address{User: "alice", Domain: "example.com"}, + AddTo: []Address{{User: "carol", Domain: "example.org"}}, + StoredWire: []byte(`{"Version":1}`), + } + cloned := orig.Clone() + + if cloned.AddToFrom == orig.AddToFrom { + t.Fatal("Clone() aliased AddToFrom pointer") + } + cloned.AddToFrom.User = "mallory" + cloned.StoredWire[0] = 'X' + + if orig.AddToFrom.User != "alice" { + t.Fatalf("mutating cloned AddToFrom mutated original: %q", orig.AddToFrom.User) + } + if orig.StoredWire[0] != '{' { + t.Fatalf("mutating cloned StoredWire mutated original: %q", orig.StoredWire) + } +} diff --git a/pkg/message/store.go b/pkg/message/store.go index 1cc1ab5..4a75079 100644 --- a/pkg/message/store.go +++ b/pkg/message/store.go @@ -213,35 +213,37 @@ func Finalize(ctx context.Context, tx Tx, id int64, timestamp float64, files *Fi // FinalizeBatch seals one add-to exchange. Its payload representation is copied // from the original (or a received batch), never recompressed independently. func FinalizeBatch(ctx context.Context, tx Tx, id, batchID int64) ([]byte, error) { - s, err := load(ctx, tx, id) - if err != nil { + var sentTime *float64 + var msgHash, prepared []byte + if err := tx.QueryRow(ctx, `SELECT time_sent,sha256,wire_message FROM msg WHERE id=$1 FOR UPDATE`, id).Scan(&sentTime, &msgHash, &prepared); err != nil { return nil, err } - if s.time == nil { + if sentTime == nil { return nil, nil } // a draft's batches finalize with its send - if len(s.hash) != 32 { + if len(msgHash) != 32 { return nil, fmt.Errorf("message %d has no finalized identity", id) } var from string var timestamp float64 var existing []byte - if err = tx.QueryRow(ctx, `SELECT add_to_from,time_added,sha256 FROM msg_add_to_batch WHERE id=$1 AND msg_id=$2 FOR UPDATE`, batchID, id).Scan(&from, ×tamp, &existing); err != nil { + if err := tx.QueryRow(ctx, `SELECT add_to_from,time_added,sha256 FROM msg_add_to_batch WHERE id=$1 AND msg_id=$2 FOR UPDATE`, batchID, id).Scan(&from, ×tamp, &existing); err != nil { return nil, err } if len(existing) > 0 { return existing, nil } var h *fmsg.Header - if len(s.prepared) > 0 { - h, err = fmsg.UnmarshalPrepared(s.prepared, s.hash) + var err error + if len(prepared) > 0 { + h, err = fmsg.UnmarshalPreparedHeader(prepared) } else { // A host first receiving this message through add-to holds a batch's // exact payload representation and the original hash carried as pid. - var snapshot, batchHash []byte - err = tx.QueryRow(ctx, `SELECT wire_message,sha256 FROM msg_add_to_batch WHERE msg_id=$1 AND wire_message IS NOT NULL ORDER BY id LIMIT 1`, id).Scan(&snapshot, &batchHash) + var snapshot []byte + err = tx.QueryRow(ctx, `SELECT wire_message FROM msg_add_to_batch WHERE msg_id=$1 AND wire_message IS NOT NULL ORDER BY id LIMIT 1`, id).Scan(&snapshot) if err == nil { - h, err = fmsg.UnmarshalPrepared(snapshot, batchHash) + h, err = fmsg.UnmarshalPreparedHeader(snapshot) } } if err != nil { @@ -249,7 +251,7 @@ func FinalizeBatch(ctx context.Context, tx Tx, id, batchID int64) ([]byte, error } h = h.Clone() h.Flags |= fmsg.FlagHasPid | fmsg.FlagHasAddTo - h.Pid = s.hash + h.Pid = msgHash h.Timestamp = timestamp h.Topic = "" h.AddTo = nil From 9e1956f888113f6ce0bec7c3ed8a3513f6a2d647 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Wed, 25 Nov 2026 18:23:54 +0800 Subject: [PATCH 2/5] Address review comments: isolate sender DB pool, raise resolver timeout, verify FinalizeBatch hash, fix attachment reject precedence, deduplicate updateRecipient --- cmd/fmsgd/dns.go | 20 +- cmd/fmsgd/dns_test.go | 84 ++++++++ cmd/fmsgd/host.go | 14 +- cmd/fmsgd/host_test.go | 72 +++++++ cmd/fmsgd/sender.go | 46 ++--- cmd/fmsgd/store.go | 60 +++++- cmd/fmsgd/store_test.go | 219 +++++++++++++++++++++ pkg/message/store.go | 8 +- pkg/message/store_integration_test.go | 50 +++++ pkg/message/store_test.go | 267 ++++++++++++++++++++++++++ 10 files changed, 783 insertions(+), 57 deletions(-) create mode 100644 cmd/fmsgd/dns_test.go create mode 100644 pkg/message/store_test.go diff --git a/cmd/fmsgd/dns.go b/cmd/fmsgd/dns.go index 3b21622..83aa848 100644 --- a/cmd/fmsgd/dns.go +++ b/cmd/fmsgd/dns.go @@ -15,11 +15,21 @@ import ( "github.com/miekg/dns" ) -const dnsLookupTimeout = 5 * time.Second +const ( + // dnsLookupTimeout bounds a single per-nameserver DNSSEC UDP/TCP exchange. + dnsLookupTimeout = 5 * time.Second + // resolverLookupTimeout bounds the full non-DNSSEC net.Resolver lookup so + // Go's stub resolver retains headroom for retries and nameserver failover + // (resolv.conf defaults to 5s per attempt). + resolverLookupTimeout = 20 * time.Second +) var ( - dnsClient = &dns.Client{Timeout: dnsLookupTimeout} - dnsTCPClient = &dns.Client{Net: "tcp", Timeout: dnsLookupTimeout} + dnsClient = &dns.Client{Timeout: dnsLookupTimeout} + dnsTCPClient = &dns.Client{Net: "tcp", Timeout: dnsLookupTimeout} + lookupIPWithContext = func(ctx context.Context, network, host string) ([]net.IP, error) { + return net.DefaultResolver.LookupIP(ctx, network, host) + } ) func dnssecRequired() bool { @@ -121,9 +131,9 @@ func lookupAuthorisedIPs(domain string) ([]net.IP, error) { return validateDNSSECResults(fmsgDomain, resA, resAAAA) } - ctx, cancel := context.WithTimeout(context.Background(), dnsLookupTimeout) + ctx, cancel := context.WithTimeout(context.Background(), resolverLookupTimeout) defer cancel() - ips, err := net.DefaultResolver.LookupIP(ctx, "ip", fmsgDomain) + ips, err := lookupIPWithContext(ctx, "ip", fmsgDomain) if err != nil { return nil, fmt.Errorf("DNS lookup for %s failed: %w", fmsgDomain, err) } diff --git a/cmd/fmsgd/dns_test.go b/cmd/fmsgd/dns_test.go new file mode 100644 index 0000000..1073f9c --- /dev/null +++ b/cmd/fmsgd/dns_test.go @@ -0,0 +1,84 @@ +package main + +import ( + "context" + "errors" + "net" + "testing" + "time" +) + +func TestLookupAuthorisedIPsResolverTimeoutAllowsFailover(t *testing.T) { + t.Setenv("FMSG_REQUIRE_DNSSEC", "") + + // Per-server DNSSEC clients keep the 5s per-attempt timeout. + if dnsClient.Timeout != dnsLookupTimeout || dnsTCPClient.Timeout != dnsLookupTimeout { + t.Fatalf("DNSSEC client timeouts = (%v, %v), want %v", dnsClient.Timeout, dnsTCPClient.Timeout, dnsLookupTimeout) + } + + origLookup := lookupIPWithContext + t.Cleanup(func() { + lookupIPWithContext = origLookup + }) + + wantIP := net.ParseIP("192.0.2.42") + var attempts int + lookupIPWithContext = func(ctx context.Context, network, host string) ([]net.IP, error) { + if network != "ip" { + t.Errorf("network = %q, want %q", network, "ip") + } + if host != "fmsg.example.com" { + t.Errorf("host = %q, want %q", host, "fmsg.example.com") + } + + deadline, ok := ctx.Deadline() + if !ok { + t.Fatal("expected context with deadline for non-DNSSEC lookup") + } + remaining := time.Until(deadline) + if remaining < 15*time.Second { + t.Fatalf("resolver context deadline remaining = %v, want >= 15s to allow nameserver failover", remaining) + } + if remaining > resolverLookupTimeout { + t.Fatalf("resolver context deadline remaining = %v, want <= %v", remaining, resolverLookupTimeout) + } + + // Simulate a multi-nameserver resolver: nameserver 1 times out after + // one 5s per-attempt timeout, and nameserver 2 succeeds because the + // overall context still has budget remaining. + nameservers := []func() ([]net.IP, error){ + func() ([]net.IP, error) { + remaining -= dnsLookupTimeout + return nil, errors.New("i/o timeout on primary nameserver") + }, + func() ([]net.IP, error) { + if remaining <= 0 || ctx.Err() != nil { + return nil, context.DeadlineExceeded + } + return []net.IP{wantIP}, nil + }, + } + + var lastErr error + for _, queryNS := range nameservers { + attempts++ + ips, err := queryNS() + if err == nil { + return ips, nil + } + lastErr = err + } + return nil, lastErr + } + + ips, err := lookupAuthorisedIPs("example.com") + if err != nil { + t.Fatalf("lookupAuthorisedIPs failed across nameserver failover: %v", err) + } + if attempts != 2 { + t.Fatalf("nameserver attempts = %d, want 2 (failover)", attempts) + } + if len(ips) != 1 || !ips[0].Equal(wantIP) { + t.Fatalf("lookupAuthorisedIPs = %v, want [%s]", ips, wantIP) + } +} diff --git a/cmd/fmsgd/host.go b/cmd/fmsgd/host.go index 2c44f72..780f1ff 100644 --- a/cmd/fmsgd/host.go +++ b/cmd/fmsgd/host.go @@ -1045,19 +1045,6 @@ func readAttachmentHeaders(c net.Conn, r *bufio.Reader, h *FMsgHeader) error { } totalSize += uint64(attSize) - if totalSize > uint64(MaxMessageSize) { - if err := sendCode(c, RejectCodeTooBig); err != nil { - return err - } - return fmt.Errorf("total message size %d exceeds max %d", totalSize, MaxMessageSize) - } - if totalExpandedSize > uint64(MaxExpandedSize) { - if err := sendCode(c, RejectCodeTooBig); err != nil { - return err - } - return fmt.Errorf("total expanded size %d exceeds MAX_EXPANDED_SIZE %d", totalExpandedSize, MaxExpandedSize) - } - h.Attachments = append(h.Attachments, FMsgAttachmentHeader{ Flags: attFlags, TypeID: attTypeID, @@ -2045,6 +2032,7 @@ func main() { log.Fatalf("ERROR: connecting to database: %s\n", err) } defer closeDB() + defer closeSenderDB() // set DataDir, Domain and IDURL from env setDataDir() diff --git a/cmd/fmsgd/host_test.go b/cmd/fmsgd/host_test.go index ce5544e..0ae7a32 100644 --- a/cmd/fmsgd/host_test.go +++ b/cmd/fmsgd/host_test.go @@ -856,6 +856,78 @@ func TestReadAttachmentHeadersRejectsUint32SizeOverflow(t *testing.T) { } } +func TestReadAttachmentHeadersInvalidPrecedesTooBig(t *testing.T) { + t.Run("wire size exceeds max before later reserved attachment flag", func(t *testing.T) { + origMax := MaxMessageSize + origExpanded := MaxExpandedSize + MaxMessageSize = 100 + MaxExpandedSize = 100 + t.Cleanup(func() { + MaxMessageSize = origMax + MaxExpandedSize = origExpanded + }) + + h := &FMsgHeader{Size: 10} + c := &testConn{} + b := []byte{2} // 2 attachments + + // Attachment 1: valid header, size 200 (> MaxMessageSize=100) + b = append(b, 0) + b = append(b, encodeUInt8String(t, "text/plain")...) + b = append(b, encodeUInt8String(t, "big.txt")...) + var sz [4]byte + binary.LittleEndian.PutUint32(sz[:], 200) + b = append(b, sz[:]...) + + // Attachment 2: reserved flag bit 2 set -> SPEC §10.3 step 3 (code 1 invalid) + b = append(b, 1<<2) + + err := readAttachmentHeaders(c, bufio.NewReader(bytes.NewReader(b)), h) + if err == nil { + t.Fatal("expected error for reserved attachment flag bit") + } + if got := c.Bytes(); len(got) != 1 || got[0] != RejectCodeInvalid { + t.Fatalf("wrote %v, want single code %d (invalid), not %d (too big)", got, RejectCodeInvalid, RejectCodeTooBig) + } + }) + + t.Run("expanded size exceeds max before later reserved attachment flag", func(t *testing.T) { + origMax := MaxMessageSize + origExpanded := MaxExpandedSize + MaxMessageSize = 1024 + MaxExpandedSize = 100 + t.Cleanup(func() { + MaxMessageSize = origMax + MaxExpandedSize = origExpanded + }) + + h := &FMsgHeader{Size: 0} + c := &testConn{} + b := []byte{2} // 2 attachments + + // Attachment 1: compressed, expanded size 200 (> MaxExpandedSize=100) + b = append(b, 1<<1) + b = append(b, encodeUInt8String(t, "text/plain")...) + b = append(b, encodeUInt8String(t, "big.txt")...) + var sz [4]byte + binary.LittleEndian.PutUint32(sz[:], 50) + b = append(b, sz[:]...) + binary.LittleEndian.PutUint32(sz[:], 200) + b = append(b, sz[:]...) + + // Attachment 2: reserved flag bit 2 set -> SPEC §10.3 step 3 (code 1 invalid) + b = append(b, 1<<2) + + err := readAttachmentHeaders(c, bufio.NewReader(bytes.NewReader(b)), h) + if err == nil { + t.Fatal("expected error for reserved attachment flag bit") + } + if got := c.Bytes(); len(got) != 1 || got[0] != RejectCodeInvalid { + t.Fatalf("wrote %v, want single code %d (invalid), not %d (too big)", got, RejectCodeInvalid, RejectCodeTooBig) + } + }) +} + func TestHandleChallengeTruncatedNoPanic(t *testing.T) { initOutgoing() c := &testConn{} diff --git a/cmd/fmsgd/sender.go b/cmd/fmsgd/sender.go index 0190b78..faf5e9f 100644 --- a/cmd/fmsgd/sender.go +++ b/cmd/fmsgd/sender.go @@ -62,7 +62,7 @@ type pendingTarget struct { // retryable recipients. This is a lightweight read-only query — row-level // locks are acquired per-delivery in deliverMessage. func findPendingTargets() ([]pendingTarget, error) { - db, err := getDB() + db, err := getSenderDB() if err != nil { return nil, err } @@ -191,33 +191,23 @@ func sendMsgData(conn net.Conn, h *FMsgHeader) error { // For msg_add_to, rows are scoped by batch_id so independent batches sharing // the same recipient address do not overwrite each other. func updateRecipient(tx *sql.Tx, table, addr string, msgID, batchID int64, now float64, code int, delivered bool) error { - var err error + targetTable, scopeCol, scopeID := "msg_to", "msg_id", msgID if table == "msg_add_to" { - if delivered { - _, err = tx.Exec(` - UPDATE msg_add_to SET time_delivered = $1, response_code = $2 - WHERE batch_id = $3 AND addr = $4 - `, now, code, batchID, addr) - } else { - _, err = tx.Exec(` - UPDATE msg_add_to SET time_last_attempt = $1, response_code = $2, - attempt_count = attempt_count + 1 - WHERE batch_id = $3 AND addr = $4 - `, now, code, batchID, addr) - } + targetTable, scopeCol, scopeID = "msg_add_to", "batch_id", batchID + } + + var err error + if delivered { + _, err = tx.Exec(fmt.Sprintf(` + UPDATE %s SET time_delivered = $1, response_code = $2 + WHERE %s = $3 AND addr = $4 + `, targetTable, scopeCol), now, code, scopeID, addr) } else { - if delivered { - _, err = tx.Exec(` - UPDATE msg_to SET time_delivered = $1, response_code = $2 - WHERE msg_id = $3 AND addr = $4 - `, now, code, msgID, addr) - } else { - _, err = tx.Exec(` - UPDATE msg_to SET time_last_attempt = $1, response_code = $2, - attempt_count = attempt_count + 1 - WHERE msg_id = $3 AND addr = $4 - `, now, code, msgID, addr) - } + _, err = tx.Exec(fmt.Sprintf(` + UPDATE %s SET time_last_attempt = $1, response_code = $2, + attempt_count = attempt_count + 1 + WHERE %s = $3 AND addr = $4 + `, targetTable, scopeCol), now, code, scopeID, addr) } if err != nil { log.Printf("ERROR: sender: update recipient %s: %s", addr, err) @@ -374,7 +364,7 @@ func deliverMessage(target pendingTarget) { return } - db, err := getDB() + db, err := getSenderDB() if err != nil { log.Printf("ERROR: sender: db open: %s", err) return @@ -513,7 +503,7 @@ func recordUnitInvalid(db *sql.DB, target pendingTarget, table string, batchID i // rather than sending over the network. (findPendingTargets skips the local // domain, so this is a defensive path.) func markLocalDelivered(target pendingTarget) { - db, err := getDB() + db, err := getSenderDB() if err != nil { log.Printf("ERROR: sender: db open for local delivery: %s", err) return diff --git a/cmd/fmsgd/store.go b/cmd/fmsgd/store.go index 00eb720..6eb5b14 100644 --- a/cmd/fmsgd/store.go +++ b/cmd/fmsgd/store.go @@ -13,25 +13,39 @@ import ( "github.com/markmnl/fmsgd/pkg/fmsg" ) +const ( + dbMaxOpenConns = 48 + dbMaxIdleConns = 16 + senderDBMaxOpenConns = 32 + senderDBMaxIdleConns = 8 +) + var ( - dbMu sync.Mutex - sharedDB *sql.DB + dbMu sync.Mutex + sharedDB *sql.DB + senderDBMu sync.Mutex + senderDB *sql.DB + + // openDBPool opens a new database pool. Overridable in tests. + openDBPool = func() (*sql.DB, error) { + return sql.Open("postgres", "") + } ) -// getDB returns the process-wide shared *sql.DB connection pool, initializing -// it lazily on first use. +// getDB returns the process-wide shared *sql.DB connection pool used by inbound +// handlers and indicators, initializing it lazily on first use. func getDB() (*sql.DB, error) { dbMu.Lock() defer dbMu.Unlock() if sharedDB != nil { return sharedDB, nil } - db, err := sql.Open("postgres", "") + db, err := openDBPool() if err != nil { return nil, err } - db.SetMaxOpenConns(48) - db.SetMaxIdleConns(16) + db.SetMaxOpenConns(dbMaxOpenConns) + db.SetMaxIdleConns(dbMaxIdleConns) db.SetConnMaxLifetime(30 * time.Minute) db.SetConnMaxIdleTime(5 * time.Minute) sharedDB = db @@ -49,6 +63,38 @@ func closeDB() { } } +// getSenderDB returns a dedicated *sql.DB connection pool for the outbound +// sender, isolated from getDB() so sender transactions held across network I/O +// cannot starve inbound handlers or indicators. +func getSenderDB() (*sql.DB, error) { + senderDBMu.Lock() + defer senderDBMu.Unlock() + if senderDB != nil { + return senderDB, nil + } + db, err := openDBPool() + if err != nil { + return nil, err + } + db.SetMaxOpenConns(senderDBMaxOpenConns) + db.SetMaxIdleConns(senderDBMaxIdleConns) + db.SetConnMaxLifetime(30 * time.Minute) + db.SetConnMaxIdleTime(5 * time.Minute) + senderDB = db + return senderDB, nil +} + +// closeSenderDB closes the sender *sql.DB connection pool if initialized. +func closeSenderDB() { + senderDBMu.Lock() + db := senderDB + senderDB = nil + senderDBMu.Unlock() + if db != nil { + _ = db.Close() + } +} + func testDb() error { db, err := getDB() if err != nil { diff --git a/cmd/fmsgd/store_test.go b/cmd/fmsgd/store_test.go index b5bfd07..f44469a 100644 --- a/cmd/fmsgd/store_test.go +++ b/cmd/fmsgd/store_test.go @@ -2,8 +2,15 @@ package main import ( "bytes" + "context" + "database/sql" + "database/sql/driver" "errors" + "io" + "strings" + "sync" "testing" + "time" ) type fakeParentLinkStore struct { @@ -225,3 +232,215 @@ func TestInboundRecipientRow(t *testing.T) { t.Fatalf("remote: got (%v, %v), want (nil, %d)", delivered, code, localResponseCodeNotOurDelivery) } } + +type fakeExecRecord struct { + query string + args []driver.NamedValue +} + +type fakeSQLConnector struct { + mu sync.Mutex + execRecords []fakeExecRecord + queryRowVal int64 +} + +func (c *fakeSQLConnector) Connect(context.Context) (driver.Conn, error) { + return &fakeSQLConn{connector: c}, nil +} + +func (c *fakeSQLConnector) Driver() driver.Driver { return fakeSQLDriver{} } + +type fakeSQLDriver struct{} + +func (fakeSQLDriver) Open(string) (driver.Conn, error) { + return nil, errors.New("unexpected Open") +} + +type fakeSQLConn struct { + connector *fakeSQLConnector +} + +func (c *fakeSQLConn) Prepare(string) (driver.Stmt, error) { + return nil, errors.New("Prepare not implemented") +} + +func (c *fakeSQLConn) Close() error { return nil } + +func (c *fakeSQLConn) Begin() (driver.Tx, error) { return fakeSQLTx{}, nil } + +func (c *fakeSQLConn) BeginTx(context.Context, driver.TxOptions) (driver.Tx, error) { + return fakeSQLTx{}, nil +} + +func (c *fakeSQLConn) QueryContext(_ context.Context, _ string, _ []driver.NamedValue) (driver.Rows, error) { + return &fakeSQLRows{val: c.connector.queryRowVal}, nil +} + +func (c *fakeSQLConn) ExecContext(_ context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + c.connector.mu.Lock() + copied := append([]driver.NamedValue(nil), args...) + c.connector.execRecords = append(c.connector.execRecords, fakeExecRecord{query: query, args: copied}) + c.connector.mu.Unlock() + return driver.RowsAffected(1), nil +} + +type fakeSQLTx struct{} + +func (fakeSQLTx) Commit() error { return nil } +func (fakeSQLTx) Rollback() error { return nil } + +type fakeSQLRows struct { + val int64 + done bool +} + +func (r *fakeSQLRows) Columns() []string { return []string{"id"} } +func (r *fakeSQLRows) Close() error { return nil } +func (r *fakeSQLRows) Next(dest []driver.Value) error { + if r.done { + return io.EOF + } + r.done = true + dest[0] = r.val + return nil +} + +func TestSenderPoolSaturationDoesNotStarveInboundPool(t *testing.T) { + origOpen := openDBPool + closeDB() + closeSenderDB() + t.Cleanup(func() { + closeDB() + closeSenderDB() + openDBPool = origOpen + }) + + conn := &fakeSQLConnector{queryRowVal: 42} + openDBPool = func() (*sql.DB, error) { + return sql.OpenDB(conn), nil + } + + sDB, err := getSenderDB() + if err != nil { + t.Fatalf("getSenderDB: %v", err) + } + inDB, err := getDB() + if err != nil { + t.Fatalf("getDB: %v", err) + } + if sDB == inDB { + t.Fatal("sender pool and inbound pool must be distinct *sql.DB instances") + } + + // Fill every single connection in the sender pool with open transactions. + heldTxs := make([]*sql.Tx, 0, senderDBMaxOpenConns) + defer func() { + for _, tx := range heldTxs { + _ = tx.Rollback() + } + }() + for i := 0; i < senderDBMaxOpenConns; i++ { + tx, err := sDB.Begin() + if err != nil { + t.Fatalf("sender Begin #%d: %v", i, err) + } + heldTxs = append(heldTxs, tx) + } + + // Queue additional Begin calls beyond senderDBMaxOpenConns to confirm the + // sender pool is genuinely saturated and blocking. + const extraWaiters = 4 + extraDone := make(chan *sql.Tx, extraWaiters) + var wg sync.WaitGroup + for i := 0; i < extraWaiters; i++ { + wg.Add(1) + go func() { + defer wg.Done() + tx, err := sDB.Begin() + if err != nil { + t.Errorf("extra sender Begin: %v", err) + return + } + extraDone <- tx + }() + } + + // Wait briefly until at least one extra waiter is blocked on the sender pool. + deadline := time.Now().Add(time.Second) + for sDB.Stats().WaitCount == 0 && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + if stats := sDB.Stats(); stats.InUse != senderDBMaxOpenConns || stats.WaitCount == 0 { + t.Fatalf("expected saturated sender pool (inUse=%d/%d, waitCount=%d)", stats.InUse, senderDBMaxOpenConns, stats.WaitCount) + } + + // While the sender pool is completely saturated, an inbound getDB() query + // must complete immediately without blocking. + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + var got int64 + if err := inDB.QueryRowContext(ctx, "SELECT id FROM msg WHERE sha256 = $1", []byte{1}).Scan(&got); err != nil { + t.Fatalf("inbound query blocked or failed while sender pool saturated: %v", err) + } + if got != 42 { + t.Fatalf("inbound query returned %d, want 42", got) + } + id, err := lookupMsgIdByHash([]byte{1, 2, 3}) + if err != nil || id != 42 { + t.Fatalf("lookupMsgIdByHash = (%d, %v), want (42, nil)", id, err) + } + + // Release held sender transactions and drain the queued waiters cleanly. + for _, tx := range heldTxs { + _ = tx.Rollback() + } + heldTxs = nil + wg.Wait() + close(extraDone) + for tx := range extraDone { + _ = tx.Rollback() + } +} + +func TestUpdateRecipientSQL(t *testing.T) { + conn := &fakeSQLConnector{} + db := sql.OpenDB(conn) + t.Cleanup(func() { _ = db.Close() }) + + tx, err := db.Begin() + if err != nil { + t.Fatalf("Begin: %v", err) + } + defer tx.Rollback() + + cases := []struct { + name string + table string + delivered bool + wantTable string + wantScope string + wantID int64 + wantSet string + }{ + {"msg_to delivered", "msg_to", true, "UPDATE msg_to SET", "WHERE msg_id = $3 AND addr = $4", 10, "time_delivered = $1, response_code = $2"}, + {"msg_to failed", "msg_to", false, "UPDATE msg_to SET", "WHERE msg_id = $3 AND addr = $4", 10, "time_last_attempt = $1, response_code = $2"}, + {"msg_add_to delivered", "msg_add_to", true, "UPDATE msg_add_to SET", "WHERE batch_id = $3 AND addr = $4", 20, "time_delivered = $1, response_code = $2"}, + {"msg_add_to failed", "msg_add_to", false, "UPDATE msg_add_to SET", "WHERE batch_id = $3 AND addr = $4", 20, "time_last_attempt = $1, response_code = $2"}, + } + + for i, tc := range cases { + if err := updateRecipient(tx, tc.table, "@bob@example.com", 10, 20, 1234.5, 200, tc.delivered); err != nil { + t.Fatalf("%s: updateRecipient error: %v", tc.name, err) + } + rec := conn.execRecords[i] + if !strings.Contains(rec.query, tc.wantTable) || !strings.Contains(rec.query, tc.wantScope) || !strings.Contains(rec.query, tc.wantSet) { + t.Fatalf("%s: unexpected SQL:\n%s", tc.name, rec.query) + } + if !tc.delivered && !strings.Contains(rec.query, "attempt_count = attempt_count + 1") { + t.Fatalf("%s: missing attempt_count increment in SQL:\n%s", tc.name, rec.query) + } + if len(rec.args) != 4 || rec.args[2].Value != tc.wantID || rec.args[3].Value != "@bob@example.com" { + t.Fatalf("%s: unexpected args: %+v", tc.name, rec.args) + } + } +} diff --git a/pkg/message/store.go b/pkg/message/store.go index 4a75079..19153c6 100644 --- a/pkg/message/store.go +++ b/pkg/message/store.go @@ -236,14 +236,14 @@ func FinalizeBatch(ctx context.Context, tx Tx, id, batchID int64) ([]byte, error var h *fmsg.Header var err error if len(prepared) > 0 { - h, err = fmsg.UnmarshalPreparedHeader(prepared) + h, err = fmsg.UnmarshalPrepared(prepared, msgHash) } else { // A host first receiving this message through add-to holds a batch's // exact payload representation and the original hash carried as pid. - var snapshot []byte - err = tx.QueryRow(ctx, `SELECT wire_message FROM msg_add_to_batch WHERE msg_id=$1 AND wire_message IS NOT NULL ORDER BY id LIMIT 1`, id).Scan(&snapshot) + var snapshot, batchHash []byte + err = tx.QueryRow(ctx, `SELECT wire_message,sha256 FROM msg_add_to_batch WHERE msg_id=$1 AND wire_message IS NOT NULL ORDER BY id LIMIT 1`, id).Scan(&snapshot, &batchHash) if err == nil { - h, err = fmsg.UnmarshalPreparedHeader(snapshot) + h, err = fmsg.UnmarshalPrepared(snapshot, batchHash) } } if err != nil { diff --git a/pkg/message/store_integration_test.go b/pkg/message/store_integration_test.go index 335f33d..b7ad9f2 100644 --- a/pkg/message/store_integration_test.go +++ b/pkg/message/store_integration_test.go @@ -236,3 +236,53 @@ func TestFinalizeDraftBatchesAndRollback(t *testing.T) { t.Fatal("rollback stamped message", err) } } + +func TestFinalizeBatchRejectsCorruptedPayload(t *testing.T) { + db, _ := testStore(t) + root := insertDraft(t, db, nil, "root payload for corruption check") + seal(t, db, root) + + var prepared []byte + if err := db.QueryRow(`SELECT wire_message FROM msg WHERE id=$1`, root).Scan(&prepared); err != nil { + t.Fatal(err) + } + h, err := fmsg.UnmarshalPreparedHeader(prepared) + if err != nil { + t.Fatal(err) + } + origBytes, err := os.ReadFile(h.Filepath) + if err != nil { + t.Fatal(err) + } + corrupted := append([]byte(nil), origBytes...) + corrupted[0] ^= 0xff + if err := os.WriteFile(h.Filepath, corrupted, 0640); err != nil { + t.Fatal(err) + } + + var batch int64 + if err := db.QueryRow(`INSERT INTO msg_add_to_batch(msg_id,add_to_from,time_added) VALUES($1,'@alice@example.com',1235.5) RETURNING id`, root).Scan(&batch); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO msg_add_to(msg_id,batch_id,addr) VALUES($1,$2,'@carol@example.com')`, root, batch); err != nil { + t.Fatal(err) + } + + tx, err := db.Begin() + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if _, err := FinalizeBatch(context.Background(), SQLTx{tx}, root, batch); err == nil { + t.Fatal("FinalizeBatch accepted corrupted stored payload") + } + _ = tx.Rollback() + + var batchHash []byte + if err := db.QueryRow(`SELECT sha256 FROM msg_add_to_batch WHERE id=$1`, batch).Scan(&batchHash); err != nil { + t.Fatal(err) + } + if len(batchHash) != 0 { + t.Fatalf("corrupted batch was unexpectedly sealed with hash %x", batchHash) + } +} diff --git a/pkg/message/store_test.go b/pkg/message/store_test.go new file mode 100644 index 0000000..84ba5ad --- /dev/null +++ b/pkg/message/store_test.go @@ -0,0 +1,267 @@ +package message + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/markmnl/fmsgd/pkg/fmsg" +) + +type fakeRow struct { + vals []any + err error +} + +func (r fakeRow) Scan(dest ...any) error { + if r.err != nil { + return r.err + } + if len(dest) != len(r.vals) { + return fmt.Errorf("scan dest count %d != val count %d", len(dest), len(r.vals)) + } + for i := range dest { + switch d := dest[i].(type) { + case **float64: + *d = r.vals[i].(*float64) + case *float64: + *d = r.vals[i].(float64) + case *string: + *d = r.vals[i].(string) + case *[]byte: + if r.vals[i] == nil { + *d = nil + } else { + *d = append([]byte(nil), r.vals[i].([]byte)...) + } + default: + return fmt.Errorf("unsupported scan type %T", dest[i]) + } + } + return nil +} + +type fakeAddrRows struct { + addrs []string + idx int +} + +func (r *fakeAddrRows) Next() bool { + if r.idx >= len(r.addrs) { + return false + } + r.idx++ + return true +} + +func (r *fakeAddrRows) Scan(dest ...any) error { + *(dest[0].(*string)) = r.addrs[r.idx-1] + return nil +} + +func (r *fakeAddrRows) Err() error { return nil } +func (r *fakeAddrRows) Close() {} + +type fakeBatchTx struct { + sentTime *float64 + msgHash []byte + msgPrepared []byte + batchFrom string + batchTimestamp float64 + batchExisting []byte + prevSnapshot []byte + prevBatchHash []byte + addToAddrs []string + + execCalls int + sealedHash []byte + sealedWire []byte +} + +func (f *fakeBatchTx) QueryRow(_ context.Context, query string, _ ...any) Row { + switch { + case strings.Contains(query, "FROM msg WHERE id=$1"): + return fakeRow{vals: []any{f.sentTime, f.msgHash, f.msgPrepared}} + case strings.Contains(query, "SELECT add_to_from,time_added,sha256 FROM msg_add_to_batch"): + return fakeRow{vals: []any{f.batchFrom, f.batchTimestamp, f.batchExisting}} + case strings.Contains(query, "SELECT wire_message,sha256 FROM msg_add_to_batch"): + return fakeRow{vals: []any{f.prevSnapshot, f.prevBatchHash}} + default: + return fakeRow{err: fmt.Errorf("unexpected QueryRow: %s", query)} + } +} + +func (f *fakeBatchTx) Query(_ context.Context, query string, _ ...any) (Rows, error) { + if strings.Contains(query, "SELECT addr FROM msg_add_to") { + return &fakeAddrRows{addrs: f.addToAddrs}, nil + } + return nil, fmt.Errorf("unexpected Query: %s", query) +} + +func (f *fakeBatchTx) Exec(_ context.Context, query string, args ...any) error { + if !strings.Contains(query, "UPDATE msg_add_to_batch SET sha256=$2,wire_message=$3") { + return fmt.Errorf("unexpected Exec: %s", query) + } + f.execCalls++ + f.sealedHash = append([]byte(nil), args[1].([]byte)...) + f.sealedWire = []byte(args[2].(string)) + return nil +} + +func prepareTestMessage(t *testing.T, body string) (*fmsg.Header, []byte, []byte) { + t.Helper() + src := filepath.Join(t.TempDir(), "body.txt") + if err := os.WriteFile(src, []byte(body), 0600); err != nil { + t.Fatal(err) + } + h := &fmsg.Header{ + Version: 1, + From: fmsg.Address{User: "alice", Domain: "example.com"}, + To: []fmsg.Address{{User: "bob", Domain: "example.com"}}, + Timestamp: 1700000000, + Type: "text/plain;charset=UTF-8", + Size: uint32(len(body)), + Filepath: src, + } + prepared, _, err := fmsg.Prepare(h) + if err != nil { + t.Fatalf("Prepare: %v", err) + } + hash, err := prepared.GetMessageHash() + if err != nil { + t.Fatalf("GetMessageHash: %v", err) + } + snapshot, err := fmsg.MarshalPrepared(prepared) + if err != nil { + t.Fatalf("MarshalPrepared: %v", err) + } + return prepared, hash, snapshot +} + +func TestFinalizeBatchVerifiesOriginalPayloadHash(t *testing.T) { + sent := 1700000000.0 + prepared, msgHash, snapshot := prepareTestMessage(t, "original message payload") + + // Control: intact payload seals cleanly. + txOK := &fakeBatchTx{ + sentTime: &sent, + msgHash: msgHash, + msgPrepared: snapshot, + batchFrom: "@alice@example.com", + batchTimestamp: 1700000010.0, + addToAddrs: []string{"@carol@example.com"}, + } + gotHash, err := FinalizeBatch(context.Background(), txOK, 1, 2) + if err != nil { + t.Fatalf("FinalizeBatch intact payload error: %v", err) + } + if len(gotHash) != 32 || txOK.execCalls != 1 || !bytes.Equal(txOK.sealedHash, gotHash) { + t.Fatalf("FinalizeBatch did not seal valid batch (execCalls=%d, hashLen=%d)", txOK.execCalls, len(gotHash)) + } + if _, err := fmsg.UnmarshalPrepared(txOK.sealedWire, txOK.sealedHash); err != nil { + t.Fatalf("sealed batch failed verification: %v", err) + } + + // Corrupt the stored payload file in place (same length, altered bytes). + origBytes, err := os.ReadFile(prepared.Filepath) + if err != nil { + t.Fatal(err) + } + corrupted := append([]byte(nil), origBytes...) + corrupted[0] ^= 0xff + if err := os.WriteFile(prepared.Filepath, corrupted, 0640); err != nil { + t.Fatal(err) + } + + txCorrupt := &fakeBatchTx{ + sentTime: &sent, + msgHash: msgHash, + msgPrepared: snapshot, + batchFrom: "@alice@example.com", + batchTimestamp: 1700000020.0, + addToAddrs: []string{"@dave@example.com"}, + } + if _, err := FinalizeBatch(context.Background(), txCorrupt, 1, 3); err == nil { + t.Fatal("FinalizeBatch accepted corrupted original payload file") + } else if !strings.Contains(err.Error(), "hash mismatch") { + t.Fatalf("FinalizeBatch error = %v, want hash mismatch", err) + } + if txCorrupt.execCalls != 0 { + t.Fatalf("FinalizeBatch sealed batch despite corrupted payload (execCalls=%d)", txCorrupt.execCalls) + } +} + +func TestFinalizeBatchVerifiesReceivedBatchPayloadHash(t *testing.T) { + sent := 1700000000.0 + prepared, msgHash, _ := prepareTestMessage(t, "received via add-to payload") + + // Build a prior received batch snapshot (the msg row has no wire_message). + prev := prepared.Clone() + prev.Flags |= fmsg.FlagHasPid | fmsg.FlagHasAddTo + prev.Pid = msgHash + prev.Topic = "" + prev.Timestamp = 1700000005.0 + prev.AddToFrom = &fmsg.Address{User: "alice", Domain: "example.com"} + prev.AddTo = []fmsg.Address{{User: "carol", Domain: "example.com"}} + prevHash, err := prev.GetMessageHash() + if err != nil { + t.Fatalf("prev batch GetMessageHash: %v", err) + } + prevSnapshot, err := fmsg.MarshalPrepared(prev) + if err != nil { + t.Fatalf("prev batch MarshalPrepared: %v", err) + } + + // Control: intact payload via received-batch snapshot seals cleanly. + txOK := &fakeBatchTx{ + sentTime: &sent, + msgHash: msgHash, + msgPrepared: nil, // original arrived via add-to + prevSnapshot: prevSnapshot, + prevBatchHash: prevHash, + batchFrom: "@bob@example.com", + batchTimestamp: 1700000010.0, + addToAddrs: []string{"@dave@example.com"}, + } + gotHash, err := FinalizeBatch(context.Background(), txOK, 1, 2) + if err != nil { + t.Fatalf("FinalizeBatch intact received-batch payload error: %v", err) + } + if len(gotHash) != 32 || txOK.execCalls != 1 { + t.Fatalf("FinalizeBatch did not seal valid batch (execCalls=%d, hashLen=%d)", txOK.execCalls, len(gotHash)) + } + + // Corrupt the stored payload file in place (same length, altered bytes). + origBytes, err := os.ReadFile(prepared.Filepath) + if err != nil { + t.Fatal(err) + } + corrupted := append([]byte(nil), origBytes...) + corrupted[0] ^= 0xff + if err := os.WriteFile(prepared.Filepath, corrupted, 0640); err != nil { + t.Fatal(err) + } + + txCorrupt := &fakeBatchTx{ + sentTime: &sent, + msgHash: msgHash, + msgPrepared: nil, + prevSnapshot: prevSnapshot, + prevBatchHash: prevHash, + batchFrom: "@bob@example.com", + batchTimestamp: 1700000020.0, + addToAddrs: []string{"@eve@example.com"}, + } + if _, err := FinalizeBatch(context.Background(), txCorrupt, 1, 3); err == nil { + t.Fatal("FinalizeBatch accepted corrupted received-batch payload file") + } else if !strings.Contains(err.Error(), "hash mismatch") { + t.Fatalf("FinalizeBatch error = %v, want hash mismatch", err) + } + if txCorrupt.execCalls != 0 { + t.Fatalf("FinalizeBatch sealed batch despite corrupted payload (execCalls=%d)", txCorrupt.execCalls) + } +} From 0dc188f475cfdf42972b785d9b1cb8f7e155067e Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Wed, 25 Nov 2026 21:10:17 +0800 Subject: [PATCH 3/5] Insert add-to batch inside transaction in TestFinalizeBatchRejectsCorruptedPayload --- pkg/message/store_integration_test.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/pkg/message/store_integration_test.go b/pkg/message/store_integration_test.go index b7ad9f2..ea68812 100644 --- a/pkg/message/store_integration_test.go +++ b/pkg/message/store_integration_test.go @@ -260,26 +260,26 @@ func TestFinalizeBatchRejectsCorruptedPayload(t *testing.T) { t.Fatal(err) } - var batch int64 - if err := db.QueryRow(`INSERT INTO msg_add_to_batch(msg_id,add_to_from,time_added) VALUES($1,'@alice@example.com',1235.5) RETURNING id`, root).Scan(&batch); err != nil { + tx, err := db.Begin() + if err != nil { t.Fatal(err) } - if _, err := db.Exec(`INSERT INTO msg_add_to(msg_id,batch_id,addr) VALUES($1,$2,'@carol@example.com')`, root, batch); err != nil { + defer tx.Rollback() + + var batch int64 + if err := tx.QueryRow(`INSERT INTO msg_add_to_batch(msg_id,add_to_from,time_added) VALUES($1,'@alice@example.com',1235.5) RETURNING id`, root).Scan(&batch); err != nil { t.Fatal(err) } - - tx, err := db.Begin() - if err != nil { + if _, err := tx.Exec(`INSERT INTO msg_add_to(msg_id,batch_id,addr) VALUES($1,$2,'@carol@example.com')`, root, batch); err != nil { t.Fatal(err) } - defer tx.Rollback() + if _, err := FinalizeBatch(context.Background(), SQLTx{tx}, root, batch); err == nil { t.Fatal("FinalizeBatch accepted corrupted stored payload") } - _ = tx.Rollback() var batchHash []byte - if err := db.QueryRow(`SELECT sha256 FROM msg_add_to_batch WHERE id=$1`, batch).Scan(&batchHash); err != nil { + if err := tx.QueryRow(`SELECT sha256 FROM msg_add_to_batch WHERE id=$1`, batch).Scan(&batchHash); err != nil { t.Fatal(err) } if len(batchHash) != 0 { From 3cff8f657b19113b251410827ef696fe1ac184fa Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Wed, 25 Nov 2026 21:27:11 +0800 Subject: [PATCH 4/5] README: note the sender pool bounds concurrent deliveries Each outbound delivery holds one connection from the 32-connection sender pool for the whole exchange, so FMSG_MAX_CONCURRENT_SEND has no effect above 32. Co-Authored-By: Claude Fable 5.2 --- README.md | 354 +++++++++++++++++++++++++++--------------------------- 1 file changed, 177 insertions(+), 177 deletions(-) diff --git a/README.md b/README.md index 22c960d..60bc95c 100644 --- a/README.md +++ b/README.md @@ -1,177 +1,177 @@ -[![Build & Test](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml/badge.svg?branch=main)](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml?query=branch%3Amain) -[![Go 1.27+](https://img.shields.io/badge/Go-1.27%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/dl/) - -# fmsgd - -Implementation of [fmsg](https://github.com/markmnl/fmsg) host written in Go! Uses local filesystem and PostgreSQL database to store messages. - -## Building from source - -Requires Go 1.27 or newer. - -1. Clone this repository -2. Run `go build ./cmd/fmsgd/` - - -## Environment - -`FMSG_DATA_DIR`, `FMSG_DOMAIN`, `FMSG_ID_URL`, `FMSG_TLS_CERT` and `FMSG_TLS_KEY` are required to be set and valid; otherwise fmsgd will abort on startup. In addition to these `FMSG_` varibles, `PG` variables need to be set for the PostgreSQL database to use, refer to: https://www.postgresql.org/docs/current/libpq-envars.html - -| Variable | Default | Description | -|----------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| FMSG_DATA_DIR | | Path where messages will be stored. e.g. /opt/fmsg/data | -| FMSG_DOMAIN | | Domain name this host is located. e.g. example.com | -| FMSG_ID_URL | | Base HTTP URL for fmsg Id API, e.g. http://localhost:5000 | -| FMSG_TLS_CERT | | Path to TLS certificate file (PEM). Certificate must match `fmsg.`. | -| FMSG_TLS_KEY | | Path to TLS private key file (PEM). | -| FMSG_TLS_INSECURE_SKIP_VERIFY | false | Set to "true" to skip TLS certificate verification on outgoing connections. For development/testing only. | -| FMSG_MAX_MSG_SIZE | 10240 | Bytes. Maximum size above which to reject messages greater than before downloading them. | -| FMSG_PORT | 4930 | TCP port to listen on, and UDP port for [indicators](#indicators-fmsg-006). 4930 is the IANA-registered port for service name `fmsg`. | -| FMSG_MAX_PAST_TIME_DELTA | 604800 | Seconds. Duration since message timestamp to reject if greater than. Note sending host could have been holding messages waiting for us to be reachable. | -| FMSG_MAX_FUTURE_TIME_DELTA | 300 | Seconds. Duration from message timestamp to reject if greater than. | -| FMSG_MIN_DOWNLOAD_RATE | 5000 | Bytes per second. Used in setting download deadlines while downloading a message. | -| FMSG_MIN_UPLOAD_RATE | 5000 | Bytes per second. Used in setting upload deadlines while sending a message. | -| FMSG_READ_BUFFER_SIZE | 1600 | Bytes. Internal read buffer size per incoming connection | -| FMSG_RETRY_INTERVAL | 20 | Seconds. Minimum time before retrying delivery to a recipient that previously failed. | -| FMSG_RETRY_MAX_AGE | 86400 | Seconds. Maximum age of a message since creation before giving up on delivery retries (default 1 day). | -| FMSG_POLL_INTERVAL | 10 | Seconds. How often the sender polls the database for pending messages. | -| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of concurrent outbound message deliveries. | -| FMSG_SKIP_DOMAIN_IP_CHECK | false | Set to "true" to skip verifying this host's external IP is in the fmsg DNS authorised IP set on startup. | -| FMSG_SKIP_AUTHORISED_IPS | false | Set to "true" to skip verifying remote hosts IP is in the fmsg DNS authorised IP set during message exchange, and an indicator datagram's source address. WARNING setting this true effectively disables sender verification. | -| FMSG_CHALLENGE_MODE | HAS_NOT_PARTICIPATED | When to issue an automatic CHALLENGE to the sending host. `HAS_NOT_PARTICIPATED` (default): challenge only when the message has no pid, or no message in the thread is from this host's domain. `ALWAYS`: always challenge. `NEVER`: never challenge. | -| FMSG_INDICATORS | true | Set to "false" or "0" to turn off [indicators](#indicators-fmsg-006): fmsgd then neither listens on UDP nor sends indicator datagrams. | - - - -## Quotas and usage - -For each local recipient of a message from another host, fmsgd asks fmsgid for the address's receive limits and usage, and rejects the recipient with `101` (user full) if one more message of this size would exceed its messages per day, size per day or total size (`-1` is unlimited). The size is the stored size: the message body plus every attachment, decompressed. Once the message is stored, fmsgd records that size for each recipient that accepted it with `POST /fmsgid/recv`, timestamped when this host accepted the message (not the sender's timestamp), so a backdated message still counts towards today. fmsgd doesn't record send usage or mail between local addresses: the client that sends and delivers locally (such as fmsg-webapi) does. - -## Indicators (FMSG-006) - -fmsgd implements [FMSG-006 Indicators](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-006-indicators.md): short-lived, single-emoji states such as ✍️ (composing a reply) that a participant shows on a message. They travel host to host as single UDP datagrams on port 4930 (`FMSG_PORT`), at the same address fmsgd listens on for TCP. They are never acknowledged, answered or stored. - -**Receiving.** Each datagram is checked in this order and dropped silently at the first failure: - -1. a per-source-address rate limit (50 datagrams per second, burst 100); -2. the datagram is version 1, exactly its fields with no trailing bytes, and its data is empty (clear) or a single emoji of at most 64 bytes; -3. its hash matches a message this host holds, or one of its add-to batch messages; -4. its index names a participant of that message (from, to, then add to from and add to for a batch message), and that participant is not on this host's domain; -5. the source address is in `fmsg.` of that participant's domain (cached for 60 seconds; skipped with `FMSG_SKIP_AUTHORISED_IPS`). - -The ttl is clamped to 120 seconds and the indicator is published to the client API (see below). - -**Sending.** For an indicator set by a participant on this host's domain, fmsgd sends one datagram to each other participant domain of the message, naming the participant by their lowest index in the message that domain holds: the original message when the domain's participants and the indicating participant are among its from and to, otherwise the first add-to batch message that has both. It sends to one address of `fmsg.` (cached for 60 seconds), alternating between addresses, from the UDP socket it listens on. Rate limits: - -- at most one datagram per participant per message every 2 seconds; more frequent changes are coalesced and only the latest is sent when the interval allows. Clearing (empty) datagrams are sent at once; -- at most 20 datagrams per second to any one receiving domain; the excess is dropped. - -**Client API.** fmsgd and the client API (such as fmsg-webapi) share the PostgreSQL NOTIFY channel `indicator`. Its payload is JSON: - -```json -{"id": 123, "from": "@bob@example.com", "emoji": "✍️", "ttl": 6} -``` - -`id` is this host's `msg.id` of the message, `from` the indicating participant, `emoji` the indicator, or `""` with `ttl` `0` to clear, and `ttl` the seconds it lasts (at most 120). The client API notifies when a local participant sets or clears an indicator, and fmsgd sends it on; fmsgd notifies when it receives and verifies a datagram, and the client API delivers it to connected local participants. fmsgd only sends for addresses on its own domain, so the indicators it publishes are never sent again. - -Firewalls in front of fmsgd need UDP 4930 open inbound and outbound, as well as TCP 4930, for indicators to work. Without it, message exchange is unaffected; indicators are simply lost. - -## Running - -An up and running [fmsg Id API](https://github.com/markmnl/fmsgid) needs to be reachable by fmsgd to know users and their quotas for this fmsgd service. See also [fmsg-docker](https://github.com/markmnl/fmsg-docker) - a docker compose stack for a fmsg host including fmsgid, fmsg-webpi and fmsgd. - -IP address to bind to and listen on is the only argument, `127.0.0.1` is used if argument not supplied. e.g. on Linux: - -``` -./fmsgd "0.0.0.0" -``` - -on Windows: -``` -fmsgd.exe "0.0.0.0" -``` - -### systemd - -An example systemd service to run fmsgd as a service on startup - -ASSUMES: -* Directory `/opt/fmsgd` has been created and contains built executable: `fmsgd` -* Text file `/etc/fmsgd/env` exists containing environment variables (example below) -* User `fmsg` has been created and has - - read and execute permissions to `/opt/fmsgd/`, e.g. with `chown -R fmsg:fmsg /opt/fmsgd` after `mkdir /opt/fmsgd` - - write permissions to FMSG_DATA_DIR - - read permissions to /var/lib/fmsgd/tls -* Directory `/var/lib/fmsgd` has been created and owned by fmsg -* Valid TLS certs (see: [FMSG-001 TCP+TLS Transport and Binding Standard](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-001-transport-and-binding.md#fmsg-001-tcptls-transport-and-binding-standard)) at paths /var/lib/fmsgd/tls/fullchain.pem and /var/lib/fmsgd/tls/privkey.pem - - -`/etc/systemd/system/fmsgd.service` - -``` -[Unit] -Description=fmsg Host -After=network-online.target -Wants=network-online.target - -[Service] -Type=simple - -User=fmsg -Group=fmsg - -EnvironmentFile=/etc/fmsgd/env - -ExecStart=/opt/fmsgd/fmsgd 0.0.0.0 -WorkingDirectory=/opt/fmsgd - -Restart=on-failure -RestartSec=3 - -# --- Filesystem access NOTE location of certs /var/lib/fmsgd/tls--- -ReadOnlyPaths=/var/lib/fmsgd/tls -ReadWritePaths=/opt/fmsgd -ReadWritePaths=/var/lib/fmsgd -PrivateTmp=true - -# --- Hardening --- -NoNewPrivileges=true -PrivateTmp=true -ProtectSystem=strict -ProtectHome=true - -# --- Logging --- -StandardOutput=journal -StandardError=journal - -[Install] -WantedBy=multi-user.target -``` - -``` -FMSG_DATA_DIR=/var/lib/fmsgd/ -FMSG_DOMAIN=example.com -FMSG_ID_URL=http://127.0.0.1:8080 - -FMSG_TLS_CERT=/var/lib/fmsgd/tls/fullchain.pem -FMSG_TLS_KEY=/var/lib/fmsgd/tls/privkey.pem - -FMSG_MAX_MSG_SIZE=10240 -FMSG_MAX_PAST_TIME_DELTA=604800 -FMSG_MAX_FUTURE_TIME_DELTA=300 -FMSG_MIN_DOWNLOAD_RATE=5000 -FMSG_MIN_UPLOAD_RATE=5000 -FMSG_READ_BUFFER_SIZE=1600 - -PGHOST=127.0.0.1 -PGPORT=5432 -PGUSER= -PGPASSWORD= -PGDATABASE=fmsgd -``` - -``` -sudo systemctl daemon-reload -sudo systemctl enable fmsgd -sudo systemctl start fmsgd -``` +[![Build & Test](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml/badge.svg?branch=main)](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml?query=branch%3Amain) +[![Go 1.27+](https://img.shields.io/badge/Go-1.27%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/dl/) + +# fmsgd + +Implementation of [fmsg](https://github.com/markmnl/fmsg) host written in Go! Uses local filesystem and PostgreSQL database to store messages. + +## Building from source + +Requires Go 1.27 or newer. + +1. Clone this repository +2. Run `go build ./cmd/fmsgd/` + + +## Environment + +`FMSG_DATA_DIR`, `FMSG_DOMAIN`, `FMSG_ID_URL`, `FMSG_TLS_CERT` and `FMSG_TLS_KEY` are required to be set and valid; otherwise fmsgd will abort on startup. In addition to these `FMSG_` varibles, `PG` variables need to be set for the PostgreSQL database to use, refer to: https://www.postgresql.org/docs/current/libpq-envars.html + +| Variable | Default | Description | +|----------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------| +| FMSG_DATA_DIR | | Path where messages will be stored. e.g. /opt/fmsg/data | +| FMSG_DOMAIN | | Domain name this host is located. e.g. example.com | +| FMSG_ID_URL | | Base HTTP URL for fmsg Id API, e.g. http://localhost:5000 | +| FMSG_TLS_CERT | | Path to TLS certificate file (PEM). Certificate must match `fmsg.`. | +| FMSG_TLS_KEY | | Path to TLS private key file (PEM). | +| FMSG_TLS_INSECURE_SKIP_VERIFY | false | Set to "true" to skip TLS certificate verification on outgoing connections. For development/testing only. | +| FMSG_MAX_MSG_SIZE | 10240 | Bytes. Maximum size above which to reject messages greater than before downloading them. | +| FMSG_PORT | 4930 | TCP port to listen on, and UDP port for [indicators](#indicators-fmsg-006). 4930 is the IANA-registered port for service name `fmsg`. | +| FMSG_MAX_PAST_TIME_DELTA | 604800 | Seconds. Duration since message timestamp to reject if greater than. Note sending host could have been holding messages waiting for us to be reachable. | +| FMSG_MAX_FUTURE_TIME_DELTA | 300 | Seconds. Duration from message timestamp to reject if greater than. | +| FMSG_MIN_DOWNLOAD_RATE | 5000 | Bytes per second. Used in setting download deadlines while downloading a message. | +| FMSG_MIN_UPLOAD_RATE | 5000 | Bytes per second. Used in setting upload deadlines while sending a message. | +| FMSG_READ_BUFFER_SIZE | 1600 | Bytes. Internal read buffer size per incoming connection | +| FMSG_RETRY_INTERVAL | 20 | Seconds. Minimum time before retrying delivery to a recipient that previously failed. | +| FMSG_RETRY_MAX_AGE | 86400 | Seconds. Maximum age of a message since creation before giving up on delivery retries (default 1 day). | +| FMSG_POLL_INTERVAL | 10 | Seconds. How often the sender polls the database for pending messages. | +| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of outbound deliveries dispatched at once. Each delivery holds one connection from the sender's database pool (32) for the whole exchange, so at most 32 run concurrently; the rest wait for a connection. | +| FMSG_SKIP_DOMAIN_IP_CHECK | false | Set to "true" to skip verifying this host's external IP is in the fmsg DNS authorised IP set on startup. | +| FMSG_SKIP_AUTHORISED_IPS | false | Set to "true" to skip verifying remote hosts IP is in the fmsg DNS authorised IP set during message exchange, and an indicator datagram's source address. WARNING setting this true effectively disables sender verification. | +| FMSG_CHALLENGE_MODE | HAS_NOT_PARTICIPATED | When to issue an automatic CHALLENGE to the sending host. `HAS_NOT_PARTICIPATED` (default): challenge only when the message has no pid, or no message in the thread is from this host's domain. `ALWAYS`: always challenge. `NEVER`: never challenge. | +| FMSG_INDICATORS | true | Set to "false" or "0" to turn off [indicators](#indicators-fmsg-006): fmsgd then neither listens on UDP nor sends indicator datagrams. | + + + +## Quotas and usage + +For each local recipient of a message from another host, fmsgd asks fmsgid for the address's receive limits and usage, and rejects the recipient with `101` (user full) if one more message of this size would exceed its messages per day, size per day or total size (`-1` is unlimited). The size is the stored size: the message body plus every attachment, decompressed. Once the message is stored, fmsgd records that size for each recipient that accepted it with `POST /fmsgid/recv`, timestamped when this host accepted the message (not the sender's timestamp), so a backdated message still counts towards today. fmsgd doesn't record send usage or mail between local addresses: the client that sends and delivers locally (such as fmsg-webapi) does. + +## Indicators (FMSG-006) + +fmsgd implements [FMSG-006 Indicators](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-006-indicators.md): short-lived, single-emoji states such as ✍️ (composing a reply) that a participant shows on a message. They travel host to host as single UDP datagrams on port 4930 (`FMSG_PORT`), at the same address fmsgd listens on for TCP. They are never acknowledged, answered or stored. + +**Receiving.** Each datagram is checked in this order and dropped silently at the first failure: + +1. a per-source-address rate limit (50 datagrams per second, burst 100); +2. the datagram is version 1, exactly its fields with no trailing bytes, and its data is empty (clear) or a single emoji of at most 64 bytes; +3. its hash matches a message this host holds, or one of its add-to batch messages; +4. its index names a participant of that message (from, to, then add to from and add to for a batch message), and that participant is not on this host's domain; +5. the source address is in `fmsg.` of that participant's domain (cached for 60 seconds; skipped with `FMSG_SKIP_AUTHORISED_IPS`). + +The ttl is clamped to 120 seconds and the indicator is published to the client API (see below). + +**Sending.** For an indicator set by a participant on this host's domain, fmsgd sends one datagram to each other participant domain of the message, naming the participant by their lowest index in the message that domain holds: the original message when the domain's participants and the indicating participant are among its from and to, otherwise the first add-to batch message that has both. It sends to one address of `fmsg.` (cached for 60 seconds), alternating between addresses, from the UDP socket it listens on. Rate limits: + +- at most one datagram per participant per message every 2 seconds; more frequent changes are coalesced and only the latest is sent when the interval allows. Clearing (empty) datagrams are sent at once; +- at most 20 datagrams per second to any one receiving domain; the excess is dropped. + +**Client API.** fmsgd and the client API (such as fmsg-webapi) share the PostgreSQL NOTIFY channel `indicator`. Its payload is JSON: + +```json +{"id": 123, "from": "@bob@example.com", "emoji": "✍️", "ttl": 6} +``` + +`id` is this host's `msg.id` of the message, `from` the indicating participant, `emoji` the indicator, or `""` with `ttl` `0` to clear, and `ttl` the seconds it lasts (at most 120). The client API notifies when a local participant sets or clears an indicator, and fmsgd sends it on; fmsgd notifies when it receives and verifies a datagram, and the client API delivers it to connected local participants. fmsgd only sends for addresses on its own domain, so the indicators it publishes are never sent again. + +Firewalls in front of fmsgd need UDP 4930 open inbound and outbound, as well as TCP 4930, for indicators to work. Without it, message exchange is unaffected; indicators are simply lost. + +## Running + +An up and running [fmsg Id API](https://github.com/markmnl/fmsgid) needs to be reachable by fmsgd to know users and their quotas for this fmsgd service. See also [fmsg-docker](https://github.com/markmnl/fmsg-docker) - a docker compose stack for a fmsg host including fmsgid, fmsg-webpi and fmsgd. + +IP address to bind to and listen on is the only argument, `127.0.0.1` is used if argument not supplied. e.g. on Linux: + +``` +./fmsgd "0.0.0.0" +``` + +on Windows: +``` +fmsgd.exe "0.0.0.0" +``` + +### systemd + +An example systemd service to run fmsgd as a service on startup + +ASSUMES: +* Directory `/opt/fmsgd` has been created and contains built executable: `fmsgd` +* Text file `/etc/fmsgd/env` exists containing environment variables (example below) +* User `fmsg` has been created and has + - read and execute permissions to `/opt/fmsgd/`, e.g. with `chown -R fmsg:fmsg /opt/fmsgd` after `mkdir /opt/fmsgd` + - write permissions to FMSG_DATA_DIR + - read permissions to /var/lib/fmsgd/tls +* Directory `/var/lib/fmsgd` has been created and owned by fmsg +* Valid TLS certs (see: [FMSG-001 TCP+TLS Transport and Binding Standard](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-001-transport-and-binding.md#fmsg-001-tcptls-transport-and-binding-standard)) at paths /var/lib/fmsgd/tls/fullchain.pem and /var/lib/fmsgd/tls/privkey.pem + + +`/etc/systemd/system/fmsgd.service` + +``` +[Unit] +Description=fmsg Host +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple + +User=fmsg +Group=fmsg + +EnvironmentFile=/etc/fmsgd/env + +ExecStart=/opt/fmsgd/fmsgd 0.0.0.0 +WorkingDirectory=/opt/fmsgd + +Restart=on-failure +RestartSec=3 + +# --- Filesystem access NOTE location of certs /var/lib/fmsgd/tls--- +ReadOnlyPaths=/var/lib/fmsgd/tls +ReadWritePaths=/opt/fmsgd +ReadWritePaths=/var/lib/fmsgd +PrivateTmp=true + +# --- Hardening --- +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true + +# --- Logging --- +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target +``` + +``` +FMSG_DATA_DIR=/var/lib/fmsgd/ +FMSG_DOMAIN=example.com +FMSG_ID_URL=http://127.0.0.1:8080 + +FMSG_TLS_CERT=/var/lib/fmsgd/tls/fullchain.pem +FMSG_TLS_KEY=/var/lib/fmsgd/tls/privkey.pem + +FMSG_MAX_MSG_SIZE=10240 +FMSG_MAX_PAST_TIME_DELTA=604800 +FMSG_MAX_FUTURE_TIME_DELTA=300 +FMSG_MIN_DOWNLOAD_RATE=5000 +FMSG_MIN_UPLOAD_RATE=5000 +FMSG_READ_BUFFER_SIZE=1600 + +PGHOST=127.0.0.1 +PGPORT=5432 +PGUSER= +PGPASSWORD= +PGDATABASE=fmsgd +``` + +``` +sudo systemctl daemon-reload +sudo systemctl enable fmsgd +sudo systemctl start fmsgd +``` From df748b4bf83d647087c23f9ee9c6f18d3f688eaa Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Wed, 25 Nov 2026 21:27:27 +0800 Subject: [PATCH 5/5] README: restore CRLF line endings changed by the previous commit Co-Authored-By: Claude Fable 5.2 --- README.md | 354 +++++++++++++++++++++++++++--------------------------- 1 file changed, 177 insertions(+), 177 deletions(-) diff --git a/README.md b/README.md index 60bc95c..491134f 100644 --- a/README.md +++ b/README.md @@ -1,177 +1,177 @@ -[![Build & Test](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml/badge.svg?branch=main)](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml?query=branch%3Amain) -[![Go 1.27+](https://img.shields.io/badge/Go-1.27%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/dl/) - -# fmsgd - -Implementation of [fmsg](https://github.com/markmnl/fmsg) host written in Go! Uses local filesystem and PostgreSQL database to store messages. - -## Building from source - -Requires Go 1.27 or newer. - -1. Clone this repository -2. Run `go build ./cmd/fmsgd/` - - -## Environment - -`FMSG_DATA_DIR`, `FMSG_DOMAIN`, `FMSG_ID_URL`, `FMSG_TLS_CERT` and `FMSG_TLS_KEY` are required to be set and valid; otherwise fmsgd will abort on startup. In addition to these `FMSG_` varibles, `PG` variables need to be set for the PostgreSQL database to use, refer to: https://www.postgresql.org/docs/current/libpq-envars.html - -| Variable | Default | Description | -|----------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| FMSG_DATA_DIR | | Path where messages will be stored. e.g. /opt/fmsg/data | -| FMSG_DOMAIN | | Domain name this host is located. e.g. example.com | -| FMSG_ID_URL | | Base HTTP URL for fmsg Id API, e.g. http://localhost:5000 | -| FMSG_TLS_CERT | | Path to TLS certificate file (PEM). Certificate must match `fmsg.`. | -| FMSG_TLS_KEY | | Path to TLS private key file (PEM). | -| FMSG_TLS_INSECURE_SKIP_VERIFY | false | Set to "true" to skip TLS certificate verification on outgoing connections. For development/testing only. | -| FMSG_MAX_MSG_SIZE | 10240 | Bytes. Maximum size above which to reject messages greater than before downloading them. | -| FMSG_PORT | 4930 | TCP port to listen on, and UDP port for [indicators](#indicators-fmsg-006). 4930 is the IANA-registered port for service name `fmsg`. | -| FMSG_MAX_PAST_TIME_DELTA | 604800 | Seconds. Duration since message timestamp to reject if greater than. Note sending host could have been holding messages waiting for us to be reachable. | -| FMSG_MAX_FUTURE_TIME_DELTA | 300 | Seconds. Duration from message timestamp to reject if greater than. | -| FMSG_MIN_DOWNLOAD_RATE | 5000 | Bytes per second. Used in setting download deadlines while downloading a message. | -| FMSG_MIN_UPLOAD_RATE | 5000 | Bytes per second. Used in setting upload deadlines while sending a message. | -| FMSG_READ_BUFFER_SIZE | 1600 | Bytes. Internal read buffer size per incoming connection | -| FMSG_RETRY_INTERVAL | 20 | Seconds. Minimum time before retrying delivery to a recipient that previously failed. | -| FMSG_RETRY_MAX_AGE | 86400 | Seconds. Maximum age of a message since creation before giving up on delivery retries (default 1 day). | -| FMSG_POLL_INTERVAL | 10 | Seconds. How often the sender polls the database for pending messages. | -| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of outbound deliveries dispatched at once. Each delivery holds one connection from the sender's database pool (32) for the whole exchange, so at most 32 run concurrently; the rest wait for a connection. | -| FMSG_SKIP_DOMAIN_IP_CHECK | false | Set to "true" to skip verifying this host's external IP is in the fmsg DNS authorised IP set on startup. | -| FMSG_SKIP_AUTHORISED_IPS | false | Set to "true" to skip verifying remote hosts IP is in the fmsg DNS authorised IP set during message exchange, and an indicator datagram's source address. WARNING setting this true effectively disables sender verification. | -| FMSG_CHALLENGE_MODE | HAS_NOT_PARTICIPATED | When to issue an automatic CHALLENGE to the sending host. `HAS_NOT_PARTICIPATED` (default): challenge only when the message has no pid, or no message in the thread is from this host's domain. `ALWAYS`: always challenge. `NEVER`: never challenge. | -| FMSG_INDICATORS | true | Set to "false" or "0" to turn off [indicators](#indicators-fmsg-006): fmsgd then neither listens on UDP nor sends indicator datagrams. | - - - -## Quotas and usage - -For each local recipient of a message from another host, fmsgd asks fmsgid for the address's receive limits and usage, and rejects the recipient with `101` (user full) if one more message of this size would exceed its messages per day, size per day or total size (`-1` is unlimited). The size is the stored size: the message body plus every attachment, decompressed. Once the message is stored, fmsgd records that size for each recipient that accepted it with `POST /fmsgid/recv`, timestamped when this host accepted the message (not the sender's timestamp), so a backdated message still counts towards today. fmsgd doesn't record send usage or mail between local addresses: the client that sends and delivers locally (such as fmsg-webapi) does. - -## Indicators (FMSG-006) - -fmsgd implements [FMSG-006 Indicators](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-006-indicators.md): short-lived, single-emoji states such as ✍️ (composing a reply) that a participant shows on a message. They travel host to host as single UDP datagrams on port 4930 (`FMSG_PORT`), at the same address fmsgd listens on for TCP. They are never acknowledged, answered or stored. - -**Receiving.** Each datagram is checked in this order and dropped silently at the first failure: - -1. a per-source-address rate limit (50 datagrams per second, burst 100); -2. the datagram is version 1, exactly its fields with no trailing bytes, and its data is empty (clear) or a single emoji of at most 64 bytes; -3. its hash matches a message this host holds, or one of its add-to batch messages; -4. its index names a participant of that message (from, to, then add to from and add to for a batch message), and that participant is not on this host's domain; -5. the source address is in `fmsg.` of that participant's domain (cached for 60 seconds; skipped with `FMSG_SKIP_AUTHORISED_IPS`). - -The ttl is clamped to 120 seconds and the indicator is published to the client API (see below). - -**Sending.** For an indicator set by a participant on this host's domain, fmsgd sends one datagram to each other participant domain of the message, naming the participant by their lowest index in the message that domain holds: the original message when the domain's participants and the indicating participant are among its from and to, otherwise the first add-to batch message that has both. It sends to one address of `fmsg.` (cached for 60 seconds), alternating between addresses, from the UDP socket it listens on. Rate limits: - -- at most one datagram per participant per message every 2 seconds; more frequent changes are coalesced and only the latest is sent when the interval allows. Clearing (empty) datagrams are sent at once; -- at most 20 datagrams per second to any one receiving domain; the excess is dropped. - -**Client API.** fmsgd and the client API (such as fmsg-webapi) share the PostgreSQL NOTIFY channel `indicator`. Its payload is JSON: - -```json -{"id": 123, "from": "@bob@example.com", "emoji": "✍️", "ttl": 6} -``` - -`id` is this host's `msg.id` of the message, `from` the indicating participant, `emoji` the indicator, or `""` with `ttl` `0` to clear, and `ttl` the seconds it lasts (at most 120). The client API notifies when a local participant sets or clears an indicator, and fmsgd sends it on; fmsgd notifies when it receives and verifies a datagram, and the client API delivers it to connected local participants. fmsgd only sends for addresses on its own domain, so the indicators it publishes are never sent again. - -Firewalls in front of fmsgd need UDP 4930 open inbound and outbound, as well as TCP 4930, for indicators to work. Without it, message exchange is unaffected; indicators are simply lost. - -## Running - -An up and running [fmsg Id API](https://github.com/markmnl/fmsgid) needs to be reachable by fmsgd to know users and their quotas for this fmsgd service. See also [fmsg-docker](https://github.com/markmnl/fmsg-docker) - a docker compose stack for a fmsg host including fmsgid, fmsg-webpi and fmsgd. - -IP address to bind to and listen on is the only argument, `127.0.0.1` is used if argument not supplied. e.g. on Linux: - -``` -./fmsgd "0.0.0.0" -``` - -on Windows: -``` -fmsgd.exe "0.0.0.0" -``` - -### systemd - -An example systemd service to run fmsgd as a service on startup - -ASSUMES: -* Directory `/opt/fmsgd` has been created and contains built executable: `fmsgd` -* Text file `/etc/fmsgd/env` exists containing environment variables (example below) -* User `fmsg` has been created and has - - read and execute permissions to `/opt/fmsgd/`, e.g. with `chown -R fmsg:fmsg /opt/fmsgd` after `mkdir /opt/fmsgd` - - write permissions to FMSG_DATA_DIR - - read permissions to /var/lib/fmsgd/tls -* Directory `/var/lib/fmsgd` has been created and owned by fmsg -* Valid TLS certs (see: [FMSG-001 TCP+TLS Transport and Binding Standard](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-001-transport-and-binding.md#fmsg-001-tcptls-transport-and-binding-standard)) at paths /var/lib/fmsgd/tls/fullchain.pem and /var/lib/fmsgd/tls/privkey.pem - - -`/etc/systemd/system/fmsgd.service` - -``` -[Unit] -Description=fmsg Host -After=network-online.target -Wants=network-online.target - -[Service] -Type=simple - -User=fmsg -Group=fmsg - -EnvironmentFile=/etc/fmsgd/env - -ExecStart=/opt/fmsgd/fmsgd 0.0.0.0 -WorkingDirectory=/opt/fmsgd - -Restart=on-failure -RestartSec=3 - -# --- Filesystem access NOTE location of certs /var/lib/fmsgd/tls--- -ReadOnlyPaths=/var/lib/fmsgd/tls -ReadWritePaths=/opt/fmsgd -ReadWritePaths=/var/lib/fmsgd -PrivateTmp=true - -# --- Hardening --- -NoNewPrivileges=true -PrivateTmp=true -ProtectSystem=strict -ProtectHome=true - -# --- Logging --- -StandardOutput=journal -StandardError=journal - -[Install] -WantedBy=multi-user.target -``` - -``` -FMSG_DATA_DIR=/var/lib/fmsgd/ -FMSG_DOMAIN=example.com -FMSG_ID_URL=http://127.0.0.1:8080 - -FMSG_TLS_CERT=/var/lib/fmsgd/tls/fullchain.pem -FMSG_TLS_KEY=/var/lib/fmsgd/tls/privkey.pem - -FMSG_MAX_MSG_SIZE=10240 -FMSG_MAX_PAST_TIME_DELTA=604800 -FMSG_MAX_FUTURE_TIME_DELTA=300 -FMSG_MIN_DOWNLOAD_RATE=5000 -FMSG_MIN_UPLOAD_RATE=5000 -FMSG_READ_BUFFER_SIZE=1600 - -PGHOST=127.0.0.1 -PGPORT=5432 -PGUSER= -PGPASSWORD= -PGDATABASE=fmsgd -``` - -``` -sudo systemctl daemon-reload -sudo systemctl enable fmsgd -sudo systemctl start fmsgd -``` +[![Build & Test](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml/badge.svg?branch=main)](https://github.com/markmnl/fmsgd/actions/workflows/build-test.yml?query=branch%3Amain) +[![Go 1.27+](https://img.shields.io/badge/Go-1.27%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/dl/) + +# fmsgd + +Implementation of [fmsg](https://github.com/markmnl/fmsg) host written in Go! Uses local filesystem and PostgreSQL database to store messages. + +## Building from source + +Requires Go 1.27 or newer. + +1. Clone this repository +2. Run `go build ./cmd/fmsgd/` + + +## Environment + +`FMSG_DATA_DIR`, `FMSG_DOMAIN`, `FMSG_ID_URL`, `FMSG_TLS_CERT` and `FMSG_TLS_KEY` are required to be set and valid; otherwise fmsgd will abort on startup. In addition to these `FMSG_` varibles, `PG` variables need to be set for the PostgreSQL database to use, refer to: https://www.postgresql.org/docs/current/libpq-envars.html + +| Variable | Default | Description | +|----------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------| +| FMSG_DATA_DIR | | Path where messages will be stored. e.g. /opt/fmsg/data | +| FMSG_DOMAIN | | Domain name this host is located. e.g. example.com | +| FMSG_ID_URL | | Base HTTP URL for fmsg Id API, e.g. http://localhost:5000 | +| FMSG_TLS_CERT | | Path to TLS certificate file (PEM). Certificate must match `fmsg.`. | +| FMSG_TLS_KEY | | Path to TLS private key file (PEM). | +| FMSG_TLS_INSECURE_SKIP_VERIFY | false | Set to "true" to skip TLS certificate verification on outgoing connections. For development/testing only. | +| FMSG_MAX_MSG_SIZE | 10240 | Bytes. Maximum size above which to reject messages greater than before downloading them. | +| FMSG_PORT | 4930 | TCP port to listen on, and UDP port for [indicators](#indicators-fmsg-006). 4930 is the IANA-registered port for service name `fmsg`. | +| FMSG_MAX_PAST_TIME_DELTA | 604800 | Seconds. Duration since message timestamp to reject if greater than. Note sending host could have been holding messages waiting for us to be reachable. | +| FMSG_MAX_FUTURE_TIME_DELTA | 300 | Seconds. Duration from message timestamp to reject if greater than. | +| FMSG_MIN_DOWNLOAD_RATE | 5000 | Bytes per second. Used in setting download deadlines while downloading a message. | +| FMSG_MIN_UPLOAD_RATE | 5000 | Bytes per second. Used in setting upload deadlines while sending a message. | +| FMSG_READ_BUFFER_SIZE | 1600 | Bytes. Internal read buffer size per incoming connection | +| FMSG_RETRY_INTERVAL | 20 | Seconds. Minimum time before retrying delivery to a recipient that previously failed. | +| FMSG_RETRY_MAX_AGE | 86400 | Seconds. Maximum age of a message since creation before giving up on delivery retries (default 1 day). | +| FMSG_POLL_INTERVAL | 10 | Seconds. How often the sender polls the database for pending messages. | +| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of outbound deliveries dispatched at once. Each delivery holds one connection from the sender's database pool (32) for the whole exchange, so at most 32 run concurrently; the rest wait for a connection. | +| FMSG_SKIP_DOMAIN_IP_CHECK | false | Set to "true" to skip verifying this host's external IP is in the fmsg DNS authorised IP set on startup. | +| FMSG_SKIP_AUTHORISED_IPS | false | Set to "true" to skip verifying remote hosts IP is in the fmsg DNS authorised IP set during message exchange, and an indicator datagram's source address. WARNING setting this true effectively disables sender verification. | +| FMSG_CHALLENGE_MODE | HAS_NOT_PARTICIPATED | When to issue an automatic CHALLENGE to the sending host. `HAS_NOT_PARTICIPATED` (default): challenge only when the message has no pid, or no message in the thread is from this host's domain. `ALWAYS`: always challenge. `NEVER`: never challenge. | +| FMSG_INDICATORS | true | Set to "false" or "0" to turn off [indicators](#indicators-fmsg-006): fmsgd then neither listens on UDP nor sends indicator datagrams. | + + + +## Quotas and usage + +For each local recipient of a message from another host, fmsgd asks fmsgid for the address's receive limits and usage, and rejects the recipient with `101` (user full) if one more message of this size would exceed its messages per day, size per day or total size (`-1` is unlimited). The size is the stored size: the message body plus every attachment, decompressed. Once the message is stored, fmsgd records that size for each recipient that accepted it with `POST /fmsgid/recv`, timestamped when this host accepted the message (not the sender's timestamp), so a backdated message still counts towards today. fmsgd doesn't record send usage or mail between local addresses: the client that sends and delivers locally (such as fmsg-webapi) does. + +## Indicators (FMSG-006) + +fmsgd implements [FMSG-006 Indicators](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-006-indicators.md): short-lived, single-emoji states such as ✍️ (composing a reply) that a participant shows on a message. They travel host to host as single UDP datagrams on port 4930 (`FMSG_PORT`), at the same address fmsgd listens on for TCP. They are never acknowledged, answered or stored. + +**Receiving.** Each datagram is checked in this order and dropped silently at the first failure: + +1. a per-source-address rate limit (50 datagrams per second, burst 100); +2. the datagram is version 1, exactly its fields with no trailing bytes, and its data is empty (clear) or a single emoji of at most 64 bytes; +3. its hash matches a message this host holds, or one of its add-to batch messages; +4. its index names a participant of that message (from, to, then add to from and add to for a batch message), and that participant is not on this host's domain; +5. the source address is in `fmsg.` of that participant's domain (cached for 60 seconds; skipped with `FMSG_SKIP_AUTHORISED_IPS`). + +The ttl is clamped to 120 seconds and the indicator is published to the client API (see below). + +**Sending.** For an indicator set by a participant on this host's domain, fmsgd sends one datagram to each other participant domain of the message, naming the participant by their lowest index in the message that domain holds: the original message when the domain's participants and the indicating participant are among its from and to, otherwise the first add-to batch message that has both. It sends to one address of `fmsg.` (cached for 60 seconds), alternating between addresses, from the UDP socket it listens on. Rate limits: + +- at most one datagram per participant per message every 2 seconds; more frequent changes are coalesced and only the latest is sent when the interval allows. Clearing (empty) datagrams are sent at once; +- at most 20 datagrams per second to any one receiving domain; the excess is dropped. + +**Client API.** fmsgd and the client API (such as fmsg-webapi) share the PostgreSQL NOTIFY channel `indicator`. Its payload is JSON: + +```json +{"id": 123, "from": "@bob@example.com", "emoji": "✍️", "ttl": 6} +``` + +`id` is this host's `msg.id` of the message, `from` the indicating participant, `emoji` the indicator, or `""` with `ttl` `0` to clear, and `ttl` the seconds it lasts (at most 120). The client API notifies when a local participant sets or clears an indicator, and fmsgd sends it on; fmsgd notifies when it receives and verifies a datagram, and the client API delivers it to connected local participants. fmsgd only sends for addresses on its own domain, so the indicators it publishes are never sent again. + +Firewalls in front of fmsgd need UDP 4930 open inbound and outbound, as well as TCP 4930, for indicators to work. Without it, message exchange is unaffected; indicators are simply lost. + +## Running + +An up and running [fmsg Id API](https://github.com/markmnl/fmsgid) needs to be reachable by fmsgd to know users and their quotas for this fmsgd service. See also [fmsg-docker](https://github.com/markmnl/fmsg-docker) - a docker compose stack for a fmsg host including fmsgid, fmsg-webpi and fmsgd. + +IP address to bind to and listen on is the only argument, `127.0.0.1` is used if argument not supplied. e.g. on Linux: + +``` +./fmsgd "0.0.0.0" +``` + +on Windows: +``` +fmsgd.exe "0.0.0.0" +``` + +### systemd + +An example systemd service to run fmsgd as a service on startup + +ASSUMES: +* Directory `/opt/fmsgd` has been created and contains built executable: `fmsgd` +* Text file `/etc/fmsgd/env` exists containing environment variables (example below) +* User `fmsg` has been created and has + - read and execute permissions to `/opt/fmsgd/`, e.g. with `chown -R fmsg:fmsg /opt/fmsgd` after `mkdir /opt/fmsgd` + - write permissions to FMSG_DATA_DIR + - read permissions to /var/lib/fmsgd/tls +* Directory `/var/lib/fmsgd` has been created and owned by fmsg +* Valid TLS certs (see: [FMSG-001 TCP+TLS Transport and Binding Standard](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-001-transport-and-binding.md#fmsg-001-tcptls-transport-and-binding-standard)) at paths /var/lib/fmsgd/tls/fullchain.pem and /var/lib/fmsgd/tls/privkey.pem + + +`/etc/systemd/system/fmsgd.service` + +``` +[Unit] +Description=fmsg Host +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple + +User=fmsg +Group=fmsg + +EnvironmentFile=/etc/fmsgd/env + +ExecStart=/opt/fmsgd/fmsgd 0.0.0.0 +WorkingDirectory=/opt/fmsgd + +Restart=on-failure +RestartSec=3 + +# --- Filesystem access NOTE location of certs /var/lib/fmsgd/tls--- +ReadOnlyPaths=/var/lib/fmsgd/tls +ReadWritePaths=/opt/fmsgd +ReadWritePaths=/var/lib/fmsgd +PrivateTmp=true + +# --- Hardening --- +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true + +# --- Logging --- +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target +``` + +``` +FMSG_DATA_DIR=/var/lib/fmsgd/ +FMSG_DOMAIN=example.com +FMSG_ID_URL=http://127.0.0.1:8080 + +FMSG_TLS_CERT=/var/lib/fmsgd/tls/fullchain.pem +FMSG_TLS_KEY=/var/lib/fmsgd/tls/privkey.pem + +FMSG_MAX_MSG_SIZE=10240 +FMSG_MAX_PAST_TIME_DELTA=604800 +FMSG_MAX_FUTURE_TIME_DELTA=300 +FMSG_MIN_DOWNLOAD_RATE=5000 +FMSG_MIN_UPLOAD_RATE=5000 +FMSG_READ_BUFFER_SIZE=1600 + +PGHOST=127.0.0.1 +PGPORT=5432 +PGUSER= +PGPASSWORD= +PGDATABASE=fmsgd +``` + +``` +sudo systemctl daemon-reload +sudo systemctl enable fmsgd +sudo systemctl start fmsgd +```