parser.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. fmt.Println("Found new email" + currentText)
  92. continue
  93. }
  94. switch pd.state {
  95. case StateHeaderScan:
  96. if currentText == "" {
  97. if pd.mandatoryHeaders&AtLeastOneHeaderMask == AtLeastOneHeaderMask { //Cause we read at least one header
  98. pd.previousHeader = nil
  99. boundaryCapture := utils.RegExpUtilsInstance().BoundaryFinder.FindStringSubmatch(pd.bodyContentType)
  100. if len(boundaryCapture) == 2 {
  101. pd.activeBoundary = boundaryCapture[1]
  102. } else {
  103. pd.activeBoundary = ""
  104. }
  105. pd.state = StateBodyScan
  106. //Header postprocessing
  107. address, err := mail.ParseAddress(pd.email.Header.From)
  108. if err == nil {
  109. pd.email.Header.From = address.Address
  110. if len(address.Name) > 0 {
  111. pd.email.Header.From = fmt.Sprintf("\"%s\" <%s>", address.Name, address.Address)
  112. }
  113. } else {
  114. fmt.Printf("Unable to parse from email: %s", err)
  115. }
  116. }
  117. } else {
  118. pd.parseHeader(currentText)
  119. }
  120. case StateBodyScan:
  121. pd.bodyData += currentText + "\n"
  122. capture := utils.RegExpUtilsInstance().BoundaryEndFinder.FindStringSubmatch(currentText)
  123. if len(capture) == 2 && pd.activeBoundary == capture[1] {
  124. pd.state = StateBodyScan
  125. pd.activeBoundary = ""
  126. }
  127. }
  128. }
  129. if pd.state == StateBodyScan {
  130. if pd.mandatoryHeaders == AllHeaderMask {
  131. pd.parseBody()
  132. emails = append(emails, pd.email)
  133. }
  134. pd.reset()
  135. }
  136. return emails
  137. }
  138. func (pd *parseData) parseHeader(headerRaw string) {
  139. capture := utils.RegExpUtilsInstance().HeaderFinder.FindStringSubmatch(headerRaw)
  140. encoded := false
  141. //Parse header
  142. if len(capture) == 3 {
  143. // fmt.Printf("capture Header %s : %s\n", strings.ToLower(capture[0]), strings.ToLower(capture[1]))
  144. header := strings.ToLower(capture[1])
  145. pd.mandatoryHeaders |= AtLeastOneHeaderMask
  146. switch header {
  147. case "from":
  148. pd.previousHeader = &pd.email.Header.From
  149. pd.mandatoryHeaders |= FromHeaderMask
  150. case "to":
  151. pd.previousHeader = &pd.email.Header.To
  152. pd.mandatoryHeaders |= ToHeaderMask
  153. case "x-original-to":
  154. if pd.email.Header.To == "" {
  155. pd.previousHeader = &pd.email.Header.To
  156. pd.mandatoryHeaders |= ToHeaderMask
  157. }
  158. case "cc":
  159. pd.previousHeader = &pd.email.Header.Cc
  160. case "bcc":
  161. pd.previousHeader = &pd.email.Header.Bcc
  162. pd.mandatoryHeaders |= ToHeaderMask
  163. case "subject":
  164. encoded = true
  165. pd.previousHeader = &pd.email.Header.Subject
  166. case "date":
  167. pd.previousHeader = nil
  168. unixTime, err := mail.ParseDate(strings.Trim(capture[2], " \t"))
  169. if err == nil {
  170. pd.email.Header.Date = unixTime.Unix()
  171. pd.mandatoryHeaders |= DateHeaderMask
  172. } else {
  173. log.Printf("Unable to parse message: %s\n", err)
  174. }
  175. case "content-transfer-encoding":
  176. pd.previousHeader = &pd.contentTransferEncoding
  177. case "content-type":
  178. pd.previousHeader = &pd.bodyContentType
  179. default:
  180. pd.previousHeader = nil
  181. }
  182. if pd.previousHeader != nil {
  183. *pd.previousHeader = strings.Trim(capture[2], " \t")
  184. if encoded {
  185. *pd.previousHeader = decodeEncoded(*pd.previousHeader)
  186. }
  187. }
  188. return
  189. }
  190. //Parse folding
  191. capture = utils.RegExpUtilsInstance().FoldingFinder.FindStringSubmatch(headerRaw)
  192. if len(capture) == 2 && pd.previousHeader != nil {
  193. *pd.previousHeader += decodeEncoded(strings.Trim(capture[1], " \t"))
  194. }
  195. }
  196. func (pd *parseData) parseBody() {
  197. buffer := bytes.NewBufferString("content-transfer-encoding: " + pd.contentTransferEncoding + "\ncontent-type: " + pd.bodyContentType + "\n\n" + pd.bodyData)
  198. en, err := enmime.ReadEnvelope(buffer)
  199. if err != nil {
  200. log.Printf("Unable to read mail body %s\n\nBody content: %s\n\n", err, pd.bodyData)
  201. return
  202. }
  203. pd.email.Body = &common.MailBody{}
  204. pd.email.Body.PlainText = en.Text
  205. pd.email.Body.RichText = en.HTML
  206. for _, attachment := range en.Attachments {
  207. uuid := uuid.New()
  208. fileName := hex.EncodeToString(uuid[:])
  209. attachmentFile, err := os.Create(config.ConfigInstance().AttachmentsPath + "/" + fileName)
  210. log.Printf("Attachment found %s\n", fileName)
  211. if err != nil {
  212. log.Printf("Unable to save attachment %s %s\n", fileName, err)
  213. continue
  214. }
  215. pd.email.Body.Attachments = append(pd.email.Body.Attachments, &common.AttachmentHeader{
  216. Id: fileName,
  217. FileName: attachment.FileName,
  218. ContentType: attachment.ContentType,
  219. })
  220. attachmentFile.Write(attachment.Content)
  221. }
  222. }
  223. func decodeEncoded(dataEncoded string) string {
  224. dataParts := utils.RegExpUtilsInstance().EncodedStringFinder.FindAllString(dataEncoded, -1)
  225. if len(dataParts) <= 0 {
  226. return dataEncoded
  227. }
  228. var decodedBuffer []byte
  229. for _, headerPart := range dataParts {
  230. headerPart = headerPart[2 : len(headerPart)-2]
  231. headerPartParts := strings.Split(headerPart, "?")
  232. if len(headerPartParts) == 3 {
  233. switch strings.ToLower(headerPartParts[1]) {
  234. case "b":
  235. fmt.Printf("Decode base64: %s\n", headerPartParts[2])
  236. decodedBase64, err := base64.StdEncoding.DecodeString(headerPartParts[2])
  237. if err == nil {
  238. decodedBuffer = append(decodedBuffer, decodedBase64...)
  239. }
  240. case "q":
  241. decodedQuotedPrintable, err := ioutil.ReadAll(quotedprintable.NewReader(strings.NewReader(headerPartParts[2])))
  242. if err == nil {
  243. decodedBuffer = append(decodedBuffer, decodedQuotedPrintable...)
  244. }
  245. default:
  246. }
  247. }
  248. }
  249. if len(decodedBuffer) > 0 {
  250. //TODO: check encoding here
  251. return string(decodedBuffer)
  252. }
  253. return dataEncoded
  254. }