server.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 web
  26. import (
  27. "bufio"
  28. "fmt"
  29. template "html/template"
  30. "log"
  31. "net/http"
  32. "strings"
  33. auth "../auth"
  34. common "../common"
  35. config "../config"
  36. utils "../utils"
  37. "github.com/gorilla/sessions"
  38. )
  39. const (
  40. StateHeaderScan = iota
  41. StateBodyScan
  42. StateContentScan
  43. )
  44. const (
  45. AtLeastOneHeaderMask = 1 << iota
  46. FromHeaderMask
  47. DateHeaderMask
  48. ToHeaderMask
  49. AllHeaderMask = 15
  50. )
  51. const (
  52. CookieSessionToken = "gostfix_session"
  53. )
  54. func NewEmail() *common.Mail {
  55. return &common.Mail{
  56. Header: &common.MailHeader{},
  57. Body: &common.MailBody{
  58. ContentType: "plain/text",
  59. },
  60. }
  61. }
  62. type Server struct {
  63. authenticator *auth.Authenticator
  64. fileServer http.Handler
  65. templater *Templater
  66. sessionStore *sessions.CookieStore
  67. }
  68. func NewServer() *Server {
  69. return &Server{
  70. authenticator: auth.NewAuthenticator(),
  71. templater: NewTemplater("./data/templates"),
  72. fileServer: http.FileServer(http.Dir("./data")),
  73. sessionStore: sessions.NewCookieStore(make([]byte, 32)),
  74. }
  75. }
  76. func (s *Server) Run() {
  77. http.Handle("/", s)
  78. log.Fatal(http.ListenAndServe(":65200", nil))
  79. }
  80. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  81. fmt.Println(r.URL.Path)
  82. if utils.StartsWith(r.URL.Path, "/css/") ||
  83. utils.StartsWith(r.URL.Path, "/assets/") ||
  84. utils.StartsWith(r.URL.Path, "/js/") {
  85. s.fileServer.ServeHTTP(w, r)
  86. } else {
  87. switch r.URL.Path {
  88. case "/login":
  89. s.handleLogin(w, r)
  90. case "/logout":
  91. s.handleLogout(w, r)
  92. case "/messageDetails":
  93. s.handleMessageDetails(w, r)
  94. default:
  95. s.handleMailbox(w, r)
  96. }
  97. }
  98. }
  99. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  100. if err := r.ParseForm(); err == nil {
  101. user := r.FormValue("user")
  102. password := r.FormValue("password")
  103. token, ok := s.authenticator.Authenticate(user, password)
  104. if ok {
  105. s.Login(user, token, w, r)
  106. return
  107. }
  108. }
  109. if s.authenticator.Verify(s.extractAuth(w, r)) {
  110. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  111. return
  112. }
  113. s.Logout(w, r)
  114. fmt.Fprint(w, s.templater.ExecuteLogin(&LoginTemplateData{
  115. common.Version,
  116. }))
  117. }
  118. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  119. s.Logout(w, r)
  120. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  121. }
  122. func (s *Server) handleMessageDetails(w http.ResponseWriter, r *http.Request) {
  123. //TODO: Not implemented yet. Need database mail storage implemented first
  124. fmt.Fprint(w, s.templater.ExecuteDetails(""))
  125. }
  126. func (s *Server) handleMailbox(w http.ResponseWriter, r *http.Request) {
  127. user, token := s.extractAuth(w, r)
  128. if !s.authenticator.Verify(user, token) {
  129. s.Logout(w, r)
  130. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  131. }
  132. mailPath := config.ConfigInstance().VMailboxBase + "/" + s.authenticator.MailPath(user)
  133. if !utils.FileExists(mailPath) {
  134. s.Logout(w, r)
  135. s.Error(http.StatusInternalServerError, "Unable to access your mailbox. Please contact Administrator.", w, r)
  136. return
  137. }
  138. file, err := utils.OpenAndLockWait(mailPath)
  139. if err != nil {
  140. s.Logout(w, r)
  141. s.Error(http.StatusInternalServerError, "Unable to access your mailbox. Please contact Administrator.", w, r)
  142. return
  143. }
  144. defer file.CloseAndUnlock()
  145. scanner := bufio.NewScanner(file)
  146. activeBoundary := ""
  147. var previousHeader *string = nil
  148. var emails []*common.Mail
  149. mandatoryHeaders := 0
  150. email := NewEmail()
  151. state := StateHeaderScan
  152. for scanner.Scan() {
  153. if scanner.Text() == "" {
  154. if state == StateHeaderScan && mandatoryHeaders&AtLeastOneHeaderMask == AtLeastOneHeaderMask {
  155. boundaryCapture := utils.RegExpUtilsInstance().BoundaryFinder.FindStringSubmatch(email.Body.ContentType)
  156. if len(boundaryCapture) == 2 {
  157. activeBoundary = boundaryCapture[1]
  158. } else {
  159. activeBoundary = ""
  160. }
  161. state = StateBodyScan
  162. // fmt.Printf("--------------------------Start body scan content type:%s boundary: %s -------------------------\n", email.Body.ContentType, activeBoundary)
  163. } else if state == StateBodyScan {
  164. // fmt.Printf("--------------------------Previous email-------------------------\n%v\n", email)
  165. if activeBoundary == "" {
  166. previousHeader = nil
  167. activeBoundary = ""
  168. // fmt.Printf("Actual headers: %d\n", mandatoryHeaders)
  169. if mandatoryHeaders == AllHeaderMask {
  170. emails = append(emails, email)
  171. }
  172. email = NewEmail()
  173. state = StateHeaderScan
  174. mandatoryHeaders = 0
  175. } else {
  176. // fmt.Printf("Still in body scan\n")
  177. continue
  178. }
  179. } else {
  180. // fmt.Printf("Empty line in state %d\n", state)
  181. }
  182. }
  183. if state == StateHeaderScan {
  184. capture := utils.RegExpUtilsInstance().HeaderFinder.FindStringSubmatch(scanner.Text())
  185. if len(capture) == 3 {
  186. // fmt.Printf("capture Header %s : %s\n", strings.ToLower(capture[0]), strings.ToLower(capture[1]))
  187. header := strings.ToLower(capture[1])
  188. mandatoryHeaders |= AtLeastOneHeaderMask
  189. switch header {
  190. case "from":
  191. previousHeader = &email.Header.From
  192. mandatoryHeaders |= FromHeaderMask
  193. case "to":
  194. previousHeader = &email.Header.To
  195. mandatoryHeaders |= ToHeaderMask
  196. case "cc":
  197. previousHeader = &email.Header.Cc
  198. case "bcc":
  199. previousHeader = &email.Header.Bcc
  200. mandatoryHeaders |= ToHeaderMask
  201. case "subject":
  202. previousHeader = &email.Header.Subject
  203. case "date":
  204. previousHeader = &email.Header.Date
  205. mandatoryHeaders |= DateHeaderMask
  206. case "content-type":
  207. previousHeader = &email.Body.ContentType
  208. default:
  209. previousHeader = nil
  210. }
  211. if previousHeader != nil {
  212. *previousHeader += capture[2]
  213. }
  214. continue
  215. }
  216. capture = utils.RegExpUtilsInstance().FoldingFinder.FindStringSubmatch(scanner.Text())
  217. if len(capture) == 2 && previousHeader != nil {
  218. *previousHeader += capture[1]
  219. continue
  220. }
  221. } else {
  222. // email.Body.Content += scanner.Text() + "\n"
  223. if activeBoundary != "" {
  224. capture := utils.RegExpUtilsInstance().BoundaryEndFinder.FindStringSubmatch(scanner.Text())
  225. if len(capture) == 2 {
  226. // fmt.Printf("capture Boundary End %s\n", capture[1])
  227. if activeBoundary == capture[1] {
  228. state = StateBodyScan
  229. activeBoundary = ""
  230. }
  231. continue
  232. }
  233. // capture = boundaryStartFinder.FindStringSubmatch(scanner.Text())
  234. // if len(capture) == 2 && activeBoundary == capture[1] {
  235. // // fmt.Printf("capture Boundary Start %s\n", capture[1])
  236. // state = StateContentScan
  237. // continue
  238. // }
  239. }
  240. }
  241. }
  242. if state == StateBodyScan && mandatoryHeaders == AllHeaderMask { //Finalize if body read till EOF
  243. // fmt.Printf("--------------------------Previous email-------------------------\n%v\n", email)
  244. previousHeader = nil
  245. activeBoundary = ""
  246. emails = append(emails, email)
  247. state = StateHeaderScan
  248. }
  249. fmt.Fprint(w, s.templater.ExecuteIndex(&IndexTemplateData{
  250. MailList: template.HTML(s.templater.ExecuteMailList(emails)),
  251. Folders: "Folders",
  252. Version: common.Version,
  253. }))
  254. }
  255. func (s *Server) Logout(w http.ResponseWriter, r *http.Request) {
  256. fmt.Println("logout")
  257. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  258. session.Values["user"] = ""
  259. session.Values["token"] = ""
  260. session.Save(r, w)
  261. }
  262. func (s *Server) Login(user, token string, w http.ResponseWriter, r *http.Request) {
  263. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  264. session.Values["user"] = user
  265. session.Values["token"] = token
  266. session.Save(r, w)
  267. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  268. }
  269. func (s *Server) Error(code int, text string, w http.ResponseWriter, r *http.Request) {
  270. w.WriteHeader(http.StatusInternalServerError)
  271. fmt.Fprint(w, s.templater.ExecuteError(&ErrorTemplateData{
  272. Code: code,
  273. Text: "Unable to access your mailbox. Please contact Administrator.",
  274. }))
  275. }
  276. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  277. session, err := s.sessionStore.Get(r, CookieSessionToken)
  278. if err != nil {
  279. log.Printf("Unable to read user session %s\n", err)
  280. return
  281. }
  282. user, _ = session.Values["user"].(string)
  283. token, _ = session.Values["token"].(string)
  284. return
  285. }