server.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 "git.semlanik.org/semlanik/gostfix/auth"
  34. common "git.semlanik.org/semlanik/gostfix/common"
  35. config "git.semlanik.org/semlanik/gostfix/config"
  36. utils "git.semlanik.org/semlanik/gostfix/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. case "/statusLine":
  95. s.handleStatusLine(w, r)
  96. default:
  97. s.handleMailbox(w, r)
  98. }
  99. }
  100. }
  101. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  102. //Check passed in form login/password pair first
  103. if err := r.ParseForm(); err == nil {
  104. user := r.FormValue("user")
  105. password := r.FormValue("password")
  106. token, ok := s.authenticator.Authenticate(user, password)
  107. if ok {
  108. s.login(user, token, w, r)
  109. return
  110. }
  111. }
  112. //Check if user already logged in and entered login page accidently
  113. if s.authenticator.Verify(s.extractAuth(w, r)) {
  114. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  115. return
  116. }
  117. //Otherwise make sure user logged out and show login page
  118. s.logout(w, r)
  119. fmt.Fprint(w, s.templater.ExecuteLogin(&LoginTemplateData{
  120. common.Version,
  121. }))
  122. }
  123. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  124. s.logout(w, r)
  125. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  126. }
  127. func (s *Server) handleMessageDetails(w http.ResponseWriter, r *http.Request) {
  128. //TODO: Not implemented yet. Need database mail storage implemented first
  129. user, token := s.extractAuth(w, r)
  130. if !s.authenticator.Verify(user, token) {
  131. fmt.Fprint(w, "")
  132. return
  133. }
  134. fmt.Fprint(w, s.templater.ExecuteDetails(""))
  135. }
  136. func (s *Server) handleStatusLine(w http.ResponseWriter, r *http.Request) {
  137. //TODO: Not implemented yet. Need database mail storage implemented first
  138. user, token := s.extractAuth(w, r)
  139. if !s.authenticator.Verify(user, token) {
  140. fmt.Fprint(w, "")
  141. return
  142. }
  143. fmt.Fprint(w, s.templater.ExecuteStatusLine(&StatusLineTemplateData{
  144. Name: "No name", //TODO: read from database
  145. Read: 0, //TODO: read from database
  146. Unread: 0, //TODO: read from database
  147. }))
  148. }
  149. func (s *Server) handleMailbox(w http.ResponseWriter, r *http.Request) {
  150. user, token := s.extractAuth(w, r)
  151. if !s.authenticator.Verify(user, token) {
  152. s.logout(w, r)
  153. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  154. }
  155. mailPath := config.ConfigInstance().VMailboxBase + "/" + s.authenticator.MailPath(user)
  156. if !utils.FileExists(mailPath) {
  157. s.logout(w, r)
  158. s.error(http.StatusInternalServerError, "Unable to access your mailbox. Please contact Administrator.", w, r)
  159. return
  160. }
  161. file, err := utils.OpenAndLockWait(mailPath)
  162. if err != nil {
  163. s.logout(w, r)
  164. s.error(http.StatusInternalServerError, "Unable to access your mailbox. Please contact Administrator.", w, r)
  165. return
  166. }
  167. defer file.CloseAndUnlock()
  168. scanner := bufio.NewScanner(file)
  169. activeBoundary := ""
  170. var previousHeader *string = nil
  171. var emails []*common.Mail
  172. mandatoryHeaders := 0
  173. email := NewEmail()
  174. state := StateHeaderScan
  175. for scanner.Scan() {
  176. if scanner.Text() == "" {
  177. if state == StateHeaderScan && mandatoryHeaders&AtLeastOneHeaderMask == AtLeastOneHeaderMask {
  178. boundaryCapture := utils.RegExpUtilsInstance().BoundaryFinder.FindStringSubmatch(email.Body.ContentType)
  179. if len(boundaryCapture) == 2 {
  180. activeBoundary = boundaryCapture[1]
  181. } else {
  182. activeBoundary = ""
  183. }
  184. state = StateBodyScan
  185. // fmt.Printf("--------------------------Start body scan content type:%s boundary: %s -------------------------\n", email.Body.ContentType, activeBoundary)
  186. } else if state == StateBodyScan {
  187. // fmt.Printf("--------------------------Previous email-------------------------\n%v\n", email)
  188. if activeBoundary == "" {
  189. previousHeader = nil
  190. activeBoundary = ""
  191. // fmt.Printf("Actual headers: %d\n", mandatoryHeaders)
  192. if mandatoryHeaders == AllHeaderMask {
  193. emails = append(emails, email)
  194. }
  195. email = NewEmail()
  196. state = StateHeaderScan
  197. mandatoryHeaders = 0
  198. } else {
  199. // fmt.Printf("Still in body scan\n")
  200. continue
  201. }
  202. } else {
  203. // fmt.Printf("Empty line in state %d\n", state)
  204. }
  205. }
  206. if state == StateHeaderScan {
  207. capture := utils.RegExpUtilsInstance().HeaderFinder.FindStringSubmatch(scanner.Text())
  208. if len(capture) == 3 {
  209. // fmt.Printf("capture Header %s : %s\n", strings.ToLower(capture[0]), strings.ToLower(capture[1]))
  210. header := strings.ToLower(capture[1])
  211. mandatoryHeaders |= AtLeastOneHeaderMask
  212. switch header {
  213. case "from":
  214. previousHeader = &email.Header.From
  215. mandatoryHeaders |= FromHeaderMask
  216. case "to":
  217. previousHeader = &email.Header.To
  218. mandatoryHeaders |= ToHeaderMask
  219. case "cc":
  220. previousHeader = &email.Header.Cc
  221. case "bcc":
  222. previousHeader = &email.Header.Bcc
  223. mandatoryHeaders |= ToHeaderMask
  224. case "subject":
  225. previousHeader = &email.Header.Subject
  226. case "date":
  227. previousHeader = &email.Header.Date
  228. mandatoryHeaders |= DateHeaderMask
  229. case "content-type":
  230. previousHeader = &email.Body.ContentType
  231. default:
  232. previousHeader = nil
  233. }
  234. if previousHeader != nil {
  235. *previousHeader += capture[2]
  236. }
  237. continue
  238. }
  239. capture = utils.RegExpUtilsInstance().FoldingFinder.FindStringSubmatch(scanner.Text())
  240. if len(capture) == 2 && previousHeader != nil {
  241. *previousHeader += capture[1]
  242. continue
  243. }
  244. } else {
  245. // email.Body.Content += scanner.Text() + "\n"
  246. if activeBoundary != "" {
  247. capture := utils.RegExpUtilsInstance().BoundaryEndFinder.FindStringSubmatch(scanner.Text())
  248. if len(capture) == 2 {
  249. // fmt.Printf("capture Boundary End %s\n", capture[1])
  250. if activeBoundary == capture[1] {
  251. state = StateBodyScan
  252. activeBoundary = ""
  253. }
  254. continue
  255. }
  256. // capture = boundaryStartFinder.FindStringSubmatch(scanner.Text())
  257. // if len(capture) == 2 && activeBoundary == capture[1] {
  258. // // fmt.Printf("capture Boundary Start %s\n", capture[1])
  259. // state = StateContentScan
  260. // continue
  261. // }
  262. }
  263. }
  264. }
  265. if state == StateBodyScan && mandatoryHeaders == AllHeaderMask { //Finalize if body read till EOF
  266. // fmt.Printf("--------------------------Previous email-------------------------\n%v\n", email)
  267. previousHeader = nil
  268. activeBoundary = ""
  269. emails = append(emails, email)
  270. state = StateHeaderScan
  271. }
  272. fmt.Fprint(w, s.templater.ExecuteIndex(&IndexTemplateData{
  273. MailList: template.HTML(s.templater.ExecuteMailList(emails)),
  274. Folders: "Folders",
  275. Version: common.Version,
  276. }))
  277. }
  278. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  279. fmt.Println("logout")
  280. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  281. session.Values["user"] = ""
  282. session.Values["token"] = ""
  283. session.Save(r, w)
  284. }
  285. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  286. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  287. session.Values["user"] = user
  288. session.Values["token"] = token
  289. session.Save(r, w)
  290. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  291. }
  292. func (s *Server) error(code int, text string, w http.ResponseWriter, r *http.Request) {
  293. w.WriteHeader(http.StatusInternalServerError)
  294. fmt.Fprint(w, s.templater.ExecuteError(&ErrorTemplateData{
  295. Code: code,
  296. Text: "Unable to access your mailbox. Please contact Administrator.",
  297. }))
  298. }
  299. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  300. session, err := s.sessionStore.Get(r, CookieSessionToken)
  301. if err != nil {
  302. log.Printf("Unable to read user session %s\n", err)
  303. return
  304. }
  305. user, _ = session.Values["user"].(string)
  306. token, _ = session.Values["token"].(string)
  307. return
  308. }