parser.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. "net/mail"
  37. "git.semlanik.org/semlanik/gostfix/common"
  38. "git.semlanik.org/semlanik/gostfix/config"
  39. utils "git.semlanik.org/semlanik/gostfix/utils"
  40. "github.com/google/uuid"
  41. enmime "github.com/jhillyerd/enmime"
  42. )
  43. const (
  44. StateHeaderScan = iota
  45. StateBodyScan
  46. )
  47. const (
  48. AtLeastOneHeaderMask = 1 << iota
  49. FromHeaderMask
  50. DateHeaderMask
  51. ToHeaderMask
  52. AllHeaderMask = 15
  53. )
  54. type parseData struct {
  55. state int
  56. mandatoryHeaders int
  57. previousHeader *string
  58. email *common.Mail
  59. bodyContentType string
  60. bodyData string
  61. activeBoundary string
  62. }
  63. func (pd *parseData) reset() {
  64. *pd = parseData{
  65. state: StateHeaderScan,
  66. previousHeader: nil,
  67. mandatoryHeaders: 0,
  68. email: common.NewMail(),
  69. bodyContentType: "plain/text",
  70. bodyData: "",
  71. activeBoundary: "",
  72. }
  73. }
  74. func parseFile(file *utils.LockedFile) []*common.Mail {
  75. log.Println("Parse file")
  76. defer log.Println("Exit parse")
  77. var emails []*common.Mail
  78. pd := &parseData{}
  79. pd.reset()
  80. scanner := bufio.NewScanner(file)
  81. for scanner.Scan() {
  82. log.Println("Scan next line")
  83. currentText := scanner.Text()
  84. if utils.RegExpUtilsInstance().MailIndicator.MatchString(currentText) {
  85. if pd.mandatoryHeaders == AllHeaderMask {
  86. pd.parseBody()
  87. emails = append(emails, pd.email)
  88. }
  89. pd.reset()
  90. fmt.Println("Found new email" + currentText)
  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. }
  106. } else {
  107. pd.parseHeader(currentText)
  108. }
  109. case StateBodyScan:
  110. // if currentText == "" {
  111. // if pd.state == StateBodyScan && pd.activeBoundary == "" {
  112. // if pd.mandatoryHeaders == AllHeaderMask {
  113. // pd.parseBody()
  114. // emails = append(emails, pd.email)
  115. // }
  116. // pd.reset()
  117. // continue
  118. // }
  119. // }
  120. // if pd.activeBoundary != "" {
  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. }
  130. if pd.state == StateBodyScan {
  131. if pd.mandatoryHeaders == AllHeaderMask {
  132. pd.parseBody()
  133. emails = append(emails, pd.email)
  134. }
  135. pd.reset()
  136. }
  137. return emails
  138. }
  139. func (pd *parseData) parseHeader(headerRaw string) {
  140. capture := utils.RegExpUtilsInstance().HeaderFinder.FindStringSubmatch(headerRaw)
  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. pd.previousHeader = &pd.email.Header.Subject
  165. case "date":
  166. pd.previousHeader = nil
  167. unixTime, err := mail.ParseDate(strings.Trim(capture[2], " \t")) //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-type":
  175. pd.previousHeader = &pd.bodyContentType
  176. default:
  177. pd.previousHeader = nil
  178. }
  179. if pd.previousHeader != nil {
  180. *pd.previousHeader = strings.Trim(capture[2], " \t")
  181. }
  182. return
  183. }
  184. //Parse folding
  185. capture = utils.RegExpUtilsInstance().FoldingFinder.FindStringSubmatch(headerRaw)
  186. if len(capture) == 2 && pd.previousHeader != nil {
  187. *pd.previousHeader += capture[1]
  188. }
  189. }
  190. func (pd *parseData) parseBody() {
  191. buffer := bytes.NewBufferString("content-type:" + pd.bodyContentType + "\n\n" + pd.bodyData)
  192. en, err := enmime.ReadEnvelope(buffer)
  193. if err != nil {
  194. log.Printf("Unable to read mail body %s\n\nBody content: %s\n\n", err, pd.bodyData)
  195. return
  196. }
  197. pd.email.Body = &common.MailBody{}
  198. pd.email.Body.PlainText = en.Text
  199. pd.email.Body.RichText = en.HTML
  200. for _, attachment := range en.Attachments {
  201. uuid := uuid.New()
  202. fileName := hex.EncodeToString(uuid[:])
  203. attachmentFile, err := os.Create(config.ConfigInstance().AttachmentsPath + "/" + fileName)
  204. log.Printf("Attachment found %s\n", fileName)
  205. if err != nil {
  206. log.Printf("Unable to save attachment %s %s\n", fileName, err)
  207. continue
  208. }
  209. pd.email.Body.Attachments = append(pd.email.Body.Attachments, &common.AttachmentHeader{
  210. Id: fileName,
  211. FileName: attachment.FileName,
  212. ContentType: attachment.ContentType,
  213. })
  214. attachmentFile.Write(attachment.Content)
  215. }
  216. }
  217. func parseDate(stringDate string) (int64, error) {
  218. formatsToTest := []string{
  219. "Mon, _2 Jan 2006 15:04:05 -0700",
  220. time.RFC1123Z,
  221. time.RFC1123,
  222. time.UnixDate,
  223. "Mon, _2 Jan 2006 15:04:05 -0700 (MST)",
  224. "Mon, _2 Jan 2006 15:04:05 -0700 (MST)"}
  225. var err error
  226. for _, format := range formatsToTest {
  227. dateTime, err := time.Parse(format, stringDate)
  228. if err == nil {
  229. return dateTime.Unix(), nil
  230. }
  231. }
  232. return 0, errors.New("Invalid date format " + stringDate + " , " + err.Error())
  233. }