Skip to content

Harden wire/zlib parsing, fix delivery/storage bugs, and share DB pool - #54

Open
markmnl wants to merge 1 commit into
mainfrom
review/perf-and-reliability
Open

markmnl wants to merge 1 commit into
mainfrom
review/perf-and-reliability

Conversation

@markmnl

@markmnl markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Summary

High-impact security, correctness, performance, and maintainability improvements from a Go code review (strictly preserving SPEC.md wire conformance and existing dd.sql schema):

Security & Protocol Correctness

  • Bound zlib decompression & fix integer overflows (pkg/fmsg/fmsg.go, pkg/fmsg/deflate.go, cmd/fmsgd/host.go): Wrap zlib.Reader in io.LimitReader(zr, int64(expandedSize)+1), remove uint32 truncation on written byte counts, check zr.Close(), accumulate attachment sizes in uint64 to prevent uint32 wrap bypassing MAX_SIZE/MAX_EXPANDED_SIZE, and use int64 in deflate.go's compression ratio check.
  • Fix wire read panics, silent truncation, and socket leaks (cmd/fmsgd/host.go, pkg/fmsg/prepare.go): Use io.ReadFull into exact-sized buffers in handleChallenge, ReadUInt8Slice, readHeader pid, and challenge; close connections on recovered panics in handleConn; send RejectCodeInvalid on duplicate to and add-to attachment count mismatch; add cycle/depth bounds to isMessageRetrievable; deep-copy AddToFrom and StoredWire in Header.Clone().
  • Fix delivery and storage bugs (cmd/fmsgd/sender.go, cmd/fmsgd/store.go, cmd/fmsgd/host.go):
    • Filter msg_add_to updates by batch_id (preventing sibling batches from overwriting each other) and propagate tx.Exec errors.
    • Only mark isLocked for recipient entries matching the unit's table (msg_to vs msg_add_to) so addresses in both To and AddTo aren't double-updated.
    • Pass localOutcome into attachAddToRecipients and use strings.EqualFold for local domain matching.
    • Defer mutating h.Attachments[i].Filepath until all copies succeed, skip persistAttachmentPayloads on skipData, deduplicate accepted local addresses before file copies and quota recording, and replace TOCTOU os.Stat+os.Create loops with atomic O_CREATE|O_EXCL.
  • Timeouts, connection leaks, DNSSEC, and shutdown (cmd/fmsgd/host.go, id.go, dns.go, sender.go): Add dial/IO deadlines and defer conn2.Close() in challenge; unwrap *tls.Conn in abortConn; include attachment sizes in upload/download deadlines and set header write deadlines; use a dedicated pooled http.Client with timeout, non-200 rejection, and body draining in id.go; add resolver timeouts, reuse *dns.Client, and verify DNSSEC AD records directly in dns.go; add SIGINT/SIGTERM graceful shutdown and accept-error backoff in main.

Performance

  • Shared *sql.DB pool (cmd/fmsgd/store.go, sender.go, indicators.go): Replace per-query sql.Open/defer db.Close() with a single shared connection pool.
  • Eliminate redundant disk hashing & dispatch storms (pkg/fmsg/prepare.go, pkg/message/store.go, cmd/fmsgd/sender.go, store.go, indicators.go): Export fmsg.UnmarshalPreparedHeader for header-only reads, skip unused queries & double hashing in FinalizeBatch, track in-flight pendingTarget keys in processPendingMessages, defer UnmarshalPrepared in deliverUnit until pending rows are locked, compress directly to a temp file in destination dir in preparePart, and pool zlib.Writer via sync.Pool in pkg/fmsg/deflate.go.
  • Indicators & hot-path allocations (cmd/fmsgd/indicators.go, pkg/fmsg/fmsg.go, cmd/fmsgd/host.go): Gate sourceLimiter and ipCache full-map pruning at >= 1s, compute ipCache TTL after lookup, remove redundant 3rd DB query in subjectsOf, optimize Header.Encode()/Address.ToString()/GetCommonMediaTypeID/GetMessageHash, batch N+1 duplicate hash lookups, replace time.After in select loops with reusable timers, and deduplicate readMediaType / addrEqualFold.

Testing

  • Added unit tests covering zlib bombs, uint32 attachment size overflow, truncated challenge/slice reads, duplicate to/add-to attachment mismatch codes, cycle detection, atomic uniqueFilepath, id.go 5xx handling, Header.Clone(), UnmarshalPreparedHeader, sourceLimiter/ipCache behavior, deliverUnit To ∩ AddTo locking, and DNSSEC validation.
  • Verified with go vet ./..., go build ./..., and go test -race -count=1 ./....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant