-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathapi.go
2077 lines (1810 loc) · 64.8 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package webmail
import (
"context"
cryptorand "crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"mime/multipart"
"net"
"net/http"
"net/mail"
"net/textproto"
"os"
"regexp"
"runtime/debug"
"slices"
"sort"
"strings"
"sync"
"time"
_ "embed"
"golang.org/x/exp/maps"
"github.com/mjl-/bstore"
"github.com/mjl-/sherpa"
"github.com/mjl-/sherpadoc"
"github.com/mjl-/sherpaprom"
"github.com/mjl-/mox/admin"
"github.com/mjl-/mox/config"
"github.com/mjl-/mox/dkim"
"github.com/mjl-/mox/dns"
"github.com/mjl-/mox/message"
"github.com/mjl-/mox/metrics"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/moxio"
"github.com/mjl-/mox/moxvar"
"github.com/mjl-/mox/mtasts"
"github.com/mjl-/mox/mtastsdb"
"github.com/mjl-/mox/queue"
"github.com/mjl-/mox/smtp"
"github.com/mjl-/mox/smtpclient"
"github.com/mjl-/mox/store"
"github.com/mjl-/mox/webauth"
"github.com/mjl-/mox/webops"
)
//go:embed api.json
var webmailapiJSON []byte
type Webmail struct {
maxMessageSize int64 // From listener.
cookiePath string // From listener.
isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
}
func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
err := json.Unmarshal(buf, &doc)
if err != nil {
pkglog.Fatalx("parsing webmail api docs", err, slog.String("api", api))
}
return doc
}
var webmailDoc = mustParseAPI("webmail", webmailapiJSON)
var sherpaHandlerOpts *sherpa.HandlerOpts
func makeSherpaHandler(maxMessageSize int64, cookiePath string, isForwarded bool) (http.Handler, error) {
return sherpa.NewHandler("/api/", moxvar.Version, Webmail{maxMessageSize, cookiePath, isForwarded}, &webmailDoc, sherpaHandlerOpts)
}
func init() {
collector, err := sherpaprom.NewCollector("moxwebmail", nil)
if err != nil {
pkglog.Fatalx("creating sherpa prometheus collector", err)
}
sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
// Just to validate.
_, err = makeSherpaHandler(0, "", false)
if err != nil {
pkglog.Fatalx("sherpa handler", err)
}
}
// LoginPrep returns a login token, and also sets it as cookie. Both must be
// present in the call to Login.
func (w Webmail) LoginPrep(ctx context.Context) string {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
log := reqInfo.Log
var data [8]byte
_, err := cryptorand.Read(data[:])
xcheckf(ctx, err, "generate token")
loginToken := base64.RawURLEncoding.EncodeToString(data[:])
webauth.LoginPrep(ctx, log, "webmail", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
return loginToken
}
// Login returns a session token for the credentials, or fails with error code
// "user:badLogin". Call LoginPrep to get a loginToken.
func (w Webmail) Login(ctx context.Context, loginToken, username, password string) store.CSRFToken {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
log := reqInfo.Log
csrfToken, err := webauth.Login(ctx, log, webauth.Accounts, "webmail", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, username, password)
if _, ok := err.(*sherpa.Error); ok {
panic(err)
}
xcheckf(ctx, err, "login")
return csrfToken
}
// Logout invalidates the session token.
func (w Webmail) Logout(ctx context.Context) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
log := reqInfo.Log
err := webauth.Logout(ctx, log, webauth.Accounts, "webmail", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, reqInfo.Account.Name, reqInfo.SessionToken)
xcheckf(ctx, err, "logout")
}
// Token returns a single-use token to use for an SSE connection. A token can only
// be used for a single SSE connection. Tokens are stored in memory for a maximum
// of 1 minute, with at most 10 unused tokens (the most recently created) per
// account.
func (Webmail) Token(ctx context.Context) string {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
return sseTokens.xgenerate(ctx, reqInfo.Account.Name, reqInfo.LoginAddress, reqInfo.SessionToken)
}
// Requests sends a new request for an open SSE connection. Any currently active
// request for the connection will be canceled, but this is done asynchrously, so
// the SSE connection may still send results for the previous request. Callers
// should take care to ignore such results. If req.Cancel is set, no new request is
// started.
func (Webmail) Request(ctx context.Context, req Request) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
if !req.Cancel && req.Page.Count <= 0 {
xcheckuserf(ctx, errors.New("Page.Count must be >= 1"), "checking request")
}
sse, ok := sseGet(req.SSEID, reqInfo.Account.Name)
if !ok {
xcheckuserf(ctx, errors.New("unknown sseid"), "looking up connection")
}
sse.Request <- req
}
// ParsedMessage returns enough to render the textual body of a message. It is
// assumed the client already has other fields through MessageItem.
func (Webmail) ParsedMessage(ctx context.Context, msgID int64) (pm ParsedMessage) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
log := reqInfo.Log
acc := reqInfo.Account
xdbread(ctx, acc, func(tx *bstore.Tx) {
m := xmessageID(ctx, tx, msgID)
state := msgState{acc: acc}
defer state.clear()
var err error
pm, err = parsedMessage(log, m, &state, true, false, false)
xcheckf(ctx, err, "parsing message")
if len(pm.envelope.From) == 1 {
pm.ViewMode, err = fromAddrViewMode(tx, pm.envelope.From[0])
xcheckf(ctx, err, "looking up view mode for from address")
}
})
return
}
// fromAddrViewMode returns the view mode for a from address.
func fromAddrViewMode(tx *bstore.Tx, from MessageAddress) (store.ViewMode, error) {
settingsViewMode := func() (store.ViewMode, error) {
settings := store.Settings{ID: 1}
if err := tx.Get(&settings); err != nil {
return store.ModeText, err
}
if settings.ShowHTML {
return store.ModeHTML, nil
}
return store.ModeText, nil
}
lp, err := smtp.ParseLocalpart(from.User)
if err != nil {
return settingsViewMode()
}
fromAddr := smtp.NewAddress(lp, from.Domain).Pack(true)
fas := store.FromAddressSettings{FromAddress: fromAddr}
err = tx.Get(&fas)
if err == bstore.ErrAbsent {
return settingsViewMode()
} else if err != nil {
return store.ModeText, err
}
return fas.ViewMode, nil
}
// FromAddressSettingsSave saves per-"From"-address settings.
func (Webmail) FromAddressSettingsSave(ctx context.Context, fas store.FromAddressSettings) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
acc := reqInfo.Account
if fas.FromAddress == "" {
xcheckuserf(ctx, errors.New("empty from address"), "checking address")
}
xdbwrite(ctx, acc, func(tx *bstore.Tx) {
if tx.Get(&store.FromAddressSettings{FromAddress: fas.FromAddress}) == nil {
err := tx.Update(&fas)
xcheckf(ctx, err, "updating settings for from address")
} else {
err := tx.Insert(&fas)
xcheckf(ctx, err, "inserting settings for from address")
}
})
}
// MessageFindMessageID looks up a message by Message-Id header, and returns the ID
// of the message in storage. Used when opening a previously saved draft message
// for editing again.
// If no message is find, zero is returned, not an error.
func (Webmail) MessageFindMessageID(ctx context.Context, messageID string) (id int64) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
acc := reqInfo.Account
messageID, _, _ = message.MessageIDCanonical(messageID)
if messageID == "" {
xcheckuserf(ctx, errors.New("empty message-id"), "parsing message-id")
}
xdbread(ctx, acc, func(tx *bstore.Tx) {
m, err := bstore.QueryTx[store.Message](tx).FilterNonzero(store.Message{MessageID: messageID}).Get()
if err == bstore.ErrAbsent {
return
}
xcheckf(ctx, err, "looking up message by message-id")
id = m.ID
})
return
}
// ComposeMessage is a message to be composed, for saving draft messages.
type ComposeMessage struct {
From string
To []string
Cc []string
Bcc []string
ReplyTo string // If non-empty, Reply-To header to add to message.
Subject string
TextBody string
ResponseMessageID int64 // If set, this was a reply or forward, based on IsForward.
DraftMessageID int64 // If set, previous draft message that will be removed after composing new message.
}
// MessageCompose composes a message and saves it to the mailbox. Used for
// saving draft messages.
func (w Webmail) MessageCompose(ctx context.Context, m ComposeMessage, mailboxID int64) (id int64) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
acc := reqInfo.Account
log := reqInfo.Log
log.Debug("message compose")
// Prevent any accidental control characters, or attempts at getting bare \r or \n
// into messages.
for _, l := range [][]string{m.To, m.Cc, m.Bcc, {m.From, m.Subject, m.ReplyTo}} {
for _, s := range l {
for _, c := range s {
if c < 0x20 {
xcheckuserf(ctx, errors.New("control characters not allowed"), "checking header values")
}
}
}
}
fromAddr, err := parseAddress(m.From)
xcheckuserf(ctx, err, "parsing From address")
var replyTo *message.NameAddress
if m.ReplyTo != "" {
addr, err := parseAddress(m.ReplyTo)
xcheckuserf(ctx, err, "parsing Reply-To address")
replyTo = &addr
}
var recipients []smtp.Address
var toAddrs []message.NameAddress
for _, s := range m.To {
addr, err := parseAddress(s)
xcheckuserf(ctx, err, "parsing To address")
toAddrs = append(toAddrs, addr)
recipients = append(recipients, addr.Address)
}
var ccAddrs []message.NameAddress
for _, s := range m.Cc {
addr, err := parseAddress(s)
xcheckuserf(ctx, err, "parsing Cc address")
ccAddrs = append(ccAddrs, addr)
recipients = append(recipients, addr.Address)
}
var bccAddrs []message.NameAddress
for _, s := range m.Bcc {
addr, err := parseAddress(s)
xcheckuserf(ctx, err, "parsing Bcc address")
bccAddrs = append(bccAddrs, addr)
recipients = append(recipients, addr.Address)
}
// We only use smtputf8 if we have to, with a utf-8 localpart. For IDNA, we use ASCII domains.
smtputf8 := false
for _, a := range recipients {
if a.Localpart.IsInternational() {
smtputf8 = true
break
}
}
if !smtputf8 && fromAddr.Address.Localpart.IsInternational() {
// todo: may want to warn user that they should consider sending with a ascii-only localpart, in case receiver doesn't support smtputf8.
smtputf8 = true
}
if !smtputf8 && replyTo != nil && replyTo.Address.Localpart.IsInternational() {
smtputf8 = true
}
// Create file to compose message into.
dataFile, err := store.CreateMessageTemp(log, "webmail-compose")
xcheckf(ctx, err, "creating temporary file for compose message")
defer store.CloseRemoveTempFile(log, dataFile, "compose message")
// If writing to the message file fails, we abort immediately.
xc := message.NewComposer(dataFile, w.maxMessageSize, smtputf8)
defer func() {
x := recover()
if x == nil {
return
}
if err, ok := x.(error); ok && errors.Is(err, message.ErrMessageSize) {
xcheckuserf(ctx, err, "making message")
} else if ok && errors.Is(err, message.ErrCompose) {
xcheckf(ctx, err, "making message")
}
panic(x)
}()
// Outer message headers.
xc.HeaderAddrs("From", []message.NameAddress{fromAddr})
if replyTo != nil {
xc.HeaderAddrs("Reply-To", []message.NameAddress{*replyTo})
}
xc.HeaderAddrs("To", toAddrs)
xc.HeaderAddrs("Cc", ccAddrs)
xc.HeaderAddrs("Bcc", bccAddrs)
if m.Subject != "" {
xc.Subject(m.Subject)
}
// Add In-Reply-To and References headers.
if m.ResponseMessageID > 0 {
xdbread(ctx, acc, func(tx *bstore.Tx) {
rm := xmessageID(ctx, tx, m.ResponseMessageID)
msgr := acc.MessageReader(rm)
defer func() {
err := msgr.Close()
log.Check(err, "closing message reader")
}()
rp, err := rm.LoadPart(msgr)
xcheckf(ctx, err, "load parsed message")
h, err := rp.Header()
xcheckf(ctx, err, "parsing header")
if rp.Envelope == nil {
return
}
if rp.Envelope.MessageID != "" {
xc.Header("In-Reply-To", rp.Envelope.MessageID)
}
refs := h.Values("References")
if len(refs) == 0 && rp.Envelope.InReplyTo != "" {
refs = []string{rp.Envelope.InReplyTo}
}
if rp.Envelope.MessageID != "" {
refs = append(refs, rp.Envelope.MessageID)
}
if len(refs) > 0 {
xc.Header("References", strings.Join(refs, "\r\n\t"))
}
})
}
xc.Header("MIME-Version", "1.0")
textBody, ct, cte := xc.TextPart("plain", m.TextBody)
xc.Header("Content-Type", ct)
xc.Header("Content-Transfer-Encoding", cte)
xc.Line()
xc.Write([]byte(textBody))
xc.Flush()
var nm store.Message
// Remove previous draft message, append message to destination mailbox.
acc.WithRLock(func() {
var changes []store.Change
xdbwrite(ctx, acc, func(tx *bstore.Tx) {
var modseq store.ModSeq // Only set if needed.
if m.DraftMessageID > 0 {
var nchanges []store.Change
modseq, nchanges = xops.MessageDeleteTx(ctx, log, tx, acc, []int64{m.DraftMessageID}, modseq)
changes = append(changes, nchanges...)
// On-disk file is removed after lock.
}
// Find mailbox to write to.
mb := store.Mailbox{ID: mailboxID}
err := tx.Get(&mb)
if err == bstore.ErrAbsent {
xcheckuserf(ctx, err, "looking up mailbox")
}
xcheckf(ctx, err, "looking up mailbox")
if modseq == 0 {
modseq, err = acc.NextModSeq(tx)
xcheckf(ctx, err, "next modseq")
}
nm = store.Message{
CreateSeq: modseq,
ModSeq: modseq,
MailboxID: mb.ID,
MailboxOrigID: mb.ID,
Flags: store.Flags{Notjunk: true},
Size: xc.Size,
}
if ok, maxSize, err := acc.CanAddMessageSize(tx, nm.Size); err != nil {
xcheckf(ctx, err, "checking quota")
} else if !ok {
xcheckuserf(ctx, fmt.Errorf("account over maximum total message size %d", maxSize), "checking quota")
}
// Update mailbox before delivery, which changes uidnext.
mb.Add(nm.MailboxCounts())
err = tx.Update(&mb)
xcheckf(ctx, err, "updating sent mailbox for counts")
err = acc.DeliverMessage(log, tx, &nm, dataFile, true, false, false, true)
xcheckf(ctx, err, "storing message in mailbox")
changes = append(changes, nm.ChangeAddUID(), mb.ChangeCounts())
})
store.BroadcastChanges(acc, changes)
})
// Remove on-disk file for removed draft message.
if m.DraftMessageID > 0 {
p := acc.MessagePath(m.DraftMessageID)
err := os.Remove(p)
log.Check(err, "removing draft message file")
}
return nm.ID
}
// Attachment is a MIME part is an existing message that is not intended as
// viewable text or HTML part.
type Attachment struct {
Path []int // Indices into top-level message.Part.Parts.
// File name based on "name" attribute of "Content-Type", or the "filename"
// attribute of "Content-Disposition".
Filename string
Part message.Part
}
// SubmitMessage is an email message to be sent to one or more recipients.
// Addresses are formatted as just email address, or with a name like "name
// <user@host>".
type SubmitMessage struct {
From string
To []string
Cc []string
Bcc []string
ReplyTo string // If non-empty, Reply-To header to add to message.
Subject string
TextBody string
Attachments []File
ForwardAttachments ForwardAttachments
IsForward bool
ResponseMessageID int64 // If set, this was a reply or forward, based on IsForward.
UserAgent string // User-Agent header added if not empty.
RequireTLS *bool // For "Require TLS" extension during delivery.
FutureRelease *time.Time // If set, time (in the future) when message should be delivered from queue.
ArchiveThread bool // If set, thread is archived after sending message.
ArchiveReferenceMailboxID int64 // If ArchiveThread is set, thread messages from this mailbox ID are moved to the archive mailbox ID. E.g. of Inbox.
DraftMessageID int64 // If set, draft message that will be removed after sending.
}
// ForwardAttachments references attachments by a list of message.Part paths.
type ForwardAttachments struct {
MessageID int64 // Only relevant if MessageID is not 0.
Paths [][]int // List of attachments, each path is a list of indices into the top-level message.Part.Parts.
}
// File is a new attachment (not from an existing message that is being
// forwarded) to send with a SubmitMessage.
type File struct {
Filename string
DataURI string // Full data of the attachment, with base64 encoding and including content-type.
}
// parseAddress expects either a plain email address like "user@domain", or a
// single address as used in a message header, like "name <user@domain>".
func parseAddress(msghdr string) (message.NameAddress, error) {
// todo: parse more fully according to ../rfc/5322:959
parser := mail.AddressParser{WordDecoder: &wordDecoder}
a, err := parser.Parse(msghdr)
if err != nil {
return message.NameAddress{}, err
}
path, err := smtp.ParseNetMailAddress(a.Address)
if err != nil {
return message.NameAddress{}, err
}
return message.NameAddress{DisplayName: a.Name, Address: path}, nil
}
func xmailboxID(ctx context.Context, tx *bstore.Tx, mailboxID int64) store.Mailbox {
if mailboxID == 0 {
xcheckuserf(ctx, errors.New("invalid zero mailbox ID"), "getting mailbox")
}
mb := store.Mailbox{ID: mailboxID}
err := tx.Get(&mb)
if err == bstore.ErrAbsent {
xcheckuserf(ctx, err, "getting mailbox")
}
xcheckf(ctx, err, "getting mailbox")
return mb
}
// xmessageID returns a non-expunged message or panics with a sherpa error.
func xmessageID(ctx context.Context, tx *bstore.Tx, messageID int64) store.Message {
if messageID == 0 {
xcheckuserf(ctx, errors.New("invalid zero message id"), "getting message")
}
m := store.Message{ID: messageID}
err := tx.Get(&m)
if err == bstore.ErrAbsent {
xcheckuserf(ctx, errors.New("message does not exist"), "getting message")
} else if err == nil && m.Expunged {
xcheckuserf(ctx, errors.New("message was removed"), "getting message")
}
xcheckf(ctx, err, "getting message")
return m
}
func xrandomID(ctx context.Context, n int) string {
return base64.RawURLEncoding.EncodeToString(xrandom(ctx, n))
}
func xrandom(ctx context.Context, n int) []byte {
buf := make([]byte, n)
x, err := cryptorand.Read(buf)
xcheckf(ctx, err, "read random")
if x != n {
xcheckf(ctx, errors.New("short random read"), "read random")
}
return buf
}
// MessageSubmit sends a message by submitting it the outgoing email queue. The
// message is sent to all addresses listed in the To, Cc and Bcc addresses, without
// Bcc message header.
//
// If a Sent mailbox is configured, messages are added to it after submitting
// to the delivery queue. If Bcc addresses were present, a header is prepended
// to the message stored in the Sent mailbox.
func (w Webmail) MessageSubmit(ctx context.Context, m SubmitMessage) {
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
acc := reqInfo.Account
log := reqInfo.Log
log.Debug("message submit")
// Similar between ../smtpserver/server.go:/submit\( and ../webmail/api.go:/MessageSubmit\( and ../webapisrv/server.go:/Send\(
// todo: consider making this an HTTP POST, so we can upload as regular form, which is probably more efficient for encoding for the client and we can stream the data in. also not unlike the webapi Submit method.
// Prevent any accidental control characters, or attempts at getting bare \r or \n
// into messages.
for _, l := range [][]string{m.To, m.Cc, m.Bcc, {m.From, m.Subject, m.ReplyTo, m.UserAgent}} {
for _, s := range l {
for _, c := range s {
if c < 0x20 {
xcheckuserf(ctx, errors.New("control characters not allowed"), "checking header values")
}
}
}
}
fromAddr, err := parseAddress(m.From)
xcheckuserf(ctx, err, "parsing From address")
var replyTo *message.NameAddress
if m.ReplyTo != "" {
a, err := parseAddress(m.ReplyTo)
xcheckuserf(ctx, err, "parsing Reply-To address")
replyTo = &a
}
var recipients []smtp.Address
var toAddrs []message.NameAddress
for _, s := range m.To {
addr, err := parseAddress(s)
xcheckuserf(ctx, err, "parsing To address")
toAddrs = append(toAddrs, addr)
recipients = append(recipients, addr.Address)
}
var ccAddrs []message.NameAddress
for _, s := range m.Cc {
addr, err := parseAddress(s)
xcheckuserf(ctx, err, "parsing Cc address")
ccAddrs = append(ccAddrs, addr)
recipients = append(recipients, addr.Address)
}
var bccAddrs []message.NameAddress
for _, s := range m.Bcc {
addr, err := parseAddress(s)
xcheckuserf(ctx, err, "parsing Bcc address")
bccAddrs = append(bccAddrs, addr)
recipients = append(recipients, addr.Address)
}
// Check if from address is allowed for account.
if !mox.AllowMsgFrom(reqInfo.Account.Name, fromAddr.Address) {
metricSubmission.WithLabelValues("badfrom").Inc()
xcheckuserf(ctx, errors.New("address not found"), `looking up "from" address for account`)
}
if len(recipients) == 0 {
xcheckuserf(ctx, errors.New("no recipients"), "composing message")
}
// Check outgoing message rate limit.
xdbread(ctx, acc, func(tx *bstore.Tx) {
rcpts := make([]smtp.Path, len(recipients))
for i, r := range recipients {
rcpts[i] = smtp.Path{Localpart: r.Localpart, IPDomain: dns.IPDomain{Domain: r.Domain}}
}
msglimit, rcptlimit, err := acc.SendLimitReached(tx, rcpts)
if msglimit >= 0 {
metricSubmission.WithLabelValues("messagelimiterror").Inc()
xcheckuserf(ctx, errors.New("message limit reached"), "checking outgoing rate")
} else if rcptlimit >= 0 {
metricSubmission.WithLabelValues("recipientlimiterror").Inc()
xcheckuserf(ctx, errors.New("recipient limit reached"), "checking outgoing rate")
}
xcheckf(ctx, err, "checking send limit")
})
// We only use smtputf8 if we have to, with a utf-8 localpart. For IDNA, we use ASCII domains.
smtputf8 := false
for _, a := range recipients {
if a.Localpart.IsInternational() {
smtputf8 = true
break
}
}
if !smtputf8 && fromAddr.Address.Localpart.IsInternational() {
// todo: may want to warn user that they should consider sending with a ascii-only localpart, in case receiver doesn't support smtputf8.
smtputf8 = true
}
if !smtputf8 && replyTo != nil && replyTo.Address.Localpart.IsInternational() {
smtputf8 = true
}
// Create file to compose message into.
dataFile, err := store.CreateMessageTemp(log, "webmail-submit")
xcheckf(ctx, err, "creating temporary file for message")
defer store.CloseRemoveTempFile(log, dataFile, "message to submit")
// If writing to the message file fails, we abort immediately.
xc := message.NewComposer(dataFile, w.maxMessageSize, smtputf8)
defer func() {
x := recover()
if x == nil {
return
}
if err, ok := x.(error); ok && errors.Is(err, message.ErrMessageSize) {
xcheckuserf(ctx, err, "making message")
} else if ok && errors.Is(err, message.ErrCompose) {
xcheckf(ctx, err, "making message")
}
panic(x)
}()
// todo spec: can we add an Authentication-Results header that indicates this is an authenticated message? the "auth" method is for SMTP AUTH, which this isn't. ../rfc/8601 https://www.iana.org/assignments/email-auth/email-auth.xhtml
// Each queued message gets a Received header.
// We don't have access to the local IP for adding.
// We cannot use VIA, because there is no registered method. We would like to use
// it to add the ascii domain name in case of smtputf8 and IDNA host name.
recvFrom := message.HeaderCommentDomain(mox.Conf.Static.HostnameDomain, smtputf8)
recvBy := mox.Conf.Static.HostnameDomain.XName(smtputf8)
recvID := mox.ReceivedID(mox.CidFromCtx(ctx))
recvHdrFor := func(rcptTo string) string {
recvHdr := &message.HeaderWriter{}
// For additional Received-header clauses, see:
// https://www.iana.org/assignments/mail-parameters/mail-parameters.xhtml#table-mail-parameters-8
// Note: we don't have "via" or "with", there is no registered for webmail.
recvHdr.Add(" ", "Received:", "from", recvFrom, "by", recvBy, "id", recvID) // ../rfc/5321:3158
if reqInfo.Request.TLS != nil {
recvHdr.Add(" ", mox.TLSReceivedComment(log, *reqInfo.Request.TLS)...)
}
recvHdr.Add(" ", "for", "<"+rcptTo+">;", time.Now().Format(message.RFC5322Z))
return recvHdr.String()
}
// Outer message headers.
xc.HeaderAddrs("From", []message.NameAddress{fromAddr})
if replyTo != nil {
xc.HeaderAddrs("Reply-To", []message.NameAddress{*replyTo})
}
xc.HeaderAddrs("To", toAddrs)
xc.HeaderAddrs("Cc", ccAddrs)
// We prepend Bcc headers to the message when adding to the Sent mailbox.
if m.Subject != "" {
xc.Subject(m.Subject)
}
messageID := fmt.Sprintf("<%s>", mox.MessageIDGen(smtputf8))
xc.Header("Message-Id", messageID)
xc.Header("Date", time.Now().Format(message.RFC5322Z))
// Add In-Reply-To and References headers.
if m.ResponseMessageID > 0 {
xdbread(ctx, acc, func(tx *bstore.Tx) {
rm := xmessageID(ctx, tx, m.ResponseMessageID)
msgr := acc.MessageReader(rm)
defer func() {
err := msgr.Close()
log.Check(err, "closing message reader")
}()
rp, err := rm.LoadPart(msgr)
xcheckf(ctx, err, "load parsed message")
h, err := rp.Header()
xcheckf(ctx, err, "parsing header")
if rp.Envelope == nil {
return
}
if rp.Envelope.MessageID != "" {
xc.Header("In-Reply-To", rp.Envelope.MessageID)
}
refs := h.Values("References")
if len(refs) == 0 && rp.Envelope.InReplyTo != "" {
refs = []string{rp.Envelope.InReplyTo}
}
if rp.Envelope.MessageID != "" {
refs = append(refs, rp.Envelope.MessageID)
}
if len(refs) > 0 {
xc.Header("References", strings.Join(refs, "\r\n\t"))
}
})
}
if m.UserAgent != "" {
xc.Header("User-Agent", m.UserAgent)
}
if m.RequireTLS != nil && !*m.RequireTLS {
xc.Header("TLS-Required", "No")
}
xc.Header("MIME-Version", "1.0")
if len(m.Attachments) > 0 || len(m.ForwardAttachments.Paths) > 0 {
mp := multipart.NewWriter(xc)
xc.Header("Content-Type", fmt.Sprintf(`multipart/mixed; boundary="%s"`, mp.Boundary()))
xc.Line()
textBody, ct, cte := xc.TextPart("plain", m.TextBody)
textHdr := textproto.MIMEHeader{}
textHdr.Set("Content-Type", ct)
textHdr.Set("Content-Transfer-Encoding", cte)
textp, err := mp.CreatePart(textHdr)
xcheckf(ctx, err, "adding text part to message")
_, err = textp.Write(textBody)
xcheckf(ctx, err, "writing text part")
xaddPart := func(ct, filename string) io.Writer {
ahdr := textproto.MIMEHeader{}
cd := mime.FormatMediaType("attachment", map[string]string{"filename": filename})
ahdr.Set("Content-Type", ct)
ahdr.Set("Content-Transfer-Encoding", "base64")
ahdr.Set("Content-Disposition", cd)
ap, err := mp.CreatePart(ahdr)
xcheckf(ctx, err, "adding attachment part to message")
return ap
}
xaddAttachmentBase64 := func(ct, filename string, base64Data []byte) {
ap := xaddPart(ct, filename)
for len(base64Data) > 0 {
line := base64Data
n := len(line)
if n > 78 {
n = 78
}
line, base64Data = base64Data[:n], base64Data[n:]
_, err := ap.Write(line)
xcheckf(ctx, err, "writing attachment")
_, err = ap.Write([]byte("\r\n"))
xcheckf(ctx, err, "writing attachment")
}
}
xaddAttachment := func(ct, filename string, r io.Reader) {
ap := xaddPart(ct, filename)
wc := moxio.Base64Writer(ap)
_, err := io.Copy(wc, r)
xcheckf(ctx, err, "adding attachment")
err = wc.Close()
xcheckf(ctx, err, "flushing attachment")
}
for _, a := range m.Attachments {
s := a.DataURI
if !strings.HasPrefix(s, "data:") {
xcheckuserf(ctx, errors.New("missing data: in datauri"), "parsing attachment")
}
s = s[len("data:"):]
t := strings.SplitN(s, ",", 2)
if len(t) != 2 {
xcheckuserf(ctx, errors.New("missing comma in datauri"), "parsing attachment")
}
if !strings.HasSuffix(t[0], "base64") {
xcheckuserf(ctx, errors.New("missing base64 in datauri"), "parsing attachment")
}
ct := strings.TrimSuffix(t[0], "base64")
ct = strings.TrimSuffix(ct, ";")
if ct == "" {
ct = "application/octet-stream"
}
filename := a.Filename
if filename == "" {
filename = "unnamed.bin"
}
params := map[string]string{"name": filename}
ct = mime.FormatMediaType(ct, params)
// Ensure base64 is valid, then we'll write the original string.
_, err := io.Copy(io.Discard, base64.NewDecoder(base64.StdEncoding, strings.NewReader(t[1])))
xcheckuserf(ctx, err, "parsing attachment as base64")
xaddAttachmentBase64(ct, filename, []byte(t[1]))
}
if len(m.ForwardAttachments.Paths) > 0 {
acc.WithRLock(func() {
xdbread(ctx, acc, func(tx *bstore.Tx) {
fm := xmessageID(ctx, tx, m.ForwardAttachments.MessageID)
msgr := acc.MessageReader(fm)
defer func() {
err := msgr.Close()
log.Check(err, "closing message reader")
}()
fp, err := fm.LoadPart(msgr)
xcheckf(ctx, err, "load parsed message")
for _, path := range m.ForwardAttachments.Paths {
ap := fp
for _, xp := range path {
if xp < 0 || xp >= len(ap.Parts) {
xcheckuserf(ctx, errors.New("unknown part"), "looking up attachment")
}
ap = ap.Parts[xp]
}
_, filename, err := ap.DispositionFilename()
if err != nil && errors.Is(err, message.ErrParamEncoding) {
log.Debugx("parsing disposition/filename", err)
} else {
xcheckf(ctx, err, "reading disposition")
}
if filename == "" {
filename = "unnamed.bin"
}
params := map[string]string{"name": filename}
if pcharset := ap.ContentTypeParams["charset"]; pcharset != "" {
params["charset"] = pcharset
}
ct := strings.ToLower(ap.MediaType + "/" + ap.MediaSubType)
ct = mime.FormatMediaType(ct, params)
xaddAttachment(ct, filename, ap.Reader())
}
})
})
}
err = mp.Close()
xcheckf(ctx, err, "writing mime multipart")
} else {
textBody, ct, cte := xc.TextPart("plain", m.TextBody)
xc.Header("Content-Type", ct)
xc.Header("Content-Transfer-Encoding", cte)
xc.Line()
xc.Write([]byte(textBody))
}
xc.Flush()
// Add DKIM-Signature headers.
var msgPrefix string
fd := fromAddr.Address.Domain
confDom, _ := mox.Conf.Domain(fd)
selectors := mox.DKIMSelectors(confDom.DKIM)
if len(selectors) > 0 {
dkimHeaders, err := dkim.Sign(ctx, log.Logger, fromAddr.Address.Localpart, fd, selectors, smtputf8, dataFile)
if err != nil {
metricServerErrors.WithLabelValues("dkimsign").Inc()
}
xcheckf(ctx, err, "sign dkim")
msgPrefix = dkimHeaders
}
accConf, _ := acc.Conf()
loginAddr, err := smtp.ParseAddress(reqInfo.LoginAddress)
xcheckf(ctx, err, "parsing login address")
useFromID := slices.Contains(accConf.ParsedFromIDLoginAddresses, loginAddr)
fromPath := fromAddr.Address.Path()
var localpartBase string
if useFromID {
localpartBase = strings.SplitN(string(fromPath.Localpart), confDom.LocalpartCatchallSeparator, 2)[0]
}
qml := make([]queue.Msg, len(recipients))
now := time.Now()
for i, rcpt := range recipients {
fp := fromPath
var fromID string
if useFromID {
fromID = xrandomID(ctx, 16)
fp.Localpart = smtp.Localpart(localpartBase + confDom.LocalpartCatchallSeparator + fromID)
}
// Don't use per-recipient unique message prefix when multiple recipients are
// present, or the queue cannot deliver it in a single smtp transaction.
var recvRcpt string
if len(recipients) == 1 {
recvRcpt = rcpt.Pack(smtputf8)
}
rcptMsgPrefix := recvHdrFor(recvRcpt) + msgPrefix
msgSize := int64(len(rcptMsgPrefix)) + xc.Size
toPath := smtp.Path{
Localpart: rcpt.Localpart,
IPDomain: dns.IPDomain{Domain: rcpt.Domain},
}
qm := queue.MakeMsg(fp, toPath, xc.Has8bit, xc.SMTPUTF8, msgSize, messageID, []byte(rcptMsgPrefix), m.RequireTLS, now, m.Subject)
if m.FutureRelease != nil {
ival := time.Until(*m.FutureRelease)
if ival < 0 {
xcheckuserf(ctx, errors.New("date/time is in the past"), "scheduling delivery")
} else if ival > queue.FutureReleaseIntervalMax {
xcheckuserf(ctx, fmt.Errorf("date/time can not be further than %v in the future", queue.FutureReleaseIntervalMax), "scheduling delivery")
}
qm.NextAttempt = *m.FutureRelease
qm.FutureReleaseRequest = "until;" + m.FutureRelease.Format(time.RFC3339)
// todo: possibly add a header to the message stored in the Sent mailbox to indicate it was scheduled for later delivery.
}
qm.FromID = fromID
// no qm.Extra from webmail
qml[i] = qm