From 8303c0566b75b7169302248cf71fd12901291f6b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 12:55:03 +0000 Subject: [PATCH 1/5] Mail kept once, with each user's entries and virtual folders The mail table keeps a message once; mailbox gives its recipient and sender entries of their own (read, starred, trash), and mail_uids its places in the Inbox, Sent, Drafts, Starred, Unread, All Mail and Trash folders, numbered so that numbers only grow in a folder (IMAP's UIDs). An older database's mail goes in its recipients' inboxes. Deleting mail now puts it in the trash. mail_queue holds mail for addresses elsewhere. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRVPRbt1YgtG7eQJZxD --- go.mod | 6 + go.sum | 43 ++ internal/store/copy.go | 2 +- internal/store/dialect.go | 4 + internal/store/mailbox.go | 733 +++++++++++++++++++++++++++++++++ internal/store/mailbox_test.go | 208 ++++++++++ internal/store/schema.go | 55 ++- internal/store/store.go | 81 +--- 8 files changed, 1058 insertions(+), 74 deletions(-) create mode 100644 internal/store/mailbox.go create mode 100644 internal/store/mailbox_test.go diff --git a/go.mod b/go.mod index 8236333..ca35359 100644 --- a/go.mod +++ b/go.mod @@ -25,9 +25,15 @@ require ( ) require ( + blitiri.com.ar/go/spf v1.5.1 // indirect filippo.io/edwards25519 v1.1.0 // indirect github.com/dlclark/regexp2 v1.11.4 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/emersion/go-imap/v2 v2.0.0-beta.8 // indirect + github.com/emersion/go-message v0.18.2 // indirect + github.com/emersion/go-msgauth v0.7.0 // indirect + github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirect + github.com/emersion/go-smtp v0.25.1 // indirect github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd // indirect github.com/google/uuid v1.6.0 // indirect diff --git a/go.sum b/go.sum index 85fa509..08f7e7c 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +blitiri.com.ar/go/spf v1.5.1 h1:CWUEasc44OrANJD8CzceRnRn1Jv0LttY68cYym2/pbE= +blitiri.com.ar/go/spf v1.5.1/go.mod h1:E71N92TfL4+Yyd5lpKuE9CAF2pd4JrUq1xQfkTxoNdk= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38 h1:fHnFrNziFJicoB5eZsBdrKHVgG5/WPV1NWZJ1CD1g7A= @@ -17,6 +19,16 @@ github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7 h1:g7JYcX9Y5RNJhrqpC/N github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/emersion/go-imap/v2 v2.0.0-beta.8 h1:5IXZK1E33DyeP526320J3RS7eFlCYGFgtbrfapqDPug= +github.com/emersion/go-imap/v2 v2.0.0-beta.8/go.mod h1:dhoFe2Q0PwLrMD7oZw8ODuaD0vLYPe5uj2wcOMnvh48= +github.com/emersion/go-message v0.18.2 h1:rl55SQdjd9oJcIoQNhubD2Acs1E6IzlZISRTK7x/Lpg= +github.com/emersion/go-message v0.18.2/go.mod h1:XpJyL70LwRvq2a8rVbHXikPgKj8+aI0kGdHlg16ibYA= +github.com/emersion/go-msgauth v0.7.0 h1:vj2hMn6KhFtW41kshIBTXvp6KgYSqpA/ZN9Pv4g1INc= +github.com/emersion/go-msgauth v0.7.0/go.mod h1:mmS9I6HkSovrNgq0HNXTeu8l3sRAAuQ9RMvbM4KU7Ck= +github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 h1:oP4q0fw+fOSWn3DfFi4EXdT+B+gTtzx8GC9xsc26Znk= +github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6/go.mod h1:iL2twTeMvZnrg54ZoPDNfJaJaqy0xIQFuBdrLsmspwQ= +github.com/emersion/go-smtp v0.25.1 h1:y6nzefT6PtFeMItFw97GX/ZCkVbh0rqSXG8b3ang8/w= +github.com/emersion/go-smtp v0.25.1/go.mod h1:ZtRRkbTyp2XTHCA+BmyTFTrj8xY4I+b4McvHxCU2gsQ= github.com/ergochat/irc-go v0.7.0 h1:IYaATcjiPRlPcmn8F63Sgb4ulvvmCif/adeKHnk2B3g= github.com/ergochat/irc-go v0.7.0/go.mod h1:2vi7KNpIPWnReB5hmLpl92eMywQvuIeIIGdt/FQCph0= github.com/fclairamb/ftpserverlib v0.30.0 h1:caB9sDn1Au//q0j2ev/icPn388qPuk4k1ajSvglDcMQ= @@ -64,23 +76,54 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68= golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg= golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= diff --git a/internal/store/copy.go b/internal/store/copy.go index c5c031d..fc00b06 100644 --- a/internal/store/copy.go +++ b/internal/store/copy.go @@ -11,7 +11,7 @@ import ( ) // copyOrder is the tables in an order their references allow. -var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "file_areas", "files", +var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "mailbox", "mail_uids", "mail_queue", "file_areas", "files", "history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read", "fido_subs", "chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag"} diff --git a/internal/store/dialect.go b/internal/store/dialect.go index 49d5681..cfb2d59 100644 --- a/internal/store/dialect.go +++ b/internal/store/dialect.go @@ -205,6 +205,10 @@ func (t *tx) Exec(q string, args ...any) (sql.Result, error) { } // QueryRow is sql.Tx's, the statement made the engine's. +func (t *tx) Query(q string, args ...any) (*sql.Rows, error) { + return t.Tx.Query(t.d.query(q), args...) +} + func (t *tx) QueryRow(q string, args ...any) *sql.Row { return t.Tx.QueryRow(t.d.query(q), args...) } diff --git a/internal/store/mailbox.go b/internal/store/mailbox.go new file mode 100644 index 0000000..1ed5c38 --- /dev/null +++ b/internal/store/mailbox.go @@ -0,0 +1,733 @@ +package store + +import ( + "database/sql" + "errors" + "fmt" + "strings" + "time" +) + +// A private mail is kept once, in mail; each user who has it has an entry +// in mailbox: its recipient, its sender (their Sent copy), or its writer +// (a draft), each with their own read and starred flags and their own +// trash. The folders are views over a user's entries, chosen by those +// flags; an entry's place in each folder it is in has a number (mail_uids: +// IMAP's UIDs), new each time it comes into that folder, so that numbers +// only grow in a folder. + +// The folders. +const ( + FolderInbox = iota // mail to the user + FolderSent // mail from the user + FolderDrafts // mail the user has not sent + FolderStarred // mail the user starred + FolderUnread // mail to the user not yet read + FolderAll // every mail, but drafts and the trash + FolderTrash // mail the user deleted, kept a while + NumFolders +) + +// FolderNames are the folders' names, as IMAP lists them. +var FolderNames = [NumFolders]string{"INBOX", "Sent", "Drafts", "Starred", "Unread", "All Mail", "Trash"} + +// FolderByName is the folder of a name (in any case), or -1. +func FolderByName(name string) int { + for i, n := range FolderNames { + if strings.EqualFold(n, name) { + return i + } + } + if strings.EqualFold(name, "Inbox") { + return FolderInbox + } + return -1 +} + +// The roles of an entry: what the mail is to its user. +const ( + RoleReceived = 0 + RoleSent = 1 + RoleDraft = 2 +) + +// inFolders is which folders an entry of that state is in. +func inFolders(role int, read, starred bool, deleted int64) [NumFolders]bool { + var in [NumFolders]bool + if deleted > 0 { + in[FolderTrash] = true + return in + } + in[FolderInbox] = role == RoleReceived + in[FolderSent] = role == RoleSent + in[FolderDrafts] = role == RoleDraft + in[FolderStarred] = starred + in[FolderUnread] = role == RoleReceived && !read + in[FolderAll] = role != RoleDraft + return in +} + +// querier is the database or a transaction. +type querier interface { + Exec(q string, args ...any) (sql.Result, error) + Query(q string, args ...any) (*sql.Rows, error) + QueryRow(q string, args ...any) *sql.Row + insertID(q string, args ...any) (int64, error) +} + +// fillMailboxes gives each mail of a database from before the mailboxes +// an entry for its recipient, and that entry its places in the folders. +func fillMailboxes(x *db) error { + if _, err := x.Exec(`INSERT INTO mailbox (user_id, mail_id, role, "read", created) + SELECT to_id, id, 0, "read", created FROM mail ORDER BY id`); err != nil { + return err + } + rows, err := x.Query(`SELECT id, user_id, role, "read", starred, deleted FROM mailbox ORDER BY id`) + if err != nil { + return err + } + type entry struct { + id, user, deleted int64 + role int + read, starred bool + } + var es []entry + for rows.Next() { + var e entry + if err := rows.Scan(&e.id, &e.user, &e.role, &e.read, &e.starred, &e.deleted); err != nil { + rows.Close() + return err + } + es = append(es, e) + } + rows.Close() + if err := rows.Err(); err != nil { + return err + } + for _, e := range es { + in := inFolders(e.role, e.read, e.starred, e.deleted) + for f, ok := range in { + if ok { + if _, err := x.Exec(`INSERT INTO mail_uids (user_id, folder, box_id) VALUES (?, ?, ?)`, e.user, f, e.id); err != nil { + return err + } + } + } + } + return nil +} + +// syncBox puts an entry in the folders its state says, and takes it out +// of the others. +func syncBox(q querier, box int64) error { + var user, deleted int64 + var role int + var read, starred bool + err := q.QueryRow(`SELECT user_id, role, "read", starred, deleted FROM mailbox WHERE id = ?`, box). + Scan(&user, &role, &read, &starred, &deleted) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + return err + } + want := inFolders(role, read, starred, deleted) + rows, err := q.Query(`SELECT folder FROM mail_uids WHERE box_id = ?`, box) + if err != nil { + return err + } + var have [NumFolders]bool + for rows.Next() { + var f int + if err := rows.Scan(&f); err != nil { + rows.Close() + return err + } + if f >= 0 && f < NumFolders { + have[f] = true + } + } + rows.Close() + if err := rows.Err(); err != nil { + return err + } + for f := range want { + switch { + case want[f] && !have[f]: + if _, err := q.Exec(`INSERT OR IGNORE INTO mail_uids (user_id, folder, box_id) VALUES (?, ?, ?)`, user, f, box); err != nil { + return err + } + case !want[f] && have[f]: + if _, err := q.Exec(`DELETE FROM mail_uids WHERE box_id = ? AND folder = ?`, box, f); err != nil { + return err + } + } + } + return nil +} + +// addBox gives user an entry for a mail. +func addBox(q querier, user, mail int64, role int, read, starred bool, deleted int64) (int64, error) { + id, err := q.insertID(`INSERT INTO mailbox (user_id, mail_id, role, "read", starred, deleted, created) + VALUES (?, ?, ?, ?, ?, ?, ?)`, user, mail, role, read, starred, deleted, now()) + if err != nil { + return 0, err + } + return id, syncBox(q, id) +} + +// gcMail deletes a mail no one has any more, and that is not waiting to +// be sent. +func gcMail(q querier, mail int64) error { + _, err := q.Exec(`DELETE FROM mail WHERE id = ? AND NOT EXISTS (SELECT 1 FROM mailbox WHERE mail_id = ?) + AND NOT EXISTS (SELECT 1 FROM mail_queue WHERE mail_id = ?)`, mail, mail, mail) + return err +} + +// Outbound is a mail waiting to go to an address elsewhere. +type Outbound struct { + ID int64 + MailID int64 + UserID int64 // who sent it (0: the system, a bounce) + Sender string // the envelope's sender ("": a bounce, <>) + Rcpt string + Attempts int + NextTry time.Time + LastError string + Created time.Time +} + +// Delivery is what a new mail is given to. +type Delivery struct { + To []int64 // users here it is for + Sent bool // the sender (m.FromID) keeps a copy in Sent + Draft bool // it is the sender's draft: not sent + Read bool // the recipients' entries are read already + Queue []*Outbound +} + +// DeliverMail keeps a new mail and gives it to its users, and puts it in +// the queue for the addresses elsewhere, all at once: its id. The mail's +// ToID is its first recipient here, or else its sender. +func (s *Store) DeliverMail(m *Message, d Delivery) (int64, error) { + if m.ToID <= 0 { + switch { + case len(d.To) > 0: + m.ToID = d.To[0] + case m.FromID > 0: + m.ToID = m.FromID + default: + return 0, errors.New("mail for no one") + } + } + if m.Created.IsZero() { + m.Created = time.Now() + } + t, err := s.db.Begin() + if err != nil { + return 0, err + } + defer t.Rollback() + id, err := t.insertID(`INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, reply_to, created, + ftn_msgid, raw, message_id, from_addr, to_addr) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.FromID, m.From, m.ToID, m.To, m.Subject, m.Body, m.ReplyTo, + m.Created.Unix(), nullString(m.FTNMsgID), m.Raw, nullString(m.MessageID), m.FromAddr, m.ToAddr) + if err != nil { + return 0, err + } + if d.Draft { + if _, err := addBox(t, m.FromID, id, RoleDraft, true, false, 0); err != nil { + return 0, err + } + } else { + seen := map[int64]bool{} + for _, u := range d.To { + if u <= 0 || seen[u] { + continue + } + seen[u] = true + if _, err := addBox(t, u, id, RoleReceived, d.Read, false, 0); err != nil { + return 0, err + } + } + if d.Sent && m.FromID > 0 { + if _, err := addBox(t, m.FromID, id, RoleSent, true, false, 0); err != nil { + return 0, err + } + } + } + for _, o := range d.Queue { + if _, err := t.Exec(`INSERT INTO mail_queue (mail_id, user_id, sender, rcpt, next_try, created) + VALUES (?, ?, ?, ?, ?, ?)`, id, o.UserID, o.Sender, o.Rcpt, now(), now()); err != nil { + return 0, err + } + } + if err := t.Commit(); err != nil { + return 0, err + } + m.ID = id + return id, nil +} + +// SendMail delivers a private message to its recipient (ToID), the sender +// (FromID, if a user here) keeping a copy in Sent. +func (s *Store) SendMail(m *Message) (int64, error) { + if m.ToID <= 0 { + return 0, errors.New("mail for no one") + } + return s.DeliverMail(m, Delivery{To: []int64{m.ToID}, Sent: m.FromID > 0}) +} + +// mailCols are a mailbox entry (b) and its mail (m). +const mailCols = `b.id, b."read", b.starred, m.id, m.from_id, m.from_name, m.to_id, m.to_name, m.subject, m.body, + m.reply_to, m.created, COALESCE(m.ftn_msgid, ''), COALESCE(m.message_id, ''), m.from_addr, m.to_addr` + +// scanMail is the mail in a row of mailCols; ErrNotFound if there is none. +func scanMail(row interface{ Scan(...any) error }, extra ...any) (*Message, error) { + var m Message + var created int64 + err := row.Scan(append([]any{&m.Box, &m.Read, &m.Starred, &m.ID, &m.FromID, &m.From, &m.ToID, &m.To, + &m.Subject, &m.Body, &m.ReplyTo, &created, &m.FTNMsgID, &m.MessageID, &m.FromAddr, &m.ToAddr}, extra...)...) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err // nothing half scanned + } + m.Created = unix(created) + return &m, nil +} + +// mailList is the mail a query of mailCols finds. +func (s *Store) mailList(q string, args ...any) ([]*Message, error) { + rows, err := s.db.Query(q, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Message + for rows.Next() { + m, err := scanMail(rows) + if err != nil { + return nil, err + } + out = append(out, m) + } + return out, rows.Err() +} + +// Inbox lists a user's mail in the Inbox, oldest first. +func (s *Store) Inbox(user int64) ([]*Message, error) { + return s.Folder(user, FolderInbox) +} + +// Folder lists a user's mail in a folder, oldest first. +func (s *Store) Folder(user int64, folder int) ([]*Message, error) { + return s.mailList(`SELECT `+mailCols+` FROM mail_uids u JOIN mailbox b ON b.id = u.box_id JOIN mail m ON m.id = b.mail_id + WHERE u.user_id = ? AND u.folder = ? ORDER BY m.created, m.id`, user, folder) +} + +// Mail finds a mail of user's by id, one they received and have not +// deleted: no one reads another's mail. +func (s *Store) Mail(user, id int64) (*Message, error) { + return scanMail(s.db.QueryRow(`SELECT `+mailCols+` FROM mailbox b JOIN mail m ON m.id = b.mail_id + WHERE b.user_id = ? AND b.mail_id = ? AND b.role = ? AND b.deleted = 0 ORDER BY b.id LIMIT 1`, user, id, RoleReceived)) +} + +// boxesOf is the user's received entries for a mail, not in the trash. +func boxesOf(q querier, user, mail int64) ([]int64, error) { + rows, err := q.Query(`SELECT id FROM mailbox WHERE user_id = ? AND mail_id = ? AND role = ? AND deleted = 0`, + user, mail, RoleReceived) + if err != nil { + return nil, err + } + defer rows.Close() + var out []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + if err := rows.Err(); err != nil { + return nil, err + } + if len(out) == 0 { + return nil, ErrNotFound + } + return out, nil +} + +// onReceived changes the user's received entries for a mail, in one go. +func (s *Store) onReceived(user, mail int64, stmt string, args ...any) error { + t, err := s.db.Begin() + if err != nil { + return err + } + defer t.Rollback() + boxes, err := boxesOf(t, user, mail) + if err != nil { + return err + } + for _, b := range boxes { + if _, err := t.Exec(stmt, append(args, b)...); err != nil { + return err + } + if err := syncBox(t, b); err != nil { + return err + } + } + return t.Commit() +} + +// MarkMailRead marks a mail of user's read. +func (s *Store) MarkMailRead(user, id int64) error { + return s.onReceived(user, id, `UPDATE mailbox SET "read" = TRUE WHERE id = ?`) +} + +// DeleteMail puts a mail of user's in their trash. +func (s *Store) DeleteMail(user, id int64) error { + return s.onReceived(user, id, `UPDATE mailbox SET deleted = ? WHERE id = ?`, now()) +} + +// StarMail stars, or unstars, a mail the user received. +func (s *Store) StarMail(user, id int64, on bool) error { + return s.onReceived(user, id, `UPDATE mailbox SET starred = ? WHERE id = ?`, on) +} + +// UnreadMail counts a user's unread mail. +func (s *Store) UnreadMail(user int64) (int, error) { + var n int + err := s.db.QueryRow(`SELECT COUNT(*) FROM mailbox WHERE user_id = ? AND role = ? AND "read" = FALSE AND deleted = 0`, + user, RoleReceived).Scan(&n) + return n, err +} + +// BoxEntry is a mail's place in a folder: what IMAP and POP3 list. +type BoxEntry struct { + UID int64 // its number in the folder + Box int64 // the mailbox entry + MailID int64 + Role int + Read bool + Starred bool + Deleted time.Time // when it was put in the trash (zero: it is not) + Flags string // IMAP's other flags, space-separated + Created time.Time // when the mail was written or came + Size int64 // its raw form's (0: written here, it has none) +} + +// FolderEntries lists a folder of the user's, by its numbers. +func (s *Store) FolderEntries(user int64, folder int) ([]*BoxEntry, error) { + rows, err := s.db.Query(`SELECT u.id, b.id, b.mail_id, b.role, b."read", b.starred, b.deleted, b.flags, m.created, + COALESCE(LENGTH(m.raw), 0) + FROM mail_uids u JOIN mailbox b ON b.id = u.box_id JOIN mail m ON m.id = b.mail_id + WHERE u.user_id = ? AND u.folder = ? ORDER BY u.id`, user, folder) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*BoxEntry + for rows.Next() { + var e BoxEntry + var deleted, created int64 + if err := rows.Scan(&e.UID, &e.Box, &e.MailID, &e.Role, &e.Read, &e.Starred, &deleted, &e.Flags, &created, &e.Size); err != nil { + return nil, err + } + e.Deleted, e.Created = unix(deleted), unix(created) + out = append(out, &e) + } + return out, rows.Err() +} + +// MailUIDNext is the least number a mail coming into any folder now could +// have. +func (s *Store) MailUIDNext() (int64, error) { + var n int64 + err := s.db.QueryRow(`SELECT COALESCE(MAX(id), 0) + 1 FROM mail_uids`).Scan(&n) + return n, err +} + +// BoxUID is an entry's number in a folder; ErrNotFound if it is not there. +func (s *Store) BoxUID(box int64, folder int) (int64, error) { + var n int64 + err := s.db.QueryRow(`SELECT id FROM mail_uids WHERE box_id = ? AND folder = ?`, box, folder).Scan(&n) + if errors.Is(err, sql.ErrNoRows) { + return 0, ErrNotFound + } + return n, err +} + +// rawScan is a raw column scanned, whatever the driver gives. +type rawScan []byte + +func (r *rawScan) Scan(v any) error { + switch b := v.(type) { + case nil: + *r = nil + case []byte: + *r = append([]byte(nil), b...) + case string: + *r = []byte(b) + default: + return fmt.Errorf("raw: %T", v) + } + return nil +} + +// BoxMail is the mail of a user's entry, its raw form too (nil if written +// here), and the entry. +func (s *Store) BoxMail(user, box int64) (*Message, *BoxEntry, error) { + var e BoxEntry + var deleted int64 + var raw rawScan + m, err := scanMail(s.db.QueryRow(`SELECT `+mailCols+`, m.raw, b.role, b.deleted, b.flags FROM mailbox b JOIN mail m ON m.id = b.mail_id + WHERE b.id = ? AND b.user_id = ?`, box, user), &raw, &e.Role, &deleted, &e.Flags) + if err != nil { + return nil, nil, err + } + m.Raw = raw + e.Box, e.MailID, e.Read, e.Starred, e.Deleted, e.Created, e.Size = m.Box, m.ID, m.Read, m.Starred, unix(deleted), m.Created, int64(len(raw)) + return m, &e, nil +} + +// changeBox runs stmt (its last argument the entry) on a user's entry, +// and puts the entry where it now belongs. +func (s *Store) changeBox(user, box int64, stmt string, args ...any) error { + t, err := s.db.Begin() + if err != nil { + return err + } + defer t.Rollback() + res, err := t.Exec(stmt+` AND user_id = ?`, append(args, box, user)...) + if err != nil { + return err + } + if n, _ := res.RowsAffected(); n == 0 { + // MySQL counts rows changed, not found: is it there? + var one int + if err := t.QueryRow(`SELECT 1 FROM mailbox WHERE id = ? AND user_id = ?`, box, user).Scan(&one); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + } + if err := syncBox(t, box); err != nil { + return err + } + return t.Commit() +} + +// SetBoxFlags sets an entry's read and starred flags, and its others. +func (s *Store) SetBoxFlags(user, box int64, read, starred bool, flags string) error { + return s.changeBox(user, box, `UPDATE mailbox SET "read" = ?, starred = ?, flags = ? WHERE id = ?`, read, starred, flags) +} + +// TrashBox puts an entry in the trash. +func (s *Store) TrashBox(user, box int64) error { + return s.changeBox(user, box, `UPDATE mailbox SET deleted = ? WHERE deleted = 0 AND id = ?`, now()) +} + +// RestoreBox takes an entry out of the trash. +func (s *Store) RestoreBox(user, box int64) error { + return s.changeBox(user, box, `UPDATE mailbox SET deleted = 0 WHERE id = ?`) +} + +// PurgeBox deletes an entry for good (and its mail, if no one else has it). +func (s *Store) PurgeBox(user, box int64) error { + t, err := s.db.Begin() + if err != nil { + return err + } + defer t.Rollback() + var mail int64 + err = t.QueryRow(`SELECT mail_id FROM mailbox WHERE id = ? AND user_id = ?`, box, user).Scan(&mail) + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return err + } + if _, err := t.Exec(`DELETE FROM mail_uids WHERE box_id = ?`, box); err != nil { + return err + } + if _, err := t.Exec(`DELETE FROM mailbox WHERE id = ?`, box); err != nil { + return err + } + if err := gcMail(t, mail); err != nil { + return err + } + return t.Commit() +} + +// AppendMail keeps a mail a user put in a folder of theirs (IMAP's +// APPEND): as received, sent or a draft, in the trash if deleted. The +// new entry. +func (s *Store) AppendMail(user int64, role int, m *Message, read, starred, deleted bool, flags string) (int64, error) { + if m.ToID <= 0 { + m.ToID = user + } + if m.Created.IsZero() { + m.Created = time.Now() + } + t, err := s.db.Begin() + if err != nil { + return 0, err + } + defer t.Rollback() + id, err := t.insertID(`INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, reply_to, created, + raw, message_id, from_addr, to_addr) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.FromID, m.From, m.ToID, m.To, m.Subject, m.Body, m.ReplyTo, + m.Created.Unix(), m.Raw, nullString(m.MessageID), m.FromAddr, m.ToAddr) + if err != nil { + return 0, err + } + var del int64 + if deleted { + del = now() + } + box, err := t.insertID(`INSERT INTO mailbox (user_id, mail_id, role, "read", starred, deleted, flags, created) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, user, id, role, read, starred, del, flags, now()) + if err != nil { + return 0, err + } + if err := syncBox(t, box); err != nil { + return 0, err + } + if err := t.Commit(); err != nil { + return 0, err + } + m.ID, m.Box = id, box + return box, nil +} + +// SentByMessageID is the user's Sent entry of a mail by its Message-ID +// (one sent here and put in Sent again by their mail program). +func (s *Store) SentByMessageID(user int64, id string) (int64, error) { + var box int64 + err := s.db.QueryRow(`SELECT b.id FROM mailbox b JOIN mail m ON m.id = b.mail_id + WHERE b.user_id = ? AND b.role = ? AND m.message_id = ? ORDER BY b.id LIMIT 1`, user, RoleSent, id).Scan(&box) + if errors.Is(err, sql.ErrNoRows) { + return 0, ErrNotFound + } + return box, err +} + +// PurgeTrash deletes for good what has been in the trash since before t: +// how many entries. +func (s *Store) PurgeTrash(before time.Time) (int, error) { + rows, err := s.db.Query(`SELECT id, user_id FROM mailbox WHERE deleted > 0 AND deleted < ?`, before.Unix()) + if err != nil { + return 0, err + } + type ub struct{ box, user int64 } + var all []ub + for rows.Next() { + var x ub + if err := rows.Scan(&x.box, &x.user); err != nil { + rows.Close() + return 0, err + } + all = append(all, x) + } + rows.Close() + if err := rows.Err(); err != nil { + return 0, err + } + n := 0 + for _, x := range all { + if err := s.PurgeBox(x.user, x.box); err == nil { + n++ + } else if !errors.Is(err, ErrNotFound) { + return n, err + } + } + return n, nil +} + +// MailRaw is a mail's raw form (nil: written here), by its id alone: for +// the queue. +func (s *Store) MailRaw(id int64) ([]byte, error) { + var raw []byte + err := s.db.QueryRow(`SELECT raw FROM mail WHERE id = ?`, id).Scan(&raw) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return raw, err +} + +const queueCols = `id, mail_id, user_id, sender, rcpt, attempts, next_try, last_error, created` + +func scanOutbound(row interface{ Scan(...any) error }) (*Outbound, error) { + var o Outbound + var next, created int64 + if err := row.Scan(&o.ID, &o.MailID, &o.UserID, &o.Sender, &o.Rcpt, &o.Attempts, &next, &o.LastError, &created); err != nil { + return nil, err + } + o.NextTry, o.Created = unix(next), unix(created) + return &o, nil +} + +// MailQueue lists the queue: those due by t (all, if t is zero), soonest +// first, at most limit (0: all). +func (s *Store) MailQueue(t time.Time, limit int) ([]*Outbound, error) { + q := `SELECT ` + queueCols + ` FROM mail_queue` + var args []any + if !t.IsZero() { + q += ` WHERE next_try <= ?` + args = append(args, t.Unix()) + } + q += ` ORDER BY next_try, id` + if limit > 0 { + q += ` LIMIT ?` + args = append(args, limit) + } + rows, err := s.db.Query(q, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Outbound + for rows.Next() { + o, err := scanOutbound(rows) + if err != nil { + return nil, err + } + out = append(out, o) + } + return out, rows.Err() +} + +// QueueDone takes a mail off the queue: sent, or given up on. +func (s *Store) QueueDone(id int64) error { + t, err := s.db.Begin() + if err != nil { + return err + } + defer t.Rollback() + var mail int64 + if err := t.QueryRow(`SELECT mail_id FROM mail_queue WHERE id = ?`, id).Scan(&mail); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + if _, err := t.Exec(`DELETE FROM mail_queue WHERE id = ?`, id); err != nil { + return err + } + if err := gcMail(t, mail); err != nil { + return err + } + return t.Commit() +} + +// QueueRetry puts a mail off till next, saying why. +func (s *Store) QueueRetry(id int64, next time.Time, why string) error { + if len(why) > 500 { + why = why[:500] + } + return s.exec1(`UPDATE mail_queue SET attempts = attempts + 1, next_try = ?, last_error = ? WHERE id = ?`, + next.Unix(), why, id) +} diff --git a/internal/store/mailbox_test.go b/internal/store/mailbox_test.go new file mode 100644 index 0000000..2c6b596 --- /dev/null +++ b/internal/store/mailbox_test.go @@ -0,0 +1,208 @@ +package store + +import ( + "database/sql" + "errors" + "path/filepath" + "testing" + "time" + + _ "modernc.org/sqlite" +) + +// uids is a folder's numbers. +func uids(t *testing.T, s *Store, user int64, folder int) []int64 { + t.Helper() + es, err := s.FolderEntries(user, folder) + if err != nil { + t.Fatal(err) + } + var out []int64 + for _, e := range es { + out = append(out, e.UID) + } + return out +} + +// TestMailbox: one copy of a mail, the recipient's and the sender's +// entries, the folders they are in, and their numbers only growing. +func TestMailbox(t *testing.T) { + s := open(t) + alice, _ := s.CreateUser("Alice", "alicepass1", "", false) + bob, _ := s.CreateUser("Bob", "bobpass123", "", false) + id, err := s.SendMail(&Message{FromID: alice.ID, From: "Alice", ToID: bob.ID, To: "Bob", Subject: "Hi", Body: "b"}) + if err != nil { + t.Fatal(err) + } + if in, _ := s.Inbox(bob.ID); len(in) != 1 || in[0].ID != id || in[0].Read { + t.Fatalf("bob's inbox: %+v", in) + } + if in, _ := s.Inbox(alice.ID); len(in) != 0 { + t.Errorf("alice's inbox: %+v", in) + } + if sent, _ := s.Folder(alice.ID, FolderSent); len(sent) != 1 || sent[0].ID != id { + t.Errorf("alice's sent: %+v", sent) + } + if u := uids(t, s, bob.ID, FolderUnread); len(u) != 1 { + t.Errorf("unread: %v", u) + } + if _, err := s.Mail(alice.ID, id); !errors.Is(err, ErrNotFound) { + t.Errorf("the sender reads it as received: %v", err) + } + + // read: out of Unread; starred: into Starred, with a new number + if err := s.MarkMailRead(bob.ID, id); err != nil { + t.Fatal(err) + } + if u := uids(t, s, bob.ID, FolderUnread); len(u) != 0 { + t.Errorf("unread after reading: %v", u) + } + inbox := uids(t, s, bob.ID, FolderInbox) + if err := s.StarMail(bob.ID, id, true); err != nil { + t.Fatal(err) + } + star := uids(t, s, bob.ID, FolderStarred) + if len(star) != 1 || star[0] <= inbox[0] { + t.Errorf("starred %v after inbox %v", star, inbox) + } + if got := uids(t, s, bob.ID, FolderInbox); len(got) != 1 || got[0] != inbox[0] { + t.Errorf("inbox changed: %v", got) + } + + // deleted: into the trash, out of everything else; the sender's + // copy stays + if err := s.DeleteMail(bob.ID, id); err != nil { + t.Fatal(err) + } + if n, _ := s.UnreadMail(bob.ID); n != 0 { + t.Errorf("unread %d", n) + } + for f := 0; f < NumFolders; f++ { + n := len(uids(t, s, bob.ID, f)) + if want := map[bool]int{true: 1, false: 0}[f == FolderTrash]; n != want { + t.Errorf("bob's %s: %d", FolderNames[f], n) + } + } + trash, _ := s.FolderEntries(bob.ID, FolderTrash) + if err := s.RestoreBox(bob.ID, trash[0].Box); err != nil { + t.Fatal(err) + } + if got := uids(t, s, bob.ID, FolderInbox); len(got) != 1 || got[0] <= star[0] { + t.Errorf("restored: %v", got) + } + if err := s.TrashBox(bob.ID, trash[0].Box); err != nil { + t.Fatal(err) + } + if err := s.RestoreBox(alice.ID, trash[0].Box); !errors.Is(err, ErrNotFound) { + t.Errorf("another's entry: %v", err) + } + + // the trash emptied: bob's entry goes, the mail stays for alice + if n, err := s.PurgeTrash(time.Now().Add(time.Hour)); err != nil || n != 1 { + t.Fatalf("purged %d %v", n, err) + } + if sent, _ := s.Folder(alice.ID, FolderSent); len(sent) != 1 { + t.Fatalf("alice's sent after bob's purge: %+v", sent) + } + if err := s.PurgeBox(alice.ID, sent0(t, s, alice.ID)); err != nil { + t.Fatal(err) + } + var n int + s.db.QueryRow(`SELECT COUNT(*) FROM mail`).Scan(&n) + if n != 0 { + t.Errorf("mail left: %d", n) + } + + // appended, found by its Message-ID; the queue keeps a mail no one + // has + box, err := s.AppendMail(alice.ID, RoleSent, &Message{FromID: alice.ID, From: "Alice", To: "x@example.com", + Subject: "Out", Body: "b", Raw: []byte("Subject: Out\r\n\r\nb\r\n"), MessageID: "<1@x>"}, true, false, false, "$Forwarded") + if err != nil { + t.Fatal(err) + } + if got, err := s.SentByMessageID(alice.ID, "<1@x>"); err != nil || got != box { + t.Errorf("by Message-ID: %d %v", got, err) + } + m, e, err := s.BoxMail(alice.ID, box) + if err != nil || string(m.Raw) != "Subject: Out\r\n\r\nb\r\n" || e.Flags != "$Forwarded" || e.Role != RoleSent { + t.Fatalf("box mail: %+v %+v %v", m, e, err) + } + if _, _, err := s.BoxMail(bob.ID, box); !errors.Is(err, ErrNotFound) { + t.Errorf("another's: %v", err) + } + mid, err := s.DeliverMail(&Message{FromID: alice.ID, From: "Alice", To: "x@example.com", Subject: "Q", Body: "b", + Raw: []byte("raw")}, Delivery{Sent: true, Queue: []*Outbound{{UserID: alice.ID, Sender: "alice@here", Rcpt: "x@example.com"}}}) + if err != nil { + t.Fatal(err) + } + q, _ := s.MailQueue(time.Now(), 0) + if len(q) != 1 || q[0].MailID != mid || q[0].Rcpt != "x@example.com" { + t.Fatalf("queue: %+v", q) + } + if err := s.QueueRetry(q[0].ID, time.Now().Add(time.Hour), "421 later"); err != nil { + t.Fatal(err) + } + if q, _ := s.MailQueue(time.Now(), 0); len(q) != 0 { + t.Errorf("not due yet: %+v", q) + } + sentBox, _ := s.FolderEntries(alice.ID, FolderSent) + for _, e := range sentBox { + s.PurgeBox(alice.ID, e.Box) + } + if raw, err := s.MailRaw(mid); err != nil || string(raw) != "raw" { + t.Errorf("queued mail gone with its entry: %q %v", raw, err) + } + if err := s.QueueDone(q[0].ID); err != nil { + t.Fatal(err) + } + if _, err := s.MailRaw(mid); !errors.Is(err, ErrNotFound) { + t.Errorf("sent and no one's: %v", err) + } +} + +func sent0(t *testing.T, s *Store, user int64) int64 { + es, _ := s.FolderEntries(user, FolderSent) + if len(es) == 0 { + t.Fatal("nothing sent") + } + return es[0].Box +} + +// TestMailboxMigration: an older database's mail is put in its +// recipients' inboxes, read or not as it was. +func TestMailboxMigration(t *testing.T) { + path := filepath.Join(t.TempDir(), "old.db") + d, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + for _, q := range []string{ + `CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, password TEXT NOT NULL, created INTEGER NOT NULL)`, + `INSERT INTO users (name, password, created) VALUES ('Bob', 'x', 1)`, + `CREATE TABLE mail (id INTEGER PRIMARY KEY, from_id INTEGER NOT NULL, from_name TEXT NOT NULL, + to_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, to_name TEXT NOT NULL, subject TEXT NOT NULL, + body TEXT NOT NULL, reply_to INTEGER NOT NULL DEFAULT 0, created INTEGER NOT NULL, "read" INTEGER NOT NULL DEFAULT 0)`, + `INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, created, "read") VALUES (0, 'Sysop', 1, 'Bob', 'Old', 'b', 5, 1)`, + `INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, created, "read") VALUES (0, 'Sysop', 1, 'Bob', 'New', 'b', 6, 0)`, + } { + if _, err := d.Exec(q); err != nil { + t.Fatal(err) + } + } + d.Close() + s, err := Open("sqlite:" + path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + in, err := s.Inbox(1) + if err != nil || len(in) != 2 || !in[0].Read || in[1].Read || in[1].Subject != "New" { + t.Fatalf("inbox: %+v %v", in, err) + } + if u := uids(t, s, 1, FolderUnread); len(u) != 1 { + t.Errorf("unread: %v", u) + } + if u := uids(t, s, 1, FolderAll); len(u) != 2 { + t.Errorf("all: %v", u) + } +} diff --git a/internal/store/schema.go b/internal/store/schema.go index b15176f..1988c6e 100644 --- a/internal/store/schema.go +++ b/internal/store/schema.go @@ -146,7 +146,39 @@ CREATE TABLE IF NOT EXISTS mail ( reply_to {int} NOT NULL DEFAULT 0, created {int} NOT NULL, "read" {bool} NOT NULL DEFAULT FALSE, - ftn_msgid {key} + ftn_msgid {key}, + raw {blob}, + message_id {key}, + from_addr {str} NOT NULL DEFAULT '', + to_addr {str} NOT NULL DEFAULT '' +)`, ` +CREATE TABLE IF NOT EXISTS mailbox ( + id {id}, + user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE, + mail_id {int} NOT NULL REFERENCES mail(id) ON DELETE CASCADE, + role {int} NOT NULL, + "read" {bool} NOT NULL DEFAULT FALSE, + starred {bool} NOT NULL DEFAULT FALSE, + deleted {int} NOT NULL DEFAULT 0, + flags {str} NOT NULL DEFAULT '', + created {int} NOT NULL +)`, ` +CREATE TABLE IF NOT EXISTS mail_uids ( + id {id}, + user_id {int} NOT NULL, + folder {int} NOT NULL, + box_id {int} NOT NULL REFERENCES mailbox(id) ON DELETE CASCADE +)`, ` +CREATE TABLE IF NOT EXISTS mail_queue ( + id {id}, + mail_id {int} NOT NULL REFERENCES mail(id) ON DELETE CASCADE, + user_id {int} NOT NULL DEFAULT 0, + sender {str} NOT NULL, + rcpt {str} NOT NULL, + attempts {int} NOT NULL DEFAULT 0, + next_try {int} NOT NULL, + last_error {str} NOT NULL DEFAULT '', + created {int} NOT NULL )`, ` CREATE TABLE IF NOT EXISTS file_areas ( id {id}, @@ -342,6 +374,13 @@ var indexes = []struct { {"messages_area", "messages", "area_id, id", false}, {"messages_reply", "messages", "reply_to", false}, {"mail_to", "mail", "to_id, id", false}, + {"mail_message_id", "mail", "message_id", false}, + {"mailbox_user", "mailbox", "user_id, role, id", false}, + {"mailbox_mail", "mailbox", "mail_id", false}, + {"mail_uids_folder", "mail_uids", "user_id, folder, id", false}, + {"mail_uids_box", "mail_uids", "box_id, folder", true}, + {"mail_queue_next", "mail_queue", "next_try", false}, + {"mail_queue_mail", "mail_queue", "mail_id", false}, {"files_uploader", "files", "uploader_id, created", false}, {"areas_newsgroup", "areas", "newsgroup", true}, {"messages_message_id", "messages", "message_id", true}, @@ -417,6 +456,10 @@ var added = []struct{ table, column, decl string }{ {"chan_posts", "page_count", "{int} NOT NULL DEFAULT 0"}, {"chan_boards", "archive", "{bool} NOT NULL DEFAULT TRUE"}, {"chan_posts", "archived_on", "{int} NOT NULL DEFAULT 0"}, + {"mail", "raw", "{blob}"}, + {"mail", "message_id", "{key}"}, + {"mail", "from_addr", "{str} NOT NULL DEFAULT ''"}, + {"mail", "to_addr", "{str} NOT NULL DEFAULT ''"}, } // migrate makes the schema, or brings an older database up to it. @@ -427,6 +470,11 @@ func migrate(x *db) error { return fmt.Errorf("the nocase collation: %w", err) } } + // the mailboxes are new: each mail there is put in its recipient's + hadBoxes, err := x.hasColumn("mailbox", "id") + if err != nil { + return err + } for _, t := range tables { if _, err := x.Exec(x.d.ddl(t)); err != nil { return err @@ -450,6 +498,11 @@ func migrate(x *db) error { return fmt.Errorf("finding the threads: %w", err) } } + if !hadBoxes { + if err := fillMailboxes(x); err != nil { + return fmt.Errorf("the mailboxes: %w", err) + } + } for _, i := range indexes { if err := x.index(i.name, i.table, i.cols, i.unique); err != nil { return fmt.Errorf("index %s: %w", i.name, err) diff --git a/internal/store/store.go b/internal/store/store.go index 9c09937..f32f63f 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -106,6 +106,15 @@ type Message struct { // the poster's country (ISO 3166-1), where it was known when they // posted here ("": not known, or written elsewhere) Country string + + // mail: the mailbox entry it was found by (0: none), and that entry's + // star; the e-mail addresses of the sender and recipients, where they + // are not users here ("": a user here); Raw and MessageID are the + // message as it came by SMTP or IMAP (nil: written here) + Box int64 + Starred bool + FromAddr string + ToAddr string } // Store is the database. @@ -600,78 +609,6 @@ func (s *Store) NewCount(user, area int64) (int, error) { return n, err } -const mailCols = `id, from_id, from_name, to_id, to_name, subject, body, reply_to, created, "read", - COALESCE(ftn_msgid, '')` - -// scanMail is the private message in a row of mailCols; ErrNotFound if -// there is none. -func scanMail(row interface{ Scan(...any) error }) (*Message, error) { - var m Message - var created int64 - err := row.Scan(&m.ID, &m.FromID, &m.From, &m.ToID, &m.To, &m.Subject, - &m.Body, &m.ReplyTo, &created, &m.Read, &m.FTNMsgID) - if errors.Is(err, sql.ErrNoRows) { - return nil, ErrNotFound - } - if err != nil { - return nil, err // nothing half scanned - } - m.Created = unix(created) - return &m, nil -} - -// SendMail delivers a private message. -func (s *Store) SendMail(m *Message) (int64, error) { - id, err := s.db.insertID(`INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, reply_to, created, - ftn_msgid) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.FromID, m.From, m.ToID, m.To, m.Subject, m.Body, m.ReplyTo, now(), - nullString(m.FTNMsgID)) - if err != nil { - return 0, err - } - return id, nil -} - -// Inbox lists a user's mail, oldest first. -func (s *Store) Inbox(user int64) ([]*Message, error) { - rows, err := s.db.Query(`SELECT `+mailCols+` FROM mail WHERE to_id = ? ORDER BY id`, user) - if err != nil { - return nil, err - } - defer rows.Close() - var out []*Message - for rows.Next() { - m, err := scanMail(rows) - if err != nil { - return nil, err - } - out = append(out, m) - } - return out, rows.Err() -} - -// Mail finds a mail of user's by id: no one reads another's mail. -func (s *Store) Mail(user, id int64) (*Message, error) { - return scanMail(s.db.QueryRow(`SELECT `+mailCols+` FROM mail WHERE id = ? AND to_id = ?`, id, user)) -} - -// MarkMailRead marks a mail of user's read. -func (s *Store) MarkMailRead(user, id int64) error { - return s.exec1(`UPDATE mail SET "read" = TRUE WHERE id = ? AND to_id = ?`, id, user) -} - -// DeleteMail deletes a mail of user's. -func (s *Store) DeleteMail(user, id int64) error { - return s.exec1(`DELETE FROM mail WHERE id = ? AND to_id = ?`, id, user) -} - -// UnreadMail counts a user's unread mail. -func (s *Store) UnreadMail(user int64) (int, error) { - var n int - err := s.db.QueryRow(`SELECT COUNT(*) FROM mail WHERE to_id = ? AND "read" = FALSE`, user).Scan(&n) - return n, err -} - // FileArea is an area of files. type FileArea struct { ID int64 From 1f018afa906123ff35abdd74674dba1497de2b76 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 13:08:26 +0000 Subject: [PATCH 2/5] E-mail: POP3, IMAP, SMTP submission, inbound SMTP and LMTP, and a queue out wip: servers, delivery and config; tests to follow Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRVPRbt1YgtG7eQJZxD --- cmd/bbs/main.go | 129 +++++ internal/bbs/api.go | 6 + internal/bbs/bbs.go | 8 + internal/bbs/email.go | 54 ++ internal/bbs/news.go | 6 +- internal/cis/mail.go | 14 +- internal/email/checks.go | 126 ++++ internal/email/deliver.go | 239 ++++++++ internal/email/dkim.go | 94 +++ internal/email/email.go | 304 ++++++++++ internal/email/imap.go | 1025 +++++++++++++++++++++++++++++++++ internal/email/imapsearch.go | 167 ++++++ internal/email/listen.go | 169 ++++++ internal/email/message.go | 329 +++++++++++ internal/email/pop3.go | 450 +++++++++++++++ internal/email/queue.go | 227 ++++++++ internal/email/smtp.go | 285 +++++++++ internal/server/bind.go | 6 + internal/server/config.go | 63 +- internal/server/mailconfig.go | 178 ++++++ 20 files changed, 3847 insertions(+), 32 deletions(-) create mode 100644 internal/bbs/email.go create mode 100644 internal/email/checks.go create mode 100644 internal/email/deliver.go create mode 100644 internal/email/dkim.go create mode 100644 internal/email/email.go create mode 100644 internal/email/imap.go create mode 100644 internal/email/imapsearch.go create mode 100644 internal/email/listen.go create mode 100644 internal/email/message.go create mode 100644 internal/email/pop3.go create mode 100644 internal/email/queue.go create mode 100644 internal/email/smtp.go create mode 100644 internal/server/mailconfig.go diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index 8564be5..fa1e7a9 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -14,6 +14,7 @@ // bbs [-config FILE] area list // bbs [-config FILE] area newsgroup AREA GROUP|- // bbs [-config FILE] news sync [PEER] +// bbs [-config FILE] mail dkim KEYFILE | queue | send | address USER // bbs [-config FILE] area echo AREA TAG|- // bbs [-config FILE] area group AREA GROUP|- // bbs [-config FILE] area aliases AREA yes|no @@ -60,6 +61,7 @@ import ( "github.com/D-Modem/bbs/internal/api" "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/email" "github.com/D-Modem/bbs/internal/events" "github.com/D-Modem/bbs/internal/fido" "github.com/D-Modem/bbs/internal/files" @@ -108,6 +110,10 @@ func usage() { bbs [-config FILE] area require AREA READ POST access requirements ("30 F", sysop, -: none) bbs [-config FILE] area newsgroup AREA GROUP|- (- : not a newsgroup) bbs [-config FILE] news sync [PEER] exchange articles with peers now + bbs [-config FILE] mail dkim KEYFILE make a DKIM key, and print the DNS record for it + bbs [-config FILE] mail queue mail waiting to go elsewhere + bbs [-config FILE] mail send try the queue now + bbs [-config FILE] mail address USER a user's e-mail address bbs [-config FILE] area echo AREA TAG|- make an area a FidoNet echo (- : not one) bbs [-config FILE] area group AREA GROUP|- list an area under a group (- : none) bbs [-config FILE] area aliases AREA yes|no whether its posters may use their aliases @@ -224,6 +230,20 @@ func main() { fmt.Printf("[peer %s] %s, groups %s, pull %v, push %v, every %v\n", p.Name, p.Address, p.Groups, p.Pull, p.Push, p.Interval) } + if m := cfg.Mail; m != nil { + out := m.Outbound + if out == email.OutboundSmarthost { + out += " " + m.Smarthost.Address + } + dk := "not signed" + if m.DKIM != nil { + dk = "DKIM " + m.DKIM.Selector + "._domainkey." + m.DKIM.Domain + } + fmt.Printf("mail: @%s, host %s, out %s, %s\n", m.Domain, m.Hostname, out, dk) + for _, ms := range cfg.MailServers { + fmt.Printf("%s: %s, tls %s\n", ms.Kind, ms.Set.Address, ms.Set.TLS) + } + } if f := cfg.Fido; f != nil { var as []string for _, a := range f.Addrs { @@ -305,6 +325,8 @@ func main() { areaCmd(cfg, args) case "news": newsCmd(cfg, args) + case "mail": + mailCmd(cfg, args) case "fido": fidoCmd(cfg, args) case "qwknet": @@ -437,6 +459,44 @@ func serve(cfg *server.Config, path string) int { }() } svc.RunPeers(ctx, cfg.Peers) + trashDays := 30 + if cfg.Mail != nil { + trashDays = cfg.Mail.TrashDays + ms := email.New(b, *cfg.Mail) + for _, m := range cfg.MailServers { + var run func(context.Context) error + switch m.Kind { + case "pop3": + x, err := ms.NewPOP3(m.Set) + if err != nil { + lg.Printf("%v", err) + return 1 + } + run = x.Run + case "imap": + x, err := ms.NewIMAP(m.Set) + if err != nil { + lg.Printf("%v", err) + return 1 + } + run = x.Run + default: + x, err := ms.NewSMTP(m.Kind, m.Set, m.Checks) + if err != nil { + lg.Printf("%v", err) + return 1 + } + run = x.Run + } + go func() { + if err := run(ctx); err != nil { + lg.Printf("%v", err) + stop() + } + }() + } + go ms.RunQueue(ctx) + } if cfg.MRC != nil { mc, err := mrc.New(b, *cfg.MRC) if err != nil { @@ -520,6 +580,11 @@ func serve(cfg *server.Config, path string) int { if _, err := b.PurgeAreas(); err != nil { b.Log.Printf("purging: %v", err) } + if trashDays > 0 { + if _, err := st.PurgeTrash(time.Now().AddDate(0, 0, -trashDays)); err != nil { + b.Log.Printf("emptying the mail trash: %v", err) + } + } select { case <-ctx.Done(): return @@ -1170,6 +1235,70 @@ func firstSysop(st *store.Store) *store.User { } // newsCmd exchanges articles with the news peers now, or the one named. +// mailCmd: a DKIM key made, the queue listed or tried, a user's address. +func mailCmd(cfg *server.Config, args []string) { + words, _ := split(args) + if len(words) == 0 { + usage() + } + switch words[0] { + case "dkim": + if len(words) != 2 { + usage() + } + k, err := email.NewDKIMKey(words[1]) + if err != nil { + fatal(err) + } + rec, err := email.DKIMRecord(k) + if err != nil { + fatal(err) + } + domain := "DOMAIN" + if cfg.Mail != nil { + domain = cfg.Mail.Domain + } + fmt.Printf("key written to %s; in [mail]: dkim_key_file = %s, dkim_selector = bbs\n", words[1], words[1]) + fmt.Printf("publish this TXT record:\n\nbbs._domainkey.%s. IN TXT \"%s\"\n", domain, rec) + return + } + if cfg.Mail == nil { + fatal(errors.New("the configuration has no [mail] section")) + } + st := open(cfg) + defer st.Close() + switch words[0] { + case "queue": + q, err := st.MailQueue(time.Time{}, 0) + if err != nil { + fatal(err) + } + for _, o := range q { + fmt.Printf("%d mail %d %s -> %s tried %d, next %s %s\n", o.ID, o.MailID, o.Sender, o.Rcpt, + o.Attempts, o.NextTry.Format("2006-01-02 15:04"), o.LastError) + } + if len(q) == 0 { + fmt.Println("the queue is empty") + } + case "send": + lg := log.New(os.Stderr, "bbs: ", log.LstdFlags) + b := bbs.New(cfg.Settings, st, lg) + email.New(b, *cfg.Mail).RunQueueOnce(context.Background()) + case "address": + if len(words) != 2 { + usage() + } + u, err := st.UserByName(words[1]) + if err != nil { + fatal(err) + } + b := bbs.New(cfg.Settings, st, log.New(io.Discard, "", 0)) + fmt.Println(email.New(b, *cfg.Mail).Address(u)) + default: + usage() + } +} + func newsCmd(cfg *server.Config, args []string) { words, _ := split(args) if len(words) == 0 || words[0] != "sync" || len(words) > 2 { diff --git a/internal/bbs/api.go b/internal/bbs/api.go index a219e4b..c09b5d3 100644 --- a/internal/bbs/api.go +++ b/internal/bbs/api.go @@ -52,4 +52,10 @@ func (b *BBS) tellMail(to int64, from, subject string) { for _, n := range ns { n.deliver(Event{Kind: Mail, From: from, Text: subject, Time: time.Now()}) } + if b.MailWatch != nil { + b.MailWatch(to) + } } + +// TellMail tells a user's callers, and their mail programs, of new mail. +func (b *BBS) TellMail(to int64, from, subject string) { b.tellMail(to, from, subject) } diff --git a/internal/bbs/bbs.go b/internal/bbs/bbs.go index ba504bd..3254b69 100644 --- a/internal/bbs/bbs.go +++ b/internal/bbs/bbs.go @@ -150,6 +150,11 @@ type BBS struct { NetmailTo func(ftn.Addr) (string, error) // Nodelist is the FidoNet nodelist (nil: none) Nodelist func() *ftn.Nodelist + // Email sends mail from u to an e-mail address, here or elsewhere; + // reply is the mail it answers (nil if none). Nil: no e-mail. + Email EmailFunc + // MailWatch is told of mail delivered to a user here (IMAP's IDLE) + MailWatch func(user int64) // ImageBoards are the image boards, for the terminals (nil: none) ImageBoards ImageBoards // MenuAuth checks the passwords of accounts modemmenu logs in (its @@ -829,6 +834,9 @@ func (n *Node) SendMail(to, subject string, body []string, replyTo int64) error } return n.sendNetmail(u, name, addr, subject, body, replyTo) } + if IsEmailAddress(to) { + return n.sendEmail(u, strings.TrimSpace(to), subject, body, replyTo) + } rcpt, err := n.b.Store.UserByName(strings.TrimSpace(to)) if errors.Is(err, store.ErrNotFound) { return fmt.Errorf("there is no user %q", Clean(to, MaxNameLen)) diff --git a/internal/bbs/email.go b/internal/bbs/email.go new file mode 100644 index 0000000..2c26524 --- /dev/null +++ b/internal/bbs/email.go @@ -0,0 +1,54 @@ +package bbs + +import ( + "errors" + "net/mail" + "strings" + + "github.com/D-Modem/bbs/internal/store" +) + +// EmailFunc sends a mail from u to an e-mail address; reply is the mail it +// answers (nil if none). +type EmailFunc func(u *store.User, to, subject, body string, reply *store.Message) error + +// IsEmailAddress reports whether a recipient is an e-mail address +// (local@domain.tld, or Name as a mail from one says +// who it is from), not a user's name or a FidoNet address. +func IsEmailAddress(to string) bool { + to = strings.TrimSpace(to) + if _, _, ok := SplitNetmail(to); ok { + return false + } + a, err := mail.ParseAddress(to) + if err != nil { + return false + } + _, domain, ok := strings.Cut(a.Address, "@") + return ok && strings.Contains(domain, ".") && !strings.HasPrefix(domain, ".") && !strings.HasSuffix(domain, ".") +} + +// sendEmail sends a mail to an e-mail address. +func (n *Node) sendEmail(u *store.User, to, subject string, body []string, replyTo int64) error { + if n.b.Email == nil { + return errors.New("this BBS does not send e-mail") + } + subj := Clean(subject, MaxSubjectLen) + text := CleanBody(body) + if subj == "" { + return errors.New("a message needs a subject") + } + if text == "" { + return errors.New("the message is empty") + } + var reply *store.Message + if replyTo > 0 { + reply, _ = n.b.Store.Mail(u.ID, replyTo) + } + if err := n.b.Email(u, to, subj, text, reply); err != nil { + return err + } + n.b.Stats.Mail.Add(1) + n.b.Log.Printf("node %d: %s sent e-mail to %s", n.Num, u.Name, to) + return nil +} diff --git a/internal/bbs/news.go b/internal/bbs/news.go index ae0e0e7..5974b78 100644 --- a/internal/bbs/news.go +++ b/internal/bbs/news.go @@ -14,8 +14,10 @@ type NewsSettings struct { Organization string } -// localPart is a user name as an address's local part: what is not a -// letter, digit or one of ._- becomes a dot. +// LocalPart is a user name as an address's local part: what is not a +// letter, digit or one of ._- becomes a dot, all in lower case. +func LocalPart(name string) string { return localPart(name) } + func localPart(name string) string { out := strings.Map(func(r rune) rune { if r < 0x80 && (r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("._-", r)) { diff --git a/internal/cis/mail.go b/internal/cis/mail.go index bceb10d..7c32fb4 100644 --- a/internal/cis/mail.go +++ b/internal/cis/mail.go @@ -9,6 +9,7 @@ import ( "time" "unicode/utf8" + "github.com/D-Modem/bbs/internal/bbs" "github.com/D-Modem/bbs/internal/store" "github.com/D-Modem/bbs/internal/xfer" ) @@ -17,7 +18,8 @@ import ( // PARAMS.SCR (5.4, 1991) and the strings it waits for ("Mail!", "ID):", // "ect:", "Action!"), and 1993 captures of menu mode. A message is // "pending" until it is read; read ones stay in the BBS's mailbox (as if -// SAVEd) until deleted. +// SAVEd) until deleted (to the user's trash). >INTERNET:addr is e-mail, +// where the BBS has it. // Mail's modes of operation. const ( @@ -579,7 +581,15 @@ func (s *session) resolveAddress(a string) (recipient, error) { break } } - return recipient{}, errors.New("Internet mail is not offered on this service") + addr := strings.TrimSpace(rest) + if s.b.Email == nil || !bbs.IsEmailAddress(addr) { + return recipient{}, errors.New("Internet mail is not offered on this service") + } + shown := "INTERNET:" + addr + if name != "" { + shown = name + " >" + shown + } + return recipient{addr, shown}, nil case "FAX", "POSTAL", "MCIMAIL", "X400", "MHS", "TLX", "TELEX", "EMS": return recipient{}, fmt.Errorf("%s mail is not offered on this service", strings.ToUpper(net)) default: diff --git a/internal/email/checks.go b/internal/email/checks.go new file mode 100644 index 0000000..4074e27 --- /dev/null +++ b/internal/email/checks.go @@ -0,0 +1,126 @@ +package email + +import ( + "bytes" + "context" + "net" + "strings" + "time" + + "blitiri.com.ar/go/spf" + "github.com/emersion/go-msgauth/authres" + "github.com/emersion/go-msgauth/dkim" + "github.com/emersion/go-msgauth/dmarc" +) + +// verdict is what the checks of a mail from elsewhere found: the +// Authentication-Results field to put on it, and why it is refused ("": +// it is not). +type verdict struct { + field string + refuse string +} + +// orgDomain is a domain's organizational domain, roughly: its last two +// labels, or three where the second is a short one under a country's +// (example.co.uk). (The public suffix list would be exact.) +func orgDomain(d string) string { + l := strings.Split(strings.ToLower(strings.TrimSuffix(d, ".")), ".") + switch { + case len(l) <= 2: + return strings.Join(l, ".") + case len(l[len(l)-1]) == 2 && len(l[len(l)-2]) <= 3: + return strings.Join(l[len(l)-3:], ".") + } + return strings.Join(l[len(l)-2:], ".") +} + +// aligned reports whether two domains are aligned as DMARC means it. +func aligned(a, b string, mode dmarc.AlignmentMode) bool { + a, b = strings.ToLower(strings.TrimSuffix(a, ".")), strings.ToLower(strings.TrimSuffix(b, ".")) + if mode == dmarc.AlignmentStrict { + return a == b + } + return orgDomain(a) == orgDomain(b) +} + +// domainOf is an address's domain. +func domainOf(addr string) string { + _, d, _ := strings.Cut(addr, "@") + return strings.ToLower(d) +} + +// check checks a mail from elsewhere: SPF for the address it came from, +// its DKIM signatures, and DMARC for its From. A mail is refused if its +// From's domain asks for that (p=reject) and it fails, or, for a domain +// with no DMARC, if SPF fails and no signature of the domain holds. +func (s *Service) check(ip net.IP, helo, mailFrom string, raw []byte) verdict { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + r := s.Set.Resolver + var results []authres.Result + + spfFor := mailFrom + if spfFor == "" { + spfFor = "postmaster@" + helo + } + spfRes, _ := spf.CheckHostWithSender(ip, helo, spfFor, spf.WithResolver(r), spf.WithContext(ctx)) + results = append(results, &authres.SPFResult{Value: authres.ResultValue(spfRes), From: mailFrom, Helo: helo}) + + lookup := func(d string) ([]string, error) { return r.LookupTXT(ctx, d) } + verifs, _ := dkim.VerifyWithOptions(bytes.NewReader(raw), &dkim.VerifyOptions{LookupTXT: lookup, MaxVerifications: 5}) + var passed []string + for _, v := range verifs { + var val authres.ResultValue = authres.ResultPass + switch { + case v.Err == nil: + passed = append(passed, v.Domain) + case dkim.IsTempFail(v.Err): + val = authres.ResultTempError + case dkim.IsPermFail(v.Err): + val = authres.ResultPermError + default: + val = authres.ResultFail + } + results = append(results, &authres.DKIMResult{Value: val, Domain: v.Domain}) + } + if len(verifs) == 0 { + results = append(results, &authres.DKIMResult{Value: authres.ResultNone}) + } + + var refuse string + from := "" + if p, err := parse(raw); err == nil { + from = domainOf(p.fromAddr) + } + var rec *dmarc.Record + if from != "" { + rec, _ = dmarc.LookupWithOptions(from, &dmarc.LookupOptions{LookupTXT: lookup}) + if rec == nil && orgDomain(from) != from { + rec, _ = dmarc.LookupWithOptions(orgDomain(from), &dmarc.LookupOptions{LookupTXT: lookup}) + } + } + if rec != nil { + pass := spfRes == spf.Pass && aligned(domainOf(mailFrom), from, rec.SPFAlignment) + for _, d := range passed { + pass = pass || aligned(d, from, rec.DKIMAlignment) + } + val := authres.ResultValue(authres.ResultPass) + if !pass { + val = authres.ResultFail + if rec.Policy == dmarc.PolicyReject { + refuse = "DMARC: " + from + " says to refuse mail from it that fails" + } + } + results = append(results, &authres.DMARCResult{Value: val, From: from}) + } else if spfRes == spf.Fail { + ok := false + for _, d := range passed { + ok = ok || aligned(d, from, dmarc.AlignmentRelaxed) + } + if !ok { + refuse = "SPF: " + domainOf(spfFor) + " does not let " + ip.String() + " send its mail" + } + } + return verdict{field: "Authentication-Results: " + authres.Format(s.Set.Hostname, results) + "\r\n", refuse: refuse} +} diff --git a/internal/email/deliver.go b/internal/email/deliver.go new file mode 100644 index 0000000..4d00ed5 --- /dev/null +++ b/internal/email/deliver.go @@ -0,0 +1,239 @@ +package email + +import ( + "bytes" + "errors" + "fmt" + "mime" + "net/mail" + "strings" + "time" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" +) + +// Errors of a mail refused. +var ( + ErrNotYours = errors.New("a mail sent here must be from your own address") + ErrNoInternet = errors.New("this BBS sends no mail elsewhere") + ErrSysopOnly = errors.New("your access allows mail only to the sysop") + ErrNoFidoNet = errors.New("this BBS is not on FidoNet") + ErrTooBig = errors.New("the mail is too big") +) + +// shownAddress is a name and address as the terminals show who a mail is +// from, and take it again as the address of a reply. +func shownAddress(name, addr string) string { + switch { + case name == "" || strings.EqualFold(name, addr): + return addr + case strings.ContainsAny(name, "\"\\,<>@;:()[]."): + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(name) + `" <` + addr + `>` + } + return name + " <" + addr + ">" +} + +// checkRecipient checks that u may send to r. +func (s *Service) checkRecipient(u *store.User, r *recipient) error { + if !s.mayMail(u) && (r.kind != toLocal || !r.user.Sysop) { + return ErrSysopOnly + } + switch r.kind { + case toInternet: + if s.Set.Outbound == OutboundNone { + return ErrNoInternet + } + case toFido: + if s.B.Netmail == nil { + return ErrNoFidoNet + } + } + return nil +} + +// Submit sends a mail a user here wrote (by SMTP submission, or on a +// terminal) to its recipients: users here, FidoNet netmail, and the queue +// for addresses elsewhere; the user keeps it in Sent. Its From must be +// the user's own address. +func (s *Service) Submit(u *store.User, rcpts []string, raw []byte) error { + if int64(len(raw)) > s.Set.MaxMessage { + return ErrTooBig + } + raw = crlf(raw) + p, err := parse(raw) + if err != nil { + return fmt.Errorf("the mail cannot be read: %w", err) + } + own := s.Address(u) + if p.fromAddr == "" { + raw = append([]byte("From: "+s.Mailbox(u.Name)+"\r\n"), raw...) + } else if !strings.EqualFold(p.fromAddr, own) { + return ErrNotYours + } + var rs []*recipient + for _, a := range rcpts { + r, err := s.resolve(a) + if err != nil { + return fmt.Errorf("%s: %w", a, err) + } + if err := s.checkRecipient(u, r); err != nil { + return fmt.Errorf("%s: %w", a, err) + } + rs = append(rs, r) + } + if len(rs) == 0 { + return errors.New("a mail for no one") + } + // the header made sound: Bcc is not shown, a Date and Message-ID + raw = withoutFields(raw, "Bcc", "Return-Path", "DKIM-Signature") + var extra bytes.Buffer + if p.date.IsZero() { + fmt.Fprintf(&extra, "Date: %s\r\n", time.Now().Format(time.RFC1123Z)) + } + if p.messageID == "" { + p.messageID = s.newMessageID() + fmt.Fprintf(&extra, "Message-ID: %s\r\n", p.messageID) + } + raw = append(extra.Bytes(), raw...) + if s.Set.DKIM != nil { + if signed, err := s.sign(raw); err == nil { + raw = signed + } else { + s.B.Log.Printf("mail: DKIM: %v", err) + } + } + subject := bbs.Clean(p.subject, bbs.MaxSubjectLen) + if subject == "" { + subject = "(no subject)" + } + text := terminalBody(p.text) + m := &store.Message{FromID: u.ID, From: u.Name, Subject: subject, Body: text, Raw: raw, + MessageID: p.messageID, ToAddr: addressList(append(p.to, p.cc...))} + d := store.Delivery{Sent: true} + var shown []string + for _, r := range rs { + switch r.kind { + case toLocal: + d.To = append(d.To, r.user.ID) + shown = append(shown, r.user.Name) + case toFido: + if err := s.B.Netmail(u, bbs.Clean(r.name, bbs.MaxFTNNameLen), r.ftn, subject, text, nil); err != nil { + return fmt.Errorf("%s: %w", r.addr, err) + } + shown = append(shown, r.name+"@"+r.ftn.String()) + case toInternet: + d.Queue = append(d.Queue, &store.Outbound{UserID: u.ID, Sender: own, Rcpt: r.addr}) + shown = append(shown, r.addr) + } + } + m.To = bbs.Clean(strings.Join(shown, ", "), bbs.MaxMailToLen) + if _, err := s.B.Store.DeliverMail(m, d); err != nil { + return err + } + for _, id := range d.To { + s.B.TellMail(id, u.Name, subject) + } + if len(d.Queue) > 0 { + s.Kick() + } + s.B.Log.Printf("mail: %s sent %q to %s", u.Name, subject, strings.Join(shown, ", ")) + return nil +} + +// fromTerminal sends a mail written on a terminal to an e-mail address +// (bbs.EmailFunc). +func (s *Service) fromTerminal(u *store.User, to, subject, body string, reply *store.Message) error { + a, err := mail.ParseAddress(to) + if err != nil { + return fmt.Errorf("%q is not an e-mail address", to) + } + var b bytes.Buffer + field := func(k, v string) { fmt.Fprintf(&b, "%s: %s\r\n", k, v) } + field("From", s.Mailbox(u.Name)) + field("To", a.String()) + field("Subject", mime.QEncoding.Encode("utf-8", subject)) + field("Date", time.Now().Format(time.RFC1123Z)) + field("Message-ID", s.newMessageID()) + if reply != nil { + id := s.messageID(reply) + field("In-Reply-To", id) + field("References", id) + } + writeTextBody(&b, body) + return s.Submit(u, []string{a.Address}, b.Bytes()) +} + +// Receive keeps a mail from elsewhere for users here: trace is the header +// fields put before it (Received, Authentication-Results). +func (s *Service) Receive(to []*store.User, raw []byte, trace string) error { + if int64(len(raw)) > s.Set.MaxMessage { + return ErrTooBig + } + raw = append([]byte(trace), crlf(raw)...) + p, err := parse(raw) + if err != nil { + return fmt.Errorf("the mail cannot be read: %w", err) + } + subject := bbs.Clean(p.subject, bbs.MaxSubjectLen) + if subject == "" { + subject = "(no subject)" + } + from := bbs.Clean(shownAddress(p.fromName, p.fromAddr), 200) + if from == "" { + from = "(unknown)" + } + var ids []int64 + var names []string + for _, u := range to { + ids = append(ids, u.ID) + names = append(names, u.Name) + } + created := time.Now() + m := &store.Message{From: from, FromAddr: p.fromAddr, To: bbs.Clean(strings.Join(names, ", "), bbs.MaxMailToLen), + Subject: subject, Body: terminalBody(p.text), Raw: raw, MessageID: p.messageID, + ToAddr: addressList(append(p.to, p.cc...)), Created: created} + if len(ids) > 0 { + m.ToID = ids[0] + } + if _, err := s.B.Store.DeliverMail(m, store.Delivery{To: ids}); err != nil { + return err + } + for _, id := range ids { + s.B.TellMail(id, from, subject) + } + s.B.Log.Printf("mail: from %s for %s: %q", p.fromAddr, strings.Join(names, ", "), subject) + return nil +} + +// bounce tells a mail's sender here it could not be sent. +func (s *Service) bounce(o *store.Outbound, why string) { + if o.UserID <= 0 { + s.B.Log.Printf("mail: %d for %s given up (%s): no one here to tell", o.MailID, o.Rcpt, why) + return + } + u, err := s.B.Store.UserByID(o.UserID) + if err != nil { + return + } + subject := "(no subject)" + var head string + if raw, err := s.B.Store.MailRaw(o.MailID); err == nil { + if p, err := parse(raw); err == nil && p.subject != "" { + subject = p.subject + } + if end := headerEnd(raw); end > 0 { + head = string(raw[:end]) + } + } + body := fmt.Sprintf("Your mail could not be delivered to %s.\n\n%s\n\nIts header was:\n\n%s", + o.Rcpt, why, strings.ReplaceAll(head, "\r\n", "\n")) + m := &store.Message{From: "Mail Delivery System", FromAddr: "mailer-daemon@" + s.Set.Domain, ToID: u.ID, To: u.Name, + Subject: bbs.Clean("Undelivered: "+subject, bbs.MaxSubjectLen), Body: terminalBody(body)} + if _, err := s.B.Store.SendMail(m); err != nil { + s.B.Log.Printf("mail: bounce for %s: %v", u.Name, err) + return + } + s.B.TellMail(u.ID, m.From, m.Subject) + s.B.Log.Printf("mail: %d for %s given up (%s): %s told", o.MailID, o.Rcpt, why, u.Name) +} diff --git a/internal/email/dkim.go b/internal/email/dkim.go new file mode 100644 index 0000000..40dbca3 --- /dev/null +++ b/internal/email/dkim.go @@ -0,0 +1,94 @@ +package email + +import ( + "bytes" + "crypto" + "crypto/ed25519" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "errors" + "fmt" + "os" + + "github.com/emersion/go-msgauth/dkim" +) + +// sign is a mail with a DKIM-Signature of this server's key. +func (s *Service) sign(raw []byte) ([]byte, error) { + k := s.Set.DKIM + var out bytes.Buffer + err := dkim.Sign(&out, bytes.NewReader(raw), &dkim.SignOptions{Domain: k.Domain, Selector: k.Selector, Signer: k.Signer, + HeaderKeys: []string{"From", "To", "Cc", "Subject", "Date", "Message-ID", "In-Reply-To", "References", + "MIME-Version", "Content-Type", "Content-Transfer-Encoding"}}) + if err != nil { + return nil, err + } + return out.Bytes(), nil +} + +// LoadDKIMKey reads a DKIM private key: PEM, RSA (PKCS #1 or #8) or +// Ed25519 (PKCS #8). +func LoadDKIMKey(path string) (crypto.Signer, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + block, _ := pem.Decode(data) + if block == nil { + return nil, fmt.Errorf("%s: no PEM key", path) + } + if k, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil { + return k, nil + } + k, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + switch k := k.(type) { + case *rsa.PrivateKey: + return k, nil + case ed25519.PrivateKey: + return k, nil + } + return nil, fmt.Errorf("%s: an RSA or Ed25519 key is needed", path) +} + +// DKIMRecord is the DNS TXT record that publishes a key's public half. +func DKIMRecord(k crypto.Signer) (string, error) { + switch pub := k.Public().(type) { + case *rsa.PublicKey: + der, err := x509.MarshalPKIXPublicKey(pub) + if err != nil { + return "", err + } + return "v=DKIM1; k=rsa; p=" + base64.StdEncoding.EncodeToString(der), nil + case ed25519.PublicKey: + return "v=DKIM1; k=ed25519; p=" + base64.StdEncoding.EncodeToString(pub), nil + } + return "", errors.New("an RSA or Ed25519 key is needed") +} + +// NewDKIMKey makes a 2048-bit RSA key (what every receiver checks) and +// writes it to path, which must not be there yet. +func NewDKIMKey(path string) (crypto.Signer, error) { + k, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + return nil, err + } + der, err := x509.MarshalPKCS8PrivateKey(k) + if err != nil { + return nil, err + } + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return nil, err + } + if err := pem.Encode(f, &pem.Block{Type: "PRIVATE KEY", Bytes: der}); err != nil { + f.Close() + return nil, err + } + return k, f.Close() +} diff --git a/internal/email/email.go b/internal/email/email.go new file mode 100644 index 0000000..5e19b97 --- /dev/null +++ b/internal/email/email.go @@ -0,0 +1,304 @@ +// Package email is the BBS's e-mail: its users' private mail by POP3 and +// IMAP, mail sent by SMTP submission, mail from the internet taken by SMTP +// (or LMTP, from a mail server in front), and mail for elsewhere sent from +// a queue, straight to the recipients' servers or through a smarthost. +// +// Mail is kept in the BBS's store, whatever its database: once, with each +// user's entries (store.DeliverMail), shown in folders (store.FolderNames) +// that are views of those entries. +package email + +import ( + "context" + "crypto" + "errors" + "fmt" + "net" + "net/mail" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/ftn" + "github.com/D-Modem/bbs/internal/store" +) + +// How mail for elsewhere goes. +const ( + OutboundDirect = "direct" // to the recipients' servers (their MX) + OutboundSmarthost = "smarthost" // through another mail server + OutboundNone = "none" // not at all: mail only here +) + +// Settings are [mail]'s. +type Settings struct { + Domain string // users' addresses: name@Domain + Hostname string // this server's name (HELO, Received, Message-IDs) + MaxMessage int64 // bytes + MaxRecipients int + TrashDays int // days mail stays in the trash (0: for ever) + Postmaster string // the user postmaster@ and abuse@ go to ("": the first sysop) + Outbound string + Smarthost Smarthost + DKIM *DKIM // nil: mail sent is not signed + QueueLife time.Duration // how long a mail is tried before it is given up + // Resolver looks up MX, SPF, DKIM and DMARC records (nil: the + // system's) + Resolver Resolver + // MXPort is the port mail is sent to straight to its servers ("25"; + // another in tests) + MXPort string +} + +// Smarthost is a mail server mail for elsewhere is given to. +type Smarthost struct { + Address string // host:port + TLS string // "starttls" (the default), "implicit" or "no" + Username string // "": no AUTH + Password string + Insecure bool // its certificate is not checked +} + +// DKIM is the key mail sent is signed with. +type DKIM struct { + Domain string + Selector string + Signer crypto.Signer +} + +// Resolver is DNS: the net package's, or a test's. +type Resolver interface { + LookupTXT(ctx context.Context, name string) ([]string, error) + LookupMX(ctx context.Context, name string) ([]*net.MX, error) + LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error) + LookupAddr(ctx context.Context, addr string) ([]string, error) +} + +// Defaults are the settings not given. +func Defaults(domain, hostname string) Settings { + return Settings{Domain: domain, Hostname: hostname, MaxMessage: 10 << 20, MaxRecipients: 50, + TrashDays: 30, Outbound: OutboundDirect, QueueLife: 5 * 24 * time.Hour, MXPort: "25"} +} + +// Service is the e-mail of a BBS: its addresses and its deliveries. +type Service struct { + B *bbs.BBS + Set Settings + + kick chan struct{} // the queue has new mail + + mu sync.Mutex + watches map[int64][]chan struct{} // IDLE's, by user +} + +// New makes the service, and hooks it to the BBS: e-mail sent from the +// terminals, and mail delivered there told to IDLE. +func New(b *bbs.BBS, set Settings) *Service { + if set.Resolver == nil { + set.Resolver = net.DefaultResolver + } + if set.MXPort == "" { + set.MXPort = "25" + } + s := &Service{B: b, Set: set, kick: make(chan struct{}, 1), watches: map[int64][]chan struct{}{}} + b.Email = s.fromTerminal + b.MailWatch = s.notify + return s +} + +// Address is a user's e-mail address. +func (s *Service) Address(u *store.User) string { + return bbs.LocalPart(u.Name) + "@" + s.Set.Domain +} + +// AddressOf is the address of a user by name. +func (s *Service) AddressOf(name string) string { + return bbs.LocalPart(name) + "@" + s.Set.Domain +} + +// Mailbox is a user's address with their name: "Alice Smith" . +func (s *Service) Mailbox(name string) string { + return (&mail.Address{Name: name, Address: s.AddressOf(name)}).String() +} + +// ours reports whether a domain is this BBS's. +func (s *Service) ours(domain string) bool { + domain = strings.TrimSuffix(strings.ToLower(domain), ".") + return domain == strings.ToLower(s.Set.Domain) || domain == strings.ToLower(s.Set.Hostname) +} + +// role addresses go to the postmaster, whoever has the name +var roleAddresses = map[string]bool{"postmaster": true, "abuse": true, "mailer-daemon": true, "hostmaster": true, "webmaster": true} + +// ErrNoUser: no user here has that address. +var ErrNoUser = errors.New("no such user here") + +// LocalUser is the user an address here is for: by their name's local +// part (the oldest account, if two names make the same), "+tag" ignored; +// postmaster@ and the like are the postmaster's. +func (s *Service) LocalUser(local string) (*store.User, error) { + local = strings.ToLower(local) + if i := strings.IndexByte(local, '+'); i > 0 { + local = local[:i] + } + if roleAddresses[local] { + return s.postmaster() + } + users, err := s.B.Store.Users() + if err != nil { + return nil, err + } + var best *store.User + for _, u := range users { + if bbs.LocalPart(u.Name) == local && (best == nil || u.ID < best.ID) { + best = u + } + } + if best == nil || best.Locked { + return nil, ErrNoUser + } + return best, nil +} + +// postmaster is the user the role addresses go to. +func (s *Service) postmaster() (*store.User, error) { + if s.Set.Postmaster != "" { + return s.B.Store.UserByName(s.Set.Postmaster) + } + users, err := s.B.Store.Users() + if err != nil { + return nil, err + } + for _, u := range users { + if u.Sysop { + return u, nil + } + } + return nil, ErrNoUser +} + +// Login finds the user a mail program logs in as: by name, or by address +// here; the password is checked as the BBS's are, throttled. +func (s *Service) Login(who string, remote net.Addr, service, name, password string) (*store.User, error) { + if strings.Contains(name, "@") { + local, domain, _ := strings.Cut(name, "@") + if !s.ours(domain) { + return nil, ErrNoUser + } + if u, err := s.LocalUser(local); err == nil && !roleAddresses[strings.ToLower(local)] { + name = u.Name + } + } + // a local client's address is everyone's: its failures count + // against the account named + source := bbs.LocalSource(service, name) + if a, ok := remote.(*net.TCPAddr); ok && !a.IP.IsLoopback() { + source = "ip:" + a.IP.String() + } + return s.B.Authenticate(who, source, name, password) +} + +// mayMail reports whether u's access lets them mail anyone (else only the +// sysop). +func (s *Service) mayMail(u *store.User) bool { return s.B.LevelOf(u).Mail } + +// Kinds of recipient. +const ( + toLocal = iota + toFido + toInternet +) + +// recipient is an address read. +type recipient struct { + kind int + addr string // as given, cleaned + user *store.User + name string // FidoNet's + ftn ftn.Addr +} + +// fidoDomain is a FidoNet gateway's domain: [p4.]f100.n1.z21.fidonet[.org] +var fidoDomain = regexp.MustCompile(`^(?:p(\d+)\.)?f(\d+)\.n(\d+)\.z(\d+)\.fidonet(?:\.org|\.net)?$`) + +// fidoAddress is a FidoNet name and address as an e-mail address. +func fidoAddress(name string, a ftn.Addr) string { + d := fmt.Sprintf("f%d.n%d.z%d.fidonet", a.Node, a.Net, a.Zone) + if a.Point > 0 { + d = fmt.Sprintf("p%d.", a.Point) + d + } + return bbs.LocalPart(name) + "@" + d +} + +// resolve reads a recipient's address: a user here, FidoNet netmail (by +// the gateway's form, John.Smith@f100.n1.z21.fidonet), or the internet. +func (s *Service) resolve(addr string) (*recipient, error) { + a, err := mail.ParseAddress(addr) + if err != nil { + return nil, fmt.Errorf("%q is not an address", addr) + } + local, domain, ok := strings.Cut(a.Address, "@") + if !ok || local == "" || domain == "" { + return nil, fmt.Errorf("%q is not an address", addr) + } + if s.ours(domain) { + u, err := s.LocalUser(local) + if err != nil { + return nil, err + } + return &recipient{kind: toLocal, addr: a.Address, user: u}, nil + } + if m := fidoDomain.FindStringSubmatch(strings.ToLower(domain)); m != nil { + n := func(s string) int { v, _ := strconv.Atoi(s); return v } + fa := ftn.Addr{Zone: n(m[4]), Net: n(m[3]), Node: n(m[2]), Point: n(m[1])} + name := strings.Join(strings.Fields(strings.NewReplacer(".", " ", "_", " ").Replace(local)), " ") + return &recipient{kind: toFido, addr: a.Address, name: titleCase(name), ftn: fa}, nil + } + return &recipient{kind: toInternet, addr: a.Address}, nil +} + +// titleCase is "john smith" as "John Smith", as FidoNet names are. +func titleCase(s string) string { + f := strings.Fields(s) + for i, w := range f { + f[i] = strings.ToUpper(w[:1]) + w[1:] + } + return strings.Join(f, " ") +} + +// watch is a channel told when mail comes for the user, and what stops it. +func (s *Service) watch(user int64) (<-chan struct{}, func()) { + ch := make(chan struct{}, 1) + s.mu.Lock() + s.watches[user] = append(s.watches[user], ch) + s.mu.Unlock() + return ch, func() { + s.mu.Lock() + defer s.mu.Unlock() + l := s.watches[user] + for i, c := range l { + if c == ch { + s.watches[user] = append(l[:i], l[i+1:]...) + break + } + } + if len(s.watches[user]) == 0 { + delete(s.watches, user) + } + } +} + +// notify tells the user's watches. +func (s *Service) notify(user int64) { + s.mu.Lock() + defer s.mu.Unlock() + for _, c := range s.watches[user] { + select { + case c <- struct{}{}: + default: + } + } +} diff --git a/internal/email/imap.go b/internal/email/imap.go new file mode 100644 index 0000000..a4d6935 --- /dev/null +++ b/internal/email/imap.go @@ -0,0 +1,1025 @@ +package email + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "sort" + "strings" + "time" + + "github.com/emersion/go-imap/v2" + "github.com/emersion/go-imap/v2/imapserver" + "github.com/emersion/go-message/textproto" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" +) + +// IMAPServer is the IMAP server (RFC 3501, with NAMESPACE, UIDPLUS, MOVE, +// SPECIAL-USE, IDLE...). Its mailboxes are the user's folders, views of +// their mail (store.FolderNames), and stay as they are: none is made, +// renamed or deleted. A mail is put in a folder by what it is (COPY into +// Starred stars it, into Trash deletes it, out of Trash restores it), and +// taken out of one by EXPUNGE: to the trash, or for good from the trash. +type IMAPServer struct { + svc *Service + set ServerSettings + srv *imapserver.Server + ln *limited +} + +const delim = '/' + +// pollEvery is how often IDLE looks for mail delivered without a word to +// this server (by another process). +var pollEvery = 15 * time.Second + +// NewIMAP makes the IMAP server. +func (s *Service) NewIMAP(set ServerSettings) (*IMAPServer, error) { + tc, err := tlsConfig(set) + if err != nil { + return nil, fmt.Errorf("imap: %w", err) + } + x := &IMAPServer{svc: s, set: set} + opts := &imapserver.Options{ + NewSession: x.newSession, + Caps: imap.CapSet{imap.CapIMAP4rev1: {}, imap.CapNamespace: {}, imap.CapUIDPlus: {}, imap.CapMove: {}, + imap.CapSpecialUse: {}, imap.CapListStatus: {}, imap.CapListExtended: {}, imap.CapStatusSize: {}, + imap.CapESearch: {}, imap.CapSearchRes: {}, imap.CapChildren: {}}, + Logger: s.B.Log, + InsecureAuth: set.TLS == TLSNo || set.TLS == TLSOptional, + } + if set.TLS == TLSOptional || set.TLS == TLSRequired { + opts.TLSConfig = tc + } + x.srv = imapserver.New(opts) + x.ln, err = s.listen("imap", set, tc, func(why string) string { return "* BYE " + why + "\r\n" }) + if err != nil { + return nil, err + } + return x, nil +} + +// Run serves until ctx is done. +func (x *IMAPServer) Run(ctx context.Context) error { + x.svc.B.Log.Printf("imap: listening on %s (tls %s)", x.set.Address, x.set.TLS) + go func() { + <-ctx.Done() + x.srv.Close() + }() + err := x.srv.Serve(x.ln) + if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { + return nil + } + if err != nil { + return fmt.Errorf("imap: %w", err) + } + return nil +} + +func (x *IMAPServer) newSession(c *imapserver.Conn) (imapserver.Session, *imapserver.GreetingData, error) { + nc := c.NetConn() + nc.SetDeadline(time.Now().Add(x.set.IdleTimeout)) + return &imapSession{x: x, conn: c, who: "imap " + nc.RemoteAddr().String()}, nil, nil +} + +// imapSession is an IMAP client's connection. +type imapSession struct { + x *IMAPServer + conn *imapserver.Conn + who string + user *store.User + wake <-chan struct{} + stop func() + sel *selection +} + +// selection is the folder selected, as the client knows it: its mail in +// order of their numbers (sequence number i+1 is msgs[i]). +type selection struct { + folder int + readOnly bool + msgs []*store.BoxEntry + searchRes imap.UIDSet +} + +var ( + errNoFolder = &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeNonExistent, Text: "No such folder"} + errFixed = &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeCannot, Text: "The folders here are fixed: Inbox, Sent, Drafts, Starred, Unread, All Mail and Trash"} + errReadOnly = &imap.Error{Type: imap.StatusResponseTypeNo, Text: "The folder is read-only (EXAMINE)"} +) + +// touch keeps the connection from timing out while it is used. +func (is *imapSession) touch() { + is.conn.NetConn().SetDeadline(time.Now().Add(is.x.set.IdleTimeout)) +} + +func (is *imapSession) Close() error { + if is.stop != nil { + is.stop() + } + return nil +} + +// Login checks a login, as the BBS's are. +func (is *imapSession) Login(username, password string) error { + u, err := is.x.svc.Login(is.who, is.conn.NetConn().RemoteAddr(), "imap", username, password) + if err != nil { + return imapserver.ErrAuthFailed + } + is.user = u + is.wake, is.stop = is.x.svc.watch(u.ID) + is.x.svc.B.Log.Printf("%s: %s logged in", is.who, u.Name) + return nil +} + +// uidValidity is the user's UIDVALIDITY, the same for every folder: the +// numbers are never used again. +func (is *imapSession) uidValidity() uint32 { + v := uint32(is.user.Created.Unix()) + if v == 0 { + v = 1 + } + return v +} + +// folder is a folder by its name. +func folderOf(name string) (int, error) { + f := store.FolderByName(strings.TrimSuffix(name, string(delim))) + if f < 0 { + return 0, errNoFolder + } + return f, nil +} + +// specialUse is a folder's SPECIAL-USE attribute. +func specialUse(f int) imap.MailboxAttr { + switch f { + case store.FolderSent: + return imap.MailboxAttrSent + case store.FolderDrafts: + return imap.MailboxAttrDrafts + case store.FolderStarred: + return imap.MailboxAttrFlagged + case store.FolderAll: + return imap.MailboxAttrAll + case store.FolderTrash: + return imap.MailboxAttrTrash + } + return "" +} + +// flagsOf is an entry's flags. +func flagsOf(e *store.BoxEntry) []imap.Flag { + var out []imap.Flag + if e.Read { + out = append(out, imap.FlagSeen) + } + if e.Starred { + out = append(out, imap.FlagFlagged) + } + if e.Role == store.RoleDraft { + out = append(out, imap.FlagDraft) + } + for _, f := range strings.Fields(e.Flags) { + out = append(out, imap.Flag(f)) + } + return out +} + +// hasFlag reports whether an entry has a flag. +func hasFlag(e *store.BoxEntry, f imap.Flag) bool { + for _, g := range flagsOf(e) { + if strings.EqualFold(string(g), string(f)) { + return true + } + } + return false +} + +// splitFlags is a set of flags as an entry keeps them: read, starred, and +// the others (\Draft and \Recent are not set, but by what a mail is). +func splitFlags(flags []imap.Flag) (read, starred bool, others string) { + var rest []string + seen := map[string]bool{} + for _, f := range flags { + switch strings.ToLower(string(f)) { + case `\seen`: + read = true + case `\flagged`: + starred = true + case `\draft`, `\recent`, `\*`: + default: + k := strings.ToLower(string(f)) + if !seen[k] && validKeyword(string(f)) { + seen[k] = true + rest = append(rest, string(f)) + } + } + } + sort.Strings(rest) + others = strings.Join(rest, " ") + if len(others) > 900 { + others = others[:strings.LastIndex(others[:900], " ")+1] + } + return read, starred, strings.TrimSpace(others) +} + +// validKeyword: a flag of printable ASCII, no specials. +func validKeyword(f string) bool { + if f == "" || len(f) > 64 { + return false + } + for i := 0; i < len(f); i++ { + c := f[i] + if c <= ' ' || c > '~' || strings.IndexByte(`(){%*"]`, c) >= 0 || c == '\\' && i > 0 { + return false + } + } + return true +} + +// permanentFlags are those a client may set. +var permanentFlags = []imap.Flag{imap.FlagSeen, imap.FlagAnswered, imap.FlagFlagged, imap.FlagDeleted, + imap.FlagDraft, imap.FlagForwarded, imap.FlagWildcard} + +// Select selects a folder. +func (is *imapSession) Select(name string, options *imap.SelectOptions) (*imap.SelectData, error) { + is.touch() + f, err := folderOf(name) + if err != nil { + return nil, err + } + es, err := is.x.svc.B.Store.FolderEntries(is.user.ID, f) + if err != nil { + return nil, err + } + next, err := is.x.svc.B.Store.MailUIDNext() + if err != nil { + return nil, err + } + is.sel = &selection{folder: f, readOnly: options != nil && options.ReadOnly, msgs: es} + d := &imap.SelectData{Flags: permanentFlags[:len(permanentFlags)-1], PermanentFlags: permanentFlags, + NumMessages: uint32(len(es)), UIDNext: imap.UID(next), UIDValidity: is.uidValidity()} + for i, e := range es { + if !e.Read { + d.FirstUnseenSeqNum = uint32(i + 1) + break + } + } + if is.sel.readOnly { + d.PermanentFlags = nil + } + return d, nil +} + +func (is *imapSession) Unselect() error { + is.sel = nil + return nil +} + +func (is *imapSession) Create(name string, options *imap.CreateOptions) error { + if store.FolderByName(name) >= 0 { + return &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeAlreadyExists, Text: "It is there already"} + } + return errFixed +} + +func (is *imapSession) Delete(name string) error { return errFixed } + +func (is *imapSession) Rename(name, newName string, options *imap.RenameOptions) error { + return errFixed +} + +// Subscribe: every folder is subscribed. +func (is *imapSession) Subscribe(name string) error { + _, err := folderOf(name) + return err +} + +func (is *imapSession) Unsubscribe(name string) error { + _, err := folderOf(name) + return err +} + +// Namespace: the folders are personal, at the top. +func (is *imapSession) Namespace() (*imap.NamespaceData, error) { + return &imap.NamespaceData{Personal: []imap.NamespaceDescriptor{{Prefix: "", Delim: delim}}}, nil +} + +// List lists the folders that match. +func (is *imapSession) List(w *imapserver.ListWriter, ref string, patterns []string, options *imap.ListOptions) error { + is.touch() + if len(patterns) == 0 { + return w.WriteList(&imap.ListData{Attrs: []imap.MailboxAttr{imap.MailboxAttrNoSelect}, Delim: delim}) + } + for f, name := range store.FolderNames { + match := false + for _, p := range patterns { + match = match || imapserver.MatchList(name, delim, ref, p) + } + use := specialUse(f) + if !match || options.SelectSpecialUse && use == "" { + continue + } + d := &imap.ListData{Mailbox: name, Delim: delim, Attrs: []imap.MailboxAttr{imap.MailboxAttrHasNoChildren}} + if use != "" { + d.Attrs = append(d.Attrs, use) + } + if options.SelectSubscribed || options.ReturnSubscribed { + d.Attrs = append(d.Attrs, imap.MailboxAttrSubscribed) + } + if options.ReturnStatus != nil { + st, err := is.Status(name, options.ReturnStatus) + if err != nil { + return err + } + d.Status = st + } + if err := w.WriteList(d); err != nil { + return err + } + } + return nil +} + +// size is a mail's size as the client is told it. +func (is *imapSession) size(e *store.BoxEntry) int64 { + if e.Size > 0 { + return e.Size + } + raw, err := is.raw(e) + if err != nil { + return 0 + } + return int64(len(raw)) +} + +// raw is a mail's raw form. +func (is *imapSession) raw(e *store.BoxEntry) ([]byte, error) { + m, _, err := is.x.svc.B.Store.BoxMail(is.user.ID, e.Box) + if err != nil { + return nil, err + } + return crlf(is.x.svc.Render(m)), nil +} + +// Status is a folder's counts. +func (is *imapSession) Status(name string, options *imap.StatusOptions) (*imap.StatusData, error) { + is.touch() + f, err := folderOf(name) + if err != nil { + return nil, err + } + es, err := is.x.svc.B.Store.FolderEntries(is.user.ID, f) + if err != nil { + return nil, err + } + d := &imap.StatusData{Mailbox: store.FolderNames[f]} + n := uint32(len(es)) + if options.NumMessages { + d.NumMessages = &n + } + if options.UIDNext { + next, err := is.x.svc.B.Store.MailUIDNext() + if err != nil { + return nil, err + } + d.UIDNext = imap.UID(next) + } + if options.UIDValidity { + d.UIDValidity = is.uidValidity() + } + if options.NumUnseen { + var u uint32 + for _, e := range es { + if !e.Read { + u++ + } + } + d.NumUnseen = &u + } + if options.NumDeleted { + var del uint32 + for _, e := range es { + if hasFlag(e, imap.FlagDeleted) { + del++ + } + } + d.NumDeleted = &del + } + if options.NumRecent { + zero := uint32(0) + d.NumRecent = &zero + } + if options.Size { + var total int64 + for _, e := range es { + total += is.size(e) + } + d.Size = &total + } + return d, nil +} + +// Append keeps a mail the client puts in a folder: in Sent as the user's +// (once: a mail sent here and put there again is the one already there), +// in Drafts as a draft, else as received. +func (is *imapSession) Append(name string, r imap.LiteralReader, options *imap.AppendOptions) (*imap.AppendData, error) { + is.touch() + f, err := folderOf(name) + if err != nil { + return nil, &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeTryCreate, Text: "No such folder"} + } + svc := is.x.svc + raw, err := io.ReadAll(io.LimitReader(r, svc.Set.MaxMessage+1)) + if err != nil { + return nil, err + } + if int64(len(raw)) > svc.Set.MaxMessage { + return nil, &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeTooBig, Text: "Too big"} + } + raw = crlf(raw) + p, err := parse(raw) + if err != nil { + return nil, &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeParse, Text: "Not a mail"} + } + read, starred, others := splitFlags(options.Flags) + st := svc.B.Store + role := store.RoleReceived + switch f { + case store.FolderSent: + role = store.RoleSent + if p.messageID != "" { + if box, err := st.SentByMessageID(is.user.ID, p.messageID); err == nil { + return is.appended(box, f) + } + } + case store.FolderDrafts: + role = store.RoleDraft + case store.FolderStarred: + starred = true + case store.FolderUnread: + read = false + } + if role != store.RoleReceived { + read = true + } + subject := bbs.Clean(p.subject, bbs.MaxSubjectLen) + if subject == "" { + subject = "(no subject)" + } + m := &store.Message{Subject: subject, Body: terminalBody(p.text), Raw: raw, MessageID: p.messageID, + FromAddr: p.fromAddr, ToAddr: addressList(append(p.to, p.cc...)), Created: options.Time} + m.From = bbs.Clean(shownAddress(p.fromName, p.fromAddr), 200) + if role != store.RoleReceived { + m.FromID, m.From, m.FromAddr = is.user.ID, is.user.Name, "" + } + m.To = bbs.Clean(addressList(p.to), bbs.MaxMailToLen) + if m.Created.IsZero() { + m.Created = p.date + } + box, err := st.AppendMail(is.user.ID, role, m, read, starred, f == store.FolderTrash, others) + if err != nil { + return nil, err + } + return is.appended(box, f) +} + +// appended is APPEND's answer for an entry put in a folder. +func (is *imapSession) appended(box int64, f int) (*imap.AppendData, error) { + uid, err := is.x.svc.B.Store.BoxUID(box, f) + if err != nil { + return &imap.AppendData{UIDValidity: is.uidValidity()}, nil + } + return &imap.AppendData{UID: imap.UID(uid), UIDValidity: is.uidValidity()}, nil +} + +// Poll tells the client what changed in the selected folder since it was +// last told: mail gone (if it may be told now), flags changed, mail come. +func (is *imapSession) Poll(w *imapserver.UpdateWriter, allowExpunge bool) error { + sel := is.sel + if sel == nil { + return nil + } + is.touch() + fresh, err := is.x.svc.B.Store.FolderEntries(is.user.ID, sel.folder) + if err != nil { + return err + } + byUID := map[int64]*store.BoxEntry{} + for _, e := range fresh { + byUID[e.UID] = e + } + if allowExpunge { + for i := len(sel.msgs) - 1; i >= 0; i-- { + if byUID[sel.msgs[i].UID] == nil { + if err := w.WriteExpunge(uint32(i + 1)); err != nil { + return err + } + sel.msgs = append(sel.msgs[:i], sel.msgs[i+1:]...) + } + } + } + var max int64 + for i, e := range sel.msgs { + if e.UID > max { + max = e.UID + } + f := byUID[e.UID] + if f == nil { + continue + } + if !sameFlags(flagsOf(e), flagsOf(f)) { + if err := w.WriteMessageFlags(uint32(i+1), imap.UID(f.UID), flagsOf(f)); err != nil { + return err + } + } + sel.msgs[i] = f + } + n := len(sel.msgs) + for _, e := range fresh { + if e.UID > max { + sel.msgs = append(sel.msgs, e) + } + } + if len(sel.msgs) != n { + return w.WriteNumMessages(uint32(len(sel.msgs))) + } + return nil +} + +func sameFlags(a, b []imap.Flag) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if !strings.EqualFold(string(a[i]), string(b[i])) { + return false + } + } + return true +} + +// Idle waits for changes, telling of them, until the client is done. +func (is *imapSession) Idle(w *imapserver.UpdateWriter, stop <-chan struct{}) error { + t := time.NewTicker(pollEvery) + defer t.Stop() + for { + if err := is.Poll(w, true); err != nil { + return err + } + select { + case <-stop: + return nil + case <-is.wake: + case <-t.C: + } + } +} + +// staticNumSet makes "*" and "$" a set's numbers. +func (sel *selection) staticNumSet(numSet imap.NumSet) imap.NumSet { + if imap.IsSearchRes(numSet) { + return sel.searchRes + } + switch ns := numSet.(type) { + case imap.SeqSet: + max := uint32(len(sel.msgs)) + out := make(imap.SeqSet, len(ns)) + copy(out, ns) + for i := range out { + staticRange(&out[i].Start, &out[i].Stop, max) + } + return out + case imap.UIDSet: + var max uint32 + if len(sel.msgs) > 0 { + max = uint32(sel.msgs[len(sel.msgs)-1].UID) + } + out := make(imap.UIDSet, len(ns)) + copy(out, ns) + for i := range out { + staticRange((*uint32)(&out[i].Start), (*uint32)(&out[i].Stop), max) + } + return out + } + return numSet +} + +func staticRange(start, stop *uint32, max uint32) { + dyn := false + if *start == 0 { + *start, dyn = max, true + } + if *stop == 0 { + *stop, dyn = max, true + } + if dyn && *start > *stop { + *start, *stop = *stop, *start + } +} + +// each calls f for the selected folder's mail in a set, by sequence +// number. +func (sel *selection) each(numSet imap.NumSet, f func(seq uint32, e *store.BoxEntry) error) error { + numSet = sel.staticNumSet(numSet) + for i, e := range sel.msgs { + seq := uint32(i + 1) + var in bool + switch ns := numSet.(type) { + case imap.SeqSet: + in = ns.Contains(seq) + case imap.UIDSet: + in = ns.Contains(imap.UID(e.UID)) + } + if in { + if err := f(seq, e); err != nil { + return err + } + } + } + return nil +} + +// Fetch answers FETCH; a body fetched (not peeked) marks the mail read. +func (is *imapSession) Fetch(w *imapserver.FetchWriter, numSet imap.NumSet, options *imap.FetchOptions) error { + is.touch() + sel := is.sel + markSeen := false + for _, bs := range options.BodySection { + markSeen = markSeen || !bs.Peek + } + needRaw := options.Envelope || options.BodyStructure != nil || len(options.BodySection) > 0 || + len(options.BinarySection) > 0 || len(options.BinarySectionSize) > 0 + return sel.each(numSet, func(seq uint32, e *store.BoxEntry) error { + var raw []byte + if needRaw || options.RFC822Size && e.Size == 0 { + var err error + if raw, err = is.raw(e); err != nil { + return nil // gone since: nothing to say of it + } + } + flagsChanged := false + if markSeen && !e.Read && !sel.readOnly { + if err := is.x.svc.B.Store.SetBoxFlags(is.user.ID, e.Box, true, e.Starred, e.Flags); err == nil { + e.Read, flagsChanged = true, true + } + } + rw := w.CreateMessage(seq) + rw.WriteUID(imap.UID(e.UID)) + if options.Flags || flagsChanged { + rw.WriteFlags(flagsOf(e)) + } + if options.InternalDate { + rw.WriteInternalDate(e.Created) + } + if options.RFC822Size { + if e.Size > 0 { + rw.WriteRFC822Size(e.Size) + } else { + rw.WriteRFC822Size(int64(len(raw))) + } + } + if options.Envelope { + if h, err := textproto.ReadHeader(bufio.NewReader(bytes.NewReader(raw))); err == nil { + rw.WriteEnvelope(imapserver.ExtractEnvelope(h)) + } + } + if options.BodyStructure != nil { + rw.WriteBodyStructure(imapserver.ExtractBodyStructure(bytes.NewReader(raw))) + } + for _, bs := range options.BodySection { + buf := imapserver.ExtractBodySection(bytes.NewReader(raw), bs) + wc := rw.WriteBodySection(bs, int64(len(buf))) + _, werr := wc.Write(buf) + if cerr := wc.Close(); werr == nil { + werr = cerr + } + if werr != nil { + return werr + } + } + for _, bs := range options.BinarySection { + buf := imapserver.ExtractBinarySection(bytes.NewReader(raw), bs) + wc := rw.WriteBinarySection(bs, int64(len(buf))) + _, werr := wc.Write(buf) + if cerr := wc.Close(); werr == nil { + werr = cerr + } + if werr != nil { + return werr + } + } + for _, bss := range options.BinarySectionSize { + rw.WriteBinarySectionSize(bss, imapserver.ExtractBinarySectionSize(bytes.NewReader(raw), bss)) + } + return rw.Close() + }) +} + +// Store changes flags. +func (is *imapSession) Store(w *imapserver.FetchWriter, numSet imap.NumSet, flags *imap.StoreFlags, options *imap.StoreOptions) error { + is.touch() + sel := is.sel + if sel.readOnly { + return errReadOnly + } + st := is.x.svc.B.Store + return sel.each(numSet, func(seq uint32, e *store.BoxEntry) error { + now := flagsOf(e) + var next []imap.Flag + switch flags.Op { + case imap.StoreFlagsSet: + next = flags.Flags + case imap.StoreFlagsAdd: + next = append(now, flags.Flags...) + case imap.StoreFlagsDel: + drop := map[string]bool{} + for _, f := range flags.Flags { + drop[strings.ToLower(string(f))] = true + } + for _, f := range now { + if !drop[strings.ToLower(string(f))] { + next = append(next, f) + } + } + } + read, starred, others := splitFlags(next) + if err := st.SetBoxFlags(is.user.ID, e.Box, read, starred, others); err != nil { + if errors.Is(err, store.ErrNotFound) { + return nil + } + return err + } + e.Read, e.Starred, e.Flags = read, starred, others + if !flags.Silent { + rw := w.CreateMessage(seq) + rw.WriteUID(imap.UID(e.UID)) + rw.WriteFlags(flagsOf(e)) + return rw.Close() + } + return nil + }) +} + +// takeOut takes an entry out of a folder, as EXPUNGE does: out of Starred +// it is unstarred, out of Unread read, out of the trash deleted for good, +// out of any other into the trash. +func (is *imapSession) takeOut(e *store.BoxEntry, folder int) error { + st := is.x.svc.B.Store + _, _, others := splitFlags(withoutFlag(flagsOf(e), imap.FlagDeleted)) + switch folder { + case store.FolderTrash: + return st.PurgeBox(is.user.ID, e.Box) + case store.FolderStarred: + return st.SetBoxFlags(is.user.ID, e.Box, e.Read, false, others) + case store.FolderUnread: + return st.SetBoxFlags(is.user.ID, e.Box, true, e.Starred, others) + } + if err := st.SetBoxFlags(is.user.ID, e.Box, e.Read, e.Starred, others); err != nil { + return err + } + return st.TrashBox(is.user.ID, e.Box) +} + +func withoutFlag(l []imap.Flag, f imap.Flag) []imap.Flag { + var out []imap.Flag + for _, g := range l { + if !strings.EqualFold(string(g), string(f)) { + out = append(out, g) + } + } + return out +} + +// Expunge takes the mail marked \Deleted out of the folder. +func (is *imapSession) Expunge(w *imapserver.ExpungeWriter, uids *imap.UIDSet) error { + is.touch() + sel := is.sel + if sel.readOnly { + return errReadOnly + } + for i := len(sel.msgs) - 1; i >= 0; i-- { + e := sel.msgs[i] + if uids != nil && !uids.Contains(imap.UID(e.UID)) || !hasFlag(e, imap.FlagDeleted) { + continue + } + if err := is.takeOut(e, sel.folder); err != nil && !errors.Is(err, store.ErrNotFound) { + return err + } + if err := w.WriteExpunge(uint32(i + 1)); err != nil { + return err + } + sel.msgs = append(sel.msgs[:i], sel.msgs[i+1:]...) + } + return nil +} + +// putIn puts an entry in a folder, as COPY does; ok false if it cannot go +// there. +func (is *imapSession) putIn(e *store.BoxEntry, folder int) (bool, error) { + st := is.x.svc.B.Store + u := is.user.ID + trashed := !e.Deleted.IsZero() + switch folder { + case store.FolderTrash: + if trashed { + return true, nil + } + return true, st.TrashBox(u, e.Box) + case store.FolderStarred: + if err := st.SetBoxFlags(u, e.Box, e.Read, true, e.Flags); err != nil { + return false, err + } + if trashed { + return true, st.RestoreBox(u, e.Box) + } + return true, nil + case store.FolderUnread: + if e.Role != store.RoleReceived { + return false, nil + } + if err := st.SetBoxFlags(u, e.Box, false, e.Starred, e.Flags); err != nil { + return false, err + } + case store.FolderInbox: + if e.Role != store.RoleReceived { + return false, nil + } + case store.FolderSent: + if e.Role != store.RoleSent { + return false, nil + } + case store.FolderDrafts: + if e.Role != store.RoleDraft { + return false, nil + } + case store.FolderAll: + if e.Role == store.RoleDraft { + return false, nil + } + } + if trashed { + return true, st.RestoreBox(u, e.Box) + } + return true, nil +} + +// copyTo puts the mail of a set in a folder: the numbers they have there. +func (is *imapSession) copyTo(numSet imap.NumSet, dest string, each func(seq uint32, e *store.BoxEntry) error) (*imap.CopyData, error) { + is.touch() + sel := is.sel + f, err := folderOf(dest) + if err != nil { + return nil, &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeTryCreate, Text: "No such folder"} + } + if f == sel.folder { + return nil, &imap.Error{Type: imap.StatusResponseTypeNo, Text: "It is in that folder already"} + } + d := &imap.CopyData{UIDValidity: is.uidValidity()} + var cannot []string + err = sel.each(numSet, func(seq uint32, e *store.BoxEntry) error { + ok, err := is.putIn(e, f) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + return nil + } + return err + } + if !ok { + cannot = append(cannot, fmt.Sprint(e.UID)) + return nil + } + if uid, err := is.x.svc.B.Store.BoxUID(e.Box, f); err == nil { + d.SourceUIDs.AddNum(imap.UID(e.UID)) + d.DestUIDs.AddNum(imap.UID(uid)) + } + if each != nil { + return each(seq, e) + } + return nil + }) + if err != nil { + return nil, err + } + if len(cannot) > 0 && len(d.SourceUIDs) == 0 { + return nil, &imap.Error{Type: imap.StatusResponseTypeNo, Code: imap.ResponseCodeCannot, + Text: "Mail goes in " + store.FolderNames[f] + " only by what it is (received, sent, a draft)"} + } + return d, nil +} + +// Copy puts mail in another folder. +func (is *imapSession) Copy(numSet imap.NumSet, dest string) (*imap.CopyData, error) { + if is.sel.readOnly { + return nil, errReadOnly + } + return is.copyTo(numSet, dest, nil) +} + +// Move puts mail in another folder; what is no longer in this one is said +// to be gone. +func (is *imapSession) Move(w *imapserver.MoveWriter, numSet imap.NumSet, dest string) error { + sel := is.sel + if sel.readOnly { + return errReadOnly + } + var moved []int64 + d, err := is.copyTo(numSet, dest, func(seq uint32, e *store.BoxEntry) error { + moved = append(moved, e.Box) + return nil + }) + if err != nil { + return err + } + if err := w.WriteCopyData(d); err != nil { + return err + } + st := is.x.svc.B.Store + gone := map[int64]bool{} + for _, b := range moved { + if _, err := st.BoxUID(b, sel.folder); errors.Is(err, store.ErrNotFound) { + gone[b] = true + } + } + for i := len(sel.msgs) - 1; i >= 0; i-- { + if gone[sel.msgs[i].Box] { + if err := w.WriteExpunge(uint32(i + 1)); err != nil { + return err + } + sel.msgs = append(sel.msgs[:i], sel.msgs[i+1:]...) + } + } + return nil +} + +// Search answers SEARCH. +func (is *imapSession) Search(kind imapserver.NumKind, criteria *imap.SearchCriteria, options *imap.SearchOptions) (*imap.SearchData, error) { + is.touch() + sel := is.sel + is.staticCriteria(criteria) + var d imap.SearchData + var seqs imap.SeqSet + var uids imap.UIDSet + for i, e := range sel.msgs { + seq := uint32(i + 1) + mm := &matcher{is: is, e: e} + if !mm.match(seq, criteria) { + continue + } + uids.AddNum(imap.UID(e.UID)) + num := seq + if kind == imapserver.NumKindUID { + num = uint32(e.UID) + } else { + seqs.AddNum(seq) + } + if d.Min == 0 || num < d.Min { + d.Min = num + } + if num > d.Max { + d.Max = num + } + d.Count++ + } + if kind == imapserver.NumKindUID { + d.All = uids + } else { + d.All = seqs + } + if options.ReturnSave { + sel.searchRes = uids + } + return &d, nil +} + +// staticCriteria makes the number sets of a search's criteria static. +func (is *imapSession) staticCriteria(c *imap.SearchCriteria) { + sel := is.sel + var seqs []imap.SeqSet + for _, s := range c.SeqNum { + switch ns := sel.staticNumSet(s).(type) { + case imap.SeqSet: + seqs = append(seqs, ns) + case imap.UIDSet: + c.UID = append(c.UID, ns) + } + } + c.SeqNum = seqs + for i := range c.UID { + c.UID[i] = sel.staticNumSet(c.UID[i]).(imap.UIDSet) + } + for i := range c.Not { + is.staticCriteria(&c.Not[i]) + } + for i := range c.Or { + is.staticCriteria(&c.Or[i][0]) + is.staticCriteria(&c.Or[i][1]) + } +} diff --git a/internal/email/imapsearch.go b/internal/email/imapsearch.go new file mode 100644 index 0000000..dc00937 --- /dev/null +++ b/internal/email/imapsearch.go @@ -0,0 +1,167 @@ +package email + +// The matching here follows go-imap's imapmemserver (MIT licence, +// Copyright (c) 2013 The Go-IMAP Authors), on mail read from the store. + +import ( + "bytes" + "io" + "strings" + "time" + + "github.com/emersion/go-imap/v2" + gomessage "github.com/emersion/go-message" + gomail "github.com/emersion/go-message/mail" + + "github.com/D-Modem/bbs/internal/store" +) + +// matcher matches one mail against search criteria, reading it only if +// they need it. +type matcher struct { + is *imapSession + e *store.BoxEntry + raw []byte + loaded bool +} + +func (mm *matcher) load() []byte { + if !mm.loaded { + mm.raw, _ = mm.is.raw(mm.e) + mm.loaded = true + } + return mm.raw +} + +func (mm *matcher) entity() *gomessage.Entity { + e, _ := gomessage.Read(bytes.NewReader(mm.load())) + if e == nil { + e, _ = gomessage.New(gomessage.Header{}, bytes.NewReader(nil)) + } + return e +} + +func (mm *matcher) match(seq uint32, c *imap.SearchCriteria) bool { + for _, s := range c.SeqNum { + if seq == 0 || !s.Contains(seq) { + return false + } + } + for _, s := range c.UID { + if !s.Contains(imap.UID(mm.e.UID)) { + return false + } + } + if !matchDate(mm.e.Created, c.Since, c.Before) { + return false + } + for _, f := range c.Flag { + if !hasFlag(mm.e, f) { + return false + } + } + for _, f := range c.NotFlag { + if hasFlag(mm.e, f) { + return false + } + } + if c.Larger != 0 || c.Smaller != 0 { + n := mm.is.size(mm.e) + if c.Larger != 0 && n <= c.Larger || c.Smaller != 0 && n >= c.Smaller { + return false + } + } + if len(c.Header) > 0 || !c.SentSince.IsZero() || !c.SentBefore.IsZero() { + h := gomail.Header{Header: mm.entity().Header} + for _, f := range c.Header { + if !matchFields(h.FieldsByKey(f.Key), f.Value) { + return false + } + } + if !c.SentSince.IsZero() || !c.SentBefore.IsZero() { + t, err := h.Date() + if err != nil || !matchDate(t, c.SentSince, c.SentBefore) { + return false + } + } + } + for _, t := range c.Text { + if !matchEntity(mm.entity(), t, true) { + return false + } + } + for _, b := range c.Body { + if !matchEntity(mm.entity(), b, false) { + return false + } + } + for i := range c.Not { + if mm.match(seq, &c.Not[i]) { + return false + } + } + for i := range c.Or { + if !mm.match(seq, &c.Or[i][0]) && !mm.match(seq, &c.Or[i][1]) { + return false + } + } + return true +} + +// matchDate compares dates without their zones, as RFC 3501 says. +func matchDate(t, since, before time.Time) bool { + t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC) + if !since.IsZero() && t.Before(since) { + return false + } + if !before.IsZero() && !t.Before(before) { + return false + } + return true +} + +func matchFields(fields gomessage.HeaderFields, pattern string) bool { + if pattern == "" { + return fields.Len() > 0 + } + pattern = strings.ToLower(pattern) + for fields.Next() { + v, _ := fields.Text() + if strings.Contains(strings.ToLower(v), pattern) { + return true + } + } + return false +} + +func matchEntity(e *gomessage.Entity, pattern string, header bool) bool { + if pattern == "" { + return true + } + if header && matchFields(e.Header.Fields(), pattern) { + return true + } + if mr := e.MultipartReader(); mr != nil { + for { + part, err := mr.NextPart() + if err != nil { + return false + } + if matchEntity(part, pattern, header) { + return true + } + } + } + t, _, err := e.Header.ContentType() + if err != nil && t == "" { + t = "text/plain" + } + if !strings.HasPrefix(t, "text/") && !strings.HasPrefix(t, "message/") { + return false + } + b, err := io.ReadAll(io.LimitReader(e.Body, readLimit)) + if err != nil { + return false + } + return bytes.Contains(bytes.ToLower(b), bytes.ToLower([]byte(pattern))) +} diff --git a/internal/email/listen.go b/internal/email/listen.go new file mode 100644 index 0000000..5241747 --- /dev/null +++ b/internal/email/listen.go @@ -0,0 +1,169 @@ +package email + +import ( + "crypto/tls" + "errors" + "fmt" + "io" + "net" + "strings" + "sync" + "time" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/sockets" +) + +// TLS modes of a server. +const ( + TLSNo = "no" // none: passwords in the clear + TLSOptional = "optional" // STARTTLS (STLS) offered + TLSRequired = "required" // STARTTLS before a login, or (SMTP) before mail + TLSImplicit = "implicit" // TLS from the first byte (993, 995, 465) +) + +// ServerSettings are a mail server's section's: [pop3], [imap], [smtp], +// [mx], [lmtp]. +type ServerSettings struct { + Address string // host:port, or a unix socket's path (LMTP) + TLS string + CertFile string + KeyFile string + MaxClients int + MaxPerIP int + IdleTimeout time.Duration +} + +// tlsConfig is a server's certificate, if TLS is on. +func tlsConfig(set ServerSettings) (*tls.Config, error) { + if set.TLS == "" || set.TLS == TLSNo { + return nil, nil + } + cert, err := tls.LoadX509KeyPair(set.CertFile, set.KeyFile) + if err != nil { + return nil, fmt.Errorf("certificate: %w", err) + } + return &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12}, nil +} + +// isUnix reports whether an address is a unix socket's path. +func isUnix(addr string) bool { return strings.HasPrefix(addr, "/") || strings.HasPrefix(addr, "./") } + +// limited is a listener that lets in only those the BBS's guard and the +// server's limits allow, telling the others why (busy: the protocol's +// words), and makes TLS implicit ones TLS. +type limited struct { + net.Listener + b *bbs.BBS + service string + set ServerSettings + tls *tls.Config + busy func(why string) string + + mu sync.Mutex + clients int + perIP map[string]int +} + +// listen listens as a server's settings say. +func (s *Service) listen(service string, set ServerSettings, tc *tls.Config, busy func(string) string) (*limited, error) { + network := "tcp" + if isUnix(set.Address) { + network = "unix" + } + ln, err := sockets.Listen(network, set.Address) + if err != nil { + return nil, fmt.Errorf("%s: %w", service, err) + } + l := &limited{Listener: ln, b: s.B, service: service, set: set, busy: busy, perIP: map[string]int{}} + if set.TLS == TLSImplicit { + l.tls = tc + } + return l, nil +} + +// hostOf is a TCP address's IP ("" for another kind of address). +func hostOf(a net.Addr) string { + if t, ok := a.(*net.TCPAddr); ok { + return t.IP.String() + } + return "" +} + +// Accept is the next connection let in. +func (l *limited) Accept() (net.Conn, error) { + for { + c, err := l.Listener.Accept() + if err != nil { + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + time.Sleep(100 * time.Millisecond) + continue + } + return nil, err + } + if why := l.admit(c); why != "" { + go func() { + c.SetWriteDeadline(time.Now().Add(5 * time.Second)) + io.WriteString(c, l.busy(why)) + c.Close() + }() + continue + } + cc := &counted{Conn: c, l: l} + if l.tls != nil { + return tls.Server(cc, l.tls), nil + } + return cc, nil + } +} + +// admit counts a connection in, or is why not. +func (l *limited) admit(c net.Conn) string { + if l.b.Refuse(l.service, c.RemoteAddr()) { + return "not here" + } + h := hostOf(c.RemoteAddr()) + l.mu.Lock() + defer l.mu.Unlock() + if l.set.MaxClients > 0 && l.clients >= l.set.MaxClients { + return "too many connections; try again later" + } + if h != "" && l.set.MaxPerIP > 0 && l.perIP[h] >= l.set.MaxPerIP { + return "too many connections from your address" + } + l.clients++ + if h != "" { + l.perIP[h]++ + } + return "" +} + +// release counts a connection out. +func (l *limited) release(c net.Conn) { + h := hostOf(c.RemoteAddr()) + l.mu.Lock() + defer l.mu.Unlock() + l.clients-- + if h != "" { + if l.perIP[h]--; l.perIP[h] <= 0 { + delete(l.perIP, h) + } + } +} + +// counted is a connection admitted, counted out when closed. +type counted struct { + net.Conn + l *limited + once sync.Once +} + +func (c *counted) Close() error { + c.once.Do(func() { c.l.release(c.Conn) }) + return c.Conn.Close() +} + +// remoteOf is the address a connection (perhaps TLS, perhaps counted) +// comes from. +func remoteOf(c net.Conn) net.Addr { return c.RemoteAddr() } diff --git a/internal/email/message.go b/internal/email/message.go new file mode 100644 index 0000000..9138c03 --- /dev/null +++ b/internal/email/message.go @@ -0,0 +1,329 @@ +package email + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "fmt" + "html" + "io" + "mime" + "mime/quotedprintable" + "net/mail" + "regexp" + "strings" + "time" + + _ "github.com/emersion/go-message/charset" // the charsets mail comes in + gomail "github.com/emersion/go-message/mail" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" +) + +// fromAddress is who a mail kept here is from, as an address. +func (s *Service) fromAddress(m *store.Message) *mail.Address { + switch { + case m.FromAddr != "": + return &mail.Address{Name: m.From, Address: m.FromAddr} + case m.FromID > 0: + return &mail.Address{Name: m.From, Address: s.AddressOf(m.From)} + } + if name, a, ok := bbs.SplitNetmail(m.From); ok { + return &mail.Address{Name: name, Address: fidoAddress(name, a)} + } + return &mail.Address{Name: m.From, Address: "postmaster@" + s.Set.Domain} +} + +// toField is who a mail kept here is to, as To says it. +func (s *Service) toField(m *store.Message) string { + if m.ToAddr != "" { + if l, err := mail.ParseAddressList(m.ToAddr); err == nil { + out := make([]string, len(l)) + for i, a := range l { + out[i] = a.String() + } + return strings.Join(out, ", ") + } + } + if name, a, ok := bbs.SplitNetmail(m.To); ok { + return (&mail.Address{Name: name, Address: fidoAddress(name, a)}).String() + } + return s.Mailbox(m.To) +} + +// messageID is a mail's Message-ID: its own, or one made of its id. +func (s *Service) messageID(m *store.Message) string { + if m.MessageID != "" { + return m.MessageID + } + return fmt.Sprintf("", m.ID, s.Set.Hostname) +} + +// newMessageID is a new Message-ID of this server's. +func (s *Service) newMessageID() string { + var b [12]byte + rand.Read(b[:]) + return fmt.Sprintf("<%d.%s@%s>", time.Now().Unix(), hex.EncodeToString(b[:]), s.Set.Hostname) +} + +// Render is a mail as a mail program has it: as it came, or, for one +// written here, made of it (the same each time: its size does not change). +func (s *Service) Render(m *store.Message) []byte { + if m.Raw != nil { + return m.Raw + } + var b bytes.Buffer + field := func(k, v string) { fmt.Fprintf(&b, "%s: %s\r\n", k, v) } + field("From", s.fromAddress(m).String()) + field("To", s.toField(m)) + field("Subject", mime.QEncoding.Encode("utf-8", m.Subject)) + field("Date", m.Created.Format(time.RFC1123Z)) + field("Message-ID", s.messageID(m)) + if m.ReplyTo > 0 { + field("In-Reply-To", fmt.Sprintf("", m.ReplyTo, s.Set.Hostname)) + } + writeTextBody(&b, m.Body) + return b.Bytes() +} + +// writeTextBody writes the MIME fields of a plain text body, and the body: +// 8bit, or quoted-printable if a line is too long for it. +func writeTextBody(b *bytes.Buffer, body string) { + lines := strings.Split(strings.TrimRight(strings.ReplaceAll(body, "\r\n", "\n"), "\n"), "\n") + qp := false + for _, l := range lines { + qp = qp || len(l) > 900 + } + b.WriteString("MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n") + if !qp { + b.WriteString("Content-Transfer-Encoding: 8bit\r\n\r\n") + for _, l := range lines { + b.WriteString(strings.TrimRight(l, "\r") + "\r\n") + } + return + } + b.WriteString("Content-Transfer-Encoding: quoted-printable\r\n\r\n") + w := quotedprintable.NewWriter(b) + w.Write([]byte(strings.Join(lines, "\r\n") + "\r\n")) + w.Close() +} + +// parsed is what the BBS shows of a mail that came as RFC 5322. +type parsed struct { + fromName, fromAddr string + to []*mail.Address + cc []*mail.Address + subject string + date time.Time + messageID string + inReplyTo string + text string // the body for the terminals +} + +// readLimit is the most of a part read for its text. +const readLimit = 1 << 20 + +var ( + htmlBreaks = regexp.MustCompile(`(?i)<\s*(br|/p|/div|/li|/tr|/h[1-6])[^>]*>`) + htmlDrop = regexp.MustCompile(`(?is)<(script|style|head)[^>]*>.*?`) + htmlTags = regexp.MustCompile(`(?s)<[^>]*>`) + blankRuns = regexp.MustCompile(`\n{3,}`) +) + +// htmlText is HTML as plain text, roughly. +func htmlText(h string) string { + h = htmlDrop.ReplaceAllString(h, "") + h = htmlBreaks.ReplaceAllString(h, "\n") + h = htmlTags.ReplaceAllString(h, "") + h = html.UnescapeString(h) + var lines []string + for _, l := range strings.Split(h, "\n") { + lines = append(lines, strings.Join(strings.Fields(l), " ")) + } + return strings.TrimSpace(blankRuns.ReplaceAllString(strings.Join(lines, "\n"), "\n\n")) +} + +// parse reads a mail: its header and its text (the first plain text part, +// else the first HTML one as text), its attachments listed after it. +func parse(raw []byte) (*parsed, error) { + mr, err := gomail.CreateReader(bytes.NewReader(raw)) + if err != nil && mr == nil { + return nil, err + } + p := &parsed{} + h := mr.Header + if l, err := h.AddressList("From"); err == nil && len(l) > 0 { + p.fromName, p.fromAddr = l[0].Name, l[0].Address + } else if v, _ := h.Text("From"); v != "" { + p.fromName = v + } + if l, err := h.AddressList("To"); err == nil { + p.to = convert(l) + } + if l, err := h.AddressList("Cc"); err == nil { + p.cc = convert(l) + } + p.subject, _ = h.Subject() + p.date, _ = h.Date() + p.messageID = h.Get("Message-ID") + p.inReplyTo = h.Get("In-Reply-To") + var plain, htm string + var attached []string + for { + part, err := mr.NextPart() + if err != nil { + break // io.EOF, or a part that cannot be read: what was read is kept + } + switch ph := part.Header.(type) { + case *gomail.InlineHeader: + ct, _, _ := ph.ContentType() + switch { + case ct == "text/plain" && plain == "", ct == "" && plain == "": + b, _ := io.ReadAll(io.LimitReader(part.Body, readLimit)) + plain = string(b) + case ct == "text/html" && htm == "": + b, _ := io.ReadAll(io.LimitReader(part.Body, readLimit)) + htm = string(b) + default: + n, _ := io.Copy(io.Discard, part.Body) + attached = append(attached, fmt.Sprintf("(%s, %s)", ct, size(n))) + } + case *gomail.AttachmentHeader: + name, _ := ph.Filename() + if name == "" { + name = "(unnamed)" + } + n, _ := io.Copy(io.Discard, part.Body) + attached = append(attached, fmt.Sprintf("%s (%s)", name, size(n))) + } + } + p.text = plain + if strings.TrimSpace(p.text) == "" && htm != "" { + p.text = htmlText(htm) + } + if len(attached) > 0 { + p.text = strings.TrimRight(p.text, "\r\n") + "\n\n[Attached, for a mail program to open: " + strings.Join(attached, ", ") + "]" + } + return p, nil +} + +func convert(l []*gomail.Address) []*mail.Address { + out := make([]*mail.Address, len(l)) + for i, a := range l { + out[i] = &mail.Address{Name: a.Name, Address: a.Address} + } + return out +} + +// size is a size in bytes for people. +func size(n int64) string { + switch { + case n >= 1<<20: + return fmt.Sprintf("%.1f MB", float64(n)/(1<<20)) + case n >= 1<<10: + return fmt.Sprintf("%d KB", (n+512)>>10) + } + return fmt.Sprintf("%d bytes", n) +} + +// terminalBody is a mail's text as the terminals keep it: lines wrapped +// and cleaned, within the BBS's limits. +func terminalBody(text string) string { + body := bbs.CleanBody(bbs.WrapBody(text)) + if body == "" { + body = "(empty)" + } + return body +} + +// addressList is addresses as a header says them. +func addressList(l []*mail.Address) string { + out := make([]string, len(l)) + for i, a := range l { + out[i] = a.String() + } + return strings.Join(out, ", ") +} + +// headerEnd is where a raw mail's header ends (its blank line's start), or +// -1. +func headerEnd(raw []byte) int { + if bytes.HasPrefix(raw, []byte("\r\n")) || bytes.HasPrefix(raw, []byte("\n")) { + return 0 + } + if i := bytes.Index(raw, []byte("\r\n\r\n")); i >= 0 { + return i + 2 + } + if i := bytes.Index(raw, []byte("\n\n")); i >= 0 { + return i + 1 + } + return -1 +} + +// headerFields is a raw header's fields, unfolded, in order: name and +// value. +func headerFields(raw []byte) [][2]string { + end := headerEnd(raw) + if end < 0 { + end = len(raw) + } + var out [][2]string + for _, line := range strings.Split(strings.ReplaceAll(string(raw[:end]), "\r\n", "\n"), "\n") { + if line == "" { + continue + } + if (line[0] == ' ' || line[0] == '\t') && len(out) > 0 { + out[len(out)-1][1] += " " + strings.TrimSpace(line) + continue + } + k, v, ok := strings.Cut(line, ":") + if !ok { + continue + } + out = append(out, [2]string{strings.TrimSpace(k), strings.TrimSpace(v)}) + } + return out +} + +// withoutFields is a raw mail with the header fields of those names (in +// any case) taken out, folded lines and all. +func withoutFields(raw []byte, names ...string) []byte { + end := headerEnd(raw) + if end < 0 { + return raw + } + drop := map[string]bool{} + for _, n := range names { + drop[strings.ToLower(n)] = true + } + var out bytes.Buffer + skipping := false + for _, line := range bytes.SplitAfter(raw[:end], []byte("\n")) { + if len(line) == 0 { + continue + } + if line[0] == ' ' || line[0] == '\t' { + if !skipping { + out.Write(line) + } + continue + } + k, _, _ := bytes.Cut(line, []byte(":")) + skipping = drop[strings.ToLower(string(bytes.TrimSpace(k)))] + if !skipping { + out.Write(line) + } + } + out.Write(raw[end:]) + return out.Bytes() +} + +// crlf is a raw mail with its lines ended by CRLF. +func crlf(raw []byte) []byte { + if !bytes.Contains(raw, []byte("\n")) { + return raw + } + raw = bytes.ReplaceAll(raw, []byte("\r\n"), []byte("\n")) + return bytes.ReplaceAll(raw, []byte("\n"), []byte("\r\n")) +} diff --git a/internal/email/pop3.go b/internal/email/pop3.go new file mode 100644 index 0000000..9768b11 --- /dev/null +++ b/internal/email/pop3.go @@ -0,0 +1,450 @@ +package email + +import ( + "bufio" + "bytes" + "context" + "crypto/tls" + "encoding/base64" + "errors" + "fmt" + "net" + "strconv" + "strings" + "sync" + "time" + + "github.com/D-Modem/bbs/internal/store" +) + +// POP3Server is the POP3 server (RFC 1939, STLS of RFC 2595, AUTH PLAIN +// of RFC 5034). The maildrop is the user's Inbox; DELE puts mail in the +// trash. +type POP3Server struct { + svc *Service + set ServerSettings + tc *tls.Config + ln *limited +} + +// NewPOP3 makes the POP3 server. +func (s *Service) NewPOP3(set ServerSettings) (*POP3Server, error) { + tc, err := tlsConfig(set) + if err != nil { + return nil, fmt.Errorf("pop3: %w", err) + } + ln, err := s.listen("pop3", set, tc, func(why string) string { return "-ERR [SYS/TEMP] " + why + "\r\n" }) + if err != nil { + return nil, err + } + return &POP3Server{svc: s, set: set, tc: tc, ln: ln}, nil +} + +// Run serves until ctx is done. +func (x *POP3Server) Run(ctx context.Context) error { + x.svc.B.Log.Printf("pop3: listening on %s (tls %s)", x.set.Address, x.set.TLS) + var mu sync.Mutex + conns := map[net.Conn]bool{} + go func() { + <-ctx.Done() + x.ln.Close() + mu.Lock() + for c := range conns { + c.Close() + } + mu.Unlock() + }() + for { + c, err := x.ln.Accept() + if err != nil { + if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { + return nil + } + return fmt.Errorf("pop3: %w", err) + } + mu.Lock() + conns[c] = true + mu.Unlock() + go func() { + x.serve(c) + mu.Lock() + delete(conns, c) + mu.Unlock() + }() + } +} + +// popSession is a POP3 client's connection. +type popSession struct { + x *POP3Server + c net.Conn + r *bufio.Reader + w *bufio.Writer + tls bool + who string + name string // USER, waiting for PASS + user *store.User + msgs []*popMsg + deleted map[int]bool +} + +// popMsg is a mail in the maildrop. +type popMsg struct { + e *store.BoxEntry + size int64 + read bool // RETR'd: marked read at QUIT +} + +// serve is a client's session. A panic is logged and ends only it. +func (x *POP3Server) serve(c net.Conn) { + defer c.Close() + defer func() { + if r := recover(); r != nil { + x.svc.B.Log.Printf("pop3: panic: %v", r) + } + }() + ps := &popSession{x: x, c: c, who: "pop3 " + c.RemoteAddr().String(), deleted: map[int]bool{}} + if tc, ok := c.(*tls.Conn); ok { + tc.SetDeadline(time.Now().Add(30 * time.Second)) + if err := tc.Handshake(); err != nil { + return + } + tc.SetDeadline(time.Time{}) + ps.tls = true + } + ps.r = bufio.NewReaderSize(c, 4096) + ps.w = bufio.NewWriterSize(c, 16384) + ps.ok(x.svc.B.Conf().Name + " POP3 server ready") + for { + ps.w.Flush() + ps.c.SetReadDeadline(time.Now().Add(x.set.IdleTimeout)) + line, err := ps.r.ReadString('\n') + if err != nil || len(line) > 512 { + return + } + f := strings.Fields(strings.TrimRight(line, "\r\n")) + if len(f) == 0 { + ps.err("No command") + continue + } + cmd, args := strings.ToUpper(f[0]), f[1:] + if cmd == "QUIT" { + ps.quit() + ps.w.Flush() + return + } + if ps.user == nil { + ps.authorization(cmd, args, line) + } else { + ps.transaction(cmd, args) + } + } +} + +func (ps *popSession) ok(msg string) { fmt.Fprintf(ps.w, "+OK %s\r\n", msg) } +func (ps *popSession) err(msg string) { fmt.Fprintf(ps.w, "-ERR %s\r\n", msg) } + +// mayLogin reports whether a login may be tried now (not in the clear if +// TLS is required), saying why not. +func (ps *popSession) mayLogin() bool { + if !ps.tls && ps.x.set.TLS == TLSRequired { + ps.err("[AUTH] Use STLS first") + return false + } + return true +} + +// authorization answers the commands before a login. +func (ps *popSession) authorization(cmd string, args []string, line string) { + switch cmd { + case "CAPA": + ps.ok("Capability list follows") + caps := []string{"TOP", "UIDL", "RESP-CODES", "AUTH-RESP-CODE", "PIPELINING", "IMPLEMENTATION bbs-sec"} + if ps.tls || ps.x.set.TLS != TLSRequired { + caps = append(caps, "USER", "SASL PLAIN") + } + if !ps.tls && ps.x.tc != nil && ps.x.set.TLS != TLSImplicit { + caps = append(caps, "STLS") + } + for _, c := range caps { + ps.w.WriteString(c + "\r\n") + } + ps.w.WriteString(".\r\n") + case "STLS": + ps.stls() + case "USER": + if !ps.mayLogin() { + return + } + _, name, _ := strings.Cut(strings.TrimRight(line, "\r\n"), " ") + ps.name = strings.TrimSpace(name) + ps.ok("Send your password") + case "PASS": + if !ps.mayLogin() { + return + } + if ps.name == "" { + ps.err("USER first") + return + } + _, pw, _ := strings.Cut(strings.TrimRight(line, "\r\n"), " ") + ps.login(ps.name, pw) + case "AUTH": + if len(args) == 0 { + ps.ok("Mechanisms follow") + ps.w.WriteString("PLAIN\r\n.\r\n") + return + } + if !strings.EqualFold(args[0], "PLAIN") { + ps.err("Only PLAIN") + return + } + if !ps.mayLogin() { + return + } + resp := "" + if len(args) > 1 { + resp = args[1] + } else { + ps.w.WriteString("+ \r\n") + ps.w.Flush() + l, err := ps.r.ReadString('\n') + if err != nil { + return + } + resp = strings.TrimSpace(l) + } + dec, err := base64.StdEncoding.DecodeString(resp) + parts := strings.Split(string(dec), "\x00") + if err != nil || len(parts) != 3 || parts[0] != "" && parts[0] != parts[1] { + ps.err("[AUTH] Malformed PLAIN") + return + } + ps.login(parts[1], parts[2]) + default: + ps.err("Log in first") + } +} + +// stls answers STLS and makes the connection TLS. Anything sent before +// the handshake hangs up (an injection). +func (ps *popSession) stls() { + if ps.tls || ps.x.tc == nil || ps.x.set.TLS == TLSImplicit { + ps.err("TLS not available") + return + } + ps.ok("Begin TLS negotiation") + ps.w.Flush() + if ps.r.Buffered() > 0 { + ps.c.Close() + return + } + tc := tls.Server(ps.c, ps.x.tc) + tc.SetDeadline(time.Now().Add(30 * time.Second)) + if err := tc.Handshake(); err != nil { + ps.c.Close() + return + } + tc.SetDeadline(time.Time{}) + ps.c, ps.tls, ps.name = tc, true, "" + ps.r = bufio.NewReaderSize(tc, 4096) + ps.w = bufio.NewWriterSize(tc, 16384) +} + +// login checks a login and opens the maildrop. +func (ps *popSession) login(name, pw string) { + svc := ps.x.svc + u, err := svc.Login(ps.who, ps.c.RemoteAddr(), "pop3", name, pw) + ps.name = "" + if err != nil { + ps.err("[AUTH] Authentication failed") + return + } + es, err := svc.B.Store.FolderEntries(u.ID, store.FolderInbox) + if err != nil { + ps.err("[SYS/TEMP] The maildrop cannot be read") + return + } + ps.msgs = nil + for _, e := range es { + size := e.Size + if size == 0 { + m, _, err := svc.B.Store.BoxMail(u.ID, e.Box) + if err != nil { + continue + } + size = int64(len(svc.Render(m))) + } + ps.msgs = append(ps.msgs, &popMsg{e: e, size: size}) + } + ps.user = u + svc.B.Log.Printf("%s: %s logged in", ps.who, u.Name) + ps.ok(fmt.Sprintf("%s has %d messages", u.Name, len(ps.msgs))) +} + +// msg is the message a number names, not deleted; nil (and said) if none. +func (ps *popSession) msg(arg string) (int, *popMsg) { + n, err := strconv.Atoi(arg) + if err != nil || n < 1 || n > len(ps.msgs) || ps.deleted[n] { + ps.err("No such message") + return 0, nil + } + return n, ps.msgs[n-1] +} + +// content is a message's raw form. +func (ps *popSession) content(m *popMsg) ([]byte, error) { + msg, _, err := ps.x.svc.B.Store.BoxMail(ps.user.ID, m.e.Box) + if err != nil { + return nil, err + } + return crlf(ps.x.svc.Render(msg)), nil +} + +// transaction answers the commands of a logged-in session. +func (ps *popSession) transaction(cmd string, args []string) { + switch cmd { + case "CAPA": + ps.ok("Capability list follows") + ps.w.WriteString("TOP\r\nUIDL\r\nRESP-CODES\r\nPIPELINING\r\nIMPLEMENTATION bbs-sec\r\n.\r\n") + case "STAT": + n, size := 0, int64(0) + for i, m := range ps.msgs { + if !ps.deleted[i+1] { + n++ + size += m.size + } + } + ps.ok(fmt.Sprintf("%d %d", n, size)) + case "LIST", "UIDL": + val := func(m *popMsg) string { + if cmd == "LIST" { + return strconv.FormatInt(m.size, 10) + } + return strconv.FormatInt(m.e.Box, 10) + } + if len(args) > 0 { + if n, m := ps.msg(args[0]); m != nil { + ps.ok(fmt.Sprintf("%d %s", n, val(m))) + } + return + } + ps.ok("Listing follows") + for i, m := range ps.msgs { + if !ps.deleted[i+1] { + fmt.Fprintf(ps.w, "%d %s\r\n", i+1, val(m)) + } + } + ps.w.WriteString(".\r\n") + case "RETR", "TOP": + if len(args) < 1 || cmd == "TOP" && len(args) < 2 { + ps.err("Which message?") + return + } + _, m := ps.msg(args[0]) + if m == nil { + return + } + raw, err := ps.content(m) + if err != nil { + ps.err("[SYS/TEMP] The message cannot be read") + return + } + if cmd == "TOP" { + lines, err := strconv.Atoi(args[1]) + if err != nil || lines < 0 { + ps.err("TOP n lines") + return + } + raw = top(raw, lines) + } else { + m.read = true + } + ps.ok(fmt.Sprintf("%d octets", len(raw))) + dotted(ps.w, raw) + case "DELE": + if len(args) < 1 { + ps.err("Which message?") + return + } + if n, m := ps.msg(args[0]); m != nil { + ps.deleted[n] = true + ps.ok("Deleted") + } + case "RSET": + ps.deleted = map[int]bool{} + for _, m := range ps.msgs { + m.read = false + } + ps.ok("Reset") + case "NOOP": + ps.ok("") + default: + ps.err("Unknown command") + } +} + +// quit ends the session: in the transaction state, what was deleted goes +// in the trash and what was retrieved is read. +func (ps *popSession) quit() { + if ps.user == nil { + ps.ok("Goodbye") + return + } + st := ps.x.svc.B.Store + failed := false + for i, m := range ps.msgs { + var err error + switch { + case ps.deleted[i+1]: + err = st.TrashBox(ps.user.ID, m.e.Box) + case m.read && !m.e.Read: + err = st.SetBoxFlags(ps.user.ID, m.e.Box, true, m.e.Starred, m.e.Flags) + } + if err != nil && !errors.Is(err, store.ErrNotFound) { + failed = true + } + } + if failed { + ps.err("[SYS/TEMP] Some changes were not kept") + return + } + ps.ok("Goodbye") +} + +// top is a mail's header and its first lines of body. +func top(raw []byte, lines int) []byte { + end := headerEnd(raw) + if end < 0 { + return raw + } + body := raw[end:] + var out bytes.Buffer + out.Write(raw[:end]) + parts := bytes.SplitAfter(body, []byte("\n")) + // the blank line, then the lines asked for + for i := 0; i < len(parts) && i <= lines; i++ { + out.Write(parts[i]) + } + return out.Bytes() +} + +// dotted writes a multi-line response: lines dot-stuffed, ended by ".". +func dotted(w *bufio.Writer, raw []byte) { + for len(raw) > 0 { + i := bytes.IndexByte(raw, '\n') + var line []byte + if i < 0 { + line, raw = raw, nil + } else { + line, raw = raw[:i], raw[i+1:] + } + line = bytes.TrimSuffix(line, []byte("\r")) + if len(line) > 0 && line[0] == '.' { + w.WriteByte('.') + } + w.Write(line) + w.WriteString("\r\n") + } + w.WriteString(".\r\n") +} diff --git a/internal/email/queue.go b/internal/email/queue.go new file mode 100644 index 0000000..54f4a20 --- /dev/null +++ b/internal/email/queue.go @@ -0,0 +1,227 @@ +package email + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "net" + "net/smtp" + "net/textproto" + "sort" + "strings" + "time" + + "github.com/D-Modem/bbs/internal/store" +) + +// Kick has the queue looked at now. +func (s *Service) Kick() { + select { + case s.kick <- struct{}{}: + default: + } +} + +// RunQueue sends the queue's mail until ctx is done: when mail is put in +// it, and each minute for what is due again. +func (s *Service) RunQueue(ctx context.Context) { + t := time.NewTicker(time.Minute) + defer t.Stop() + for { + s.RunQueueOnce(ctx) + select { + case <-ctx.Done(): + return + case <-t.C: + case <-s.kick: + } + } +} + +// permanent is a refusal that trying again will not change (a 5xx reply). +type permanent struct{ error } + +func (p permanent) Unwrap() error { return p.error } + +// isPermanent reports whether err is a permanent failure. +func isPermanent(err error) bool { + var p permanent + if errors.As(err, &p) { + return true + } + var te *textproto.Error + return errors.As(err, &te) && te.Code >= 500 +} + +// retryAfter is how long to wait after the nth failure. +func retryAfter(n int) time.Duration { + steps := []time.Duration{5 * time.Minute, 15 * time.Minute, 30 * time.Minute, time.Hour, 2 * time.Hour} + if n < len(steps) { + return steps[n] + } + return 4 * time.Hour +} + +// RunQueueOnce tries what is due in the queue, once. +func (s *Service) RunQueueOnce(ctx context.Context) { + due, err := s.B.Store.MailQueue(time.Now(), 100) + if err != nil { + s.B.Log.Printf("mail: queue: %v", err) + return + } + for _, o := range due { + if ctx.Err() != nil { + return + } + raw, err := s.B.Store.MailRaw(o.MailID) + if err != nil { + s.B.Store.QueueDone(o.ID) + continue + } + err = s.send(ctx, o, raw) + switch { + case err == nil: + s.B.Store.QueueDone(o.ID) + s.B.Log.Printf("mail: %d sent to %s", o.MailID, o.Rcpt) + case isPermanent(err) || time.Since(o.Created) > s.Set.QueueLife: + s.B.Store.QueueDone(o.ID) + s.bounce(o, err.Error()) + default: + s.B.Store.QueueRetry(o.ID, time.Now().Add(retryAfter(o.Attempts)), err.Error()) + s.B.Log.Printf("mail: %d for %s: %v (tried again later)", o.MailID, o.Rcpt, err) + } + } +} + +// send sends one mail to one recipient, as the settings say. +func (s *Service) send(ctx context.Context, o *store.Outbound, raw []byte) error { + ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) + defer cancel() + switch s.Set.Outbound { + case OutboundSmarthost: + return s.sendSmarthost(ctx, o, raw) + case OutboundDirect: + return s.sendDirect(ctx, o, raw) + } + return permanent{ErrNoInternet} +} + +// hosts are the servers that take mail for a domain, in the order they +// are tried: its MX records (RFC 5321 5.1), or the domain itself. +func (s *Service) hosts(ctx context.Context, domain string) ([]string, error) { + mxs, err := s.Set.Resolver.LookupMX(ctx, domain) + if err != nil { + var de *net.DNSError + if errors.As(err, &de) && de.IsNotFound { + return []string{domain}, nil + } + return nil, fmt.Errorf("looking up %s: %w", domain, err) + } + if len(mxs) == 1 && (mxs[0].Host == "." || mxs[0].Host == "") { + return nil, permanent{fmt.Errorf("%s takes no mail (null MX)", domain)} + } + sort.SliceStable(mxs, func(i, j int) bool { return mxs[i].Pref < mxs[j].Pref }) + var out []string + for _, mx := range mxs { + out = append(out, strings.TrimSuffix(mx.Host, ".")) + } + if len(out) == 0 { + return []string{domain}, nil + } + return out, nil +} + +// sendDirect sends a mail to its recipient's servers, each in turn until +// one takes it or refuses it for good. TLS is used where a server offers +// it, its certificate unchecked: as most servers do (RFC 7435), since mail +// would otherwise go in the clear. +func (s *Service) sendDirect(ctx context.Context, o *store.Outbound, raw []byte) error { + _, domain, ok := strings.Cut(o.Rcpt, "@") + if !ok { + return permanent{fmt.Errorf("%q is not an address", o.Rcpt)} + } + hosts, err := s.hosts(ctx, domain) + if err != nil { + return err + } + var last error + for _, h := range hosts { + err := s.sendTo(ctx, net.JoinHostPort(h, s.Set.MXPort), h, "starttls-opportunistic", nil, o, raw) + if err == nil || isPermanent(err) { + return err + } + last = err + } + return last +} + +// sendSmarthost gives a mail to the smarthost. +func (s *Service) sendSmarthost(ctx context.Context, o *store.Outbound, raw []byte) error { + sh := s.Set.Smarthost + host, _, _ := net.SplitHostPort(sh.Address) + var auth smtp.Auth + if sh.Username != "" { + auth = smtp.PlainAuth("", sh.Username, sh.Password, host) + } + return s.sendTo(ctx, sh.Address, host, sh.TLS, auth, o, raw) +} + +// sendTo sends a mail on a connection to addr: TLS "implicit", "starttls" +// (required), "starttls-opportunistic", or "no". +func (s *Service) sendTo(ctx context.Context, addr, host, mode string, auth smtp.Auth, o *store.Outbound, raw []byte) error { + d := net.Dialer{Timeout: 30 * time.Second} + conn, err := d.DialContext(ctx, "tcp", addr) + if err != nil { + return err + } + if dl, ok := ctx.Deadline(); ok { + conn.SetDeadline(dl) + } + insecure := mode == "starttls-opportunistic" || s.Set.Smarthost.Insecure + tc := &tls.Config{ServerName: host, InsecureSkipVerify: insecure, MinVersion: tls.VersionTLS12} //nolint:gosec // opportunistic TLS (RFC 7435), or as the sysop says + if mode == "implicit" { + conn = tls.Client(conn, tc) + } + c, err := smtp.NewClient(conn, host) + if err != nil { + conn.Close() + return err + } + defer c.Close() + if err := c.Hello(s.Set.Hostname); err != nil { + return err + } + if mode == "starttls" || mode == "starttls-opportunistic" { + if ok, _ := c.Extension("STARTTLS"); ok { + if err := c.StartTLS(tc); err != nil { + return err + } + } else if mode == "starttls" { + return fmt.Errorf("%s offers no STARTTLS", addr) + } + } + if auth != nil { + if err := c.Auth(auth); err != nil { + return err + } + } + if err := c.Mail(o.Sender); err != nil { + return err + } + if err := c.Rcpt(o.Rcpt); err != nil { + return err + } + w, err := c.Data() + if err != nil { + return err + } + if _, err := w.Write(raw); err != nil { + return err + } + if err := w.Close(); err != nil { + return err + } + c.Quit() + return nil +} diff --git a/internal/email/smtp.go b/internal/email/smtp.go new file mode 100644 index 0000000..6b17e81 --- /dev/null +++ b/internal/email/smtp.go @@ -0,0 +1,285 @@ +package email + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "strings" + "time" + + "github.com/emersion/go-sasl" + "github.com/emersion/go-smtp" + + "github.com/D-Modem/bbs/internal/store" +) + +// The kinds of SMTP server. +const ( + Submission = "smtp" // users send mail (587, 465): AUTH needed + MX = "mx" // mail from the internet for users here (25) + LMTP = "lmtp" // mail for users here from a mail server in front +) + +// SMTPServer is an SMTP (or LMTP) server. +type SMTPServer struct { + svc *Service + kind string + set ServerSettings + checks bool // MX: SPF, DKIM and DMARC are checked + srv *smtp.Server + ln *limited +} + +// NewSMTP makes an SMTP server of a kind; checks: SPF, DKIM and DMARC +// checked on mail from the internet. +func (s *Service) NewSMTP(kind string, set ServerSettings, checks bool) (*SMTPServer, error) { + tc, err := tlsConfig(set) + if err != nil { + return nil, fmt.Errorf("%s: %w", kind, err) + } + x := &SMTPServer{svc: s, kind: kind, set: set, checks: checks} + srv := smtp.NewServer(x) + srv.Domain = s.Set.Hostname + srv.MaxMessageBytes = s.Set.MaxMessage + srv.MaxRecipients = s.Set.MaxRecipients + srv.ReadTimeout = set.IdleTimeout + srv.WriteTimeout = set.IdleTimeout + srv.ErrorLog = s.B.Log + srv.LMTP = kind == LMTP + srv.AllowInsecureAuth = set.TLS == TLSNo || set.TLS == TLSOptional + if set.TLS == TLSOptional || set.TLS == TLSRequired { + srv.TLSConfig = tc + } + x.srv = srv + x.ln, err = s.listen(kind, set, tc, func(why string) string { return "421 4.7.0 " + why + "\r\n" }) + if err != nil { + return nil, err + } + return x, nil +} + +// Run serves until ctx is done. +func (x *SMTPServer) Run(ctx context.Context) error { + x.svc.B.Log.Printf("%s: listening on %s (tls %s)", x.kind, x.set.Address, x.set.TLS) + go func() { + <-ctx.Done() + x.srv.Close() + }() + err := x.srv.Serve(x.ln) + if ctx.Err() != nil || errors.Is(err, smtp.ErrServerClosed) || errors.Is(err, net.ErrClosed) { + return nil + } + return fmt.Errorf("%s: %w", x.kind, err) +} + +// NewSession is a client's session (smtp.Backend). +func (x *SMTPServer) NewSession(c *smtp.Conn) (smtp.Session, error) { + return &smtpSession{x: x, c: c, who: x.kind + " " + c.Conn().RemoteAddr().String()}, nil +} + +// smtpSession is an SMTP client's connection. +type smtpSession struct { + x *SMTPServer + c *smtp.Conn + who string + user *store.User // submission: who logged in + from string + rcpts []string + local []*store.User +} + +func smtpErr(code int, enh smtp.EnhancedCode, msg string) *smtp.SMTPError { + return &smtp.SMTPError{Code: code, EnhancedCode: enh, Message: msg} +} + +var ( + errTLSFirst = smtpErr(530, smtp.EnhancedCode{5, 7, 0}, "Use STARTTLS first") + errNoRelay = smtpErr(550, smtp.EnhancedCode{5, 7, 1}, "Mail for elsewhere is not taken here") + errNoUser = smtpErr(550, smtp.EnhancedCode{5, 1, 1}, "No such user here") +) + +// tls reports whether the session is in TLS. +func (ss *smtpSession) tls() bool { + _, ok := ss.c.TLSConnectionState() + return ok +} + +// AuthMechanisms are those offered: PLAIN and LOGIN, for submission. +func (ss *smtpSession) AuthMechanisms() []string { + if ss.x.kind != Submission { + return nil + } + return []string{sasl.Plain, sasl.Login} +} + +// Auth is a mechanism's server. +func (ss *smtpSession) Auth(mech string) (sasl.Server, error) { + if ss.x.kind != Submission { + return nil, smtp.ErrAuthUnsupported + } + login := func(identity, name, password string) error { + if identity != "" && identity != name { + return smtp.ErrAuthFailed + } + u, err := ss.x.svc.Login(ss.who, ss.c.Conn().RemoteAddr(), "smtp", name, password) + if err != nil { + return smtp.ErrAuthFailed + } + ss.user = u + ss.x.svc.B.Log.Printf("%s: %s logged in", ss.who, u.Name) + return nil + } + switch mech { + case sasl.Plain: + return sasl.NewPlainServer(login), nil + case sasl.Login: + return &loginServer{auth: login}, nil + } + return nil, smtp.ErrAuthUnsupported +} + +// Mail is MAIL FROM. +func (ss *smtpSession) Mail(from string, opts *smtp.MailOptions) error { + if ss.x.kind == Submission { + if ss.user == nil { + if !ss.tls() && ss.x.set.TLS == TLSRequired { + return errTLSFirst + } + return smtp.ErrAuthRequired + } + if from != "" && !strings.EqualFold(from, ss.x.svc.Address(ss.user)) { + return smtpErr(553, smtp.EnhancedCode{5, 7, 1}, "Send from your own address, "+ss.x.svc.Address(ss.user)) + } + } + ss.from = from + return nil +} + +// Rcpt is RCPT TO. +func (ss *smtpSession) Rcpt(to string, opts *smtp.RcptOptions) error { + svc := ss.x.svc + r, err := svc.resolve(to) + if err != nil { + if errors.Is(err, ErrNoUser) { + return errNoUser + } + return smtpErr(553, smtp.EnhancedCode{5, 1, 3}, err.Error()) + } + if ss.x.kind == Submission { + if err := svc.checkRecipient(ss.user, r); err != nil { + return smtpErr(550, smtp.EnhancedCode{5, 7, 1}, err.Error()) + } + ss.rcpts = append(ss.rcpts, to) + return nil + } + if r.kind != toLocal { + return errNoRelay + } + ss.rcpts = append(ss.rcpts, to) + ss.local = append(ss.local, r.user) + return nil +} + +// Data is DATA: the mail sent, or kept. +func (ss *smtpSession) Data(r io.Reader) error { + raw, err := io.ReadAll(r) + if err != nil { + return err + } + svc := ss.x.svc + if ss.x.kind == Submission { + if err := svc.Submit(ss.user, ss.rcpts, raw); err != nil { + if errors.Is(err, ErrNotYours) { + return smtpErr(553, smtp.EnhancedCode{5, 7, 1}, err.Error()) + } + return smtpErr(554, smtp.EnhancedCode{5, 6, 0}, err.Error()) + } + return nil + } + trace := ss.received() + if ss.x.checks { + raw = withoutFields(raw, "Authentication-Results") + ip := net.ParseIP(hostOf(ss.c.Conn().RemoteAddr())) + v := svc.check(ip, ss.c.Hostname(), ss.from, raw) + if v.refuse != "" { + svc.B.Log.Printf("%s: refused mail from %s: %s", ss.who, ss.from, v.refuse) + return smtpErr(550, smtp.EnhancedCode{5, 7, 1}, v.refuse) + } + trace += v.field + } + if err := svc.Receive(ss.local, raw, trace); err != nil { + return smtpErr(451, smtp.EnhancedCode{4, 3, 0}, "Not kept: "+err.Error()) + } + return nil +} + +// received is the Received field for a mail taken from the session. +func (ss *smtpSession) received() string { + with := "ESMTP" + if ss.tls() { + with = "ESMTPS" + } + if ss.x.kind == LMTP { + with = "LMTP" + } + addr := ss.c.Conn().RemoteAddr().String() + if h := hostOf(ss.c.Conn().RemoteAddr()); h != "" { + addr = "[" + h + "]" + } + return fmt.Sprintf("Received: from %s (%s)\r\n\tby %s with %s; %s\r\n", sanitize(ss.c.Hostname()), addr, + ss.x.svc.Set.Hostname, with, time.Now().Format(time.RFC1123Z)) +} + +// sanitize is a client's word fit for a header: printable ASCII, no +// spaces or parentheses. +func sanitize(s string) string { + s = strings.Map(func(r rune) rune { + if r <= ' ' || r > '~' || r == '(' || r == ')' { + return -1 + } + return r + }, s) + if s == "" { + return "unknown" + } + if len(s) > 100 { + s = s[:100] + } + return s +} + +// Reset forgets the mail begun. +func (ss *smtpSession) Reset() { + ss.from, ss.rcpts, ss.local = "", nil, nil +} + +// Logout ends the session. +func (ss *smtpSession) Logout() error { return nil } + +// loginServer is SASL's LOGIN, which some mail programs use (Outlook). +type loginServer struct { + auth func(identity, name, password string) error + step int + name string +} + +func (l *loginServer) Next(response []byte) ([]byte, bool, error) { + switch l.step { + case 0: + l.step = 1 + if len(response) == 0 { + return []byte("Username:"), false, nil + } + fallthrough + case 1: + l.name = string(response) + l.step = 2 + return []byte("Password:"), false, nil + case 2: + l.step = 3 + return nil, true, l.auth("", l.name, string(response)) + } + return nil, true, sasl.ErrUnexpectedClientResponse +} diff --git a/internal/server/bind.go b/internal/server/bind.go index 5751d13..85dcbc8 100644 --- a/internal/server/bind.go +++ b/internal/server/bind.go @@ -4,6 +4,7 @@ import ( "fmt" "net" "os" + "strings" "github.com/D-Modem/bbs/internal/sockets" ) @@ -80,6 +81,11 @@ func Bind(cfg *Config) ([]sockets.Socket, error) { if cfg.NNTP != nil { addrs = append(addrs, cfg.NNTP.Address) } + for _, ms := range cfg.MailServers { + if !strings.HasPrefix(ms.Set.Address, "/") { + addrs = append(addrs, ms.Set.Address) + } + } if i := cfg.IRC; i != nil { addrs = append(addrs, i.Address, i.TLSAddress) } diff --git a/internal/server/config.go b/internal/server/config.go index fd5eecb..55a635f 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -17,6 +17,7 @@ import ( "github.com/D-Modem/bbs/internal/bbs" "github.com/D-Modem/bbs/internal/config" "github.com/D-Modem/bbs/internal/door" + "github.com/D-Modem/bbs/internal/email" "github.com/D-Modem/bbs/internal/events" "github.com/D-Modem/bbs/internal/fido" "github.com/D-Modem/bbs/internal/finger" @@ -50,33 +51,35 @@ type Config struct { FTP *ftp.Settings // nil: no FTP server FTPAdvertise string // the FTP server's address, as users are told it - News bbs.NewsSettings - MaxArticle int64 - NNTP *nntp.ServerSettings // nil: no NNTP server - Peers []*nntp.Peer - Fido *fido.Settings // nil: not on FidoNet - QWKNets []*qwknet.Net // [qwknet NAME]: QWK networks this is a node of - Binkp *BinkpSettings // nil: no binkp answering - Doors []*door.Door - Finger *finger.Settings // nil: no finger server - IRC *ircd.Settings // nil: no IRC server - OSCAR *oscar.Settings // nil: no AIM/ICQ server - MRC *mrc.Settings // nil: not on Multi Relay Chat - Screens *screens.Set // nil: no screens of the sysop's - ScriptsDir string // "": no scripts - Menus map[string]*bbs.Menu - Text map[string]string // [strings] - HTTP *api.Settings // nil: no HTTP API - Chan imageboard.Settings - Gopher *gopher.Settings // nil: no gopher server - Database string - Log string // syslog, stderr, none, or a file - Listeners []*Listener - Warnings []string - Guard *guard.Guard // [security] - RunAs *sockets.Account // [general] user and group: who serve becomes, its ports bound (nil: as it is started) - MenuAuth *MenuAuth // [modemmenu]: passwords asked of modemmenu (nil: none) - Events []*events.Event + News bbs.NewsSettings + MaxArticle int64 + NNTP *nntp.ServerSettings // nil: no NNTP server + Peers []*nntp.Peer + Mail *email.Settings // [mail]; nil: no e-mail + MailServers []*MailServer + Fido *fido.Settings // nil: not on FidoNet + QWKNets []*qwknet.Net // [qwknet NAME]: QWK networks this is a node of + Binkp *BinkpSettings // nil: no binkp answering + Doors []*door.Door + Finger *finger.Settings // nil: no finger server + IRC *ircd.Settings // nil: no IRC server + OSCAR *oscar.Settings // nil: no AIM/ICQ server + MRC *mrc.Settings // nil: not on Multi Relay Chat + Screens *screens.Set // nil: no screens of the sysop's + ScriptsDir string // "": no scripts + Menus map[string]*bbs.Menu + Text map[string]string // [strings] + HTTP *api.Settings // nil: no HTTP API + Chan imageboard.Settings + Gopher *gopher.Settings // nil: no gopher server + Database string + Log string // syslog, stderr, none, or a file + Listeners []*Listener + Warnings []string + Guard *guard.Guard // [security] + RunAs *sockets.Account // [general] user and group: who serve becomes, its ports bound (nil: as it is started) + MenuAuth *MenuAuth // [modemmenu]: passwords asked of modemmenu (nil: none) + Events []*events.Event } // DefaultListeners are used when the file has no [listen] section: telnet @@ -130,6 +133,9 @@ func load(cf *config.File) (*Config, error) { if err := c.fidoSections(cf); err != nil { return nil, err } + if err := c.mailSections(cf); err != nil { + return nil, err + } if err := c.qwkNets(cf); err != nil { return nil, err } @@ -208,7 +214,8 @@ func load(cf *config.File) (*Config, error) { } for _, s := range cf.Sections { switch s.Kind { - case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "oscar", "mrc", "menu", "strings", "http", "level", "chan": + case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "oscar", "mrc", "menu", "strings", "http", "level", "chan", + "mail", "smarthost", "pop3", "imap", "smtp", "mx", "lmtp": default: return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind) } diff --git a/internal/server/mailconfig.go b/internal/server/mailconfig.go new file mode 100644 index 0000000..db6707a --- /dev/null +++ b/internal/server/mailconfig.go @@ -0,0 +1,178 @@ +package server + +import ( + "errors" + "fmt" + "net" + "strings" + "time" + + "github.com/D-Modem/bbs/internal/config" + "github.com/D-Modem/bbs/internal/email" + "github.com/D-Modem/bbs/internal/news" +) + +// MailServer is a mail server's section: [pop3], [imap], [smtp], [mx] or +// [lmtp]. +type MailServer struct { + Kind string + Set email.ServerSettings + Checks bool // [mx]: SPF, DKIM and DMARC checked +} + +// mailServers are the mail servers' sections, their default addresses +// (unprivileged, as [nntp]'s; [mx] has to be on 25 to be found) and TLS. +var mailServers = []struct{ kind, addr, tls string }{ + {"pop3", ":1110", email.TLSRequired}, + {"imap", ":1143", email.TLSRequired}, + {email.Submission, ":1587", email.TLSRequired}, + {email.MX, ":25", email.TLSOptional}, + {email.LMTP, "", email.TLSNo}, +} + +// mailSections reads [mail], [smarthost] and the mail servers' sections. +// [mail] is needed for any of them; without it the BBS has no e-mail. +func (c *Config) mailSections(cf *config.File) error { + m := cf.Get("mail", "") + if m == nil { + for _, ms := range mailServers { + if cf.Get(ms.kind, "") != nil { + return fmt.Errorf("[%s] needs a [mail] section (the domain, how mail goes out)", ms.kind) + } + } + if cf.Get("smarthost", "") != nil { + return errors.New("[smarthost] needs a [mail] section with outbound = smarthost") + } + return nil + } + set := email.Defaults(m.String("domain", c.News.Domain), m.String("hostname", c.News.PathHost)) + if !news.ValidMessageID("") || !strings.Contains(set.Domain, ".") { + return errors.New("[mail] domain: a domain, like example.org") + } + if !news.ValidMessageID("") { + return errors.New("[mail] hostname: a host name, like mail.example.org") + } + var err error + if set.MaxMessage, err = parseSize(m, "max_message", set.MaxMessage); err != nil { + return fmt.Errorf("[mail] %w", err) + } + if set.MaxRecipients, err = m.Int("max_recipients", set.MaxRecipients, 1, 1000); err != nil { + return fmt.Errorf("[mail] %w", err) + } + if set.TrashDays, err = m.Int("trash_days", set.TrashDays, 0, 3650); err != nil { + return fmt.Errorf("[mail] %w", err) + } + days, err := m.Int("queue_days", 5, 1, 30) + if err != nil { + return fmt.Errorf("[mail] %w", err) + } + set.QueueLife = time.Duration(days) * 24 * time.Hour + set.Postmaster = m.String("postmaster", "") + sh := cf.Get("smarthost", "") + def := email.OutboundDirect + if sh != nil { + def = email.OutboundSmarthost + } + set.Outbound = strings.ToLower(m.String("outbound", def)) + switch set.Outbound { + case email.OutboundDirect: + c.Warnings = append(c.Warnings, "[mail] outbound = direct: mail goes straight to its servers on port 25; "+ + "many networks block that, and receivers want SPF, DKIM and a reverse DNS name for this host (or set a [smarthost])") + case email.OutboundSmarthost: + if sh == nil { + return errors.New("[mail] outbound = smarthost: no [smarthost] section") + } + set.Smarthost = email.Smarthost{Address: sh.String("address", ""), TLS: strings.ToLower(sh.String("tls", "starttls")), + Username: sh.String("username", ""), Password: sh.String("password", "")} + if set.Smarthost.Insecure, err = sh.Bool("insecure", false); err != nil { + return fmt.Errorf("[smarthost] %w", err) + } + if _, _, err := net.SplitHostPort(set.Smarthost.Address); err != nil { + return fmt.Errorf("[smarthost] address: %v (host:port, like smtp.example.net:587)", err) + } + switch set.Smarthost.TLS { + case "starttls", "implicit": + case "no": + if set.Smarthost.Password != "" { + c.Warnings = append(c.Warnings, "[smarthost] tls = no: its password goes in the clear") + } + default: + return fmt.Errorf("[smarthost] tls: %q is not starttls, implicit or no", set.Smarthost.TLS) + } + case email.OutboundNone: + default: + return fmt.Errorf("[mail] outbound: %q is not direct, smarthost or none", set.Outbound) + } + if key := m.String("dkim_key_file", ""); key != "" { + signer, err := email.LoadDKIMKey(key) + if err != nil { + return fmt.Errorf("[mail] dkim_key_file: %w", err) + } + set.DKIM = &email.DKIM{Domain: set.Domain, Selector: m.String("dkim_selector", "bbs"), Signer: signer} + } else if set.Outbound == email.OutboundDirect { + c.Warnings = append(c.Warnings, "[mail] no dkim_key_file: mail sent is not signed, and many receivers will refuse it (bbs mail dkim makes a key)") + } + certFile, keyFile := m.String("cert_file", ""), m.String("key_file", "") + c.Mail = &set + for _, ms := range mailServers { + s := cf.Get(ms.kind, "") + if s == nil { + continue + } + srv, err := mailServer(s, ms.kind, ms.addr, ms.tls, certFile, keyFile) + if err != nil { + return fmt.Errorf("[%s] %w", ms.kind, err) + } + switch { + case srv.Set.TLS == email.TLSNo && ms.kind != email.MX && ms.kind != email.LMTP: + c.Warnings = append(c.Warnings, fmt.Sprintf("[%s] tls = no: passwords go in the clear", ms.kind)) + case srv.Set.TLS == email.TLSOptional && ms.kind != email.MX && ms.kind != email.LMTP: + c.Warnings = append(c.Warnings, fmt.Sprintf("[%s] tls = optional: mail programs that do not STARTTLS send passwords in the clear", ms.kind)) + } + c.MailServers = append(c.MailServers, srv) + } + return nil +} + +// mailServer reads a mail server's section. +func mailServer(s *config.Section, kind, addr, tls, certFile, keyFile string) (*MailServer, error) { + ms := &MailServer{Kind: kind, Set: email.ServerSettings{Address: s.String("address", addr), + TLS: strings.ToLower(s.String("tls", tls)), CertFile: s.String("cert_file", certFile), KeyFile: s.String("key_file", keyFile)}} + set := &ms.Set + if set.Address == "" { + return nil, errors.New("address: none given (a unix socket's path, or host:port)") + } + if !strings.HasPrefix(set.Address, "/") { + if _, _, err := net.SplitHostPort(set.Address); err != nil { + return nil, fmt.Errorf("address: %v", err) + } + } + switch set.TLS { + case email.TLSNo, email.TLSOptional, email.TLSRequired, email.TLSImplicit: + default: + return nil, fmt.Errorf("tls: %q is not no, optional, required or implicit", set.TLS) + } + if set.TLS != email.TLSNo && (set.CertFile == "" || set.KeyFile == "") { + return nil, errors.New("cert_file and key_file are needed for TLS (here or in [mail]), or tls = no") + } + var err error + if set.MaxClients, err = s.Int("max_clients", 64, 1, 10000); err != nil { + return nil, err + } + if set.MaxPerIP, err = s.Int("max_per_ip", 10, 0, 1000); err != nil { + return nil, err + } + idle := 1800 // IMAP's IDLE wants 30 minutes + if kind != "imap" { + idle = 600 + } + if set.IdleTimeout, err = s.Seconds("idle_timeout", idle, 30, 86400); err != nil { + return nil, err + } + if kind == email.MX { + if ms.Checks, err = s.Bool("checks", true); err != nil { + return nil, err + } + } + return ms, nil +} From fcb5cabd822fd3831f8bde43db6cbcac84a02fe1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 13:17:45 +0000 Subject: [PATCH 3/5] E-mail: tests with Python's mail clients, docs and the sample configuration The E-mail wiki page (addresses, folders, a smarthost or direct delivery, DNS, the MX and LMTP), the mail sections in bbs.conf.sample, SMTP's 530 for mail before a login, and the TODO section done. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRVPRbt1YgtG7eQJZxD --- README.md | 1 + TODO.md | 33 -- bbs.conf.sample | 71 ++++ docs/wiki/Configuration-Reference.md | 91 +++++ docs/wiki/E-mail.md | 159 ++++++++ docs/wiki/Home.md | 4 + docs/wiki/_Sidebar.md | 1 + internal/email/email_test.go | 567 +++++++++++++++++++++++++++ internal/email/listen.go | 11 +- internal/email/python_test.go | 95 +++++ internal/email/smtp.go | 9 +- 11 files changed, 1002 insertions(+), 40 deletions(-) create mode 100644 docs/wiki/E-mail.md create mode 100644 internal/email/email_test.go create mode 100644 internal/email/python_test.go diff --git a/README.md b/README.md index fb23dda..b170bd0 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Main menu - Message areas, private mail, chat, paging and doors (DOS doors in dosemu2, or Linux programs) - File areas with X/Y/ZMODEM, Kermit, IND$FILE and FTP +- E-mail: IMAP, POP3 and SMTP, to and from the internet, directly or through a smarthost - Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC, AIM and ICQ, and MRC - Terminals: ANSI, VT, PETSCII, RIPscrip, sixel and 3270 graphics - On the web: a forum, image boards, a web terminal and an HTTP API diff --git a/TODO.md b/TODO.md index 5d5f7b3..bae1fc7 100644 --- a/TODO.md +++ b/TODO.md @@ -42,36 +42,3 @@ layer between a door and a 3270 could show them: be tried by hand. - **Shape.** An option on a `[door]` (`tn3270 = yes`) that shows the door on the 3270 Doors menu and puts this layer between them. - -## Email: POP3, IMAP and SMTP - -*Status: pinned; scope not chosen.* - -Private mail already lives in SQLite, one inbox per user with a read flag; -NNTP and FTP already share the BBS's login, throttling and TLS modes, and -`internal/news` already makes and safely decodes RFC 5322/MIME messages. - -- **POP3** (RFC 1939, STLS): small. The inbox is the mailbox, a mail's id - its UIDL, DELE deletes. -- **IMAP** (RFC 3501/9051): moderate, with emersion's go-imap server (v2 - is beta: pin it). INBOX is the inbox, \Seen the read flag; new: a Sent - folder (mail is kept only in the recipient's inbox today), stored flags, - UIDVALIDITY. -- **SMTP**, three jobs: - - *submission* (587, AUTH required, so never an open relay) to BBS users - and FidoNet netmail: small, with emersion's go-smtp; - - *inbound from the internet*: easy code, hard operations (MX, port 25 - often blocked, spam, SPF/DKIM/DMARC checks); - - *outbound to the internet*: queue, retries, bounces, DKIM, SPF/DMARC, - rDNS, IP reputation: most of the long-term trouble. -- **Suggested shape**: phase 1, POP3 + IMAP + submission for BBS users; - phase 2, internet mail through Postfix: inbound delivered to the BBS by - LMTP (go-smtp does LMTP), outbound by a smarthost. The BBS as its own - internet MTA is possible but not advised. -- **To decide**: addresses for names with spaces (`alice.smith@domain`, as - news posters' already are) and collisions; attachments (kept whole for - POP/IMAP, text part plus a list of attachments on terminals, a size - limit); `user@domain` as a third recipient form beside user names and - FidoNet addresses (those have `:` and `/`); app passwords (optional). -- **Testing**: Python's imaplib, poplib and smtplib; Postfix (Ubuntu) for - LMTP and the smarthost. diff --git a/bbs.conf.sample b/bbs.conf.sample index 84b29ad..46bdae4 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -472,6 +472,77 @@ address = 127.0.0.1:2513 ; the addresses it may send us articles from (IHAVE) ;accept_from = news.example.net +; E-mail. Each user is name@domain (bbs mail address NAME shows it), and +; their BBS mail is their e-mail: Inbox, Sent, Drafts, Starred, Unread, +; All Mail and Trash, in any mail program, over POP3 and IMAP. Without +; this section the BBS has no e-mail +;[mail] +;domain = example.org +; this host's name, said in SMTP's greeting and Received lines +;hostname = mail.example.org +; how mail for elsewhere goes: direct (to each domain's MX, port 25), +; smarthost (through [smarthost]) or none (only mail here) +;outbound = direct +; the largest message taken; recipients in one; days in the trash before +; mail is gone (0: until emptied); days the queue keeps trying +;max_message = 10M +;max_recipients = 50 +;trash_days = 30 +;queue_days = 5 +; who gets postmaster@, abuse@ and bounces' notes (default: the sysop) +;postmaster = sysop +; DKIM: bbs mail dkim /etc/bbs/dkim.pem makes the key and prints its DNS +; record (selector._domainkey.domain) +;dkim_key_file = /etc/bbs/dkim.pem +;dkim_selector = bbs +; the certificate for the mail servers (each can name its own) +;cert_file = /etc/bbs/cert.pem +;key_file = /etc/bbs/key.pem + +; An outgoing mail server to send through, instead of straight to each +; domain's MX: your provider's, or a relay such as Postfix. tls: starttls, +; implicit (port 465) or no. insecure = yes: its certificate unchecked +;[smarthost] +;address = smtp.example.net:587 +;tls = starttls +;username = bbs@example.org +;password = secret +;insecure = no + +; The mail servers: each runs only with its section. tls: no, optional +; (STARTTLS offered), required (STARTTLS before a login) or implicit (TLS +; from the first byte: POP3S 995, IMAPS 993, SMTPS 465). Each takes +; address, tls, cert_file, key_file, max_clients, max_per_ip and +; idle_timeout, as [nntp] does. POP3: mail programs fetch the inbox +;[pop3] +;address = :1110 +;tls = required + +; IMAP: mail programs read and file mail in the folders. Its IDLE wants a +; long idle_timeout +;[imap] +;address = :1143 +;tls = required +;idle_timeout = 1800 + +; mail submission: users send mail, logged in (port 587 or 465) +;[smtp] +;address = :1587 +;tls = required + +; mail from the internet: on port 25, named by the domain's MX record. +; checks = yes: SPF, DKIM and DMARC checked; mail is refused that fails +; a DMARC reject policy, or (no DMARC) fails SPF and is not signed +;[mx] +;address = :25 +;tls = optional +;checks = yes + +; LMTP, for a mail server in front (Postfix's virtual_transport) to hand +; mail in: a unix socket's path or host:port +;[lmtp] +;address = /run/bbs/lmtp.sock + ; FidoNet (or another FTN network). bbs area echo General FSX_GEN makes an ; area an echo; mail to Name@zone:net/node is netmail. Without this section ; the BBS is not on FidoNet diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index 98ee3bf..d479f61 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -25,6 +25,13 @@ the file is laid out. | [`[news]`](#news) | Newsgroups: a message area with a newsgroup name (bbs area newsgroup General bbs.general) is a newsgroup, served by NNTP to newsreaders and kept in step with peer news servers. | | [`[nntp]`](#nntp) | The NNTP server. | | [`[peer NAME]`](#peer-name) | A peer news server, one section each. | +| [`[mail]`](#mail) | E-mail. | +| [`[smarthost]`](#smarthost) | An outgoing mail server to send through, instead of straight to each domain's MX: your provider's, or a relay such as Postfix. | +| [`[pop3]`](#pop3) | The mail servers: each runs only with its section. | +| [`[imap]`](#imap) | IMAP: mail programs read and file mail in the folders. | +| [`[smtp]`](#smtp) | mail submission: users send mail, logged in (port 587 or 465) | +| [`[mx]`](#mx) | mail from the internet: on port 25, named by the domain's MX record. | +| [`[lmtp]`](#lmtp) | LMTP, for a mail server in front (Postfix's virtual_transport) to hand mail in: a unix socket's path or host:port. | | [`[fido]`](#fido) | FidoNet (or another FTN network). | | [`[binkp]`](#binkp) | binkp: answer the links' calls. | | [`[link NAME]`](#link-name) | A system we exchange mail with, one section each. | @@ -313,6 +320,90 @@ There may be any number of these, each with its own NAME. | `accept_from` | | | the addresses it may send us articles from (IHAVE) Examples: `news.example.net`. | +## `[mail]` + +E-mail. Each user is name@domain (bbs mail address NAME shows it), and their BBS mail is their e-mail: Inbox, Sent, Drafts, Starred, Unread, All Mail and Trash, in any mail program, over POP3 and IMAP. Without this section the BBS has no e-mail. + +| key | default | live | what it does | +|---|---|---|---| +| `domain` | | | See the section above. Examples: `example.org`. | +| `hostname` | | | this host's name, said in SMTP's greeting and Received lines. Examples: `mail.example.org`. | +| `outbound` | | | how mail for elsewhere goes: direct (to each domain's MX, port 25), smarthost (through [smarthost]) or none (only mail here) Examples: `direct`. | +| `max_message` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `10M`. | +| `max_recipients` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `50`. | +| `trash_days` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `30`. | +| `queue_days` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `5`. | +| `postmaster` | | | who gets postmaster@, abuse@ and bounces' notes (default: the sysop) Examples: `sysop`. | +| `dkim_key_file` | | | DKIM: bbs mail dkim /etc/bbs/dkim.pem makes the key and prints its DNS record (selector._domainkey.domain) Examples: `/etc/bbs/dkim.pem`. | +| `dkim_selector` | | | DKIM: bbs mail dkim /etc/bbs/dkim.pem makes the key and prints its DNS record (selector._domainkey.domain) Examples: `bbs`. | +| `cert_file` | | | the certificate for the mail servers (each can name its own) Examples: `/etc/bbs/cert.pem`. | +| `key_file` | | | the certificate for the mail servers (each can name its own) Examples: `/etc/bbs/key.pem`. | + + +## `[smarthost]` + +An outgoing mail server to send through, instead of straight to each domain's MX: your provider's, or a relay such as Postfix. tls: starttls, implicit (port 465) or no. insecure = yes: its certificate unchecked. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `smtp.example.net:587`. | +| `tls` | | | See the section above. Examples: `starttls`. | +| `username` | | | See the section above. Examples: `bbs@example.org`. | +| `password` | | | See the section above. Examples: `secret`. | +| `insecure` | | | See the section above. Examples: `no`. | + + +## `[pop3]` + +The mail servers: each runs only with its section. tls: no, optional (STARTTLS offered), required (STARTTLS before a login) or implicit (TLS from the first byte: POP3S 995, IMAPS 993, SMTPS 465). Each takes address, tls, cert_file, key_file, max_clients, max_per_ip and idle_timeout, as [nntp] does. POP3: mail programs fetch the inbox. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:1110`. | +| `tls` | | | See the section above. Examples: `required`. | + + +## `[imap]` + +IMAP: mail programs read and file mail in the folders. Its IDLE wants a long idle_timeout. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:1143`. | +| `tls` | | | See the section above. Examples: `required`. | +| `idle_timeout` | | | See the section above. Examples: `1800`. | + + +## `[smtp]` + +mail submission: users send mail, logged in (port 587 or 465) + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:1587`. | +| `tls` | | | See the section above. Examples: `required`. | + + +## `[mx]` + +mail from the internet: on port 25, named by the domain's MX record. checks = yes: SPF, DKIM and DMARC checked; mail is refused that fails a DMARC reject policy, or (no DMARC) fails SPF and is not signed. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:25`. | +| `tls` | | | See the section above. Examples: `optional`. | +| `checks` | | | See the section above. Examples: `yes`. | + + +## `[lmtp]` + +LMTP, for a mail server in front (Postfix's virtual_transport) to hand mail in: a unix socket's path or host:port. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `/run/bbs/lmtp.sock`. | + + ## `[fido]` FidoNet (or another FTN network). bbs area echo General FSX_GEN makes an area an echo; mail to Name@zone:net/node is netmail. Without this section the BBS is not on FidoNet. diff --git a/docs/wiki/E-mail.md b/docs/wiki/E-mail.md new file mode 100644 index 0000000..d08f665 --- /dev/null +++ b/docs/wiki/E-mail.md @@ -0,0 +1,159 @@ +With a `[mail]` section each user has an e-mail address, and their BBS +mail is their e-mail. A letter written on a 3270, a modem or the web goes +out to the internet, and mail from the internet arrives in the same inbox +the CompuServe and BBS mail commands read. Mail programs (Thunderbird, +Apple Mail, mutt, K-9) read it over IMAP or POP3 and send over SMTP, logged +in with the BBS name and password. + +``` +; bbs.conf +[mail] +domain = example.org +hostname = mail.example.org +dkim_key_file = /etc/bbs/dkim.pem +cert_file = /etc/bbs/cert.pem +key_file = /etc/bbs/key.pem + +[imap] +address = :993 +tls = implicit + +[pop3] +address = :995 +tls = implicit + +[smtp] ; submission: users send mail, logged in +address = :587 +tls = required + +[mx] ; mail from the internet +address = :25 +``` + +Every server runs only if its section is there. All of them use the BBS's +guard (bans, throttling), and each has `max_clients`, `max_per_ip` and +`idle_timeout`. `tls` is `no`, `optional` (STARTTLS offered), `required` +(no login before STARTTLS) or `implicit` (TLS from the first byte). Ports +below 1024 are bound before the BBS drops root, as the others are. + +## Addresses + +A user's address is their name in lower case, with spaces as dots, at the +domain: `Alice Smith` is `alice.smith@example.org`. `bbs mail address +NAME` prints it. `+tags` are ignored (`alice.smith+lists@` reaches Alice). +`postmaster@`, `abuse@`, `hostmaster@` and `webmaster@` go to `[mail] +postmaster`, or the first sysop. + +When writing mail on the BBS, the recipient can be a user's name, a FidoNet +address (`Name@1:234/5`) or an internet address (`bob@example.net`). In +CompuServe Mail, `>INTERNET:bob@example.net` works as it did there. Mail to +FidoNet's internet form (`john.doe@f5.n234.z1.fidonet.org`) goes as +netmail. + +## Folders + +Mail is kept once. Each user has their own entry for it, with its read and +starred marks, so the same mail sent to five users is stored once. Every +mail program sees the same folders: + +| Folder | Holds | Special-use | +|---|---|---| +| INBOX | mail received, not deleted | | +| Sent | mail sent | `\Sent` | +| Drafts | drafts saved by a mail program | `\Drafts` | +| Starred | starred mail (`\Flagged`) | `\Flagged` | +| Unread | unread mail received | | +| All Mail | everything not deleted | `\All` | +| Trash | deleted mail | `\Trash` | + +Starred, Unread and All Mail are views: starring a mail in the inbox puts +it in Starred, and taking it out of Starred unstars it. Deleting moves mail +to the Trash, where a mail program can restore it (by moving it out) or +expunge it. Mail in the trash longer than `trash_days` (30) is removed for +good. Folders cannot be created or renamed. + +POP3 sees the inbox. Mail retrieved is marked read, and `DELE` puts it in +the trash. + +## Sending to the internet + +`[mail] outbound` says how mail for other domains leaves: + +- `direct` (the default): the BBS looks up each domain's MX and delivers + on port 25, with STARTTLS when the other side offers it. Many home and + cloud networks block port 25 out, and receivers want SPF, DKIM and a + reverse DNS name for the host, so this needs some DNS work (below). +- `smarthost`: everything goes through another mail server (your + provider's, a relay such as Postfix, or a service like Mailgun), given in + `[smarthost]`. That server does the delivering. This is the easy route + when one is at hand. +- `none`: only mail between users here, and FidoNet. + +``` +[mail] +domain = example.org +outbound = smarthost + +[smarthost] +address = smtp.example.net:587 +tls = starttls ; or implicit (465), or no +username = bbs@example.org +password = secret +``` + +Mail out waits in a queue, tried again with longer gaps (five minutes, then +up to four hours) for `queue_days` (5). When a server refuses a recipient for +good, or the days run out, the sender gets a note in their inbox saying +why. `bbs mail queue` lists what is waiting, and `bbs mail send` tries it +all now. + +## DNS for a domain of its own + +For mail to arrive, and to be believed when sent directly: + +``` +example.org. MX 10 mail.example.org. +mail.example.org. A 203.0.113.5 +example.org. TXT "v=spf1 mx -all" +bbs._domainkey.example.org. TXT "v=DKIM1; k=rsa; p=..." +_dmarc.example.org. TXT "v=DMARC1; p=quarantine" +``` + +and a reverse DNS (PTR) name for 203.0.113.5 of `mail.example.org`, which +the hosting provider sets. `bbs mail dkim /etc/bbs/dkim.pem` makes the DKIM +key and prints its record. With a smarthost, use the SPF and DKIM its +provider gives instead. + +## Mail from the internet + +`[mx]` takes mail for the domain on port 25, without a login, and only for +users here: it is never an open relay. With `checks = yes` (the default) it +checks SPF, DKIM and DMARC, and adds an `Authentication-Results` header. A +mail is refused when it fails a DMARC policy of `p=reject`, or, for a domain +with no DMARC record, when SPF fails and no signature of that domain holds. + +If another mail server already takes the domain's mail (Postfix, with its +own spam filtering), it can hand mail to the BBS by LMTP instead: + +``` +[lmtp] +address = /run/bbs/lmtp.sock +``` + +``` +# Postfix main.cf +virtual_mailbox_domains = example.org +virtual_transport = lmtp:unix:/run/bbs/lmtp.sock +``` + +## On the terminal + +Mail from the internet is shown as text: HTML mail is turned into plain +text, and attachments are listed by name and size (they stay whole for +mail programs). Messages larger than `max_message` (10M) are refused. + +## Databases + +Mail lives in the BBS's database, whichever it is: SQLite, PostgreSQL, +MySQL or MariaDB. `bbs db copy` carries the mail, the folders and the +queue along with the rest. diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 8357ebb..94fd454 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -40,6 +40,7 @@ Main menu | Make it look like your own | [Customization](Customization), [Scripting](Scripting) | | Take calls by modem | [Modem callers](Modem-Callers) | | Join FidoNet, QWK networks or Usenet | [FidoNet](FidoNet), [Offline mail](Offline-Mail#qwk-networks), [Newsgroups and NNTP](Newsgroups-and-NNTP) | +| Give users e-mail addresses | [E-mail](E-mail) | | Put the board on the web | [Web forum](Web-Forum), [Image boards](Image-Boards), [HTTP API](HTTP-API) | | Work on the code | [Development](Development) | @@ -76,6 +77,8 @@ which is generated from `bbs.conf.sample`. - [FidoNet](FidoNet) and other FTN networks: echomail, netmail, file echoes, AreaFix and a built-in binkp mailer +- [E-mail](E-mail): each user an address, their BBS mail read over IMAP + and POP3 and sent over SMTP, to and from the internet - [Newsgroups](Newsgroups-and-NNTP) served by NNTP and exchanged with other news servers - [IRC](IRC), where the chat rooms are channels, [AIM and ICQ](AIM-and-ICQ) @@ -130,6 +133,7 @@ which is generated from `bbs.conf.sample`. | [Files and FTP](Files-and-FTP) | file areas, the FTP (FTPS) server | | [File transfers](File-Transfers) | X/Y/ZMODEM, Kermit, IND$FILE | | [Doors](Doors) | DOS doors in dosemu2 (Docker), Linux doors, doors on other systems | +| [E-mail](E-mail) | addresses, IMAP, POP3, SMTP, the MX, a smarthost, DNS | | [Newsgroups and NNTP](Newsgroups-and-NNTP) | the NNTP server, news peers | | [FidoNet](FidoNet) | echomail, netmail, binkp, file echoes, AreaFix, nodelists | | [Chat and paging](Chat-and-Paging) | chat rooms, node messages, paging the sysop | diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 4dcd373..9127141 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -29,6 +29,7 @@ - [Files and FTP](Files-and-FTP) - [File transfers](File-Transfers) - [Doors](Doors) +- [E-mail](E-mail) - [Newsgroups and NNTP](Newsgroups-and-NNTP) - [FidoNet](FidoNet) - [Chat and paging](Chat-and-Paging) diff --git a/internal/email/email_test.go b/internal/email/email_test.go new file mode 100644 index 0000000..221779c --- /dev/null +++ b/internal/email/email_test.go @@ -0,0 +1,567 @@ +package email + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "crypto/rsa" + "errors" + "fmt" + "log" + "net" + "net/smtp" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/emersion/go-imap/v2" + "github.com/emersion/go-imap/v2/imapclient" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" +) + +func init() { store.BcryptCost = 4 } + +// fakeDNS is DNS for the tests. +type fakeDNS struct { + mu sync.Mutex + txt map[string][]string + mx map[string][]*net.MX +} + +func (d *fakeDNS) LookupTXT(ctx context.Context, name string) ([]string, error) { + d.mu.Lock() + defer d.mu.Unlock() + if v, ok := d.txt[strings.TrimSuffix(name, ".")]; ok { + return v, nil + } + return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true} +} + +func (d *fakeDNS) LookupMX(ctx context.Context, name string) ([]*net.MX, error) { + d.mu.Lock() + defer d.mu.Unlock() + if v, ok := d.mx[strings.TrimSuffix(name, ".")]; ok { + return v, nil + } + return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true} +} + +func (d *fakeDNS) LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, nil +} + +func (d *fakeDNS) LookupAddr(ctx context.Context, addr string) ([]string, error) { + return nil, &net.DNSError{Err: "no such host", Name: addr, IsNotFound: true} +} + +// site is a BBS with e-mail, its servers on local ports. +type site struct { + b *bbs.BBS + svc *Service + st *store.Store + log *bytes.Buffer + addrs map[string]string + users map[string]*store.User +} + +// newSite makes a BBS for domain with users, and the servers of kinds +// asked for (pop3, imap, smtp, mx), without TLS. +func newSite(t *testing.T, domain string, dns *fakeDNS, users []string, kinds ...string) *site { + t.Helper() + st, err := store.Open(filepath.Join(t.TempDir(), "bbs.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + s := &site{st: st, log: &bytes.Buffer{}, addrs: map[string]string{}, users: map[string]*store.User{}} + for _, name := range users { + u, err := st.CreateUser(name, "password1", "", name == "sysop") + if err != nil { + t.Fatal(err) + } + s.users[name] = u + } + set := bbs.Defaults() + set.FailDelay = 0 + s.b = bbs.New(set, st, log.New(&syncWriter{w: s.log}, domain+": ", 0)) + ms := Defaults(domain, "mail."+domain) + ms.Resolver = dns + s.svc = New(s.b, ms) + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + for _, k := range kinds { + set := ServerSettings{Address: "127.0.0.1:0", TLS: TLSNo, MaxClients: 10, MaxPerIP: 10, IdleTimeout: time.Minute} + var run func(context.Context) error + var addr net.Addr + switch k { + case "pop3": + x, err := s.svc.NewPOP3(set) + if err != nil { + t.Fatal(err) + } + run, addr = x.Run, x.Addr() + case "imap": + x, err := s.svc.NewIMAP(set) + if err != nil { + t.Fatal(err) + } + run, addr = x.Run, x.Addr() + default: + x, err := s.svc.NewSMTP(k, set, k == MX) + if err != nil { + t.Fatal(err) + } + run, addr = x.Run, x.Addr() + } + s.addrs[k] = addr.String() + wg.Add(1) + go func() { defer wg.Done(); run(ctx) }() + } + t.Cleanup(func() { + cancel() + wg.Wait() + if t.Failed() { + t.Logf("%s log:\n%s", domain, s.log.String()) + } + }) + return s +} + +type syncWriter struct { + mu sync.Mutex + w *bytes.Buffer +} + +func (w *syncWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.w.Write(p) +} + +// submit sends a mail by SMTP submission, as name. +func submit(t *testing.T, addr, name, from string, to []string, msg string) error { + t.Helper() + host, _, _ := net.SplitHostPort(addr) + return smtp.SendMail(addr, smtp.PlainAuth("", name, "password1", host), from, to, []byte(msg)) +} + +// inbox is a user's inbox. +func inbox(t *testing.T, s *site, name string, folder int) []*store.Message { + t.Helper() + id := s.users[name].ID + l, err := s.st.Folder(id, folder) + if err != nil { + t.Fatal(err) + } + for i, m := range l { + full, _, err := s.st.BoxMail(id, m.Box) + if err != nil { + t.Fatal(err) + } + l[i].Raw = full.Raw + } + return l +} + +// TestAddresses: users' addresses, those here and FidoNet's read. +func TestAddresses(t *testing.T) { + dns := &fakeDNS{} + s := newSite(t, "bbs.test", dns, []string{"Alice Smith", "sysop", "Bob"}) + if a := s.svc.Address(s.users["Alice Smith"]); a != "alice.smith@bbs.test" { + t.Errorf("address %q", a) + } + for addr, want := range map[string]string{"alice.smith@bbs.test": "Alice Smith", "ALICE.SMITH+lists@BBS.TEST": "Alice Smith", + "postmaster@bbs.test": "sysop", "abuse@mail.bbs.test": "sysop", "bob@bbs.test": "Bob"} { + r, err := s.svc.resolve(addr) + if err != nil || r.kind != toLocal || r.user.Name != want { + t.Errorf("%s: %+v %v", addr, r, err) + } + } + if _, err := s.svc.resolve("carol@bbs.test"); !errors.Is(err, ErrNoUser) { + t.Errorf("no such user: %v", err) + } + r, err := s.svc.resolve("john.doe@p4.f100.n1.z21.fidonet.org") + if err != nil || r.kind != toFido || r.name != "John Doe" || r.ftn.String() != "21:1/100.4" { + t.Errorf("fidonet: %+v %v", r, err) + } + if r, _ := s.svc.resolve("x@example.com"); r.kind != toInternet { + t.Errorf("internet: %+v", r) + } + if !bbs.IsEmailAddress("x@example.com") || !bbs.IsEmailAddress(`"Jo, Smith" `) || + bbs.IsEmailAddress("Bob@1:2/3") || bbs.IsEmailAddress("Bob") || bbs.IsEmailAddress("x@localhost") { + t.Error("IsEmailAddress") + } + if got := shownAddress("Jo, Smith", "jo@example.com"); !bbs.IsEmailAddress(got) { + t.Errorf("shown %q is not an address again", got) + } +} + +// TestParse: a mail's text for the terminals, from plain text, HTML, and +// with attachments listed. +func TestParse(t *testing.T) { + raw := "From: \"Jo\" \r\nTo: bob@bbs.test\r\nSubject: =?utf-8?q?Caf=C3=A9?=\r\n" + + "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=b\r\n\r\n" + + "--b\r\nContent-Type: text/html; charset=utf-8\r\n\r\n

Hello there

bye & all

\r\n" + + "--b\r\nContent-Type: application/pdf\r\nContent-Disposition: attachment; filename=a.pdf\r\n" + + "Content-Transfer-Encoding: base64\r\n\r\nJVBERi0=\r\n--b--\r\n" + p, err := parse([]byte(raw)) + if err != nil { + t.Fatal(err) + } + if p.subject != "Café" || p.fromAddr != "jo@example.com" || p.fromName != "Jo" { + t.Errorf("header: %+v", p) + } + if !strings.Contains(p.text, "Hello there\nbye & all") || !strings.Contains(p.text, "a.pdf (5 bytes)") { + t.Errorf("text: %q", p.text) + } +} + +// TestRender: mail written here, as a mail program gets it. +func TestRender(t *testing.T) { + s := newSite(t, "bbs.test", &fakeDNS{}, []string{"alice", "sysop"}) + m := &store.Message{ID: 7, FromID: s.users["alice"].ID, From: "alice", ToID: s.users["sysop"].ID, To: "sysop", + Subject: "Grüße", Body: "line one\n.dot line", Created: time.Unix(1e9, 0), ReplyTo: 3} + raw := string(s.svc.Render(m)) + for _, want := range []string{"From: \"alice\" \r\n", "To: \"sysop\" \r\n", + "Subject: =?utf-8?q?Gr=C3=BC=C3=9Fe?=\r\n", "Message-ID: \r\n", + "In-Reply-To: \r\n", "\r\n\r\nline one\r\n.dot line\r\n"} { + if !strings.Contains(raw, want) { + t.Errorf("no %q in\n%s", want, raw) + } + } + if string(s.svc.Render(m)) != raw { + t.Error("not the same twice") + } + fido := &store.Message{From: "Hub Sysop@21:1/100", Subject: "s", Body: "b"} + if a := s.svc.fromAddress(fido); a.Address != "hub.sysop@f100.n1.z21.fidonet" { + t.Errorf("fido from %v", a) + } +} + +// TestMail: mail sent by SMTP submission to a user here and to another +// BBS, which takes it from the queue by SMTP with its SPF, DKIM and DMARC +// holding; mail refused for elsewhere, forged, or for no one; a bounce; +// then the other BBS's user reads it by POP3 and IMAP. +func TestMail(t *testing.T) { + dns := &fakeDNS{txt: map[string][]string{}, mx: map[string][]*net.MX{}} + a := newSite(t, "a.test", dns, []string{"alice", "sysop"}, Submission) + b := newSite(t, "b.test", dns, []string{"bob", "sysop"}, MX, "pop3", "imap") + + // a.test signs; its records say so, and that it sends from here + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + a.svc.Set.DKIM = &DKIM{Domain: "a.test", Selector: "bbs", Signer: key} + rec, _ := DKIMRecord(key) + dns.txt["bbs._domainkey.a.test"] = []string{rec} + dns.txt["a.test"] = []string{"v=spf1 ip4:127.0.0.1 -all"} + dns.txt["_dmarc.a.test"] = []string{"v=DMARC1; p=reject"} + _, port, _ := net.SplitHostPort(b.addrs[MX]) + dns.mx["b.test"] = []*net.MX{{Host: "127.0.0.1", Pref: 10}} + a.svc.Set.MXPort = port + + sub := a.addrs[Submission] + msg := "From: alice \r\nTo: bob@b.test, sysop@a.test\r\nBcc: secret@b.test\r\nSubject: Hello\r\n\r\nHi Bob.\r\n" + if err := submit(t, sub, "alice", "alice@a.test", []string{"bob@b.test", "sysop@a.test"}, msg); err != nil { + t.Fatal(err) + } + if in := inbox(t, a, "sysop", store.FolderInbox); len(in) != 1 || in[0].Subject != "Hello" || in[0].FromID != a.users["alice"].ID { + t.Fatalf("sysop's inbox: %+v", in) + } + sent := inbox(t, a, "alice", store.FolderSent) + if len(sent) != 1 || strings.Contains(string(sent[0].Raw), "secret") || !strings.Contains(string(sent[0].Raw), "DKIM-Signature:") { + t.Fatalf("alice's sent: %+v", sent) + } + + // refused: another's address, a user not there, mail before a login + if err := submit(t, sub, "alice", "sysop@a.test", []string{"bob@b.test"}, msg); err == nil { + t.Error("sent as another") + } + if err := submit(t, sub, "alice", "alice@a.test", []string{"nobody@a.test"}, msg); err == nil { + t.Error("sent to no one") + } + if c, err := smtp.Dial(sub); err == nil { + if err := c.Mail("alice@a.test"); err == nil || !strings.Contains(err.Error(), "530") { + t.Errorf("mail without a login: %v", err) + } + c.Close() + } + + // the queue: to b.test, where it is checked + if q, _ := a.st.MailQueue(time.Time{}, 0); len(q) != 1 || q[0].Rcpt != "bob@b.test" { + t.Fatalf("queue: %+v", q) + } + a.svc.RunQueueOnce(context.Background()) + if q, _ := a.st.MailQueue(time.Time{}, 0); len(q) != 0 { + t.Fatalf("queue after: %+v", q) + } + got := inbox(t, b, "bob", store.FolderInbox) + if len(got) != 1 { + t.Fatalf("bob's inbox: %+v", got) + } + raw := string(got[0].Raw) + for _, want := range []string{"spf=pass", "dkim=pass", "dmarc=pass", "Received: from mail.a.test", "Hi Bob."} { + if !strings.Contains(raw, want) { + t.Errorf("no %q in\n%s", want, raw) + } + } + if got[0].From != "alice " || got[0].FromID != 0 || !bbs.IsEmailAddress(got[0].From) { + t.Errorf("from %q", got[0].From) + } + + // b.test's MX: no relaying, no one there, and a forgery refused + mx := b.addrs[MX] + err = smtp.SendMail(mx, nil, "x@c.test", []string{"y@elsewhere.test"}, []byte("Subject: x\r\n\r\nx\r\n")) + if err == nil || !strings.Contains(err.Error(), "550") { + t.Errorf("relayed: %v", err) + } + forged := "From: alice@a.test\r\nTo: bob@b.test\r\nSubject: Forged\r\n\r\nGive me money\r\n" + err = smtp.SendMail(mx, nil, "x@c.test", []string{"bob@b.test"}, []byte(forged)) + if err == nil || !strings.Contains(err.Error(), "DMARC") { + t.Errorf("forged: %v", err) + } + if n := len(inbox(t, b, "bob", store.FolderInbox)); n != 1 { + t.Errorf("bob has %d", n) + } + + // a bounce, for no one at b.test + if err := submit(t, sub, "alice", "alice@a.test", []string{"nobody@b.test"}, "Subject: Lost\r\n\r\nx\r\n"); err != nil { + t.Fatal(err) + } + a.svc.RunQueueOnce(context.Background()) + if in := inbox(t, a, "alice", store.FolderInbox); len(in) != 1 || in[0].Subject != "Undelivered: Lost" || + !strings.Contains(in[0].Body, "nobody@b.test") { + t.Errorf("bounce: %+v", in) + } + + // from a terminal + n, _ := a.b.Enter(&bbs.Caller{Via: "test"}, nil) + n.SetUser(a.users["alice"]) + if err := n.SendMail("bob@b.test", "From the BBS", []string{"typed on a terminal"}, 0); err != nil { + t.Fatal(err) + } + a.svc.RunQueueOnce(context.Background()) + if in := inbox(t, b, "bob", store.FolderInbox); len(in) != 2 || in[1].Subject != "From the BBS" { + t.Fatalf("bob's inbox: %+v", in) + } + + testPOP3(t, b) + testIMAP(t, b) +} + +// pop is a POP3 command's reply. +func pop(t *testing.T, r *bufio.Reader, c net.Conn, cmd string, multi bool) string { + t.Helper() + if cmd != "" { + fmt.Fprintf(c, "%s\r\n", cmd) + } + line, err := r.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if !multi || !strings.HasPrefix(line, "+OK") { + return line + } + var b strings.Builder + b.WriteString(line) + for { + l, err := r.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if l == ".\r\n" { + return b.String() + } + b.WriteString(l) + } +} + +// testPOP3: bob's inbox by POP3: listed, read, one deleted (to the trash). +func testPOP3(t *testing.T, b *site) { + c, err := net.Dial("tcp", b.addrs["pop3"]) + if err != nil { + t.Fatal(err) + } + defer c.Close() + r := bufio.NewReader(c) + pop(t, r, c, "", false) + if got := pop(t, r, c, "PASS x", false); !strings.HasPrefix(got, "-ERR") { + t.Errorf("PASS first: %q", got) + } + pop(t, r, c, "USER bob", false) + if got := pop(t, r, c, "PASS wrong", false); !strings.HasPrefix(got, "-ERR") { + t.Errorf("a wrong password: %q", got) + } + pop(t, r, c, "USER bob@b.test", false) + if got := pop(t, r, c, "PASS password1", false); !strings.HasPrefix(got, "+OK") { + t.Fatalf("login: %q", got) + } + if got := pop(t, r, c, "STAT", false); !strings.HasPrefix(got, "+OK 2 ") { + t.Errorf("STAT %q", got) + } + if got := pop(t, r, c, "UIDL", true); strings.Count(got, "\r\n") != 3 { + t.Errorf("UIDL %q", got) + } + if got := pop(t, r, c, "RETR 1", true); !strings.Contains(got, "Subject: Hello") || !strings.Contains(got, "Hi Bob.") { + t.Errorf("RETR %q", got) + } + if got := pop(t, r, c, "TOP 2 0", true); !strings.Contains(got, "Subject: From the BBS") || strings.Contains(got, "typed") { + t.Errorf("TOP %q", got) + } + pop(t, r, c, "DELE 2", false) + if got := pop(t, r, c, "RETR 2", false); !strings.HasPrefix(got, "-ERR") { + t.Errorf("deleted RETR %q", got) + } + pop(t, r, c, "QUIT", false) + in := inbox(t, b, "bob", store.FolderInbox) + if len(in) != 1 || !in[0].Read { + t.Errorf("after POP3: %+v", in) + } + if tr := inbox(t, b, "bob", store.FolderTrash); len(tr) != 1 || tr[0].Subject != "From the BBS" { + t.Errorf("trash: %+v", tr) + } +} + +// testIMAP: bob's folders by IMAP: listed with their special uses, mail +// restored from the trash, starred, read, put in Sent once, and new mail +// told of. +func testIMAP(t *testing.T, b *site) { + var mu sync.Mutex + var exists []uint32 + c, err := imapclient.DialInsecure(b.addrs["imap"], &imapclient.Options{UnilateralDataHandler: &imapclient.UnilateralDataHandler{ + Mailbox: func(d *imapclient.UnilateralDataMailbox) { + if d.NumMessages != nil { + mu.Lock() + exists = append(exists, *d.NumMessages) + mu.Unlock() + } + }}}) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.Login("bob", "wrong").Wait(); err == nil { + t.Error("a wrong password") + } + if err := c.Login("bob", "password1").Wait(); err != nil { + t.Fatal(err) + } + list, err := c.List("", "*", &imap.ListOptions{ReturnSpecialUse: true}).Collect() + if err != nil { + t.Fatal(err) + } + var names []string + for _, l := range list { + n := l.Mailbox + for _, a := range l.Attrs { + if a != imap.MailboxAttrHasNoChildren { + n += string(a) + } + } + names = append(names, n) + } + if strings.Join(names, " ") != `INBOX Sent\Sent Drafts\Drafts Starred\Flagged Unread All Mail\All Trash\Trash` { + t.Errorf("list: %v", names) + } + if err := c.Create("Work", nil).Wait(); err == nil { + t.Error("a folder made") + } + + // out of the trash, into the inbox + if d, err := c.Select("Trash", nil).Wait(); err != nil || d.NumMessages != 1 { + t.Fatalf("trash: %+v %v", d, err) + } + cd, err := c.Copy(imap.SeqSetNum(1), "INBOX").Wait() + if err != nil || len(cd.DestUIDs) != 1 { + t.Fatalf("copy: %+v %v", cd, err) + } + if err := c.Noop().Wait(); err != nil { + t.Fatal(err) + } + if mb := c.Mailbox(); mb == nil || mb.NumMessages != 0 { + t.Errorf("trash after: %+v", mb) + } + d, err := c.Select("INBOX", nil).Wait() + if err != nil || d.NumMessages != 2 { + t.Fatalf("inbox: %+v %v", d, err) + } + + // starred; read by fetching + if _, err := c.Store(imap.SeqSetNum(1), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Flags: []imap.Flag{imap.FlagFlagged}}, nil).Collect(); err != nil { + t.Fatal(err) + } + if st, _ := c.Status("Starred", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 1 { + t.Errorf("starred: %+v", st) + } + msgs, err := c.Fetch(imap.SeqSetNum(2), &imap.FetchOptions{Envelope: true, Flags: true, RFC822Size: true, + BodySection: []*imap.FetchItemBodySection{{}}}).Collect() + if err != nil || len(msgs) != 1 { + t.Fatalf("fetch: %v %v", msgs, err) + } + body := string(msgs[0].FindBodySection(&imap.FetchItemBodySection{})) + if msgs[0].Envelope.Subject != "From the BBS" || !strings.Contains(body, "typed on a terminal") || int64(len(body)) != msgs[0].RFC822Size { + t.Errorf("fetched: %+v %q", msgs[0].Envelope, body) + } + if st, _ := c.Status("Unread", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 0 { + t.Errorf("unread: %+v", st) + } + res, err := c.Search(&imap.SearchCriteria{Body: []string{"terminal"}}, nil).Wait() + if err != nil || len(res.AllSeqNums()) != 1 || res.AllSeqNums()[0] != 2 { + t.Errorf("search: %+v %v", res, err) + } + + // put in Sent: once, by its Message-ID + mail := "From: bob@b.test\r\nTo: x@example.com\r\nSubject: Mine\r\nMessage-ID: \r\n\r\nkept\r\n" + for i := 0; i < 2; i++ { + ap := c.Append("Sent", int64(len(mail)), &imap.AppendOptions{Flags: []imap.Flag{imap.FlagSeen}}) + ap.Write([]byte(mail)) + ap.Close() + if _, err := ap.Wait(); err != nil { + t.Fatal(err) + } + } + if st, _ := c.Status("Sent", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 1 { + t.Errorf("sent: %+v", st) + } + + // deleted: to the trash + if _, err := c.Store(imap.SeqSetNum(2), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Silent: true, Flags: []imap.Flag{imap.FlagDeleted}}, nil).Collect(); err != nil { + t.Fatal(err) + } + if _, err := c.Expunge().Collect(); err != nil { + t.Fatal(err) + } + if st, _ := c.Status("Trash", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 1 { + t.Errorf("trash: %+v", st) + } + + // new mail, told by IDLE + idle, err := c.Idle() + if err != nil { + t.Fatal(err) + } + b.svc.Receive([]*store.User{b.users["bob"]}, []byte("From: z@example.com\r\nSubject: New\r\n\r\nnew\r\n"), "") + deadline := time.Now().Add(5 * time.Second) + for { + mu.Lock() + n := len(exists) + mu.Unlock() + if n > 0 || time.Now().After(deadline) { + break + } + time.Sleep(20 * time.Millisecond) + } + idle.Close() + idle.Wait() + mu.Lock() + defer mu.Unlock() + if len(exists) == 0 || exists[len(exists)-1] != 2 { + t.Errorf("IDLE: %v", exists) + } +} diff --git a/internal/email/listen.go b/internal/email/listen.go index 5241747..90dca7a 100644 --- a/internal/email/listen.go +++ b/internal/email/listen.go @@ -164,6 +164,11 @@ func (c *counted) Close() error { return c.Conn.Close() } -// remoteOf is the address a connection (perhaps TLS, perhaps counted) -// comes from. -func remoteOf(c net.Conn) net.Addr { return c.RemoteAddr() } +// Addr is where a server listens. +func (x *POP3Server) Addr() net.Addr { return x.ln.Addr() } + +// Addr is where a server listens. +func (x *IMAPServer) Addr() net.Addr { return x.ln.Addr() } + +// Addr is where a server listens. +func (x *SMTPServer) Addr() net.Addr { return x.ln.Addr() } diff --git a/internal/email/python_test.go b/internal/email/python_test.go new file mode 100644 index 0000000..bcd585a --- /dev/null +++ b/internal/email/python_test.go @@ -0,0 +1,95 @@ +package email + +import ( + "fmt" + "net" + "os/exec" + "strings" + "testing" + + "github.com/D-Modem/bbs/internal/store" +) + +// Python's smtplib, poplib and imaplib, mail programs of someone else's +// making, send, fetch, file and search mail. +func TestPythonClients(t *testing.T) { + if exec.Command("python3", "-c", "import smtplib, poplib, imaplib").Run() != nil { + t.Skip("no python3") + } + s := newSite(t, "a.test", &fakeDNS{}, []string{"sysop", "alice", "bob"}, Submission, "pop3", "imap") + hp := func(kind string) (string, string) { + h, p, _ := net.SplitHostPort(s.addrs[kind]) + return h, p + } + sh, sp := hp(Submission) + ph, pp := hp("pop3") + ih, ip := hp("imap") + script := fmt.Sprintf(` +import smtplib, poplib, imaplib, email +from email.message import EmailMessage + +m = EmailMessage() +m['From'] = 'alice ' +m['To'] = 'bob@a.test' +m['Subject'] = 'From Python' +m.set_content('Hello Bob, from smtplib.') +with smtplib.SMTP(%[1]q, %[2]s) as c: + c.login('alice', 'password1') + c.send_message(m) + +p = poplib.POP3(%[3]q, %[4]s) +p.user('bob') +p.pass_('password1') +count, size = p.stat() +assert count == 1, count +resp, lines, octets = p.retr(1) +msg = email.message_from_bytes(b'\r\n'.join(lines)) +assert msg['Subject'] == 'From Python', msg['Subject'] +assert 'from smtplib' in msg.get_payload(), msg.get_payload() +resp, uids, _ = p.uidl() +assert len(uids) == 1, uids +p.quit() + +i = imaplib.IMAP4(%[5]q, %[6]s) +i.login('bob', 'password1') +typ, folders = i.list() +names = b'\n'.join(folders).decode() +for want in ('INBOX', 'Sent', 'Drafts', 'Starred', 'Unread', 'All Mail', 'Trash', '\\Flagged', '\\Trash'): + assert want in names, (want, names) +typ, data = i.select('INBOX') +assert data[0] == b'1', data +typ, data = i.uid('SEARCH', None, 'SUBJECT', '"From Python"') +uid = data[0].split()[0] +typ, data = i.uid('FETCH', uid, '(FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT)])') +assert b'From Python' in data[0][1], data +assert b'\\Seen' in data[0][0], data +typ, _ = i.uid('STORE', uid, '+FLAGS', '(\\Flagged)') +assert typ == 'OK', typ +typ, data = i.select('Starred') +assert data[0] == b'1', data +i.select('INBOX') +typ, _ = i.uid('MOVE', uid, 'Trash') +assert typ == 'OK', typ +typ, data = i.select('INBOX') +assert data[0] == b'0', data +typ, data = i.select('Trash') +assert data[0] == b'1', data +typ, data = i.append('Drafts', '', imaplib.Time2Internaldate(0), b'Subject: Draft\r\n\r\nNot yet.\r\n') +assert typ == 'OK', (typ, data) +i.logout() +print('ok') +`, sh, sp, ph, pp, ih, ip) + out, err := exec.Command("python3", "-W", "ignore", "-c", script).CombinedOutput() + if err != nil || !strings.Contains(string(out), "ok") { + t.Fatalf("python: %v\n%s", err, out) + } + if l := inbox(t, s, "bob", store.FolderTrash); len(l) != 1 || !l[0].Starred { + t.Errorf("bob's trash: %+v", l) + } + if l := inbox(t, s, "bob", store.FolderDrafts); len(l) != 1 || l[0].Subject != "Draft" { + t.Errorf("bob's drafts: %+v", l) + } + if l := inbox(t, s, "alice", store.FolderSent); len(l) != 1 || l[0].Subject != "From Python" { + t.Errorf("alice's sent: %+v", l) + } +} diff --git a/internal/email/smtp.go b/internal/email/smtp.go index 6b17e81..073224d 100644 --- a/internal/email/smtp.go +++ b/internal/email/smtp.go @@ -95,9 +95,10 @@ func smtpErr(code int, enh smtp.EnhancedCode, msg string) *smtp.SMTPError { } var ( - errTLSFirst = smtpErr(530, smtp.EnhancedCode{5, 7, 0}, "Use STARTTLS first") - errNoRelay = smtpErr(550, smtp.EnhancedCode{5, 7, 1}, "Mail for elsewhere is not taken here") - errNoUser = smtpErr(550, smtp.EnhancedCode{5, 1, 1}, "No such user here") + errTLSFirst = smtpErr(530, smtp.EnhancedCode{5, 7, 0}, "Use STARTTLS first") + errAuthFirst = smtpErr(530, smtp.EnhancedCode{5, 7, 0}, "Authentication required") + errNoRelay = smtpErr(550, smtp.EnhancedCode{5, 7, 1}, "Mail for elsewhere is not taken here") + errNoUser = smtpErr(550, smtp.EnhancedCode{5, 1, 1}, "No such user here") ) // tls reports whether the session is in TLS. @@ -147,7 +148,7 @@ func (ss *smtpSession) Mail(from string, opts *smtp.MailOptions) error { if !ss.tls() && ss.x.set.TLS == TLSRequired { return errTLSFirst } - return smtp.ErrAuthRequired + return errAuthFirst } if from != "" && !strings.EqualFold(from, ss.x.svc.Address(ss.user)) { return smtpErr(553, smtp.EnhancedCode{5, 7, 1}, "Send from your own address, "+ss.x.svc.Address(ss.user)) From 863febd9a5b37ed1328487c7abd935f267c9ea05 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 13:22:14 +0000 Subject: [PATCH 4/5] go.mod: the mail libraries are direct requirements (go mod tidy) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRVPRbt1YgtG7eQJZxD --- go.mod | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index ca35359..182cae9 100644 --- a/go.mod +++ b/go.mod @@ -5,10 +5,16 @@ go 1.24.0 toolchain go1.24.7 require ( + blitiri.com.ar/go/spf v1.5.1 github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38 github.com/D-Modem/menu v0.0.0-20261106031303-853189d86fb2 github.com/coder/websocket v1.8.13 github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7 + github.com/emersion/go-imap/v2 v2.0.0-beta.8 + github.com/emersion/go-message v0.18.2 + github.com/emersion/go-msgauth v0.7.0 + github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 + github.com/emersion/go-smtp v0.25.1 github.com/ergochat/irc-go v0.7.0 github.com/fclairamb/ftpserverlib v0.30.0 github.com/go-sql-driver/mysql v1.8.1 @@ -25,15 +31,9 @@ require ( ) require ( - blitiri.com.ar/go/spf v1.5.1 // indirect filippo.io/edwards25519 v1.1.0 // indirect github.com/dlclark/regexp2 v1.11.4 // indirect github.com/dustin/go-humanize v1.0.1 // indirect - github.com/emersion/go-imap/v2 v2.0.0-beta.8 // indirect - github.com/emersion/go-message v0.18.2 // indirect - github.com/emersion/go-msgauth v0.7.0 // indirect - github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirect - github.com/emersion/go-smtp v0.25.1 // indirect github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd // indirect github.com/google/uuid v1.6.0 // indirect From 17cd941f1a52814add15eed8ea9f1fdb6c9126d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 19:57:20 +0000 Subject: [PATCH 5/5] E-mail: DNS blocklists for mail from the internet ([mx] dnsbl) The sending address is looked up in each list at once at the first MAIL FROM; a listed sender is refused (554 5.7.1, with the list's TXT reason) and logged. A list that does not answer, or refuses the query (Spamhaus's 127.255.255.x through public resolvers, logged), refuses no one. Local and private addresses, and logged-in submission, are never looked up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRVPRbt1YgtG7eQJZxD --- bbs.conf.sample | 6 ++ cmd/bbs/main.go | 6 +- docs/wiki/Configuration-Reference.md | 1 + docs/wiki/E-mail.md | 35 ++++++++++ docs/wiki/Security.md | 3 + internal/email/dnsbl.go | 95 ++++++++++++++++++++++++++++ internal/email/dnsbl_test.go | 57 +++++++++++++++++ internal/email/email_test.go | 12 ++++ internal/email/listen.go | 1 + internal/email/smtp.go | 13 ++++ internal/server/mailconfig.go | 9 +++ 11 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 internal/email/dnsbl.go create mode 100644 internal/email/dnsbl_test.go diff --git a/bbs.conf.sample b/bbs.conf.sample index 46bdae4..a0bf7ec 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -537,6 +537,12 @@ address = 127.0.0.1:2513 ;address = :25 ;tls = optional ;checks = yes +; DNS blocklists the sending address is looked up in (none by default). +; A listed sender is refused at MAIL FROM (554, with the list's reason); +; a list that does not answer refuses no one. Spamhaus refuses queries +; through public resolvers (8.8.8.8, 1.1.1.1) and wants a paid feed for +; heavy or commercial use: run a resolver of your own (unbound) for it +;dnsbl = zen.spamhaus.org, bl.spamcop.net ; LMTP, for a mail server in front (Postfix's virtual_transport) to hand ; mail in: a unix socket's path or host:port diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index fa1e7a9..d972215 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -241,7 +241,11 @@ func main() { } fmt.Printf("mail: @%s, host %s, out %s, %s\n", m.Domain, m.Hostname, out, dk) for _, ms := range cfg.MailServers { - fmt.Printf("%s: %s, tls %s\n", ms.Kind, ms.Set.Address, ms.Set.TLS) + fmt.Printf("%s: %s, tls %s", ms.Kind, ms.Set.Address, ms.Set.TLS) + if len(ms.Set.DNSBL) > 0 { + fmt.Printf(", dnsbl %s", strings.Join(ms.Set.DNSBL, ", ")) + } + fmt.Println() } } if f := cfg.Fido; f != nil { diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index d479f61..5c55145 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -393,6 +393,7 @@ mail from the internet: on port 25, named by the domain's MX record. checks = ye | `address` | | | See the section above. Examples: `:25`. | | `tls` | | | See the section above. Examples: `optional`. | | `checks` | | | See the section above. Examples: `yes`. | +| `dnsbl` | | | DNS blocklists the sending address is looked up in (none by default). A listed sender is refused at MAIL FROM (554, with the list's reason); a list that does not answer refuses no one. Spamhaus refuses queries through public resolvers (8.8.8.8, 1.1.1.1) and wants a paid feed for heavy or commercial use: run a resolver of your own (unbound) for it. Examples: `zen.spamhaus.org, bl.spamcop.net`. | ## `[lmtp]` diff --git a/docs/wiki/E-mail.md b/docs/wiki/E-mail.md index d08f665..024c4ca 100644 --- a/docs/wiki/E-mail.md +++ b/docs/wiki/E-mail.md @@ -132,6 +132,41 @@ checks SPF, DKIM and DMARC, and adds an `Authentication-Results` header. A mail is refused when it fails a DMARC policy of `p=reject`, or, for a domain with no DMARC record, when SPF fails and no signature of that domain holds. +### Spam: DNS blocklists + +A DNSBL is a list of addresses known to send spam, asked by DNS. `[mx] +dnsbl` names the lists to ask; none are asked unless it is set: + +``` +[mx] +address = :25 +dnsbl = zen.spamhaus.org, bl.spamcop.net +``` + +The connecting address is looked up in every list at once, at the first +`MAIL FROM`. If any list has it, the mail is refused with `554 5.7.1` and +the list's reason (its TXT record, often a link where the sender can ask to +be taken off), and the refusal is logged. A list that does not answer in +ten seconds, or answers with an error, refuses no one: mail is not lost +because a list is down. Addresses on this machine and private networks are +never looked up, and nor are users sending through `[smtp]`, who log in: +a user on a listed home connection can still send. + +Spamhaus answers nothing useful to queries through public resolvers +(8.8.8.8, 1.1.1.1, a cloud provider's): the BBS logs `refused the query` +when that happens. Run a resolver of your own (unbound, or the system's +with no forwarders) on the mail host, and see Spamhaus's terms: heavy or +commercial use needs their paid feed. Lists to consider: `zen.spamhaus.org` +(Spamhaus SBL, XBL and PBL in one), `bl.spamcop.net`, `b.barracudacentral.org` +(free, after registering the resolver's address with them). + +DNSBLs only look at the sending address. SPF, DKIM and DMARC (above) check +that mail claiming a domain comes from it. Together they keep out most +spam; for content filtering (SpamAssassin, rspamd) put Postfix in front +and hand mail in by LMTP, below. + +### LMTP + If another mail server already takes the domain's mail (Postfix, with its own spam filtering), it can hand mail to the BBS by LMTP instead: diff --git a/docs/wiki/Security.md b/docs/wiki/Security.md index 4fe79dd..e7a411f 100644 --- a/docs/wiki/Security.md +++ b/docs/wiki/Security.md @@ -112,6 +112,9 @@ ban_minutes = 60 ; a throttled address is banned this long gopher and binkp. Callers through unix sockets (a modem server, an upstream menu) are never refused. The file is read again when it changes; `bbs check` warns of lines that are not addresses. +- Mail from the internet (`[mx]`) can also be checked against DNS + blocklists (`dnsbl = zen.spamhaus.org`), and is checked for SPF, DKIM and + DMARC: see [E-mail](E-mail#spam-dns-blocklists). - `ban_minutes`: an address that `throttle_failures` turns away is banned outright for that long, from every service (not a caller ID: those are a modem server's callers, and a ban would not stop them). Bans are kept diff --git a/internal/email/dnsbl.go b/internal/email/dnsbl.go new file mode 100644 index 0000000..c51100b --- /dev/null +++ b/internal/email/dnsbl.go @@ -0,0 +1,95 @@ +package email + +import ( + "context" + "fmt" + "net" + "strings" + "sync" + "time" +) + +// reversed is an IP's DNSBL query name under a list: 1.2.0.192.list for +// 192.0.2.1, and for IPv6 its 32 nibbles backwards. +func reversed(ip net.IP, list string) string { + if v4 := ip.To4(); v4 != nil { + return fmt.Sprintf("%d.%d.%d.%d.%s", v4[3], v4[2], v4[1], v4[0], list) + } + const hex = "0123456789abcdef" + var b strings.Builder + for i := len(ip) - 1; i >= 0; i-- { + b.WriteByte(hex[ip[i]&0xf]) + b.WriteByte('.') + b.WriteByte(hex[ip[i]>>4]) + b.WriteByte('.') + } + return b.String() + list +} + +// unlisted: addresses no list has (this machine's, a private network's). +var unlisted = func(ip net.IP) bool { return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() } + +// listedBy is the first of the lists that has an IP on it, and the reason it +// gives (its TXT record), or "" if none does. A list that cannot be asked +// (no answer in time, or a refusal: 127.255.255.x, as Spamhaus answers +// queries through public resolvers) does not count: mail is not refused +// because a list is down. +func (s *Service) listedBy(ip net.IP, lists []string) (list, why string) { + if ip == nil || unlisted(ip) || len(lists) == 0 { + return "", "" + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + r := s.Set.Resolver + hits := make([]string, len(lists)) + var wg sync.WaitGroup + for i, l := range lists { + wg.Add(1) + go func() { + defer wg.Done() + name := reversed(ip, l) + addrs, err := r.LookupIPAddr(ctx, name) + if err != nil { + return + } + for _, a := range addrs { + v4 := a.IP.To4() + if v4 == nil || v4[0] != 127 { + continue + } + if v4[1] == 255 && v4[2] == 255 { + s.B.Log.Printf("mx: dnsbl %s refused the query (%s): use a resolver of your own for it", l, a.IP) + return + } + hits[i] = name + return + } + }() + } + wg.Wait() + for i, name := range hits { + if name == "" { + continue + } + if txt, err := r.LookupTXT(ctx, name); err == nil && len(txt) > 0 { + why = txt[0] + } + return lists[i], why + } + return "", "" +} + +// printable is a list's reason fit for an SMTP reply: printable ASCII, on +// one line, not too long. +func printable(s string) string { + s = strings.Map(func(r rune) rune { + if r < ' ' || r > '~' { + return ' ' + } + return r + }, s) + if len(s) > 200 { + s = s[:200] + } + return strings.TrimSpace(s) +} diff --git a/internal/email/dnsbl_test.go b/internal/email/dnsbl_test.go new file mode 100644 index 0000000..ccb1206 --- /dev/null +++ b/internal/email/dnsbl_test.go @@ -0,0 +1,57 @@ +package email + +import ( + "net" + "net/smtp" + "strings" + "testing" +) + +func TestReversed(t *testing.T) { + if r := reversed(net.ParseIP("192.0.2.1"), "zen.spamhaus.org"); r != "1.2.0.192.zen.spamhaus.org" { + t.Error(r) + } + r := reversed(net.ParseIP("2001:db8::1"), "bl.test") + if r != "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.bl.test" { + t.Error(r) + } +} + +// A sender on a blocklist is refused at MAIL FROM, with the list's reason; +// one the list cannot answer for, or that is not on it, is not. +func TestDNSBL(t *testing.T) { + dns := &fakeDNS{bl: map[string]string{ + "9.2.0.192.bl.test": "127.0.0.2", "8.2.0.192.bl.test": "127.255.255.254", + "9.2.0.192.other.test": "127.0.0.4", + }, txt: map[string][]string{"9.2.0.192.bl.test": {"Listed: see https://bl.test/lookup"}}} + s := newSite(t, "a.test", dns, []string{"sysop", "bob"}, MX) + lists := []string{"other.bl.test", "bl.test"} + if l, why := s.svc.listedBy(net.ParseIP("192.0.2.9"), lists); l != "bl.test" || !strings.Contains(why, "https://bl.test/lookup") { + t.Errorf("listed: %q %q", l, why) + } + for _, ip := range []string{"192.0.2.8", "192.0.2.7", "127.0.0.1", "10.1.2.3"} { + if l, _ := s.svc.listedBy(net.ParseIP(ip), lists); l != "" { + t.Errorf("%s listed by %s", ip, l) + } + } + if !strings.Contains(s.log.String(), "refused the query") { + t.Error("no note of the refused query") + } + + // over SMTP: this test's 127.0.0.1, put on the list + old := unlisted + unlisted = func(net.IP) bool { return false } + t.Cleanup(func() { unlisted = old }) + dns.mu.Lock() + dns.bl["1.0.0.127.bl.test"] = "127.0.0.2" + dns.mu.Unlock() + c, err := smtp.Dial(s.addrs[MX]) + if err != nil { + t.Fatal(err) + } + defer c.Close() + err = c.Mail("z@example.com") + if err == nil || !strings.Contains(err.Error(), "554") || !strings.Contains(err.Error(), "listed by bl.test") { + t.Fatalf("mail from a listed address: %v", err) + } +} diff --git a/internal/email/email_test.go b/internal/email/email_test.go index 221779c..20635f8 100644 --- a/internal/email/email_test.go +++ b/internal/email/email_test.go @@ -31,6 +31,7 @@ type fakeDNS struct { mu sync.Mutex txt map[string][]string mx map[string][]*net.MX + bl map[string]string // DNSBL query names listed: their address } func (d *fakeDNS) LookupTXT(ctx context.Context, name string) ([]string, error) { @@ -52,6 +53,14 @@ func (d *fakeDNS) LookupMX(ctx context.Context, name string) ([]*net.MX, error) } func (d *fakeDNS) LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error) { + d.mu.Lock() + defer d.mu.Unlock() + if a, ok := d.bl[host]; ok { + return []net.IPAddr{{IP: net.ParseIP(a)}}, nil + } + if strings.HasSuffix(host, ".bl.test") { + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} + } return []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, nil } @@ -96,6 +105,9 @@ func newSite(t *testing.T, domain string, dns *fakeDNS, users []string, kinds .. var wg sync.WaitGroup for _, k := range kinds { set := ServerSettings{Address: "127.0.0.1:0", TLS: TLSNo, MaxClients: 10, MaxPerIP: 10, IdleTimeout: time.Minute} + if k == MX { + set.DNSBL = []string{"bl.test"} + } var run func(context.Context) error var addr net.Addr switch k { diff --git a/internal/email/listen.go b/internal/email/listen.go index 90dca7a..640274c 100644 --- a/internal/email/listen.go +++ b/internal/email/listen.go @@ -32,6 +32,7 @@ type ServerSettings struct { MaxClients int MaxPerIP int IdleTimeout time.Duration + DNSBL []string // [mx]: DNS blocklists the sending IP is looked up in } // tlsConfig is a server's certificate, if TLS is on. diff --git a/internal/email/smtp.go b/internal/email/smtp.go index 073224d..832882b 100644 --- a/internal/email/smtp.go +++ b/internal/email/smtp.go @@ -88,6 +88,7 @@ type smtpSession struct { from string rcpts []string local []*store.User + bl bool // the blocklists asked } func smtpErr(code int, enh smtp.EnhancedCode, msg string) *smtp.SMTPError { @@ -154,6 +155,18 @@ func (ss *smtpSession) Mail(from string, opts *smtp.MailOptions) error { return smtpErr(553, smtp.EnhancedCode{5, 7, 1}, "Send from your own address, "+ss.x.svc.Address(ss.user)) } } + if ss.x.kind == MX && len(ss.x.set.DNSBL) > 0 && !ss.bl { + ss.bl = true + ip := net.ParseIP(hostOf(ss.c.Conn().RemoteAddr())) + if list, why := ss.x.svc.listedBy(ip, ss.x.set.DNSBL); list != "" { + ss.x.svc.B.Log.Printf("%s: refused: %s is listed by %s %s", ss.who, ip, list, why) + msg := fmt.Sprintf("%s is listed by %s", ip, list) + if why != "" { + msg += ": " + printable(why) + } + return smtpErr(554, smtp.EnhancedCode{5, 7, 1}, msg) + } + } ss.from = from return nil } diff --git a/internal/server/mailconfig.go b/internal/server/mailconfig.go index db6707a..6effaf3 100644 --- a/internal/server/mailconfig.go +++ b/internal/server/mailconfig.go @@ -173,6 +173,15 @@ func mailServer(s *config.Section, kind, addr, tls, certFile, keyFile string) (* if ms.Checks, err = s.Bool("checks", true); err != nil { return nil, err } + for _, l := range strings.Split(s.String("dnsbl", ""), ",") { + if l = strings.ToLower(strings.Trim(strings.TrimSpace(l), ".")); l == "" { + continue + } + if !news.ValidMessageID("") || !strings.Contains(l, ".") { + return nil, fmt.Errorf("dnsbl: %q is not a domain, like zen.spamhaus.org", l) + } + set.DNSBL = append(set.DNSBL, l) + } } return ms, nil }