compose.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. package email
  2. /*
  3. compose.go
  4. Building outgoing messages.
  5. Structure produced (parts only appear when needed):
  6. multipart/mixed
  7. ├─ multipart/alternative
  8. │ ├─ text/plain (generated from the HTML when not given)
  9. │ └─ multipart/related
  10. │ ├─ text/html
  11. │ └─ image/* (Content-ID) (pasted images, data: URIs in the editor)
  12. └─ attachments
  13. Text parts are quoted-printable UTF-8 and attachments base64, so the
  14. message is 7-bit clean and survives any relay.
  15. */
  16. import (
  17. "bytes"
  18. "context"
  19. "encoding/base64"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "mime"
  24. "net/mail"
  25. "path/filepath"
  26. "regexp"
  27. "strings"
  28. "time"
  29. gomessage "github.com/emersion/go-message"
  30. gomail "github.com/emersion/go-message/mail"
  31. )
  32. // ComposeAttachment is a file attached by the user. The AGI layer resolves
  33. // ArozOS paths and supplies Open; Data is used by tests and small payloads.
  34. type ComposeAttachment struct {
  35. Name string
  36. ContentType string
  37. Size int64
  38. Open func() (io.ReadCloser, error)
  39. Data []byte
  40. }
  41. // ForwardedPart re-attaches an attachment of an existing message (forward,
  42. // or reopening a draft) straight from the server.
  43. type ForwardedPart struct {
  44. AccountID string `json:"accountId"`
  45. Folder string `json:"folder"`
  46. UID uint32 `json:"uid"`
  47. PartID string `json:"partId"`
  48. }
  49. // ComposeRequest is a message from the composer.
  50. type ComposeRequest struct {
  51. AccountID string `json:"accountId"`
  52. FromName string `json:"fromName"`
  53. To []string `json:"to"`
  54. Cc []string `json:"cc"`
  55. Bcc []string `json:"bcc"`
  56. ReplyTo string `json:"replyTo"`
  57. Subject string `json:"subject"`
  58. HTML string `json:"html"`
  59. Text string `json:"text"`
  60. PlainOnly bool `json:"plainOnly"`
  61. Priority string `json:"priority"` //high | normal | low
  62. ReadReceipt bool `json:"readReceipt"`
  63. InReplyTo string `json:"inReplyTo"`
  64. References []string `json:"references"`
  65. ReplyMode string `json:"replyMode"` //reply | forward
  66. OriginalFolder string `json:"originalFolder"`
  67. OriginalUID uint32 `json:"originalUid"`
  68. DraftFolder string `json:"draftFolder"`
  69. DraftUID uint32 `json:"draftUid"`
  70. Forwarded []ForwardedPart `json:"forwarded"`
  71. SendAt int64 `json:"sendAt"` //Unix ms, 0 sends now
  72. UndoSeconds int `json:"undoSeconds"` //Delay that allows "Undo"
  73. Attachments []ComposeAttachment `json:"-"`
  74. }
  75. // builtMessage is a rendered message ready for SMTP or APPEND.
  76. type builtMessage struct {
  77. raw []byte
  78. messageID string
  79. from string
  80. recipients []string
  81. bccHeader string //"Bcc: ..." line added to the Sent copy only
  82. date time.Time
  83. }
  84. var dataImagePattern = regexp.MustCompile(`(?i)(<img\b[^>]*?\bsrc\s*=\s*["'])data:(image/[a-z0-9.+-]+);base64,([a-z0-9+/=\s]+)(["'])`)
  85. // parseRecipients validates a recipient list, accepting "Name <a@b>",
  86. // bare addresses and comma / semicolon separated strings.
  87. func parseRecipients(values []string) ([]*mail.Address, error) {
  88. results := []*mail.Address{}
  89. seen := map[string]bool{}
  90. for _, value := range values {
  91. for _, piece := range splitAddressList(value) {
  92. piece = strings.TrimSpace(piece)
  93. if piece == "" {
  94. continue
  95. }
  96. address, err := mail.ParseAddress(piece)
  97. if err != nil {
  98. return nil, fmt.Errorf("%q is not a valid email address", piece)
  99. }
  100. key := strings.ToLower(address.Address)
  101. if seen[key] {
  102. continue
  103. }
  104. seen[key] = true
  105. results = append(results, address)
  106. }
  107. }
  108. return results, nil
  109. }
  110. // splitAddressList splits on commas and semicolons outside quotes / brackets.
  111. func splitAddressList(value string) []string {
  112. parts := []string{}
  113. var current strings.Builder
  114. inQuotes, inAngle := false, false
  115. for _, r := range value {
  116. switch {
  117. case r == '"':
  118. inQuotes = !inQuotes
  119. case r == '<' && !inQuotes:
  120. inAngle = true
  121. case r == '>' && !inQuotes:
  122. inAngle = false
  123. case (r == ',' || r == ';') && !inQuotes && !inAngle:
  124. parts = append(parts, current.String())
  125. current.Reset()
  126. continue
  127. }
  128. current.WriteRune(r)
  129. }
  130. parts = append(parts, current.String())
  131. return parts
  132. }
  133. // buildMessage renders a compose request. forDraft keeps Bcc in the headers
  134. // and allows an empty recipient list.
  135. func (m *Manager) buildMessage(ctx context.Context, p Principal, account *Account, request *ComposeRequest, forDraft bool) (*builtMessage, error) {
  136. to, err := parseRecipients(request.To)
  137. if err != nil {
  138. return nil, err
  139. }
  140. cc, err := parseRecipients(request.Cc)
  141. if err != nil {
  142. return nil, err
  143. }
  144. bcc, err := parseRecipients(request.Bcc)
  145. if err != nil {
  146. return nil, err
  147. }
  148. if !forDraft && len(to)+len(cc)+len(bcc) == 0 {
  149. return nil, errors.New("add at least one recipient")
  150. }
  151. if len(to)+len(cc)+len(bcc) > 500 {
  152. return nil, errors.New("too many recipients")
  153. }
  154. now := m.now()
  155. header := gomail.Header{}
  156. header.SetDate(now)
  157. fromName := strings.TrimSpace(request.FromName)
  158. if fromName == "" {
  159. fromName = account.DisplayName
  160. }
  161. from := &mail.Address{Name: fromName, Address: account.Email}
  162. header.SetAddressList("From", []*mail.Address{from})
  163. if len(to) > 0 {
  164. header.SetAddressList("To", to)
  165. }
  166. if len(cc) > 0 {
  167. header.SetAddressList("Cc", cc)
  168. }
  169. if forDraft && len(bcc) > 0 {
  170. header.SetAddressList("Bcc", bcc)
  171. }
  172. replyTo := strings.TrimSpace(request.ReplyTo)
  173. if replyTo == "" {
  174. replyTo = account.ReplyTo
  175. }
  176. if replyTo != "" {
  177. if parsed, err := mail.ParseAddress(replyTo); err == nil {
  178. header.SetAddressList("Reply-To", []*mail.Address{parsed})
  179. }
  180. }
  181. header.SetSubject(strings.TrimSpace(request.Subject))
  182. hostname := domainOf(account.Email)
  183. if hostname == "" {
  184. hostname = m.options.Hostname
  185. }
  186. if hostname == "" {
  187. hostname = "arozos.local"
  188. }
  189. if err := header.GenerateMessageIDWithHostname(hostname); err != nil {
  190. return nil, err
  191. }
  192. messageID, _ := header.MessageID()
  193. if id := strings.Trim(strings.TrimSpace(request.InReplyTo), "<>"); id != "" {
  194. header.SetMsgIDList("In-Reply-To", []string{id})
  195. references := []string{}
  196. for _, ref := range request.References {
  197. if ref = strings.Trim(strings.TrimSpace(ref), "<>"); ref != "" {
  198. references = append(references, ref)
  199. }
  200. }
  201. //Keep the chain bounded but always end with the message replied to
  202. if len(references) > 20 {
  203. references = append(references[:1], references[len(references)-19:]...)
  204. }
  205. if len(references) == 0 || references[len(references)-1] != id {
  206. references = append(references, id)
  207. }
  208. header.SetMsgIDList("References", references)
  209. }
  210. switch strings.ToLower(request.Priority) {
  211. case "high":
  212. header.Set("X-Priority", "1 (Highest)")
  213. header.Set("Importance", "High")
  214. case "low":
  215. header.Set("X-Priority", "5 (Lowest)")
  216. header.Set("Importance", "Low")
  217. }
  218. if request.ReadReceipt {
  219. header.SetAddressList("Disposition-Notification-To", []*mail.Address{from})
  220. }
  221. header.Set("User-Agent", "ArozOS Mail")
  222. header.Set("MIME-Version", "1.0")
  223. attachments, err := m.collectAttachments(ctx, p, request)
  224. if err != nil {
  225. return nil, err
  226. }
  227. var buffer bytes.Buffer
  228. if err := writeMessageBody(&buffer, header, request, attachments); err != nil {
  229. return nil, err
  230. }
  231. recipients := []string{}
  232. for _, list := range [][]*mail.Address{to, cc, bcc} {
  233. for _, address := range list {
  234. recipients = append(recipients, address.Address)
  235. }
  236. }
  237. built := &builtMessage{
  238. raw: buffer.Bytes(),
  239. messageID: messageID,
  240. from: account.Email,
  241. recipients: recipients,
  242. date: now,
  243. }
  244. if !forDraft && len(bcc) > 0 {
  245. bccHeader := gomail.Header{}
  246. bccHeader.SetAddressList("Bcc", bcc)
  247. var line bytes.Buffer
  248. for fields := bccHeader.Fields(); fields.Next(); {
  249. raw, err := fields.Raw()
  250. if err == nil {
  251. line.Write(raw)
  252. }
  253. }
  254. built.bccHeader = line.String()
  255. }
  256. return built, nil
  257. }
  258. type attachmentPayload struct {
  259. name string
  260. contentType string
  261. open func() (io.ReadCloser, error)
  262. }
  263. // collectAttachments gathers user files and forwarded server parts and
  264. // enforces the administrator's size budget.
  265. func (m *Manager) collectAttachments(ctx context.Context, p Principal, request *ComposeRequest) ([]attachmentPayload, error) {
  266. limit := m.maxAttachmentBytes()
  267. var total int64
  268. payloads := []attachmentPayload{}
  269. for _, attachment := range request.Attachments {
  270. attachment := attachment
  271. total += attachment.Size
  272. if attachment.Data != nil && attachment.Size == 0 {
  273. total += int64(len(attachment.Data))
  274. }
  275. contentType := attachment.ContentType
  276. if contentType == "" {
  277. contentType = contentTypeFor(attachment.Name)
  278. }
  279. open := attachment.Open
  280. if open == nil {
  281. data := attachment.Data
  282. open = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil }
  283. }
  284. payloads = append(payloads, attachmentPayload{name: sanitizeFilename(attachment.Name), contentType: contentType, open: open})
  285. }
  286. for _, forwarded := range request.Forwarded {
  287. accountID := forwarded.AccountID
  288. if accountID == "" {
  289. accountID = request.AccountID
  290. }
  291. if forwarded.PartID == "" {
  292. //"Forward as attachment": the whole original message
  293. raw, err := m.GetRaw(ctx, p, accountID, forwarded.Folder, forwarded.UID)
  294. if err != nil {
  295. return nil, fmt.Errorf("could not attach the original message: %w", err)
  296. }
  297. total += int64(len(raw.Data))
  298. data := raw.Data
  299. payloads = append(payloads, attachmentPayload{
  300. name: raw.Filename,
  301. contentType: "message/rfc822",
  302. open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil },
  303. })
  304. continue
  305. }
  306. part, err := m.GetPart(ctx, p, accountID, forwarded.Folder, forwarded.UID, forwarded.PartID)
  307. if err != nil {
  308. return nil, fmt.Errorf("could not include an attachment of the original message: %w", err)
  309. }
  310. total += int64(len(part.Data))
  311. data := part.Data
  312. payloads = append(payloads, attachmentPayload{
  313. name: part.Filename,
  314. contentType: part.ContentType,
  315. open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil },
  316. })
  317. }
  318. if limit > 0 && total > limit {
  319. return nil, fmt.Errorf("attachments total %s, the limit is %s", humanSize(total), humanSize(limit))
  320. }
  321. return payloads, nil
  322. }
  323. // writeMessageBody writes the MIME tree described at the top of this file.
  324. func writeMessageBody(w io.Writer, header gomail.Header, request *ComposeRequest, attachments []attachmentPayload) error {
  325. htmlBody := request.HTML
  326. textBody := request.Text
  327. if request.PlainOnly {
  328. if textBody == "" {
  329. textBody = htmlToText(htmlBody, true)
  330. }
  331. htmlBody = ""
  332. } else if textBody == "" && htmlBody != "" {
  333. textBody = htmlToText(htmlBody, true)
  334. }
  335. //Pasted images arrive as data: URIs; mail clients need them as parts
  336. type inlineImage struct {
  337. cid string
  338. contentType string
  339. data []byte
  340. }
  341. inlineImages := []inlineImage{}
  342. if htmlBody != "" {
  343. counter := 0
  344. htmlBody = dataImagePattern.ReplaceAllStringFunc(htmlBody, func(match string) string {
  345. groups := dataImagePattern.FindStringSubmatch(match)
  346. data, err := base64.StdEncoding.DecodeString(strings.Join(strings.Fields(groups[3]), ""))
  347. if err != nil {
  348. return match
  349. }
  350. counter++
  351. cid := fmt.Sprintf("img%d.%s@arozos", counter, randomID(6))
  352. inlineImages = append(inlineImages, inlineImage{cid: cid, contentType: strings.ToLower(groups[2]), data: data})
  353. return groups[1] + "cid:" + cid + groups[4]
  354. })
  355. htmlBody = wrapHTMLDocument(htmlBody)
  356. }
  357. top := header.Header
  358. writeText := func(create func(gomessage.Header) (*gomessage.Writer, error), contentType string, body string) error {
  359. partHeader := gomessage.Header{}
  360. partHeader.SetContentType(contentType, map[string]string{"charset": "utf-8"})
  361. partHeader.Set("Content-Transfer-Encoding", "quoted-printable")
  362. part, err := create(partHeader)
  363. if err != nil {
  364. return err
  365. }
  366. if _, err := io.WriteString(part, normaliseNewlines(body)); err != nil {
  367. return err
  368. }
  369. return part.Close()
  370. }
  371. writeHTML := func(create func(gomessage.Header) (*gomessage.Writer, error)) error {
  372. if len(inlineImages) == 0 {
  373. return writeText(create, "text/html", htmlBody)
  374. }
  375. relatedHeader := gomessage.Header{}
  376. relatedHeader.SetContentType("multipart/related", map[string]string{"type": "text/html"})
  377. related, err := create(relatedHeader)
  378. if err != nil {
  379. return err
  380. }
  381. if err := writeText(related.CreatePart, "text/html", htmlBody); err != nil {
  382. return err
  383. }
  384. for index, image := range inlineImages {
  385. imageHeader := gomessage.Header{}
  386. ext := ".png"
  387. if extensions, _ := mime.ExtensionsByType(image.contentType); len(extensions) > 0 {
  388. ext = extensions[0]
  389. }
  390. name := fmt.Sprintf("image%d%s", index+1, ext)
  391. imageHeader.SetContentType(image.contentType, map[string]string{"name": name})
  392. imageHeader.SetContentDisposition("inline", map[string]string{"filename": name})
  393. imageHeader.Set("Content-Id", "<"+image.cid+">")
  394. imageHeader.Set("Content-Transfer-Encoding", "base64")
  395. part, err := related.CreatePart(imageHeader)
  396. if err != nil {
  397. return err
  398. }
  399. if _, err := part.Write(image.data); err != nil {
  400. return err
  401. }
  402. if err := part.Close(); err != nil {
  403. return err
  404. }
  405. }
  406. return related.Close()
  407. }
  408. writeContent := func(create func(gomessage.Header) (*gomessage.Writer, error)) error {
  409. if htmlBody == "" {
  410. return writeText(create, "text/plain", textBody)
  411. }
  412. alternativeHeader := gomessage.Header{}
  413. alternativeHeader.SetContentType("multipart/alternative", nil)
  414. alternative, err := create(alternativeHeader)
  415. if err != nil {
  416. return err
  417. }
  418. if err := writeText(alternative.CreatePart, "text/plain", textBody); err != nil {
  419. return err
  420. }
  421. if err := writeHTML(alternative.CreatePart); err != nil {
  422. return err
  423. }
  424. return alternative.Close()
  425. }
  426. //The first part created at the top level carries the message header
  427. topLevel := func(partHeader gomessage.Header) (*gomessage.Writer, error) {
  428. merged := top.Copy()
  429. for fields := partHeader.Fields(); fields.Next(); {
  430. merged.Set(fields.Key(), fields.Value())
  431. }
  432. return gomessage.CreateWriter(w, merged)
  433. }
  434. if len(attachments) == 0 {
  435. return writeContent(topLevel)
  436. }
  437. mixedHeader := gomessage.Header{}
  438. mixedHeader.SetContentType("multipart/mixed", nil)
  439. mixed, err := topLevel(mixedHeader)
  440. if err != nil {
  441. return err
  442. }
  443. if err := writeContent(mixed.CreatePart); err != nil {
  444. return err
  445. }
  446. for _, attachment := range attachments {
  447. attachmentHeader := gomessage.Header{}
  448. attachmentHeader.SetContentType(attachment.contentType, map[string]string{"name": attachment.name})
  449. attachmentHeader.SetContentDisposition("attachment", map[string]string{"filename": attachment.name})
  450. if attachment.contentType == "message/rfc822" {
  451. //RFC 2046 forbids base64 for message/rfc822; the original already
  452. //crossed SMTP, so its lines are within limits
  453. attachmentHeader.Set("Content-Transfer-Encoding", "8bit")
  454. } else {
  455. attachmentHeader.Set("Content-Transfer-Encoding", "base64")
  456. }
  457. part, err := mixed.CreatePart(attachmentHeader)
  458. if err != nil {
  459. return err
  460. }
  461. reader, err := attachment.open()
  462. if err != nil {
  463. return fmt.Errorf("cannot read attachment %s: %w", attachment.name, err)
  464. }
  465. _, copyErr := io.Copy(part, reader)
  466. reader.Close()
  467. if copyErr != nil {
  468. return copyErr
  469. }
  470. if err := part.Close(); err != nil {
  471. return err
  472. }
  473. }
  474. return mixed.Close()
  475. }
  476. // wrapHTMLDocument gives editor HTML a complete document with a UTF-8 hint.
  477. func wrapHTMLDocument(body string) string {
  478. lower := strings.ToLower(body)
  479. if strings.Contains(lower, "<html") {
  480. return body
  481. }
  482. return "<!DOCTYPE html>\r\n<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>" +
  483. body + "</body></html>"
  484. }
  485. func normaliseNewlines(text string) string {
  486. text = strings.ReplaceAll(text, "\r\n", "\n")
  487. text = strings.ReplaceAll(text, "\r", "\n")
  488. return strings.ReplaceAll(text, "\n", "\r\n")
  489. }
  490. // contentTypeFor guesses a media type from a file name.
  491. func contentTypeFor(name string) string {
  492. if byExt := mime.TypeByExtension(strings.ToLower(filepath.Ext(name))); byExt != "" {
  493. //Drop the charset Go appends for text types; attachments are bytes
  494. if semicolon := strings.Index(byExt, ";"); semicolon > 0 {
  495. return strings.TrimSpace(byExt[:semicolon])
  496. }
  497. return byExt
  498. }
  499. return "application/octet-stream"
  500. }
  501. func humanSize(size int64) string {
  502. const unit = 1024
  503. if size < unit {
  504. return fmt.Sprintf("%d B", size)
  505. }
  506. div, exp := int64(unit), 0
  507. for n := size / unit; n >= unit; n /= unit {
  508. div *= unit
  509. exp++
  510. }
  511. return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
  512. }