main.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 main
  26. import (
  27. "bufio"
  28. "fmt"
  29. template "html/template"
  30. "log"
  31. "net/http"
  32. "os"
  33. "regexp"
  34. "strings"
  35. unix "golang.org/x/sys/unix"
  36. )
  37. const (
  38. StateHeaderScan = iota
  39. StateBodyScan
  40. StateContentScan
  41. )
  42. const (
  43. HeaderRegExp = "^([\x21-\x7E^:]+):(.*)"
  44. FoldingRegExp = "^\\s+(.*)"
  45. BoundaryStartRegExp = "^--(.*)"
  46. BoundaryEndRegExp = "^--(.*)--$"
  47. BoundaryRegExp = "boundary=\"(.*)\""
  48. UserRegExp = "^[a-zA-Z][\\w0-9\\._]*"
  49. )
  50. // type Email struct {
  51. // From string
  52. // To string
  53. // Cc string
  54. // Bcc string
  55. // Date string
  56. // Subject string
  57. // ContentType string
  58. // Body string
  59. // }
  60. func NewEmail() *Mail {
  61. return &Mail{
  62. Header: &MailHeader{},
  63. Body: &MailBody{
  64. ContentType: "plain/text",
  65. },
  66. }
  67. }
  68. type GofixEngine struct {
  69. templater *Templater
  70. fileServer http.Handler
  71. userChecker *regexp.Regexp
  72. scanner *MailScanner
  73. mailPath string
  74. }
  75. func NewGofixEngine(mailPath string) (e *GofixEngine) {
  76. e = &GofixEngine{
  77. templater: NewTemplater("templates"),
  78. fileServer: http.FileServer(http.Dir("./")),
  79. scanner: NewMailScanner(mailPath),
  80. mailPath: mailPath,
  81. }
  82. var err error = nil
  83. e.userChecker, err = regexp.Compile(UserRegExp)
  84. if err != nil {
  85. log.Fatal("Could not compile user checker regex")
  86. }
  87. return
  88. }
  89. func (e *GofixEngine) Run() {
  90. defer e.scanner.watcher.Close()
  91. e.scanner.Run()
  92. http.Handle("/", e)
  93. log.Fatal(http.ListenAndServe(":65200", nil))
  94. }
  95. func (e *GofixEngine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  96. fmt.Println(r.URL.Path)
  97. switch r.URL.Path {
  98. case "/css/styles.css":
  99. e.fileServer.ServeHTTP(w, r)
  100. default:
  101. {
  102. user := r.URL.Query().Get("user")
  103. if e.userChecker.FindString(user) != user || user == "" {
  104. fmt.Print("Invalid user")
  105. w.WriteHeader(http.StatusUnauthorized)
  106. fmt.Fprint(w, "401 - Access denied")
  107. return
  108. }
  109. state := StateHeaderScan
  110. headerFinder, err := regexp.Compile(HeaderRegExp)
  111. if err != nil {
  112. log.Fatalf("Invalid regexp %s\n", err)
  113. }
  114. foldingFinder, err := regexp.Compile(FoldingRegExp)
  115. if err != nil {
  116. log.Fatalf("Invalid regexp %s\n", err)
  117. }
  118. boundaryStartFinder, err := regexp.Compile(BoundaryStartRegExp)
  119. if err != nil {
  120. log.Fatalf("Invalid regexp %s\n", err)
  121. }
  122. boundaryEndFinder, err := regexp.Compile(BoundaryEndRegExp)
  123. if err != nil {
  124. log.Fatalf("Invalid regexp %s\n", err)
  125. }
  126. boundaryFinder, err := regexp.Compile(BoundaryRegExp)
  127. if !fileExists(e.mailPath + "/" + r.URL.Query().Get("user")) {
  128. w.WriteHeader(http.StatusForbidden)
  129. fmt.Fprint(w, "403 Unknown user")
  130. return
  131. }
  132. file, _ := os.Open(e.mailPath + "/" + r.URL.Query().Get("user"))
  133. scanner := bufio.NewScanner(file)
  134. activeBoundary := ""
  135. var previousHeader *string = nil
  136. var emails []*Mail
  137. email := NewEmail()
  138. for scanner.Scan() {
  139. if scanner.Text() == "" {
  140. if state == StateHeaderScan {
  141. boundaryCapture := boundaryFinder.FindStringSubmatch(email.Body.ContentType)
  142. if len(boundaryCapture) == 2 {
  143. activeBoundary = boundaryCapture[1]
  144. } else {
  145. activeBoundary = ""
  146. }
  147. state = StateBodyScan
  148. // fmt.Printf("--------------------------Start body scan content type:%s boundary: %s -------------------------\n", email.Body.ContentType, activeBoundary)
  149. } else if state == StateBodyScan {
  150. // fmt.Printf("--------------------------Previous email-------------------------\n%v\n", email)
  151. previousHeader = nil
  152. activeBoundary = ""
  153. emails = append(emails, email)
  154. email = NewEmail()
  155. state = StateHeaderScan
  156. } else {
  157. // fmt.Printf("Empty line in state %d\n", state)
  158. }
  159. }
  160. if state == StateHeaderScan {
  161. capture := headerFinder.FindStringSubmatch(scanner.Text())
  162. if len(capture) == 3 {
  163. // fmt.Printf("capture Header %s : %s\n", strings.ToLower(capture[0]), strings.ToLower(capture[1]))
  164. header := strings.ToLower(capture[1])
  165. switch header {
  166. case "from":
  167. previousHeader = &email.Header.From
  168. case "to":
  169. previousHeader = &email.Header.To
  170. case "cc":
  171. previousHeader = &email.Header.Cc
  172. case "bcc":
  173. previousHeader = &email.Header.Bcc
  174. case "subject":
  175. previousHeader = &email.Header.Subject
  176. case "date":
  177. previousHeader = &email.Header.Date
  178. case "content-type":
  179. previousHeader = &email.Body.ContentType
  180. default:
  181. previousHeader = nil
  182. }
  183. if previousHeader != nil {
  184. *previousHeader += capture[2]
  185. }
  186. continue
  187. }
  188. capture = foldingFinder.FindStringSubmatch(scanner.Text())
  189. if len(capture) == 2 && previousHeader != nil {
  190. *previousHeader += capture[1]
  191. continue
  192. }
  193. } else {
  194. // email.Body.Content += scanner.Text() + "\n"
  195. if activeBoundary != "" {
  196. capture := boundaryEndFinder.FindStringSubmatch(scanner.Text())
  197. if len(capture) == 2 {
  198. // fmt.Printf("capture Boundary End %s\n", capture[1])
  199. if activeBoundary == capture[1] {
  200. state = StateBodyScan
  201. }
  202. continue
  203. }
  204. capture = boundaryStartFinder.FindStringSubmatch(scanner.Text())
  205. if len(capture) == 2 {
  206. // fmt.Printf("capture Boundary Start %s\n", capture[1])
  207. state = StateContentScan
  208. continue
  209. }
  210. }
  211. }
  212. }
  213. if state == StateBodyScan { //Finalize if body read till EOF
  214. // fmt.Printf("--------------------------Previous email-------------------------\n%v\n", email)
  215. previousHeader = nil
  216. activeBoundary = ""
  217. emails = append(emails, email)
  218. state = StateHeaderScan
  219. }
  220. content := template.HTML(e.templater.ExecuteMailList(emails))
  221. fmt.Fprint(w, e.templater.ExecuteIndex(content))
  222. }
  223. }
  224. }
  225. func openAndLockMailFile() {
  226. file, err := os.OpenFile("/home/vmail/semlanik.org/ci", os.O_RDWR, 0)
  227. if err != nil {
  228. log.Fatalf("Error to open /home/vmail/semlanik.org/ci %s", err)
  229. }
  230. defer file.Close()
  231. lk := &unix.Flock_t{
  232. Type: unix.F_WRLCK,
  233. }
  234. err = unix.FcntlFlock(file.Fd(), unix.F_SETLKW, lk)
  235. lk.Type = unix.F_UNLCK
  236. if err != nil {
  237. log.Fatalf("Error to set lock %s", err)
  238. }
  239. defer unix.FcntlFlock(file.Fd(), unix.F_SETLKW, lk)
  240. fmt.Printf("Succesfully locked PID: %d", lk.Pid)
  241. input := bufio.NewScanner(os.Stdin)
  242. input.Scan()
  243. }
  244. func fileExists(filename string) bool {
  245. info, err := os.Stat(filename)
  246. if os.IsNotExist(err) {
  247. return false
  248. }
  249. return err == nil && !info.IsDir() && info != nil
  250. }
  251. func main() {
  252. mailPath := "./"
  253. if len(os.Args) >= 2 {
  254. mailPath = os.Args[1]
  255. }
  256. engine := NewGofixEngine(mailPath)
  257. engine.Run()
  258. }