mailscanner.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. "fmt"
  29. "log"
  30. "os"
  31. "strings"
  32. "git.semlanik.org/semlanik/gostfix/common"
  33. config "git.semlanik.org/semlanik/gostfix/config"
  34. db "git.semlanik.org/semlanik/gostfix/db"
  35. utils "git.semlanik.org/semlanik/gostfix/utils"
  36. fsnotify "github.com/fsnotify/fsnotify"
  37. )
  38. const (
  39. SignalReconfigure = iota
  40. )
  41. func NewEmail() *common.Mail {
  42. return &common.Mail{
  43. Header: &common.MailHeader{},
  44. Body: &common.MailBody{},
  45. }
  46. }
  47. type MailScanner struct {
  48. watcher *fsnotify.Watcher
  49. emailMaps map[string]string
  50. storage *db.Storage
  51. signalChannel chan int
  52. }
  53. func NewMailScanner() (ms *MailScanner) {
  54. watcher, err := fsnotify.NewWatcher()
  55. if err != nil {
  56. log.Fatal(err)
  57. return
  58. }
  59. storage, err := db.NewStorage()
  60. if err != nil {
  61. log.Fatal(err)
  62. return
  63. }
  64. ms = &MailScanner{
  65. watcher: watcher,
  66. storage: storage,
  67. signalChannel: make(chan int),
  68. }
  69. return
  70. }
  71. func (ms *MailScanner) checkEmailRegistred(email string) bool {
  72. emails, err := ms.storage.GetAllEmails()
  73. if err != nil {
  74. return false
  75. }
  76. for _, e := range emails {
  77. if email == e {
  78. return true
  79. }
  80. }
  81. return false
  82. }
  83. func (ms *MailScanner) readEmailMaps() {
  84. registredEmails, err := ms.storage.GetAllEmails()
  85. if err != nil {
  86. log.Fatal(err)
  87. return
  88. }
  89. mailPath := config.ConfigInstance().VMailboxBase
  90. emailMaps := make(map[string]string)
  91. mapsFile := config.ConfigInstance().VMailboxMaps
  92. if !utils.FileExists(mapsFile) {
  93. log.Fatal("Could not read virtual mailbox maps")
  94. return
  95. }
  96. file, err := os.Open(mapsFile)
  97. if err != nil {
  98. log.Fatalf("Unable to open virtual mailbox maps %s\n", mapsFile)
  99. }
  100. scanner := bufio.NewScanner(file)
  101. for scanner.Scan() {
  102. emailMapPair := strings.Split(scanner.Text(), " ")
  103. if len(emailMapPair) != 2 {
  104. log.Printf("Invalid record in virtual mailbox maps %s\n", scanner.Text())
  105. continue
  106. }
  107. found := false
  108. email := emailMapPair[0]
  109. for _, registredEmail := range registredEmails {
  110. if email == registredEmail {
  111. found = true
  112. }
  113. }
  114. if !found {
  115. log.Fatalf("Found non-registred mailbox <%s> in mail maps. Database has inconsistancy.\n", email)
  116. return
  117. }
  118. emailMaps[email] = mailPath + "/" + emailMapPair[1]
  119. }
  120. for _, registredEmail := range registredEmails {
  121. if _, exists := emailMaps[registredEmail]; !exists {
  122. log.Fatalf("Found existing mailbox <%s> in database. Mail maps has inconsistancy.\n", registredEmail)
  123. }
  124. }
  125. ms.emailMaps = emailMaps
  126. for mailbox, mailPath := range ms.emailMaps {
  127. if !utils.FileExists(mailPath) {
  128. file, err := os.Create(mailPath)
  129. if err != nil {
  130. fmt.Printf("Unable to create mailbox for watching %s\n", err)
  131. continue
  132. }
  133. file.Close()
  134. }
  135. mails := ms.readMailFile(mailPath)
  136. for _, mail := range mails {
  137. ms.storage.SaveMail(mailbox, "Inbox", mail)
  138. }
  139. log.Printf("New email for %s, emails read %d", mailPath, len(mails))
  140. err := ms.watcher.Add(mailPath)
  141. if err != nil {
  142. fmt.Printf("Unable to add mailbox for watching\n")
  143. } else {
  144. fmt.Printf("Add mail file %s for watching\n", mailPath)
  145. }
  146. }
  147. }
  148. func (ms *MailScanner) Run() {
  149. go func() {
  150. ms.readEmailMaps()
  151. for {
  152. select {
  153. case signal := <-ms.signalChannel:
  154. switch signal {
  155. case SignalReconfigure:
  156. ms.readEmailMaps()
  157. }
  158. case event, ok := <-ms.watcher.Events:
  159. if !ok {
  160. return
  161. }
  162. if event.Op&fsnotify.Write == fsnotify.Write {
  163. mailPath := event.Name
  164. mailbox := ""
  165. for k, v := range ms.emailMaps {
  166. if v == mailPath {
  167. mailbox = k
  168. }
  169. }
  170. if mailbox != "" {
  171. mails := ms.readMailFile(mailPath)
  172. for _, mail := range mails {
  173. ms.storage.SaveMail(mailbox, "Inbox", mail)
  174. }
  175. log.Printf("New email for %s, emails read %d", mailPath, len(mails))
  176. } else {
  177. log.Printf("Invalid path update triggered: %s", mailPath)
  178. }
  179. }
  180. case err, ok := <-ms.watcher.Errors:
  181. if !ok {
  182. return
  183. }
  184. log.Println("error:", err)
  185. }
  186. }
  187. }()
  188. }
  189. func (ms *MailScanner) Stop() {
  190. defer ms.watcher.Close()
  191. }
  192. func (ms *MailScanner) readMailFile(mailPath string) (mails []*common.Mail) {
  193. if !utils.FileExists(mailPath) {
  194. return nil
  195. }
  196. file, err := utils.OpenAndLockWait(mailPath)
  197. if err != nil {
  198. return nil
  199. }
  200. defer file.CloseAndUnlock()
  201. mails = parseFile(file)
  202. if len(mails) > 0 {
  203. file.Truncate(0)
  204. }
  205. return mails
  206. }