server.go 11 KB

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