parser.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package scanner
  26. import (
  27. "bufio"
  28. "bytes"
  29. "encoding/base64"
  30. "encoding/hex"
  31. "fmt"
  32. "io/ioutil"
  33. "log"
  34. "mime/quotedprintable"
  35. "os"
  36. "strings"
  37. "net/mail"
  38. "git.semlanik.org/semlanik/gostfix/common"
  39. "git.semlanik.org/semlanik/gostfix/config"
  40. utils "git.semlanik.org/semlanik/gostfix/utils"
  41. "github.com/google/uuid"
  42. enmime "github.com/jhillyerd/enmime"
  43. )
  44. const (
  45. StateHeaderScan = iota
  46. StateBodyScan
  47. )
  48. const (
  49. AtLeastOneHeaderMask = 1 << iota
  50. FromHeaderMask
  51. DateHeaderMask
  52. ToHeaderMask
  53. AllHeaderMask = 15
  54. )
  55. type parseData struct {
  56. state int
  57. mandatoryHeaders int
  58. previousHeader *string
  59. email *common.Mail
  60. contentTransferEncoding string
  61. bodyContentType string
  62. bodyData string
  63. activeBoundary string
  64. }
  65. func (pd *parseData) reset() {
  66. *pd = parseData{
  67. state: StateHeaderScan,
  68. previousHeader: nil,
  69. mandatoryHeaders: 0,
  70. email: common.NewMail(),
  71. bodyContentType: "plain/text",
  72. bodyData: "",
  73. activeBoundary: "",
  74. }
  75. }
  76. func parseFile(file *utils.LockedFile) []*common.Mail {
  77. log.Println("Parse file")
  78. defer log.Println("Exit parse")
  79. var emails []*common.Mail
  80. pd := &parseData{}
  81. pd.reset()
  82. scanner := bufio.NewScanner(file)
  83. for scanner.Scan() {
  84. currentText := scanner.Text()
  85. if utils.RegExpUtilsInstance().MailIndicator.MatchString(currentText) {
  86. if pd.mandatoryHeaders == AllHeaderMask {
  87. pd.parseBody()
  88. emails = append(emails, pd.email)
  89. }
  90. pd.reset()
  91. continue
  92. }
  93. switch pd.state {
  94. case StateHeaderScan:
  95. if currentText == "" {
  96. if pd.mandatoryHeaders&AtLeastOneHeaderMask == AtLeastOneHeaderMask { //Cause we read at least one header
  97. pd.previousHeader = nil
  98. boundaryCapture := utils.RegExpUtilsInstance().BoundaryFinder.FindStringSubmatch(pd.bodyContentType)
  99. if len(boundaryCapture) == 2 {
  100. pd.activeBoundary = boundaryCapture[1]
  101. } else {
  102. pd.activeBoundary = ""
  103. }
  104. pd.state = StateBodyScan
  105. //Header postprocessing
  106. address, err := mail.ParseAddress(pd.email.Header.From)
  107. if err == nil {
  108. pd.email.Header.From = address.Address
  109. if len(address.Name) > 0 {
  110. pd.email.Header.From = fmt.Sprintf("\"%s\" <%s>", address.Name, address.Address)
  111. }
  112. } else {
  113. fmt.Printf("Unable to parse from email: %s", err)
  114. }
  115. }
  116. } else {
  117. pd.parseHeader(currentText)
  118. }
  119. case StateBodyScan:
  120. pd.bodyData += currentText + "\n"
  121. capture := utils.RegExpUtilsInstance().BoundaryEndFinder.FindStringSubmatch(currentText)
  122. if len(capture) == 2 && pd.activeBoundary == capture[1] {
  123. pd.state = StateBodyScan
  124. pd.activeBoundary = ""
  125. }
  126. }
  127. }
  128. if pd.state == StateBodyScan {
  129. if pd.mandatoryHeaders == AllHeaderMask {
  130. pd.parseBody()
  131. emails = append(emails, pd.email)
  132. }
  133. pd.reset()
  134. }
  135. return emails
  136. }
  137. func (pd *parseData) parseHeader(headerRaw string) {
  138. capture := utils.RegExpUtilsInstance().HeaderFinder.FindStringSubmatch(headerRaw)
  139. encoded := false
  140. //Parse header
  141. if len(capture) == 3 {
  142. // fmt.Printf("capture Header %s : %s\n", strings.ToLower(capture[0]), strings.ToLower(capture[1]))
  143. header := strings.ToLower(capture[1])
  144. pd.mandatoryHeaders |= AtLeastOneHeaderMask
  145. switch header {
  146. case "from":
  147. pd.previousHeader = &pd.email.Header.From
  148. pd.mandatoryHeaders |= FromHeaderMask
  149. case "to":
  150. pd.previousHeader = &pd.email.Header.To
  151. pd.mandatoryHeaders |= ToHeaderMask
  152. case "x-original-to":
  153. if pd.email.Header.To == "" {
  154. pd.previousHeader = &pd.email.Header.To
  155. pd.mandatoryHeaders |= ToHeaderMask
  156. }
  157. case "cc":
  158. pd.previousHeader = &pd.email.Header.Cc
  159. case "bcc":
  160. pd.previousHeader = &pd.email.Header.Bcc
  161. pd.mandatoryHeaders |= ToHeaderMask
  162. case "subject":
  163. encoded = true
  164. pd.previousHeader = &pd.email.Header.Subject
  165. case "date":
  166. pd.previousHeader = nil
  167. unixTime, err := mail.ParseDate(strings.Trim(capture[2], " \t"))
  168. if err == nil {
  169. pd.email.Header.Date = unixTime.Unix()
  170. pd.mandatoryHeaders |= DateHeaderMask
  171. } else {
  172. log.Printf("Unable to parse message: %s\n", err)
  173. }
  174. case "content-transfer-encoding":
  175. pd.previousHeader = &pd.contentTransferEncoding
  176. case "content-type":
  177. pd.previousHeader = &pd.bodyContentType
  178. default:
  179. pd.previousHeader = nil
  180. }
  181. if pd.previousHeader != nil {
  182. *pd.previousHeader = strings.Trim(capture[2], " \t")
  183. if encoded {
  184. *pd.previousHeader = decodeEncoded(*pd.previousHeader)
  185. }
  186. }
  187. return
  188. }
  189. //Parse folding
  190. capture = utils.RegExpUtilsInstance().FoldingFinder.FindStringSubmatch(headerRaw)
  191. if len(capture) == 2 && pd.previousHeader != nil {
  192. *pd.previousHeader += decodeEncoded(strings.Trim(capture[1], " \t"))
  193. }
  194. }
  195. func (pd *parseData) parseBody() {
  196. buffer := bytes.NewBufferString("content-transfer-encoding: " + pd.contentTransferEncoding + "\ncontent-type: " + pd.bodyContentType + "\n\n" + pd.bodyData)
  197. en, err := enmime.ReadEnvelope(buffer)
  198. if err != nil {
  199. log.Printf("Unable to read mail body %s\n\nBody content: %s\n\n", err, pd.bodyData)
  200. return
  201. }
  202. pd.email.Body = &common.MailBody{}
  203. pd.email.Body.PlainText = en.Text
  204. pd.email.Body.RichText = en.HTML
  205. for _, attachment := range en.Attachments {
  206. uuid := uuid.New()
  207. fileName := hex.EncodeToString(uuid[:])
  208. attachmentFile, err := os.Create(config.ConfigInstance().AttachmentsPath + "/" + fileName)
  209. log.Printf("Attachment found %s\n", fileName)
  210. if err != nil {
  211. log.Printf("Unable to save attachment %s %s\n", fileName, err)
  212. continue
  213. }
  214. pd.email.Body.Attachments = append(pd.email.Body.Attachments, &common.AttachmentHeader{
  215. Id: fileName,
  216. FileName: attachment.FileName,
  217. ContentType: attachment.ContentType,
  218. })
  219. attachmentFile.Write(attachment.Content)
  220. }
  221. }
  222. func decodeEncoded(dataEncoded string) string {
  223. dataParts := utils.RegExpUtilsInstance().EncodedStringFinder.FindAllString(dataEncoded, -1)
  224. if len(dataParts) <= 0 {
  225. return dataEncoded
  226. }
  227. var decodedBuffer []byte
  228. for _, headerPart := range dataParts {
  229. headerPart = headerPart[2 : len(headerPart)-2]
  230. headerPartParts := strings.Split(headerPart, "?")
  231. if len(headerPartParts) == 3 {
  232. switch strings.ToLower(headerPartParts[1]) {
  233. case "b":
  234. fmt.Printf("Decode base64: %s\n", headerPartParts[2])
  235. decodedBase64, err := base64.StdEncoding.DecodeString(headerPartParts[2])
  236. if err == nil {
  237. decodedBuffer = append(decodedBuffer, decodedBase64...)
  238. }
  239. case "q":
  240. decodedQuotedPrintable, err := ioutil.ReadAll(quotedprintable.NewReader(strings.NewReader(headerPartParts[2])))
  241. if err == nil {
  242. decodedBuffer = append(decodedBuffer, decodedQuotedPrintable...)
  243. }
  244. default:
  245. }
  246. }
  247. }
  248. if len(decodedBuffer) > 0 {
  249. //TODO: check encoding here
  250. return string(decodedBuffer)
  251. }
  252. return dataEncoded
  253. }