mailscanner.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. if !utils.DirectoryExists(config.ConfigInstance().AttachmentsPath) {
  65. err = os.Mkdir(config.ConfigInstance().AttachmentsPath, 0755)
  66. if err != nil {
  67. log.Fatal(err)
  68. return
  69. }
  70. }
  71. ms = &MailScanner{
  72. watcher: watcher,
  73. storage: storage,
  74. signalChannel: make(chan int),
  75. }
  76. return
  77. }
  78. func (ms *MailScanner) checkEmailRegistred(email string) bool {
  79. emails, err := ms.storage.GetAllEmails()
  80. if err != nil {
  81. return false
  82. }
  83. for _, e := range emails {
  84. if email == e {
  85. return true
  86. }
  87. }
  88. return false
  89. }
  90. func (ms *MailScanner) readEmailMaps() {
  91. registredEmails, err := ms.storage.GetAllEmails()
  92. if err != nil {
  93. log.Fatal(err)
  94. return
  95. }
  96. mailPath := config.ConfigInstance().VMailboxBase
  97. emailMaps := make(map[string]string)
  98. mapsFile := config.ConfigInstance().VMailboxMaps
  99. if !utils.FileExists(mapsFile) {
  100. log.Fatal("Could not read virtual mailbox maps")
  101. return
  102. }
  103. file, err := os.Open(mapsFile)
  104. if err != nil {
  105. log.Fatalf("Unable to open virtual mailbox maps %s\n", mapsFile)
  106. }
  107. scanner := bufio.NewScanner(file)
  108. for scanner.Scan() {
  109. emailMapPair := strings.Split(scanner.Text(), " ")
  110. if len(emailMapPair) != 2 {
  111. log.Printf("Invalid record in virtual mailbox maps %s\n", scanner.Text())
  112. continue
  113. }
  114. found := false
  115. email := emailMapPair[0]
  116. for _, registredEmail := range registredEmails {
  117. if email == registredEmail {
  118. found = true
  119. }
  120. }
  121. if !found {
  122. log.Fatalf("Found non-registred mailbox <%s> in mail maps. Database has inconsistancy.\n", email)
  123. return
  124. }
  125. emailMaps[email] = mailPath + "/" + emailMapPair[1]
  126. }
  127. for _, registredEmail := range registredEmails {
  128. if _, exists := emailMaps[registredEmail]; !exists {
  129. log.Fatalf("Found existing mailbox <%s> in database. Mail maps has inconsistancy.\n", registredEmail)
  130. }
  131. }
  132. ms.emailMaps = emailMaps
  133. for mailbox, mailPath := range ms.emailMaps {
  134. if !utils.FileExists(mailPath) {
  135. file, err := os.Create(mailPath)
  136. if err != nil {
  137. fmt.Printf("Unable to create mailbox for watching %s\n", err)
  138. continue
  139. }
  140. file.Close()
  141. }
  142. mails := ms.readMailFile(mailPath)
  143. for _, mail := range mails {
  144. ms.storage.SaveMail(mailbox, common.Inbox, mail, false)
  145. }
  146. log.Printf("New email for %s, emails read %d", mailPath, len(mails))
  147. err := ms.watcher.Add(mailPath)
  148. if err != nil {
  149. fmt.Printf("Unable to add mailbox for watching\n")
  150. } else {
  151. fmt.Printf("Add mail file %s for watching\n", mailPath)
  152. }
  153. }
  154. }
  155. func (ms *MailScanner) Run() {
  156. go func() {
  157. ms.readEmailMaps()
  158. for {
  159. select {
  160. case signal := <-ms.signalChannel:
  161. switch signal {
  162. case SignalReconfigure:
  163. ms.readEmailMaps()
  164. }
  165. case event, ok := <-ms.watcher.Events:
  166. if !ok {
  167. return
  168. }
  169. if event.Op&fsnotify.Write == fsnotify.Write {
  170. log.Println("iNotify write")
  171. mailPath := event.Name
  172. mailbox := ""
  173. for k, v := range ms.emailMaps {
  174. if v == mailPath {
  175. mailbox = k
  176. }
  177. }
  178. if mailbox != "" {
  179. mails := ms.readMailFile(mailPath)
  180. for _, mail := range mails {
  181. ms.storage.SaveMail(mailbox, common.Inbox, mail, false)
  182. }
  183. log.Printf("New email for %s, emails read %d", mailPath, len(mails))
  184. } else {
  185. log.Printf("Invalid path update triggered: %s", mailPath)
  186. }
  187. }
  188. case err, ok := <-ms.watcher.Errors:
  189. if !ok {
  190. return
  191. }
  192. log.Println("error:", err)
  193. }
  194. }
  195. }()
  196. }
  197. func (ms *MailScanner) Stop() {
  198. defer ms.watcher.Close()
  199. }
  200. func (ms *MailScanner) readMailFile(mailPath string) (mails []*common.Mail) {
  201. log.Println("Read mail file")
  202. defer log.Println("Exit read mail file")
  203. if !utils.FileExists(mailPath) {
  204. return nil
  205. }
  206. file, err := utils.OpenAndLockWait(mailPath)
  207. if err != nil {
  208. return nil
  209. }
  210. defer file.CloseAndUnlock()
  211. mails = parseFile(file)
  212. if len(mails) > 0 {
  213. file.Truncate(0)
  214. }
  215. return mails
  216. }