main.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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() *MailHeader {
  61. return &MailHeader{
  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 []*MailHeader
  132. lastContentType := "plain/text"
  133. for email := NewEmail(); scanner.Scan(); {
  134. if scanner.Text() == "" {
  135. if state == StateHeaderScan {
  136. boundaryCapture := boundaryFinder.FindStringSubmatch(lastContentType)
  137. if len(boundaryCapture) == 2 {
  138. activeBoundary = boundaryCapture[1]
  139. } else {
  140. activeBoundary = ""
  141. }
  142. state = StateBodyScan
  143. // fmt.Printf("--------------------------Start body scan content type:%s boundary: %s -------------------------\n", lastContentType, activeBoundary)
  144. } else if state == StateBodyScan {
  145. // fmt.Printf("--------------------------Previous email-------------------------\n%v\n", email)
  146. previousHeader = nil
  147. activeBoundary = ""
  148. emails = append(emails, email)
  149. email = NewEmail()
  150. state = StateHeaderScan
  151. } else {
  152. // fmt.Printf("Empty line in state %d\n", state)
  153. }
  154. }
  155. if state == StateHeaderScan {
  156. capture := headerFinder.FindStringSubmatch(scanner.Text())
  157. if len(capture) == 3 {
  158. // fmt.Printf("capture Header %s : %s\n", strings.ToLower(capture[0]), strings.ToLower(capture[1]))
  159. header := strings.ToLower(capture[1])
  160. switch header {
  161. case "from":
  162. previousHeader = &email.From
  163. case "to":
  164. previousHeader = &email.To
  165. case "cc":
  166. previousHeader = &email.Cc
  167. case "bcc":
  168. previousHeader = &email.Bcc
  169. case "subject":
  170. previousHeader = &email.Subject
  171. case "date":
  172. previousHeader = &email.Date
  173. case "content-type":
  174. previousHeader = &lastContentType
  175. default:
  176. previousHeader = nil
  177. }
  178. if previousHeader != nil {
  179. *previousHeader += capture[2]
  180. }
  181. continue
  182. }
  183. capture = foldingFinder.FindStringSubmatch(scanner.Text())
  184. if len(capture) == 2 && previousHeader != nil {
  185. *previousHeader += capture[1]
  186. continue
  187. }
  188. } else {
  189. // email.Body += scanner.Text() + "\n"
  190. if activeBoundary != "" {
  191. capture := boundaryEndFinder.FindStringSubmatch(scanner.Text())
  192. if len(capture) == 2 {
  193. // fmt.Printf("capture Boundary End %s\n", capture[1])
  194. if activeBoundary == capture[1] {
  195. state = StateBodyScan
  196. }
  197. continue
  198. }
  199. capture = boundaryStartFinder.FindStringSubmatch(scanner.Text())
  200. if len(capture) == 2 {
  201. // fmt.Printf("capture Boundary Start %s\n", capture[1])
  202. state = StateContentScan
  203. continue
  204. }
  205. }
  206. }
  207. }
  208. content := template.HTML(e.templater.ExecuteMailList(emails))
  209. fmt.Fprint(w, e.templater.ExecuteIndex(content))
  210. }
  211. }
  212. }
  213. func openAndLockMailFile() {
  214. file, err := os.OpenFile("/home/vmail/semlanik.org/ci", os.O_RDWR, 0)
  215. if err != nil {
  216. log.Fatalf("Error to open /home/vmail/semlanik.org/ci %s", err)
  217. }
  218. defer file.Close()
  219. lk := &unix.Flock_t{
  220. Type: unix.F_WRLCK,
  221. }
  222. err = unix.FcntlFlock(file.Fd(), unix.F_SETLKW, lk)
  223. lk.Type = unix.F_UNLCK
  224. if err != nil {
  225. log.Fatalf("Error to set lock %s", err)
  226. }
  227. defer unix.FcntlFlock(file.Fd(), unix.F_SETLKW, lk)
  228. fmt.Printf("Succesfully locked PID: %d", lk.Pid)
  229. input := bufio.NewScanner(os.Stdin)
  230. input.Scan()
  231. }
  232. func fileExists(filename string) bool {
  233. info, err := os.Stat(filename)
  234. if os.IsNotExist(err) {
  235. return false
  236. }
  237. return err == nil && !info.IsDir() && info != nil
  238. }
  239. func main() {
  240. engine := NewGofixEngine()
  241. engine.Run()
  242. }