main.go 7.2 KB

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