server.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "fmt"
  28. "html/template"
  29. "log"
  30. "net/http"
  31. "strconv"
  32. auth "git.semlanik.org/semlanik/gostfix/auth"
  33. common "git.semlanik.org/semlanik/gostfix/common"
  34. "git.semlanik.org/semlanik/gostfix/config"
  35. db "git.semlanik.org/semlanik/gostfix/db"
  36. utils "git.semlanik.org/semlanik/gostfix/utils"
  37. sessions "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. type Server struct {
  55. authenticator *auth.Authenticator
  56. fileServer http.Handler
  57. attachmentsServer http.Handler
  58. templater *Templater
  59. sessionStore *sessions.CookieStore
  60. storage *db.Storage
  61. Notifier *webNotifier
  62. scanner common.Scanner
  63. }
  64. func NewServer(scanner common.Scanner) *Server {
  65. storage, err := db.NewStorage()
  66. if err != nil {
  67. log.Fatalf("Unable to intialize mail storage %s", err)
  68. return nil
  69. }
  70. authenticator, err := auth.NewAuthenticator()
  71. if err != nil {
  72. log.Fatalf("Unable to intialize authenticator %s", err)
  73. return nil
  74. }
  75. s := &Server{
  76. authenticator: authenticator,
  77. templater: NewTemplater("data/templates"),
  78. fileServer: http.FileServer(http.Dir("data")),
  79. attachmentsServer: http.StripPrefix("/attachment/", http.FileServer(http.Dir(config.ConfigInstance().AttachmentsPath))),
  80. sessionStore: sessions.NewCookieStore(make([]byte, 32)),
  81. storage: storage,
  82. Notifier: NewWebNotifier(),
  83. scanner: scanner,
  84. }
  85. return s
  86. }
  87. func (s *Server) Run() {
  88. http.Handle("/", s)
  89. log.Fatal(http.ListenAndServe(":"+config.ConfigInstance().WebPort, nil))
  90. }
  91. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  92. fmt.Println(r.URL.Path)
  93. if utils.StartsWith(r.URL.Path, "/css/") ||
  94. utils.StartsWith(r.URL.Path, "/assets/") ||
  95. utils.StartsWith(r.URL.Path, "/js/") {
  96. s.fileServer.ServeHTTP(w, r)
  97. } else if utils.StartsWith(r.URL.Path, "/attachment") {
  98. s.attachmentsServer.ServeHTTP(w, r)
  99. } else if cap := utils.RegExpUtilsInstance().MailboxFinder.FindStringSubmatch(r.URL.Path); len(cap) == 3 {
  100. user, token := s.extractAuth(w, r)
  101. if !s.authenticator.Verify(user, token) {
  102. s.logout(w, r)
  103. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  104. return
  105. }
  106. mailbox, err := strconv.Atoi(cap[1])
  107. if err != nil || mailbox < 0 {
  108. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  109. return
  110. }
  111. path := cap[2]
  112. s.handleMailboxRequest(path, user, mailbox, w, r)
  113. } else {
  114. switch r.URL.Path {
  115. case "/login":
  116. s.handleLogin(w, r)
  117. case "/logout":
  118. s.handleLogout(w, r)
  119. case "/register":
  120. s.handleRegister(w, r)
  121. case "/checkEmail":
  122. s.handleCheckEmail(w, r)
  123. case "/mail":
  124. fallthrough
  125. case "/setRead":
  126. fallthrough
  127. case "/remove":
  128. fallthrough
  129. case "/restore":
  130. fallthrough
  131. case "/delete":
  132. s.handleMailRequest(w, r)
  133. case "/settings":
  134. fallthrough
  135. case "/update":
  136. fallthrough
  137. case "/admin":
  138. s.handleSecureZone(w, r)
  139. default:
  140. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  141. }
  142. }
  143. }
  144. func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
  145. // if session, err := s.sessionStore.Get(r, CookieSessionToken); err == nil && session.Values["user"] != nil && session.Values["token"] != nil {
  146. // http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  147. // return
  148. // }
  149. if !config.ConfigInstance().RegistrationEnabled {
  150. s.error(http.StatusNotImplemented, "Registration is disabled on this server", w)
  151. return
  152. }
  153. if err := r.ParseForm(); err == nil {
  154. user := r.FormValue("user")
  155. password := r.FormValue("password")
  156. fullName := r.FormValue("fullName")
  157. if user != "" && password != "" && fullName != "" {
  158. ok, email := s.checkEmail(user)
  159. if ok && len(password) < 128 && len(fullName) < 128 && utils.RegExpUtilsInstance().FullNameChecker.MatchString(fullName) {
  160. err := s.storage.AddUser(email, password, fullName)
  161. if err != nil {
  162. log.Println(err.Error())
  163. s.error(http.StatusInternalServerError, "Unable to create user", w)
  164. return
  165. }
  166. s.scanner.Reconfigure()
  167. token, _ := s.authenticator.Login(email, password)
  168. s.login(email, token, w, r)
  169. return
  170. }
  171. }
  172. }
  173. fmt.Fprint(w, s.templater.ExecuteRegister(&struct {
  174. Version string
  175. Domain string
  176. }{common.Version, config.ConfigInstance().MyDomain}))
  177. }
  178. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  179. //Check passed in form login/password pair first
  180. if err := r.ParseForm(); err == nil {
  181. user := r.FormValue("user")
  182. password := r.FormValue("password")
  183. token, ok := s.authenticator.Login(user, password)
  184. if ok {
  185. s.login(user, token, w, r)
  186. return
  187. }
  188. }
  189. //Check if user already logged in and entered login page accidently
  190. if s.authenticator.Verify(s.extractAuth(w, r)) {
  191. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  192. return
  193. }
  194. var signupTemplate template.HTML
  195. if config.ConfigInstance().RegistrationEnabled {
  196. signupTemplate = template.HTML(s.templater.ExecuteSignup(""))
  197. } else {
  198. signupTemplate = ""
  199. }
  200. //Otherwise make sure user logged out and show login page
  201. s.logout(w, r)
  202. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  203. Version string
  204. Signup template.HTML
  205. }{common.Version, signupTemplate}))
  206. }
  207. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  208. s.logout(w, r)
  209. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  210. }
  211. func (s *Server) handleCheckEmail(w http.ResponseWriter, r *http.Request) {
  212. if err := r.ParseForm(); err == nil {
  213. if ok, _ := s.checkEmail(r.FormValue("user")); ok {
  214. w.Write([]byte{0})
  215. return
  216. }
  217. s.error(http.StatusNotAcceptable, "Email exists", w)
  218. return
  219. }
  220. s.error(http.StatusBadRequest, "Invalid arguments", w)
  221. return
  222. }
  223. func (s *Server) checkEmail(user string) (bool, string) {
  224. email := user + "@" + config.ConfigInstance().MyDomain
  225. return utils.RegExpUtilsInstance().EmailChecker.MatchString(email) && !s.storage.CheckEmailExists(email), email
  226. }
  227. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  228. session, err := s.sessionStore.Get(r, CookieSessionToken)
  229. if err == nil {
  230. if session.Values["user"] != nil && session.Values["token"] != nil {
  231. s.authenticator.Logout(session.Values["user"].(string), session.Values["token"].(string))
  232. }
  233. session.Values["user"] = ""
  234. session.Values["token"] = ""
  235. session.Save(r, w)
  236. }
  237. }
  238. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  239. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  240. session.Values["user"] = user
  241. session.Values["token"] = token
  242. session.Save(r, w)
  243. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  244. }
  245. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  246. w.WriteHeader(code)
  247. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  248. Code int
  249. Text string
  250. Version string
  251. }{
  252. Code: code,
  253. Text: text,
  254. Version: common.Version,
  255. }))
  256. }
  257. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  258. session, err := s.sessionStore.Get(r, CookieSessionToken)
  259. if err != nil {
  260. log.Printf("Unable to read user session %s\n", err)
  261. return
  262. }
  263. user, _ = session.Values["user"].(string)
  264. token, _ = session.Values["token"].(string)
  265. return
  266. }