1// Package webapisrv implements the server-side of the webapi.
4// In a separate package from webapi, so webapi.Client can be used and imported
5// without including all mox internals. Documentation for the functions is in
11 cryptorand "crypto/rand"
16 htmltemplate "html/template"
30 "github.com/prometheus/client_golang/prometheus"
31 "github.com/prometheus/client_golang/prometheus/promauto"
33 "github.com/mjl-/bstore"
35 "github.com/mjl-/mox/dkim"
36 "github.com/mjl-/mox/dns"
37 "github.com/mjl-/mox/message"
38 "github.com/mjl-/mox/metrics"
39 "github.com/mjl-/mox/mlog"
40 "github.com/mjl-/mox/mox-"
41 "github.com/mjl-/mox/moxio"
42 "github.com/mjl-/mox/moxvar"
43 "github.com/mjl-/mox/queue"
44 "github.com/mjl-/mox/smtp"
45 "github.com/mjl-/mox/store"
46 "github.com/mjl-/mox/webapi"
47 "github.com/mjl-/mox/webauth"
48 "github.com/mjl-/mox/webops"
51var pkglog = mlog.New("webapi", nil)
54 // Similar between ../webmail/webmail.go:/metricSubmission and ../smtpserver/server.go:/metricSubmission and ../webapisrv/server.go:/metricSubmission
55 metricSubmission = promauto.NewCounterVec(
56 prometheus.CounterOpts{
57 Name: "mox_webapi_submission_total",
58 Help: "Webapi message submission results, known values (those ending with error are server errors): ok, badfrom, messagelimiterror, recipientlimiterror, queueerror, storesenterror, domaindisabled.",
64 metricServerErrors = promauto.NewCounterVec(
65 prometheus.CounterOpts{
66 Name: "mox_webapi_errors_total",
67 Help: "Webapi server errors, known values: dkimsign, submit.",
73 metricResults = promauto.NewCounterVec(
74 prometheus.CounterOpts{
75 Name: "mox_webapi_results_total",
76 Help: "HTTP webapi results by method and result.",
78 []string{"method", "result"}, // result: "badauth", "ok", or error code
80 metricDuration = promauto.NewHistogramVec(
81 prometheus.HistogramOpts{
82 Name: "mox_webapi_duration_seconds",
83 Help: "HTTP webhook call duration.",
84 Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1, 5, 10, 20, 30},
90// We pass the request to the handler so the TLS info can be used for
91// the Received header in submitted messages. Most API calls need just the
95var requestInfoCtxKey ctxKey = "requestInfo"
97type requestInfo struct {
100 Account *store.Account
101 Response http.ResponseWriter // For setting headers for non-JSON responses.
102 Request *http.Request // For Proto and TLS connection state during message submit.
105// todo: show a curl invocation on the method pages
107var docsMethodTemplate = htmltemplate.Must(htmltemplate.New("method").Parse(`<!doctype html>
109 <meta charset="utf-8" />
110 <meta name="robots" content="noindex,nofollow" />
111 <title>Method {{ .Method }} - WebAPI - Mox</title>
113body, html { padding: 1em; font-size: 16px; }
114* { font-size: inherit; font-family: ubuntu, lato, sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
115h1, h2, h3, h4 { margin-bottom: 1ex; }
116h1 { font-size: 1.2rem; }
117h2 { font-size: 1.1rem; }
118h3, h4 { font-size: 1rem; }
119ul { padding-left: 1rem; }
120p { margin-bottom: 1em; max-width: 50em; }
121[title] { text-decoration: underline; text-decoration-style: dotted; }
122fieldset { border: 0; }
123textarea { width: 100%; max-width: 50em; }
127 <h1><a href="../">WebAPI</a> - Method {{ .Method }}</h1>
128 <form id="webapicall" method="POST">
129 <fieldset id="webapifieldset">
130 <h2>Request JSON</h2>
131 <div><textarea id="webapirequest" name="request" required rows="20">{{ .Request }}</textarea></div>
134 <button type="reset">Reset</button>
135 <button type="submit">Call</button>
138{{ if .ReturnsBytes }}
139 <p>Method has a non-JSON response.</p>
141 <h2>Response JSON</h2>
142 <div><textarea id="webapiresponse" rows="20">{{ .Response }}</textarea></div>
147window.addEventListener('load', () => {
148 window.webapicall.addEventListener('submit', async (e) => {
156 req = JSON.parse(window.webapirequest.value)
158 window.alert('Error parsing request: ' + err.message)
163 window.alert('Empty request')
168 if ({{ .ReturnsBytes }}) {
169 // Just POST to this URL.
174 // Do call ourselves, get response and put it in the response textarea.
175 window.webapifieldset.disabled = true
176 let data = new window.FormData()
177 data.append("request", window.webapirequest.value)
179 const response = await fetch("{{ .Method }}", {body: data, method: "POST"})
180 const text = await response.text()
182 window.webapiresponse.value = JSON.stringify(JSON.parse(text), undefined, '\t')
184 window.webapiresponse.value = text
187 window.alert('Error: ' + err.message)
189 window.webapifieldset.disabled = false
202 mt := reflect.TypeFor[webapi.Methods]()
204 for i := 0; i < n; i++ {
205 methods = append(methods, mt.Method(i).Name)
207 docsIndexTmpl := htmltemplate.Must(htmltemplate.New("index").Parse(`<!doctype html>
210 <meta charset="utf-8" />
211 <meta name="robots" content="noindex,nofollow" />
212 <title>Webapi - Mox</title>
214body, html { padding: 1em; font-size: 16px; }
215* { font-size: inherit; font-family: ubuntu, lato, sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
216h1, h2, h3, h4 { margin-bottom: 1ex; }
217h1 { font-size: 1.2rem; }
218h2 { font-size: 1.1rem; }
219h3, h4 { font-size: 1rem; }
220ul { padding-left: 1rem; }
221p { margin-bottom: 1em; max-width: 50em; }
222[title] { text-decoration: underline; text-decoration-style: dotted; }
223fieldset { border: 0; }
227 <h1>Webapi and webhooks</h1>
228 <p>The mox webapi is a simple HTTP/JSON-based API for sending messages and processing incoming messages.</p>
229 <p>Configure webhooks in mox to receive notifications about outgoing delivery event, and/or incoming deliveries of messages.</p>
230 <p>Documentation and examples:</p>
231 <p><a href="{{ .WebapiDocsURL }}">{{ .WebapiDocsURL }}</a></p>
233 <p>The methods below are available in this version of mox. Follow a link for an example request/response JSON, and a button to make an API call.</p>
235{{ range $i, $method := .Methods }}
236 <li><a href="{{ $method }}">{{ $method }}</a></li>
242 webapiDocsURL := "https://pkg.go.dev/github.com/mjl-/mox@" + moxvar.VersionBare + "/webapi/"
243 webhookDocsURL := "https://pkg.go.dev/github.com/mjl-/mox@" + moxvar.VersionBare + "/webhook/"
244 indexArgs := struct {
246 WebhookDocsURL string
248 }{webapiDocsURL, webhookDocsURL, methods}
250 err := docsIndexTmpl.Execute(&b, indexArgs)
252 panic("executing api docs index template: " + err.Error())
254 docsIndex = b.Bytes()
256 mox.NewWebapiHandler = func(maxMsgSize int64, basePath string, isForwarded bool) http.Handler {
257 return NewServer(maxMsgSize, basePath, isForwarded)
261// NewServer returns a new http.Handler for a webapi server.
262func NewServer(maxMsgSize int64, path string, isForwarded bool) http.Handler {
263 return server{maxMsgSize, path, isForwarded}
266// server implements the webapi methods.
268 maxMsgSize int64 // Of outgoing messages.
269 path string // Path webapi is configured under, typically /webapi/, with methods at /webapi/v0/<method>.
270 isForwarded bool // Whether incoming requests are reverse-proxied. Used for getting remote IPs for rate limiting.
273var _ webapi.Methods = server{}
275// ServeHTTP implements http.Handler.
276func (s server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
277 log := pkglog.WithContext(r.Context()) // Take cid from webserver.
279 // Send requests to /webapi/ to /webapi/v0/.
280 if r.URL.Path == "/" {
281 if r.Method != "GET" {
282 http.Error(w, "405 - method not allow", http.StatusMethodNotAllowed)
285 http.Redirect(w, r, s.path+"v0/", http.StatusSeeOther)
288 // Serve short introduction and list to methods at /webapi/v0/.
289 if r.URL.Path == "/v0/" {
290 w.Header().Set("Content-Type", "text/html; charset=utf-8")
295 // Anything else must be a method endpoint.
296 if !strings.HasPrefix(r.URL.Path, "/v0/") {
300 fn := r.URL.Path[len("/v0/"):]
301 log = log.With(slog.String("method", fn))
302 rfn := reflect.ValueOf(s).MethodByName(fn)
303 var zero reflect.Value
304 if rfn == zero || rfn.Type().NumIn() != 2 || rfn.Type().NumOut() != 2 {
305 log.Debug("unknown webapi method")
310 // GET on method returns an example request JSON, a button to call the method,
311 // which either fills a textarea with the response (in case of JSON) or posts to
312 // the URL letting the browser handle the response (e.g. raw message or part).
313 if r.Method == "GET" {
314 formatJSON := func(v any) (string, error) {
316 enc := json.NewEncoder(&b)
317 enc.SetIndent("", "\t")
318 enc.SetEscapeHTML(false)
320 return string(b.String()), err
323 req, err := formatJSON(mox.FillExample(nil, reflect.New(rfn.Type().In(1))).Interface())
325 log.Errorx("formatting request as json", err)
326 http.Error(w, "500 - internal server error - marshal request: "+err.Error(), http.StatusInternalServerError)
329 // todo: could check for io.ReadCloser, but we don't return other interfaces than that one.
330 returnsBytes := rfn.Type().Out(0).Kind() == reflect.Interface
333 resp, err = formatJSON(mox.FillExample(nil, reflect.New(rfn.Type().Out(0))).Interface())
335 log.Errorx("formatting response as json", err)
336 http.Error(w, "500 - internal server error - marshal response: "+err.Error(), http.StatusInternalServerError)
345 }{fn, req, resp, returnsBytes}
346 w.Header().Set("Content-Type", "text/html; charset=utf-8")
347 err = docsMethodTemplate.Execute(w, args)
348 log.Check(err, "executing webapi method template")
350 } else if r.Method != "POST" {
351 http.Error(w, "405 - method not allowed - use get or post", http.StatusMethodNotAllowed)
355 // Account is available during call, but we close it before we start writing a
356 // response, to prevent slow readers from holding a reference for a long time.
357 var acc *store.Account
358 closeAccount := func() {
361 log.Check(err, "closing account")
367 email, password, aok := r.BasicAuth()
369 metricResults.WithLabelValues(fn, "badauth").Inc()
370 log.Debug("missing http basic authentication credentials")
371 w.Header().Set("WWW-Authenticate", "Basic realm=webapi")
372 http.Error(w, "401 - unauthorized - use http basic auth with email address as username", http.StatusUnauthorized)
375 log = log.With(slog.String("username", email))
379 // If remote IP/network resulted in too many authentication failures, refuse to serve.
380 remoteIP := webauth.RemoteIP(log, s.isForwarded, r)
382 metricResults.WithLabelValues(fn, "internal").Inc()
383 log.Debug("cannot find remote ip for rate limiter")
384 http.Error(w, "500 - internal server error - cannot find remote ip", http.StatusInternalServerError)
387 if !mox.LimiterFailedAuth.CanAdd(remoteIP, t0, 1) {
388 metrics.AuthenticationRatelimitedInc("webapi")
389 log.Debug("refusing connection due to many auth failures", slog.Any("remoteip", remoteIP))
390 http.Error(w, "429 - too many auth attempts", http.StatusTooManyRequests)
394 writeError := func(err webapi.Error) {
396 metricResults.WithLabelValues(fn, err.Code).Inc()
398 if err.Code == "server" {
399 log.Errorx("webapi call result", err, slog.String("resultcode", err.Code))
401 log.Infox("webapi call result", err, slog.String("resultcode", err.Code))
404 w.Header().Set("Content-Type", "application/json; charset=utf-8")
405 w.WriteHeader(http.StatusBadRequest)
406 enc := json.NewEncoder(w)
407 enc.SetEscapeHTML(false)
408 werr := enc.Encode(err)
409 if werr != nil && !moxio.IsClosed(werr) {
410 log.Infox("writing error response", werr)
414 // Called for all successful JSON responses, not non-JSON responses.
415 writeResponse := func(resp any) {
417 metricResults.WithLabelValues(fn, "ok").Inc()
418 log.Debug("webapi call result", slog.String("resultcode", "ok"))
419 w.Header().Set("Content-Type", "application/json; charset=utf-8")
420 enc := json.NewEncoder(w)
421 enc.SetEscapeHTML(false)
422 werr := enc.Encode(resp)
423 if werr != nil && !moxio.IsClosed(werr) {
424 log.Infox("writing error response", werr)
428 la := loginAttempt(r, "webapi", "httpbasic")
429 la.LoginAddress = email
431 store.LoginAttemptAdd(context.Background(), log, la)
432 metricDuration.WithLabelValues(fn).Observe(float64(time.Since(t0)) / float64(time.Second))
436 acc, la.AccountName, err = store.OpenEmailAuth(log, email, password, true)
438 mox.LimiterFailedAuth.Add(remoteIP, t0, 1)
439 if errors.Is(err, mox.ErrDomainNotFound) || errors.Is(err, mox.ErrAddressNotFound) || errors.Is(err, store.ErrUnknownCredentials) || errors.Is(err, store.ErrLoginDisabled) {
440 log.Debug("bad http basic authentication credentials")
441 metricResults.WithLabelValues(fn, "badauth").Inc()
442 la.Result = store.AuthBadCredentials
443 msg := "use http basic auth with email address as username"
444 if errors.Is(err, store.ErrLoginDisabled) {
445 la.Result = store.AuthLoginDisabled
446 msg = "login is disabled for this account"
448 w.Header().Set("WWW-Authenticate", "Basic realm=webapi")
449 http.Error(w, "401 - unauthorized - "+msg, http.StatusUnauthorized)
452 writeError(webapi.Error{Code: "server", Message: "error verifying credentials"})
455 la.AccountName = acc.Name
456 la.Result = store.AuthSuccess
457 mox.LimiterFailedAuth.Reset(remoteIP, t0)
459 ct := r.Header.Get("Content-Type")
460 ct, _, err = mime.ParseMediaType(ct)
462 writeError(webapi.Error{Code: "protocol", Message: "unknown content-type " + r.Header.Get("Content-Type")})
465 if ct == "multipart/form-data" {
466 err = r.ParseMultipartForm(200 * 1024)
471 writeError(webapi.Error{Code: "protocol", Message: "parsing form: " + err.Error()})
475 reqstr := r.PostFormValue("request")
477 writeError(webapi.Error{Code: "protocol", Message: "missing/empty request"})
486 if err, eok := x.(webapi.Error); eok {
490 log.Error("unhandled panic in webapi call", slog.Any("x", x), slog.String("resultcode", "server"))
491 metrics.PanicInc(metrics.Webapi)
493 writeError(webapi.Error{Code: "server", Message: "unhandled error"})
495 req := reflect.New(rfn.Type().In(1))
496 dec := json.NewDecoder(strings.NewReader(reqstr))
497 dec.DisallowUnknownFields()
498 if err := dec.Decode(req.Interface()); err != nil {
499 writeError(webapi.Error{Code: "protocol", Message: fmt.Sprintf("parsing request: %s", err)})
503 reqInfo := requestInfo{log, email, acc, w, r}
504 nctx := context.WithValue(r.Context(), requestInfoCtxKey, reqInfo)
505 resp := rfn.Call([]reflect.Value{reflect.ValueOf(nctx), req.Elem()})
506 if !resp[1].IsZero() {
508 err := resp[1].Interface().(error)
509 if x, eok := err.(webapi.Error); eok {
512 e = webapi.Error{Code: "error", Message: err.Error()}
517 rc, ok := resp[0].Interface().(io.ReadCloser)
519 rv, _ := mox.FillNil(resp[0])
520 writeResponse(rv.Interface())
524 log.Debug("webapi call result", slog.String("resultcode", "ok"))
525 metricResults.WithLabelValues(fn, "ok").Inc()
527 if _, err := io.Copy(w, rc); err != nil && !moxio.IsClosed(err) {
528 log.Errorx("writing response to client", err)
532// loginAttempt initializes a store.LoginAttempt, for adding to the store after
533// filling in the results and other details.
534func loginAttempt(r *http.Request, protocol, authMech string) store.LoginAttempt {
535 remoteIP, _, _ := net.SplitHostPort(r.RemoteAddr)
537 remoteIP = r.RemoteAddr
540 return store.LoginAttempt{
542 TLS: store.LoginAttemptTLS(r.TLS),
545 UserAgent: r.UserAgent(),
546 Result: store.AuthError, // Replaced by caller.
550func xcheckf(err error, format string, args ...any) {
552 msg := fmt.Sprintf(format, args...)
553 panic(webapi.Error{Code: "server", Message: fmt.Sprintf("%s: %s", msg, err)})
557func xcheckuserf(err error, format string, args ...any) {
559 msg := fmt.Sprintf(format, args...)
560 panic(webapi.Error{Code: "user", Message: fmt.Sprintf("%s: %s", msg, err)})
564func xdbwrite(ctx context.Context, acc *store.Account, fn func(tx *bstore.Tx)) {
565 err := acc.DB.Write(ctx, func(tx *bstore.Tx) error {
569 xcheckf(err, "transaction")
572func xdbread(ctx context.Context, acc *store.Account, fn func(tx *bstore.Tx)) {
573 err := acc.DB.Read(ctx, func(tx *bstore.Tx) error {
577 xcheckf(err, "transaction")
580func xcheckcontrol(s string) {
581 for _, c := range s {
583 xcheckuserf(errors.New("control characters not allowed"), "checking header values")
588func xparseAddress(addr string) smtp.Address {
589 a, err := smtp.ParseAddress(addr)
591 panic(webapi.Error{Code: "badAddress", Message: fmt.Sprintf("parsing address %q: %s", addr, err)})
596func xparseAddresses(l []webapi.NameAddress) ([]message.NameAddress, []smtp.Path) {
597 r := make([]message.NameAddress, len(l))
598 paths := make([]smtp.Path, len(l))
599 for i, a := range l {
600 xcheckcontrol(a.Name)
601 addr := xparseAddress(a.Address)
602 r[i] = message.NameAddress{DisplayName: a.Name, Address: addr}
603 paths[i] = addr.Path()
608func xrandomID(n int) string {
609 return base64.RawURLEncoding.EncodeToString(xrandom(n))
612func xrandom(n int) []byte {
613 buf := make([]byte, n)
614 x, err := cryptorand.Read(buf)
618 panic("short random read")
623func (s server) Send(ctx context.Context, req webapi.SendRequest) (resp webapi.SendResult, err error) {
624 // Similar between ../smtpserver/server.go:/submit\( and ../webmail/api.go:/MessageSubmit\( and ../webapisrv/server.go:/Send\(
626 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
628 acc := reqInfo.Account
632 accConf, _ := acc.Conf()
634 if m.Text == "" && m.HTML == "" {
635 return resp, webapi.Error{Code: "missingBody", Message: "at least text or html body required"}
638 if len(m.From) == 0 {
639 m.From = []webapi.NameAddress{{Name: accConf.FullName, Address: reqInfo.LoginAddress}}
640 } else if len(m.From) > 1 {
641 return resp, webapi.Error{Code: "multipleFrom", Message: "multiple from-addresses not allowed"}
643 froms, fromPaths := xparseAddresses(m.From)
644 from, fromPath := froms[0], fromPaths[0]
645 to, toPaths := xparseAddresses(m.To)
646 cc, ccPaths := xparseAddresses(m.CC)
647 bcc, bccPaths := xparseAddresses(m.BCC)
649 recipients := append(append(toPaths, ccPaths...), bccPaths...)
650 addresses := append(append(m.To, m.CC...), m.BCC...)
652 // Check if from address is allowed for account.
653 if ok, disabled := mox.AllowMsgFrom(acc.Name, from.Address); disabled {
654 metricSubmission.WithLabelValues("domaindisabled").Inc()
655 return resp, webapi.Error{Code: "domainDisabled", Message: "domain of from-address is temporarily disabled"}
657 metricSubmission.WithLabelValues("badfrom").Inc()
658 return resp, webapi.Error{Code: "badFrom", Message: "from-address not configured for account"}
661 if len(recipients) == 0 {
662 return resp, webapi.Error{Code: "noRecipients", Message: "no recipients"}
665 // Check outgoing message rate limit.
666 xdbread(ctx, acc, func(tx *bstore.Tx) {
667 msglimit, rcptlimit, err := acc.SendLimitReached(tx, recipients)
669 metricSubmission.WithLabelValues("messagelimiterror").Inc()
670 panic(webapi.Error{Code: "messageLimitReached", Message: "outgoing message rate limit reached"})
671 } else if rcptlimit >= 0 {
672 metricSubmission.WithLabelValues("recipientlimiterror").Inc()
673 panic(webapi.Error{Code: "recipientLimitReached", Message: "outgoing new recipient rate limit reached"})
675 xcheckf(err, "checking send limit")
678 // If we have a non-ascii localpart, we will be sending with smtputf8. We'll go
680 intl := func(l []smtp.Path) bool {
681 for _, p := range l {
682 if p.Localpart.IsInternational() {
688 smtputf8 := intl([]smtp.Path{fromPath}) || intl(toPaths) || intl(ccPaths) || intl(bccPaths)
690 replyTos, replyToPaths := xparseAddresses(m.ReplyTo)
691 for _, rt := range replyToPaths {
692 if rt.Localpart.IsInternational() {
697 // Create file to compose message into.
698 dataFile, err := store.CreateMessageTemp(log, "webapi-submit")
699 xcheckf(err, "creating temporary file for message")
700 defer store.CloseRemoveTempFile(log, dataFile, "message to submit")
702 // If writing to the message file fails, we abort immediately.
703 xc := message.NewComposer(dataFile, s.maxMsgSize, smtputf8)
709 if err, ok := x.(error); ok && errors.Is(err, message.ErrMessageSize) {
710 panic(webapi.Error{Code: "messageTooLarge", Message: "message too large"})
711 } else if ok && errors.Is(err, message.ErrCompose) {
712 xcheckf(err, "making message")
717 // Each queued message gets a Received header.
718 // We cannot use VIA, because there is no registered method. We would like to use
719 // it to add the ascii domain name in case of smtputf8 and IDNA host name.
720 // We don't add the IP address of the submitter. Exposing likely not desirable.
721 recvFrom := message.HeaderCommentDomain(mox.Conf.Static.HostnameDomain, smtputf8)
722 recvBy := mox.Conf.Static.HostnameDomain.XName(smtputf8)
723 recvID := mox.ReceivedID(mox.CidFromCtx(ctx))
724 recvHdrFor := func(rcptTo string) string {
725 recvHdr := &message.HeaderWriter{}
726 // For additional Received-header clauses, see:
727 // https://www.iana.org/assignments/mail-parameters/mail-parameters.xhtml#table-mail-parameters-8
728 // Note: we don't have "via" or "with", there is no registered for webmail.
729 recvHdr.Add(" ", "Received:", "from", recvFrom, "by", recvBy, "id", recvID) //
../rfc/5321:3158
730 if reqInfo.Request.TLS != nil {
731 recvHdr.Add(" ", mox.TLSReceivedComment(log, *reqInfo.Request.TLS)...)
733 recvHdr.Add(" ", "for", "<"+rcptTo+">;", time.Now().Format(message.RFC5322Z))
734 return recvHdr.String()
737 // Outer message headers.
738 xc.HeaderAddrs("From", []message.NameAddress{from})
739 if len(replyTos) > 0 {
740 xc.HeaderAddrs("Reply-To", replyTos)
742 xc.HeaderAddrs("To", to)
743 xc.HeaderAddrs("Cc", cc)
744 // We prepend Bcc headers to the message when adding to the Sent mailbox.
746 xcheckcontrol(m.Subject)
747 xc.Subject(m.Subject)
756 xc.Header("Date", date.Format(message.RFC5322Z))
758 if m.MessageID == "" {
759 m.MessageID = fmt.Sprintf("<%s>", mox.MessageIDGen(smtputf8))
760 } else if !strings.HasPrefix(m.MessageID, "<") || !strings.HasSuffix(m.MessageID, ">") {
761 return resp, webapi.Error{Code: "malformedMessageID", Message: "missing <> in message-id"}
763 xcheckcontrol(m.MessageID)
764 xc.Header("Message-Id", m.MessageID)
766 if len(m.References) > 0 {
767 for _, ref := range m.References {
769 // We don't check for <>'s. If caller just puts in what they got, we don't want to
770 // reject the message.
772 xc.Header("References", strings.Join(m.References, "\r\n\t"))
773 xc.Header("In-Reply-To", m.References[len(m.References)-1])
775 xc.Header("MIME-Version", "1.0")
777 var haveUserAgent bool
778 for _, kv := range req.Headers {
781 xc.Header(kv[0], kv[1])
782 if strings.EqualFold(kv[0], "User-Agent") || strings.EqualFold(kv[0], "X-Mailer") {
787 xc.Header("User-Agent", "mox/"+moxvar.Version)
790 // Whether we have additional separately alternative/inline/attached file(s).
791 mpf := reqInfo.Request.MultipartForm
792 formAlternative := mpf != nil && len(mpf.File["alternativefile"]) > 0
793 formInline := mpf != nil && len(mpf.File["inlinefile"]) > 0
794 formAttachment := mpf != nil && len(mpf.File["attachedfile"]) > 0
796 // MIME structure we'll build:
797 // - multipart/mixed (in case of attached files)
798 // - multipart/related (in case of inline files, we assume they are relevant both text and html part if present)
799 // - multipart/alternative (in case we have both text and html bodies)
800 // - text/plain (optional)
801 // - text/html (optional)
802 // - alternative file, ...
803 // - inline file, ...
804 // - attached file, ...
806 // We keep track of cur, which is where we add new parts to, whether the text or
807 // html part, or the inline or attached files.
808 var cur, mixed, related, alternative *multipart.Writer
809 xcreateMultipart := func(subtype string) *multipart.Writer {
810 mp := multipart.NewWriter(xc)
812 xc.Header("Content-Type", fmt.Sprintf(`multipart/%s; boundary="%s"`, subtype, mp.Boundary()))
815 _, err := cur.CreatePart(textproto.MIMEHeader{"Content-Type": []string{fmt.Sprintf(`multipart/%s; boundary="%s"`, subtype, mp.Boundary())}})
816 xcheckf(err, "adding multipart")
820 xcreatePart := func(header textproto.MIMEHeader) io.Writer {
822 for k, vl := range header {
823 for _, v := range vl {
830 p, err := cur.CreatePart(header)
831 xcheckf(err, "adding part")
834 // We create multiparts from outer structure to inner. Then for each we add its
835 // inner parts and close the multipart.
836 if len(req.AttachedFiles) > 0 || formAttachment {
837 mixed = xcreateMultipart("mixed")
840 if len(req.InlineFiles) > 0 || formInline {
841 related = xcreateMultipart("related")
844 if m.Text != "" && m.HTML != "" || len(req.AlternativeFiles) > 0 || formAlternative {
845 alternative = xcreateMultipart("alternative")
849 textBody, ct, cte := xc.TextPart("plain", m.Text)
850 tp := xcreatePart(textproto.MIMEHeader{"Content-Type": []string{ct}, "Content-Transfer-Encoding": []string{cte}})
851 _, err := tp.Write([]byte(textBody))
852 xcheckf(err, "write text part")
855 htmlBody, ct, cte := xc.TextPart("html", m.HTML)
856 tp := xcreatePart(textproto.MIMEHeader{"Content-Type": []string{ct}, "Content-Transfer-Encoding": []string{cte}})
857 _, err := tp.Write([]byte(htmlBody))
858 xcheckf(err, "write html part")
861 xaddFileBase64 := func(ct string, inline bool, filename string, cid string, base64Data string) {
862 h := textproto.MIMEHeader{}
867 cd := mime.FormatMediaType(disp, map[string]string{"filename": filename})
869 h.Set("Content-Type", ct)
870 h.Set("Content-Disposition", cd)
872 h.Set("Content-ID", cid)
874 h.Set("Content-Transfer-Encoding", "base64")
877 for len(base64Data) > 0 {
883 line, base64Data = base64Data[:n], base64Data[n:]
884 _, err := p.Write([]byte(line))
885 xcheckf(err, "writing attachment")
886 _, err = p.Write([]byte("\r\n"))
887 xcheckf(err, "writing attachment")
890 xaddJSONFiles := func(l []webapi.File, inline bool) {
891 for _, f := range l {
892 if f.ContentType == "" {
893 buf, _ := io.ReadAll(io.LimitReader(base64.NewDecoder(base64.StdEncoding, strings.NewReader(f.Data)), 512))
894 f.ContentType = http.DetectContentType(buf)
895 if f.ContentType == "application/octet-stream" {
900 // Ensure base64 is valid, then we'll write the original string.
901 _, err := io.Copy(io.Discard, base64.NewDecoder(base64.StdEncoding, strings.NewReader(f.Data)))
902 xcheckuserf(err, "parsing attachment as base64")
904 xaddFileBase64(f.ContentType, inline, f.Name, f.ContentID, f.Data)
907 xaddFile := func(fh *multipart.FileHeader, inline bool) {
909 xcheckf(err, "open uploaded file")
912 log.Check(err, "closing uploaded file")
915 ct := fh.Header.Get("Content-Type")
917 buf, err := io.ReadAll(io.LimitReader(f, 512))
919 ct = http.DetectContentType(buf)
921 _, err = f.Seek(0, 0)
922 xcheckf(err, "rewind uploaded file after content-detection")
923 if ct == "application/octet-stream" {
928 h := textproto.MIMEHeader{}
933 cd := mime.FormatMediaType(disp, map[string]string{"filename": fh.Filename})
936 h.Set("Content-Type", ct)
938 h.Set("Content-Disposition", cd)
939 cid := fh.Header.Get("Content-ID")
941 h.Set("Content-ID", cid)
943 h.Set("Content-Transfer-Encoding", "base64")
945 bw := moxio.Base64Writer(p)
946 _, err = io.Copy(bw, f)
947 xcheckf(err, "adding uploaded file")
949 xcheckf(err, "flushing uploaded file")
953 xaddJSONFiles(req.AlternativeFiles, true)
955 for _, fh := range mpf.File["alternativefile"] {
959 if alternative != nil {
965 xaddJSONFiles(req.InlineFiles, true)
967 for _, fh := range mpf.File["inlinefile"] {
976 xaddJSONFiles(req.AttachedFiles, false)
978 for _, fh := range mpf.File["attachedfile"] {
989 // Add DKIM-Signature headers.
991 fd := from.Address.Domain
992 confDom, _ := mox.Conf.Domain(fd)
993 if confDom.Disabled {
994 xcheckuserf(mox.ErrDomainDisabled, "checking domain")
996 selectors := mox.DKIMSelectors(confDom.DKIM)
997 if len(selectors) > 0 {
998 dkimHeaders, err := dkim.Sign(ctx, log.Logger, from.Address.Localpart, fd, selectors, smtputf8, dataFile)
1000 metricServerErrors.WithLabelValues("dkimsign").Inc()
1002 xcheckf(err, "sign dkim")
1004 msgPrefix = dkimHeaders
1007 loginAddr, err := smtp.ParseAddress(reqInfo.LoginAddress)
1008 xcheckf(err, "parsing login address")
1009 useFromID := slices.Contains(accConf.ParsedFromIDLoginAddresses, loginAddr)
1010 var localpartBase string
1012 if confDom.LocalpartCatchallSeparator == "" {
1013 xcheckuserf(errors.New(`localpart catchall separator must be configured for domain`), `composing unique "from" address`)
1015 localpartBase = strings.SplitN(string(fromPath.Localpart), confDom.LocalpartCatchallSeparator, 2)[0]
1017 fromIDs := make([]string, len(recipients))
1018 qml := make([]queue.Msg, len(recipients))
1020 for i, rcpt := range recipients {
1023 fromIDs[i] = xrandomID(16)
1024 fp.Localpart = smtp.Localpart(localpartBase + confDom.LocalpartCatchallSeparator + fromIDs[i])
1027 // Don't use per-recipient unique message prefix when multiple recipients are
1028 // present, we want to keep the message identical.
1030 if len(recipients) == 1 {
1031 recvRcpt = rcpt.XString(smtputf8)
1033 rcptMsgPrefix := recvHdrFor(recvRcpt) + msgPrefix
1034 msgSize := int64(len(rcptMsgPrefix)) + xc.Size
1035 qm := queue.MakeMsg(fp, rcpt, xc.Has8bit, xc.SMTPUTF8, msgSize, m.MessageID, []byte(rcptMsgPrefix), req.RequireTLS, now, m.Subject)
1036 qm.FromID = fromIDs[i]
1037 qm.Extra = req.Extra
1038 if req.FutureRelease != nil {
1039 ival := time.Until(*req.FutureRelease)
1040 if ival > queue.FutureReleaseIntervalMax {
1041 xcheckuserf(fmt.Errorf("date/time can not be further than %v in the future", queue.FutureReleaseIntervalMax), "scheduling delivery")
1043 qm.NextAttempt = *req.FutureRelease
1044 qm.FutureReleaseRequest = "until;" + req.FutureRelease.Format(time.RFC3339)
1045 // todo: possibly add a header to the message stored in the Sent mailbox to indicate it was scheduled for later delivery.
1049 err = queue.Add(ctx, log, acc.Name, dataFile, qml...)
1051 metricSubmission.WithLabelValues("queueerror").Inc()
1053 xcheckf(err, "adding messages to the delivery queue")
1054 metricSubmission.WithLabelValues("ok").Inc()
1057 // Append message to Sent mailbox and mark original messages as answered/forwarded.
1058 acc.WithRLock(func() {
1059 var changes []store.Change
1063 if x := recover(); x != nil {
1065 metricServerErrors.WithLabelValues("submit").Inc()
1070 xdbwrite(ctx, reqInfo.Account, func(tx *bstore.Tx) {
1071 sentmb, err := bstore.QueryTx[store.Mailbox](tx).FilterEqual("Sent", true).Get()
1072 if err == bstore.ErrAbsent {
1073 // There is no mailbox designated as Sent mailbox, so we're done.
1076 xcheckf(err, "message submitted to queue, adding to Sent mailbox")
1078 modseq, err := acc.NextModSeq(tx)
1079 xcheckf(err, "next modseq")
1081 // If there were bcc headers, prepend those to the stored message only, before the
1082 // DKIM signature. The DKIM-signature oversigns the bcc header, so this stored message
1083 // won't validate with DKIM anymore, which is fine.
1085 var sb strings.Builder
1086 xbcc := message.NewComposer(&sb, 100*1024, smtputf8)
1087 xbcc.HeaderAddrs("Bcc", bcc)
1089 msgPrefix = sb.String() + msgPrefix
1092 sentm := store.Message{
1095 MailboxID: sentmb.ID,
1096 MailboxOrigID: sentmb.ID,
1097 Flags: store.Flags{Notjunk: true, Seen: true},
1098 Size: int64(len(msgPrefix)) + xc.Size,
1099 MsgPrefix: []byte(msgPrefix),
1102 if ok, maxSize, err := acc.CanAddMessageSize(tx, sentm.Size); err != nil {
1103 xcheckf(err, "checking quota")
1105 panic(webapi.Error{Code: "sentOverQuota", Message: fmt.Sprintf("message was sent, but not stored in sent mailbox due to quota of total %d bytes reached", maxSize)})
1108 // Update mailbox before delivery, which changes uidnext.
1109 sentmb.Add(sentm.MailboxCounts())
1110 err = tx.Update(&sentmb)
1111 xcheckf(err, "updating sent mailbox for counts")
1113 err = acc.DeliverMessage(log, tx, &sentm, dataFile, true, false, false, true)
1115 metricSubmission.WithLabelValues("storesenterror").Inc()
1118 xcheckf(err, "message submitted to queue, appending message to Sent mailbox")
1120 changes = append(changes, sentm.ChangeAddUID(), sentmb.ChangeCounts())
1123 store.BroadcastChanges(acc, changes)
1127 submissions := make([]webapi.Submission, len(qml))
1128 for i, qm := range qml {
1129 submissions[i] = webapi.Submission{
1130 Address: addresses[i].Address,
1135 resp = webapi.SendResult{
1136 MessageID: m.MessageID,
1137 Submissions: submissions,
1142func (s server) SuppressionList(ctx context.Context, req webapi.SuppressionListRequest) (resp webapi.SuppressionListResult, err error) {
1143 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1144 resp.Suppressions, err = queue.SuppressionList(ctx, reqInfo.Account.Name)
1148func (s server) SuppressionAdd(ctx context.Context, req webapi.SuppressionAddRequest) (resp webapi.SuppressionAddResult, err error) {
1149 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1150 addr := xparseAddress(req.EmailAddress)
1151 sup := webapi.Suppression{
1152 Account: reqInfo.Account.Name,
1156 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
1160func (s server) SuppressionRemove(ctx context.Context, req webapi.SuppressionRemoveRequest) (resp webapi.SuppressionRemoveResult, err error) {
1161 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1162 addr := xparseAddress(req.EmailAddress)
1163 err = queue.SuppressionRemove(ctx, reqInfo.Account.Name, addr.Path())
1167func (s server) SuppressionPresent(ctx context.Context, req webapi.SuppressionPresentRequest) (resp webapi.SuppressionPresentResult, err error) {
1168 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1169 addr := xparseAddress(req.EmailAddress)
1170 xcheckuserf(err, "parsing address %q", req.EmailAddress)
1171 sup, err := queue.SuppressionLookup(ctx, reqInfo.Account.Name, addr.Path())
1178func xwebapiAddresses(l []message.Address) (r []webapi.NameAddress) {
1179 r = make([]webapi.NameAddress, len(l))
1180 for i, ma := range l {
1181 dom, err := dns.ParseDomain(ma.Host)
1182 xcheckf(err, "parsing host %q for address", ma.Host)
1183 lp, err := smtp.ParseLocalpart(ma.User)
1184 xcheckf(err, "parsing localpart %q for address", ma.User)
1185 path := smtp.Path{Localpart: lp, IPDomain: dns.IPDomain{Domain: dom}}
1186 r[i] = webapi.NameAddress{Name: ma.Name, Address: path.XString(true)}
1191// caller should hold account lock.
1192func xmessageGet(ctx context.Context, acc *store.Account, msgID int64) (store.Message, store.Mailbox) {
1193 m := store.Message{ID: msgID}
1194 var mb store.Mailbox
1195 err := acc.DB.Read(ctx, func(tx *bstore.Tx) error {
1196 if err := tx.Get(&m); err == bstore.ErrAbsent || err == nil && m.Expunged {
1197 panic(webapi.Error{Code: "messageNotFound", Message: "message not found"})
1199 mb = store.Mailbox{ID: m.MailboxID}
1202 xcheckf(err, "get message")
1206func (s server) MessageGet(ctx context.Context, req webapi.MessageGetRequest) (resp webapi.MessageGetResult, err error) {
1207 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1209 acc := reqInfo.Account
1212 var mb store.Mailbox
1213 var msgr *store.MsgReader
1214 acc.WithRLock(func() {
1215 m, mb = xmessageGet(ctx, acc, req.MsgID)
1216 msgr = acc.MessageReader(m)
1224 p, err := m.LoadPart(msgr)
1225 xcheckf(err, "load parsed message")
1227 var env message.Envelope
1228 if p.Envelope != nil {
1231 text, html, _, err := webops.ReadableParts(p, 1*1024*1024)
1233 log.Debugx("looking for text and html content in message", err)
1240 // Parse References message header.
1241 h, err := p.Header()
1243 log.Debugx("parsing headers for References", err)
1246 for _, s := range h.Values("References") {
1247 s = strings.ReplaceAll(s, "\t", " ")
1248 for _, w := range strings.Split(s, " ") {
1250 refs = append(refs, w)
1254 if env.InReplyTo != "" && !slices.Contains(refs, env.InReplyTo) {
1255 // References are ordered, most recent first. In-Reply-To is less powerful/older.
1256 // So if both are present, give References preference, prepending the In-Reply-To
1258 refs = append([]string{env.InReplyTo}, refs...)
1261 msg := webapi.Message{
1262 From: xwebapiAddresses(env.From),
1263 To: xwebapiAddresses(env.To),
1264 CC: xwebapiAddresses(env.CC),
1265 BCC: xwebapiAddresses(env.BCC),
1266 ReplyTo: xwebapiAddresses(env.ReplyTo),
1267 MessageID: env.MessageID,
1270 Subject: env.Subject,
1271 Text: strings.ReplaceAll(text, "\r\n", "\n"),
1272 HTML: strings.ReplaceAll(html, "\r\n", "\n"),
1276 if d, err := dns.ParseDomain(m.MsgFromDomain); err == nil {
1277 msgFrom = smtp.NewAddress(m.MsgFromLocalpart, d).Pack(true)
1280 if m.RcptToDomain != "" {
1281 rcptTo = m.RcptToLocalpart.String() + "@" + m.RcptToDomain
1283 meta := webapi.MessageMeta{
1286 Flags: append(m.Flags.Strings(), m.Keywords...),
1287 MailFrom: m.MailFrom,
1288 MailFromValidated: m.MailFromValidated,
1291 MsgFromValidated: m.MsgFromValidated,
1292 DKIMVerifiedDomains: m.DKIMDomains,
1293 RemoteIP: m.RemoteIP,
1294 MailboxName: mb.Name,
1297 structure, err := queue.PartStructure(log, &p)
1298 xcheckf(err, "parsing structure")
1300 result := webapi.MessageGetResult{
1302 Structure: structure,
1308func (s server) MessageRawGet(ctx context.Context, req webapi.MessageRawGetRequest) (resp io.ReadCloser, err error) {
1309 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1310 acc := reqInfo.Account
1313 var msgr *store.MsgReader
1314 acc.WithRLock(func() {
1315 m, _ = xmessageGet(ctx, acc, req.MsgID)
1316 msgr = acc.MessageReader(m)
1319 reqInfo.Response.Header().Set("Content-Type", "text/plain")
1323func (s server) MessagePartGet(ctx context.Context, req webapi.MessagePartGetRequest) (resp io.ReadCloser, err error) {
1324 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1325 acc := reqInfo.Account
1328 var msgr *store.MsgReader
1329 acc.WithRLock(func() {
1330 m, _ = xmessageGet(ctx, acc, req.MsgID)
1331 msgr = acc.MessageReader(m)
1339 p, err := m.LoadPart(msgr)
1340 xcheckf(err, "load parsed message")
1342 for i, index := range req.PartPath {
1343 if index < 0 || index >= len(p.Parts) {
1344 return nil, webapi.Error{Code: "partNotFound", Message: fmt.Sprintf("part %d at index %d not found", index, i)}
1351 }{Reader: p.Reader(), Closer: msgr}, nil
1354var xops = webops.XOps{
1356 Checkf: func(ctx context.Context, err error, format string, args ...any) {
1357 xcheckf(err, format, args...)
1359 Checkuserf: func(ctx context.Context, err error, format string, args ...any) {
1360 if err != nil && errors.Is(err, webops.ErrMessageNotFound) {
1361 msg := fmt.Sprintf("%s: %s", fmt.Sprintf(format, args...), err)
1362 panic(webapi.Error{Code: "messageNotFound", Message: msg})
1364 xcheckuserf(err, format, args...)
1368func (s server) MessageDelete(ctx context.Context, req webapi.MessageDeleteRequest) (resp webapi.MessageDeleteResult, err error) {
1369 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1370 xops.MessageDelete(ctx, reqInfo.Log, reqInfo.Account, []int64{req.MsgID})
1374func (s server) MessageFlagsAdd(ctx context.Context, req webapi.MessageFlagsAddRequest) (resp webapi.MessageFlagsAddResult, err error) {
1375 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1376 xops.MessageFlagsAdd(ctx, reqInfo.Log, reqInfo.Account, []int64{req.MsgID}, req.Flags)
1380func (s server) MessageFlagsRemove(ctx context.Context, req webapi.MessageFlagsRemoveRequest) (resp webapi.MessageFlagsRemoveResult, err error) {
1381 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1382 xops.MessageFlagsClear(ctx, reqInfo.Log, reqInfo.Account, []int64{req.MsgID}, req.Flags)
1386func (s server) MessageMove(ctx context.Context, req webapi.MessageMoveRequest) (resp webapi.MessageMoveResult, err error) {
1387 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
1388 xops.MessageMove(ctx, reqInfo.Log, reqInfo.Account, []int64{req.MsgID}, req.DestMailboxName, 0)