parser.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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/hex"
  30. "errors"
  31. "fmt"
  32. "log"
  33. "os"
  34. "strings"
  35. "time"
  36. "git.semlanik.org/semlanik/gostfix/common"
  37. "git.semlanik.org/semlanik/gostfix/config"
  38. utils "git.semlanik.org/semlanik/gostfix/utils"
  39. "github.com/google/uuid"
  40. enmime "github.com/jhillyerd/enmime"
  41. )
  42. const (
  43. StateHeaderScan = iota
  44. StateBodyScan
  45. )
  46. const (
  47. AtLeastOneHeaderMask = 1 << iota
  48. FromHeaderMask
  49. DateHeaderMask
  50. ToHeaderMask
  51. AllHeaderMask = 15
  52. )
  53. type parseData struct {
  54. state int
  55. mandatoryHeaders int
  56. previousHeader *string
  57. email *common.Mail
  58. bodyContentType string
  59. bodyData string
  60. activeBoundary string
  61. }
  62. func (pd *parseData) reset() {
  63. *pd = parseData{
  64. state: StateHeaderScan,
  65. previousHeader: nil,
  66. mandatoryHeaders: 0,
  67. email: NewEmail(),
  68. bodyContentType: "plain/text",
  69. bodyData: "",
  70. activeBoundary: "",
  71. }
  72. }
  73. func parseFile(file *utils.LockedFile) []*common.Mail {
  74. var emails []*common.Mail
  75. pd := &parseData{}
  76. pd.reset()
  77. scanner := bufio.NewScanner(file)
  78. for scanner.Scan() {
  79. currentText := scanner.Text()
  80. if utils.RegExpUtilsInstance().MailIndicator.MatchString(currentText) {
  81. if pd.mandatoryHeaders == AllHeaderMask {
  82. pd.parseBody()
  83. emails = append(emails, pd.email)
  84. }
  85. pd.reset()
  86. fmt.Println("Found new email" + currentText)
  87. continue
  88. }
  89. switch pd.state {
  90. case StateHeaderScan:
  91. if currentText == "" {
  92. if pd.mandatoryHeaders&AtLeastOneHeaderMask == AtLeastOneHeaderMask { //Cause we read at least one header
  93. pd.previousHeader = nil
  94. boundaryCapture := utils.RegExpUtilsInstance().BoundaryFinder.FindStringSubmatch(pd.bodyContentType)
  95. if len(boundaryCapture) == 2 {
  96. pd.activeBoundary = boundaryCapture[1]
  97. } else {
  98. pd.activeBoundary = ""
  99. }
  100. pd.state = StateBodyScan
  101. }
  102. } else {
  103. pd.parseHeader(currentText)
  104. }
  105. case StateBodyScan:
  106. // if currentText == "" {
  107. // if pd.state == StateBodyScan && pd.activeBoundary == "" {
  108. // if pd.mandatoryHeaders == AllHeaderMask {
  109. // pd.parseBody()
  110. // emails = append(emails, pd.email)
  111. // }
  112. // pd.reset()
  113. // continue
  114. // }
  115. // }
  116. // if pd.activeBoundary != "" {
  117. pd.bodyData += currentText + "\n"
  118. capture := utils.RegExpUtilsInstance().BoundaryEndFinder.FindStringSubmatch(currentText)
  119. if len(capture) == 2 && pd.activeBoundary == capture[1] {
  120. pd.state = StateBodyScan
  121. pd.activeBoundary = ""
  122. }
  123. // }
  124. }
  125. }
  126. if pd.state == StateBodyScan {
  127. if pd.mandatoryHeaders == AllHeaderMask {
  128. pd.parseBody()
  129. emails = append(emails, pd.email)
  130. }
  131. pd.reset()
  132. }
  133. return emails
  134. }
  135. func (pd *parseData) parseHeader(headerRaw string) {
  136. capture := utils.RegExpUtilsInstance().HeaderFinder.FindStringSubmatch(headerRaw)
  137. //Parse header
  138. if len(capture) == 3 {
  139. // fmt.Printf("capture Header %s : %s\n", strings.ToLower(capture[0]), strings.ToLower(capture[1]))
  140. header := strings.ToLower(capture[1])
  141. pd.mandatoryHeaders |= AtLeastOneHeaderMask
  142. switch header {
  143. case "from":
  144. pd.previousHeader = &pd.email.Header.From
  145. pd.mandatoryHeaders |= FromHeaderMask
  146. case "to":
  147. pd.previousHeader = &pd.email.Header.To
  148. pd.mandatoryHeaders |= ToHeaderMask
  149. case "x-original-to":
  150. if pd.email.Header.To == "" {
  151. pd.previousHeader = &pd.email.Header.To
  152. pd.mandatoryHeaders |= ToHeaderMask
  153. }
  154. case "cc":
  155. pd.previousHeader = &pd.email.Header.Cc
  156. case "bcc":
  157. pd.previousHeader = &pd.email.Header.Bcc
  158. pd.mandatoryHeaders |= ToHeaderMask
  159. case "subject":
  160. pd.previousHeader = &pd.email.Header.Subject
  161. case "date":
  162. pd.previousHeader = nil
  163. unixTime, err := parseDate(strings.Trim(capture[2], " \t"))
  164. if err == nil {
  165. pd.email.Header.Date = unixTime
  166. pd.mandatoryHeaders |= DateHeaderMask
  167. } else {
  168. log.Printf("Unable to parse message: %s\n", err)
  169. }
  170. case "content-type":
  171. pd.previousHeader = &pd.bodyContentType
  172. default:
  173. pd.previousHeader = nil
  174. }
  175. if pd.previousHeader != nil {
  176. *pd.previousHeader = strings.Trim(capture[2], " \t")
  177. }
  178. return
  179. }
  180. //Parse folding
  181. capture = utils.RegExpUtilsInstance().FoldingFinder.FindStringSubmatch(headerRaw)
  182. if len(capture) == 2 && pd.previousHeader != nil {
  183. *pd.previousHeader += capture[1]
  184. }
  185. }
  186. func (pd *parseData) parseBody() {
  187. buffer := bytes.NewBufferString("content-type:" + pd.bodyContentType + "\n\n" + pd.bodyData)
  188. en, err := enmime.ReadEnvelope(buffer)
  189. if err != nil {
  190. log.Printf("Unable to read mail body %s\n\nBody content: %s\n\n", err, pd.bodyData)
  191. return
  192. }
  193. pd.email.Body = &common.MailBody{}
  194. pd.email.Body.PlainText = en.Text
  195. pd.email.Body.RichText = en.HTML
  196. for _, attachment := range en.Attachments {
  197. uuid := uuid.New()
  198. fileName := hex.EncodeToString(uuid[:])
  199. attachmentFile, err := os.Create(config.ConfigInstance().AttachmentsPath + "/" + fileName)
  200. log.Printf("Attachment found %s\n", fileName)
  201. if err != nil {
  202. log.Printf("Unable to save attachment %s %s\n", fileName, err)
  203. continue
  204. }
  205. pd.email.Body.Attachments = append(pd.email.Body.Attachments, &common.AttachmentHeader{
  206. Id: fileName,
  207. FileName: attachment.FileName,
  208. ContentType: attachment.ContentType,
  209. })
  210. attachmentFile.Write(attachment.Content)
  211. }
  212. }
  213. func parseDate(stringDate string) (int64, error) {
  214. formatsToTest := []string{
  215. "Mon, _2 Jan 2006 15:04:05 -0700",
  216. time.RFC1123Z,
  217. time.RFC1123,
  218. time.UnixDate,
  219. "Mon, _2 Jan 2006 15:04:05 -0700 (MST)",
  220. "Mon, _2 Jan 2006 15:04:05 -0700 (MST)"}
  221. var err error
  222. for _, format := range formatsToTest {
  223. dateTime, err := time.Parse(format, stringDate)
  224. if err == nil {
  225. return dateTime.Unix(), nil
  226. }
  227. }
  228. return 0, errors.New("Invalid date format " + stringDate + " , " + err.Error())
  229. }