A webmail client. Forked from https://git.sr.ht/~migadu/alps
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

435 lines
9.8 KiB

  1. package koushin
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "mime"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "time"
  10. "github.com/emersion/go-imap"
  11. imapclient "github.com/emersion/go-imap/client"
  12. "github.com/emersion/go-message"
  13. "github.com/emersion/go-sasl"
  14. "github.com/labstack/echo/v4"
  15. )
  16. const cookieName = "koushin_session"
  17. type Server struct {
  18. imap struct {
  19. host string
  20. tls bool
  21. insecure bool
  22. pool *ConnPool
  23. }
  24. smtp struct {
  25. host string
  26. tls bool
  27. insecure bool
  28. }
  29. }
  30. func (s *Server) parseIMAPURL(imapURL string) error {
  31. u, err := url.Parse(imapURL)
  32. if err != nil {
  33. return fmt.Errorf("failed to parse IMAP server URL: %v", err)
  34. }
  35. s.imap.host = u.Host
  36. switch u.Scheme {
  37. case "imap":
  38. // This space is intentionally left blank
  39. case "imaps":
  40. s.imap.tls = true
  41. case "imap+insecure":
  42. s.imap.insecure = true
  43. default:
  44. return fmt.Errorf("unrecognized IMAP URL scheme: %s", u.Scheme)
  45. }
  46. return nil
  47. }
  48. func (s *Server) parseSMTPURL(smtpURL string) error {
  49. u, err := url.Parse(smtpURL)
  50. if err != nil {
  51. return fmt.Errorf("failed to parse SMTP server URL: %v", err)
  52. }
  53. s.smtp.host = u.Host
  54. switch u.Scheme {
  55. case "smtp":
  56. // This space is intentionally left blank
  57. case "smtps":
  58. s.smtp.tls = true
  59. case "smtp+insecure":
  60. s.smtp.insecure = true
  61. default:
  62. return fmt.Errorf("unrecognized SMTP URL scheme: %s", u.Scheme)
  63. }
  64. return nil
  65. }
  66. func NewServer(imapURL, smtpURL string) (*Server, error) {
  67. s := &Server{}
  68. if err := s.parseIMAPURL(imapURL); err != nil {
  69. return nil, err
  70. }
  71. s.imap.pool = NewConnPool()
  72. if smtpURL != "" {
  73. if err := s.parseSMTPURL(smtpURL); err != nil {
  74. return nil, err
  75. }
  76. }
  77. return s, nil
  78. }
  79. type context struct {
  80. echo.Context
  81. server *Server
  82. session *Session
  83. }
  84. var aLongTimeAgo = time.Unix(233431200, 0)
  85. func (c *context) setToken(token string) {
  86. cookie := http.Cookie{
  87. Name: cookieName,
  88. Value: token,
  89. HttpOnly: true,
  90. // TODO: domain, secure
  91. }
  92. if token == "" {
  93. cookie.Expires = aLongTimeAgo // unset the cookie
  94. }
  95. c.SetCookie(&cookie)
  96. }
  97. func handleLogin(ectx echo.Context) error {
  98. ctx := ectx.(*context)
  99. username := ctx.FormValue("username")
  100. password := ctx.FormValue("password")
  101. if username != "" && password != "" {
  102. conn, err := ctx.server.connectIMAP()
  103. if err != nil {
  104. return err
  105. }
  106. if err := conn.Login(username, password); err != nil {
  107. conn.Logout()
  108. return ctx.Render(http.StatusOK, "login.html", nil)
  109. }
  110. token, err := ctx.server.imap.pool.Put(conn, username, password)
  111. if err != nil {
  112. return fmt.Errorf("failed to put connection in pool: %v", err)
  113. }
  114. ctx.setToken(token)
  115. return ctx.Redirect(http.StatusFound, "/mailbox/INBOX")
  116. }
  117. return ctx.Render(http.StatusOK, "login.html", nil)
  118. }
  119. func handleGetPart(ctx *context, raw bool) error {
  120. mboxName, uid, err := parseMboxAndUid(ctx.Param("mbox"), ctx.Param("uid"))
  121. if err != nil {
  122. return echo.NewHTTPError(http.StatusBadRequest, err)
  123. }
  124. partPathString := ctx.QueryParam("part")
  125. partPath, err := parsePartPath(partPathString)
  126. if err != nil {
  127. return echo.NewHTTPError(http.StatusBadRequest, err)
  128. }
  129. var msg *imapMessage
  130. var part *message.Entity
  131. var mbox *imap.MailboxStatus
  132. err = ctx.session.Do(func(c *imapclient.Client) error {
  133. var err error
  134. msg, part, err = getMessagePart(c, mboxName, uid, partPath)
  135. mbox = c.Mailbox()
  136. return err
  137. })
  138. if err != nil {
  139. return err
  140. }
  141. mimeType, _, err := part.Header.ContentType()
  142. if err != nil {
  143. return fmt.Errorf("failed to parse part Content-Type: %v", err)
  144. }
  145. if len(partPath) == 0 {
  146. mimeType = "message/rfc822"
  147. }
  148. if raw {
  149. disp, dispParams, _ := part.Header.ContentDisposition()
  150. filename := dispParams["filename"]
  151. // TODO: set Content-Length if possible
  152. if !strings.EqualFold(mimeType, "text/plain") || strings.EqualFold(disp, "attachment") {
  153. dispParams := make(map[string]string)
  154. if filename != "" {
  155. dispParams["filename"] = filename
  156. }
  157. disp := mime.FormatMediaType("attachment", dispParams)
  158. ctx.Response().Header().Set("Content-Disposition", disp)
  159. }
  160. return ctx.Stream(http.StatusOK, mimeType, part.Body)
  161. }
  162. var body string
  163. if strings.HasPrefix(strings.ToLower(mimeType), "text/") {
  164. b, err := ioutil.ReadAll(part.Body)
  165. if err != nil {
  166. return fmt.Errorf("failed to read part body: %v", err)
  167. }
  168. body = string(b)
  169. }
  170. return ctx.Render(http.StatusOK, "message.html", map[string]interface{}{
  171. "Mailbox": mbox,
  172. "Message": msg,
  173. "Body": body,
  174. "PartPath": partPathString,
  175. })
  176. }
  177. func handleCompose(ectx echo.Context) error {
  178. ctx := ectx.(*context)
  179. var msg OutgoingMessage
  180. if strings.ContainsRune(ctx.session.username, '@') {
  181. msg.From = ctx.session.username
  182. }
  183. if ctx.Request().Method == http.MethodGet && ctx.Param("uid") != "" {
  184. // This is a reply
  185. mboxName, uid, err := parseMboxAndUid(ctx.Param("mbox"), ctx.Param("uid"))
  186. if err != nil {
  187. return echo.NewHTTPError(http.StatusBadRequest, err)
  188. }
  189. partPath, err := parsePartPath(ctx.QueryParam("part"))
  190. if err != nil {
  191. return echo.NewHTTPError(http.StatusBadRequest, err)
  192. }
  193. var inReplyTo *imapMessage
  194. var part *message.Entity
  195. err = ctx.session.Do(func(c *imapclient.Client) error {
  196. var err error
  197. inReplyTo, part, err = getMessagePart(c, mboxName, uid, partPath)
  198. return err
  199. })
  200. if err != nil {
  201. return err
  202. }
  203. mimeType, _, err := part.Header.ContentType()
  204. if err != nil {
  205. return fmt.Errorf("failed to parse part Content-Type: %v", err)
  206. }
  207. if !strings.HasPrefix(strings.ToLower(mimeType), "text/") {
  208. err := fmt.Errorf("cannot reply to \"%v\" part", mimeType)
  209. return echo.NewHTTPError(http.StatusBadRequest, err)
  210. }
  211. msg.Text, err = quote(part.Body)
  212. if err != nil {
  213. return err
  214. }
  215. msg.InReplyTo = inReplyTo.Envelope.MessageId
  216. // TODO: populate From from known user addresses and inReplyTo.Envelope.To
  217. replyTo := inReplyTo.Envelope.ReplyTo
  218. if len(replyTo) == 0 {
  219. replyTo = inReplyTo.Envelope.From
  220. }
  221. if len(replyTo) > 0 {
  222. msg.To = make([]string, len(replyTo))
  223. for i, to := range replyTo {
  224. msg.To[i] = to.MailboxName + "@" + to.HostName
  225. }
  226. }
  227. msg.Subject = inReplyTo.Envelope.Subject
  228. if !strings.HasPrefix(strings.ToLower(msg.Subject), "re:") {
  229. msg.Subject = "Re: " + msg.Subject
  230. }
  231. }
  232. if ctx.Request().Method == http.MethodPost {
  233. // TODO: parse address lists
  234. from := ctx.FormValue("from")
  235. to := ctx.FormValue("to")
  236. subject := ctx.FormValue("subject")
  237. text := ctx.FormValue("text")
  238. c, err := ctx.server.connectSMTP()
  239. if err != nil {
  240. return err
  241. }
  242. defer c.Close()
  243. auth := sasl.NewPlainClient("", ctx.session.username, ctx.session.password)
  244. if err := c.Auth(auth); err != nil {
  245. return echo.NewHTTPError(http.StatusForbidden, err)
  246. }
  247. msg.From = from
  248. msg.To = []string{to}
  249. msg.Subject = subject
  250. msg.Text = text
  251. if err := sendMessage(c, &msg); err != nil {
  252. return err
  253. }
  254. if err := c.Quit(); err != nil {
  255. return fmt.Errorf("QUIT failed: %v", err)
  256. }
  257. // TODO: append to IMAP Sent mailbox
  258. return ctx.Redirect(http.StatusFound, "/mailbox/INBOX")
  259. }
  260. return ctx.Render(http.StatusOK, "compose.html", map[string]interface{}{
  261. "Message": &msg,
  262. })
  263. }
  264. func New(imapURL, smtpURL string) *echo.Echo {
  265. e := echo.New()
  266. s, err := NewServer(imapURL, smtpURL)
  267. if err != nil {
  268. e.Logger.Fatal(err)
  269. }
  270. e.HTTPErrorHandler = func(err error, c echo.Context) {
  271. code := http.StatusInternalServerError
  272. if he, ok := err.(*echo.HTTPError); ok {
  273. code = he.Code
  274. } else {
  275. c.Logger().Error(err)
  276. }
  277. // TODO: hide internal errors
  278. c.String(code, err.Error())
  279. }
  280. e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
  281. return func(ectx echo.Context) error {
  282. ctx := &context{Context: ectx, server: s}
  283. cookie, err := ctx.Cookie(cookieName)
  284. if err == http.ErrNoCookie {
  285. // Require auth for all pages except /login
  286. if ctx.Path() == "/login" || strings.HasPrefix(ctx.Path(), "/assets/") {
  287. return next(ctx)
  288. } else {
  289. return ctx.Redirect(http.StatusFound, "/login")
  290. }
  291. } else if err != nil {
  292. return err
  293. }
  294. ctx.session, err = ctx.server.imap.pool.Get(cookie.Value)
  295. if err == ErrSessionExpired {
  296. ctx.setToken("")
  297. return ctx.Redirect(http.StatusFound, "/login")
  298. } else if err != nil {
  299. return err
  300. }
  301. return next(ctx)
  302. }
  303. })
  304. e.Renderer, err = loadTemplates()
  305. if err != nil {
  306. e.Logger.Fatal("Failed to load templates:", err)
  307. }
  308. e.GET("/mailbox/:mbox", func(ectx echo.Context) error {
  309. ctx := ectx.(*context)
  310. mboxName, err := url.PathUnescape(ctx.Param("mbox"))
  311. if err != nil {
  312. return echo.NewHTTPError(http.StatusBadRequest, err)
  313. }
  314. var mailboxes []*imap.MailboxInfo
  315. var msgs []imapMessage
  316. var mbox *imap.MailboxStatus
  317. err = ctx.session.Do(func(c *imapclient.Client) error {
  318. var err error
  319. if mailboxes, err = listMailboxes(c); err != nil {
  320. return err
  321. }
  322. if msgs, err = listMessages(c, mboxName); err != nil {
  323. return err
  324. }
  325. mbox = c.Mailbox()
  326. return nil
  327. })
  328. if err != nil {
  329. return err
  330. }
  331. return ctx.Render(http.StatusOK, "mailbox.html", map[string]interface{}{
  332. "Mailbox": mbox,
  333. "Mailboxes": mailboxes,
  334. "Messages": msgs,
  335. })
  336. })
  337. e.GET("/message/:mbox/:uid", func(ectx echo.Context) error {
  338. ctx := ectx.(*context)
  339. return handleGetPart(ctx, false)
  340. })
  341. e.GET("/message/:mbox/:uid/raw", func(ectx echo.Context) error {
  342. ctx := ectx.(*context)
  343. return handleGetPart(ctx, true)
  344. })
  345. e.GET("/login", handleLogin)
  346. e.POST("/login", handleLogin)
  347. e.GET("/logout", func(ectx echo.Context) error {
  348. ctx := ectx.(*context)
  349. err := ctx.session.Do(func(c *imapclient.Client) error {
  350. return c.Logout()
  351. })
  352. if err != nil {
  353. return fmt.Errorf("failed to logout: %v", err)
  354. }
  355. ctx.setToken("")
  356. return ctx.Redirect(http.StatusFound, "/login")
  357. })
  358. e.GET("/compose", handleCompose)
  359. e.POST("/compose", handleCompose)
  360. e.GET("/message/:mbox/:uid/reply", handleCompose)
  361. e.POST("/message/:mbox/:uid/reply", handleCompose)
  362. e.Static("/assets", "public/assets")
  363. return e
  364. }