server.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "embed"
  6. "encoding/json"
  7. "errors"
  8. firebase "firebase.google.com/go"
  9. "firebase.google.com/go/messaging"
  10. "fmt"
  11. "github.com/emersion/go-smtp"
  12. "google.golang.org/api/option"
  13. "heckel.io/ntfy/util"
  14. "html/template"
  15. "io"
  16. "log"
  17. "mime"
  18. "net"
  19. "net/http"
  20. "net/http/httptest"
  21. "os"
  22. "path/filepath"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "unicode/utf8"
  29. )
  30. // TODO add "max messages in a topic" limit
  31. // TODO implement "since=<ID>"
  32. // Server is the main server, providing the UI and API for ntfy
  33. type Server struct {
  34. config *Config
  35. httpServer *http.Server
  36. httpsServer *http.Server
  37. smtpServer *smtp.Server
  38. smtpBackend *smtpBackend
  39. topics map[string]*topic
  40. visitors map[string]*visitor
  41. firebase subscriber
  42. mailer mailer
  43. messages int64
  44. cache cache
  45. closeChan chan bool
  46. mu sync.Mutex
  47. }
  48. // errHTTP is a generic HTTP error for any non-200 HTTP error
  49. type errHTTP struct {
  50. Code int `json:"code,omitempty"`
  51. HTTPCode int `json:"http"`
  52. Message string `json:"error"`
  53. Link string `json:"link,omitempty"`
  54. }
  55. func (e errHTTP) Error() string {
  56. return e.Message
  57. }
  58. func (e errHTTP) JSON() string {
  59. b, _ := json.Marshal(&e)
  60. return string(b)
  61. }
  62. type indexPage struct {
  63. Topic string
  64. CacheDuration time.Duration
  65. }
  66. type sinceTime time.Time
  67. func (t sinceTime) IsAll() bool {
  68. return t == sinceAllMessages
  69. }
  70. func (t sinceTime) IsNone() bool {
  71. return t == sinceNoMessages
  72. }
  73. func (t sinceTime) Time() time.Time {
  74. return time.Time(t)
  75. }
  76. var (
  77. sinceAllMessages = sinceTime(time.Unix(0, 0))
  78. sinceNoMessages = sinceTime(time.Unix(1, 0))
  79. )
  80. var (
  81. topicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No /!
  82. topicPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}$`) // Regex must match JS & Android app!
  83. jsonPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/json$`)
  84. ssePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/sse$`)
  85. rawPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/raw$`)
  86. publishPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/(publish|send|trigger)$`)
  87. staticRegex = regexp.MustCompile(`^/static/.+`)
  88. docsRegex = regexp.MustCompile(`^/docs(|/.*)$`)
  89. fileRegex = regexp.MustCompile(`^/file/([-_A-Za-z0-9]{1,64})(?:\.[A-Za-z0-9]{1,16})?$`)
  90. disallowedTopics = []string{"docs", "static", "file"}
  91. templateFnMap = template.FuncMap{
  92. "durationToHuman": util.DurationToHuman,
  93. }
  94. //go:embed "index.gohtml"
  95. indexSource string
  96. indexTemplate = template.Must(template.New("index").Funcs(templateFnMap).Parse(indexSource))
  97. //go:embed "example.html"
  98. exampleSource string
  99. //go:embed static
  100. webStaticFs embed.FS
  101. webStaticFsCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: webStaticFs}
  102. //go:embed docs
  103. docsStaticFs embed.FS
  104. docsStaticCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: docsStaticFs}
  105. errHTTPNotFound = &errHTTP{40401, http.StatusNotFound, "page not found", ""}
  106. errHTTPTooManyRequestsLimitRequests = &errHTTP{42901, http.StatusTooManyRequests, "limit reached: too many requests, please be nice", "https://ntfy.sh/docs/publish/#limitations"}
  107. errHTTPTooManyRequestsLimitEmails = &errHTTP{42902, http.StatusTooManyRequests, "limit reached: too many emails, please be nice", "https://ntfy.sh/docs/publish/#limitations"}
  108. errHTTPTooManyRequestsLimitSubscriptions = &errHTTP{42903, http.StatusTooManyRequests, "limit reached: too many active subscriptions, please be nice", "https://ntfy.sh/docs/publish/#limitations"}
  109. errHTTPTooManyRequestsLimitGlobalTopics = &errHTTP{42904, http.StatusTooManyRequests, "limit reached: the total number of topics on the server has been reached, please contact the admin", "https://ntfy.sh/docs/publish/#limitations"}
  110. errHTTPBadRequestEmailDisabled = &errHTTP{40001, http.StatusBadRequest, "e-mail notifications are not enabled", "https://ntfy.sh/docs/config/#e-mail-notifications"}
  111. errHTTPBadRequestDelayNoCache = &errHTTP{40002, http.StatusBadRequest, "cannot disable cache for delayed message", ""}
  112. errHTTPBadRequestDelayNoEmail = &errHTTP{40003, http.StatusBadRequest, "delayed e-mail notifications are not supported", ""}
  113. errHTTPBadRequestDelayCannotParse = &errHTTP{40004, http.StatusBadRequest, "invalid delay parameter: unable to parse delay", "https://ntfy.sh/docs/publish/#scheduled-delivery"}
  114. errHTTPBadRequestDelayTooSmall = &errHTTP{40005, http.StatusBadRequest, "invalid delay parameter: too small, please refer to the docs", "https://ntfy.sh/docs/publish/#scheduled-delivery"}
  115. errHTTPBadRequestDelayTooLarge = &errHTTP{40006, http.StatusBadRequest, "invalid delay parameter: too large, please refer to the docs", "https://ntfy.sh/docs/publish/#scheduled-delivery"}
  116. errHTTPBadRequestPriorityInvalid = &errHTTP{40007, http.StatusBadRequest, "invalid priority parameter", "https://ntfy.sh/docs/publish/#message-priority"}
  117. errHTTPBadRequestSinceInvalid = &errHTTP{40008, http.StatusBadRequest, "invalid since parameter", "https://ntfy.sh/docs/subscribe/api/#fetch-cached-messages"}
  118. errHTTPBadRequestTopicInvalid = &errHTTP{40009, http.StatusBadRequest, "invalid topic: path invalid", ""}
  119. errHTTPBadRequestTopicDisallowed = &errHTTP{40010, http.StatusBadRequest, "invalid topic: topic name is disallowed", ""}
  120. errHTTPBadRequestAttachmentsDisallowed = &errHTTP{40011, http.StatusBadRequest, "attachments disallowed", ""}
  121. errHTTPBadRequestAttachmentsPublishDisallowed = &errHTTP{40011, http.StatusBadRequest, "invalid message: invalid encoding or too large, and attachments are not allowed", ""}
  122. errHTTPBadRequestMessageTooLarge = &errHTTP{40013, http.StatusBadRequest, "invalid message: too large", ""}
  123. errHTTPInternalError = &errHTTP{50001, http.StatusInternalServerError, "internal server error", ""}
  124. errHTTPInternalErrorInvalidFilePath = &errHTTP{50002, http.StatusInternalServerError, "internal server error: invalid file path", ""}
  125. )
  126. const (
  127. firebaseControlTopic = "~control" // See Android if changed
  128. emptyMessageBody = "triggered"
  129. )
  130. // New instantiates a new Server. It creates the cache and adds a Firebase
  131. // subscriber (if configured).
  132. func New(conf *Config) (*Server, error) {
  133. var firebaseSubscriber subscriber
  134. if conf.FirebaseKeyFile != "" {
  135. var err error
  136. firebaseSubscriber, err = createFirebaseSubscriber(conf)
  137. if err != nil {
  138. return nil, err
  139. }
  140. }
  141. var mailer mailer
  142. if conf.SMTPSenderAddr != "" {
  143. mailer = &smtpSender{config: conf}
  144. }
  145. cache, err := createCache(conf)
  146. if err != nil {
  147. return nil, err
  148. }
  149. topics, err := cache.Topics()
  150. if err != nil {
  151. return nil, err
  152. }
  153. if conf.AttachmentCacheDir != "" {
  154. if err := os.MkdirAll(conf.AttachmentCacheDir, 0700); err != nil {
  155. return nil, err
  156. }
  157. }
  158. return &Server{
  159. config: conf,
  160. cache: cache,
  161. firebase: firebaseSubscriber,
  162. mailer: mailer,
  163. topics: topics,
  164. visitors: make(map[string]*visitor),
  165. }, nil
  166. }
  167. func createCache(conf *Config) (cache, error) {
  168. if conf.CacheDuration == 0 {
  169. return newNopCache(), nil
  170. } else if conf.CacheFile != "" {
  171. return newSqliteCache(conf.CacheFile)
  172. }
  173. return newMemCache(), nil
  174. }
  175. func createFirebaseSubscriber(conf *Config) (subscriber, error) {
  176. fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(conf.FirebaseKeyFile))
  177. if err != nil {
  178. return nil, err
  179. }
  180. msg, err := fb.Messaging(context.Background())
  181. if err != nil {
  182. return nil, err
  183. }
  184. return func(m *message) error {
  185. var data map[string]string // Matches https://ntfy.sh/docs/subscribe/api/#json-message-format
  186. switch m.Event {
  187. case keepaliveEvent, openEvent:
  188. data = map[string]string{
  189. "id": m.ID,
  190. "time": fmt.Sprintf("%d", m.Time),
  191. "event": m.Event,
  192. "topic": m.Topic,
  193. }
  194. case messageEvent:
  195. data = map[string]string{
  196. "id": m.ID,
  197. "time": fmt.Sprintf("%d", m.Time),
  198. "event": m.Event,
  199. "topic": m.Topic,
  200. "priority": fmt.Sprintf("%d", m.Priority),
  201. "tags": strings.Join(m.Tags, ","),
  202. "title": m.Title,
  203. "message": m.Message,
  204. }
  205. }
  206. _, err := msg.Send(context.Background(), &messaging.Message{
  207. Topic: m.Topic,
  208. Data: data,
  209. })
  210. return err
  211. }, nil
  212. }
  213. // Run executes the main server. It listens on HTTP (+ HTTPS, if configured), and starts
  214. // a manager go routine to print stats and prune messages.
  215. func (s *Server) Run() error {
  216. listenStr := fmt.Sprintf("%s/http", s.config.ListenHTTP)
  217. if s.config.ListenHTTPS != "" {
  218. listenStr += fmt.Sprintf(" %s/https", s.config.ListenHTTPS)
  219. }
  220. if s.config.SMTPServerListen != "" {
  221. listenStr += fmt.Sprintf(" %s/smtp", s.config.SMTPServerListen)
  222. }
  223. log.Printf("Listening on %s", listenStr)
  224. mux := http.NewServeMux()
  225. mux.HandleFunc("/", s.handle)
  226. errChan := make(chan error)
  227. s.mu.Lock()
  228. s.closeChan = make(chan bool)
  229. s.httpServer = &http.Server{Addr: s.config.ListenHTTP, Handler: mux}
  230. go func() {
  231. errChan <- s.httpServer.ListenAndServe()
  232. }()
  233. if s.config.ListenHTTPS != "" {
  234. s.httpsServer = &http.Server{Addr: s.config.ListenHTTP, Handler: mux}
  235. go func() {
  236. errChan <- s.httpsServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile)
  237. }()
  238. }
  239. if s.config.SMTPServerListen != "" {
  240. go func() {
  241. errChan <- s.runSMTPServer()
  242. }()
  243. }
  244. s.mu.Unlock()
  245. go s.runManager()
  246. go s.runAtSender()
  247. go s.runFirebaseKeepliver()
  248. return <-errChan
  249. }
  250. // Stop stops HTTP (+HTTPS) server and all managers
  251. func (s *Server) Stop() {
  252. s.mu.Lock()
  253. defer s.mu.Unlock()
  254. if s.httpServer != nil {
  255. s.httpServer.Close()
  256. }
  257. if s.httpsServer != nil {
  258. s.httpsServer.Close()
  259. }
  260. if s.smtpServer != nil {
  261. s.smtpServer.Close()
  262. }
  263. close(s.closeChan)
  264. }
  265. func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
  266. if err := s.handleInternal(w, r); err != nil {
  267. var e *errHTTP
  268. var ok bool
  269. if e, ok = err.(*errHTTP); !ok {
  270. e = errHTTPInternalError
  271. }
  272. log.Printf("[%s] %s - %d - %s", r.RemoteAddr, r.Method, e.HTTPCode, err.Error())
  273. w.Header().Set("Content-Type", "application/json")
  274. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  275. w.WriteHeader(e.HTTPCode)
  276. io.WriteString(w, e.JSON()+"\n")
  277. }
  278. }
  279. func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request) error {
  280. if r.Method == http.MethodGet && r.URL.Path == "/" {
  281. return s.handleHome(w, r)
  282. } else if r.Method == http.MethodGet && r.URL.Path == "/example.html" {
  283. return s.handleExample(w, r)
  284. } else if r.Method == http.MethodHead && r.URL.Path == "/" {
  285. return s.handleEmpty(w, r)
  286. } else if r.Method == http.MethodGet && staticRegex.MatchString(r.URL.Path) {
  287. return s.handleStatic(w, r)
  288. } else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) {
  289. return s.handleDocs(w, r)
  290. } else if r.Method == http.MethodGet && fileRegex.MatchString(r.URL.Path) {
  291. return s.handleFile(w, r)
  292. } else if r.Method == http.MethodOptions {
  293. return s.handleOptions(w, r)
  294. } else if r.Method == http.MethodGet && topicPathRegex.MatchString(r.URL.Path) {
  295. return s.handleTopic(w, r)
  296. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicPathRegex.MatchString(r.URL.Path) {
  297. return s.withRateLimit(w, r, s.handlePublish)
  298. } else if r.Method == http.MethodGet && publishPathRegex.MatchString(r.URL.Path) {
  299. return s.withRateLimit(w, r, s.handlePublish)
  300. } else if r.Method == http.MethodGet && jsonPathRegex.MatchString(r.URL.Path) {
  301. return s.withRateLimit(w, r, s.handleSubscribeJSON)
  302. } else if r.Method == http.MethodGet && ssePathRegex.MatchString(r.URL.Path) {
  303. return s.withRateLimit(w, r, s.handleSubscribeSSE)
  304. } else if r.Method == http.MethodGet && rawPathRegex.MatchString(r.URL.Path) {
  305. return s.withRateLimit(w, r, s.handleSubscribeRaw)
  306. }
  307. return errHTTPNotFound
  308. }
  309. func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) error {
  310. return indexTemplate.Execute(w, &indexPage{
  311. Topic: r.URL.Path[1:],
  312. CacheDuration: s.config.CacheDuration,
  313. })
  314. }
  315. func (s *Server) handleTopic(w http.ResponseWriter, r *http.Request) error {
  316. unifiedpush := readParam(r, "x-unifiedpush", "unifiedpush", "up") == "1" // see PUT/POST too!
  317. if unifiedpush {
  318. w.Header().Set("Content-Type", "application/json")
  319. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  320. _, err := io.WriteString(w, `{"unifiedpush":{"version":1}}`+"\n")
  321. return err
  322. }
  323. return s.handleHome(w, r)
  324. }
  325. func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request) error {
  326. return nil
  327. }
  328. func (s *Server) handleExample(w http.ResponseWriter, _ *http.Request) error {
  329. _, err := io.WriteString(w, exampleSource)
  330. return err
  331. }
  332. func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request) error {
  333. http.FileServer(http.FS(webStaticFsCached)).ServeHTTP(w, r)
  334. return nil
  335. }
  336. func (s *Server) handleDocs(w http.ResponseWriter, r *http.Request) error {
  337. http.FileServer(http.FS(docsStaticCached)).ServeHTTP(w, r)
  338. return nil
  339. }
  340. func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) error {
  341. if s.config.AttachmentCacheDir == "" {
  342. return errHTTPBadRequestAttachmentsDisallowed
  343. }
  344. matches := fileRegex.FindStringSubmatch(r.URL.Path)
  345. if len(matches) != 2 {
  346. return errHTTPInternalErrorInvalidFilePath
  347. }
  348. messageID := matches[1]
  349. file := filepath.Join(s.config.AttachmentCacheDir, messageID)
  350. stat, err := os.Stat(file)
  351. if err != nil {
  352. return errHTTPNotFound
  353. }
  354. w.Header().Set("Length", fmt.Sprintf("%d", stat.Size()))
  355. f, err := os.Open(file)
  356. if err != nil {
  357. return err
  358. }
  359. defer f.Close()
  360. _, err = io.Copy(util.NewContentTypeWriter(w), f)
  361. return err
  362. }
  363. func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, v *visitor) error {
  364. t, err := s.topicFromPath(r.URL.Path)
  365. if err != nil {
  366. return err
  367. }
  368. body, err := util.Peak(r.Body, s.config.MessageLimit)
  369. if err != nil {
  370. return err
  371. }
  372. m := newDefaultMessage(t.ID, "")
  373. if !body.LimitReached && utf8.Valid(body.PeakedBytes) {
  374. m.Message = strings.TrimSpace(string(body.PeakedBytes))
  375. } else if err := s.writeAttachment(v, m, body); err != nil {
  376. return err
  377. }
  378. cache, firebase, email, err := s.parsePublishParams(r, m)
  379. if err != nil {
  380. return err
  381. }
  382. if email != "" {
  383. if err := v.EmailAllowed(); err != nil {
  384. return errHTTPTooManyRequestsLimitEmails
  385. }
  386. }
  387. if s.mailer == nil && email != "" {
  388. return errHTTPBadRequestEmailDisabled
  389. }
  390. if m.Message == "" {
  391. m.Message = emptyMessageBody
  392. }
  393. delayed := m.Time > time.Now().Unix()
  394. if !delayed {
  395. if err := t.Publish(m); err != nil {
  396. return err
  397. }
  398. }
  399. if s.firebase != nil && firebase && !delayed {
  400. go func() {
  401. if err := s.firebase(m); err != nil {
  402. log.Printf("Unable to publish to Firebase: %v", err.Error())
  403. }
  404. }()
  405. }
  406. if s.mailer != nil && email != "" && !delayed {
  407. go func() {
  408. if err := s.mailer.Send(v.ip, email, m); err != nil {
  409. log.Printf("Unable to send email: %v", err.Error())
  410. }
  411. }()
  412. }
  413. if cache {
  414. if err := s.cache.AddMessage(m); err != nil {
  415. return err
  416. }
  417. }
  418. w.Header().Set("Content-Type", "application/json")
  419. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  420. if err := json.NewEncoder(w).Encode(m); err != nil {
  421. return err
  422. }
  423. s.inc(&s.messages)
  424. return nil
  425. }
  426. func (s *Server) parsePublishParams(r *http.Request, m *message) (cache bool, firebase bool, email string, err error) {
  427. cache = readParam(r, "x-cache", "cache") != "no"
  428. firebase = readParam(r, "x-firebase", "firebase") != "no"
  429. email = readParam(r, "x-email", "x-e-mail", "email", "e-mail", "mail", "e")
  430. m.Title = readParam(r, "x-title", "title", "t")
  431. messageStr := readParam(r, "x-message", "message", "m")
  432. if messageStr != "" {
  433. m.Message = messageStr
  434. }
  435. m.Priority, err = util.ParsePriority(readParam(r, "x-priority", "priority", "prio", "p"))
  436. if err != nil {
  437. return false, false, "", errHTTPBadRequestPriorityInvalid
  438. }
  439. tagsStr := readParam(r, "x-tags", "tags", "tag", "ta")
  440. if tagsStr != "" {
  441. m.Tags = make([]string, 0)
  442. for _, s := range util.SplitNoEmpty(tagsStr, ",") {
  443. m.Tags = append(m.Tags, strings.TrimSpace(s))
  444. }
  445. }
  446. delayStr := readParam(r, "x-delay", "delay", "x-at", "at", "x-in", "in")
  447. if delayStr != "" {
  448. if !cache {
  449. return false, false, "", errHTTPBadRequestDelayNoCache
  450. }
  451. if email != "" {
  452. return false, false, "", errHTTPBadRequestDelayNoEmail // we cannot store the email address (yet)
  453. }
  454. delay, err := util.ParseFutureTime(delayStr, time.Now())
  455. if err != nil {
  456. return false, false, "", errHTTPBadRequestDelayCannotParse
  457. } else if delay.Unix() < time.Now().Add(s.config.MinDelay).Unix() {
  458. return false, false, "", errHTTPBadRequestDelayTooSmall
  459. } else if delay.Unix() > time.Now().Add(s.config.MaxDelay).Unix() {
  460. return false, false, "", errHTTPBadRequestDelayTooLarge
  461. }
  462. m.Time = delay.Unix()
  463. }
  464. unifiedpush := readParam(r, "x-unifiedpush", "unifiedpush", "up") == "1" // see GET too!
  465. if unifiedpush {
  466. firebase = false
  467. }
  468. return cache, firebase, email, nil
  469. }
  470. func readParam(r *http.Request, names ...string) string {
  471. for _, name := range names {
  472. value := r.Header.Get(name)
  473. if value != "" {
  474. return strings.TrimSpace(value)
  475. }
  476. }
  477. for _, name := range names {
  478. value := r.URL.Query().Get(strings.ToLower(name))
  479. if value != "" {
  480. return strings.TrimSpace(value)
  481. }
  482. }
  483. return ""
  484. }
  485. func (s *Server) writeAttachment(v *visitor, m *message, body *util.PeakedReadCloser) error {
  486. if s.config.AttachmentCacheDir == "" || !util.FileExists(s.config.AttachmentCacheDir) {
  487. return errHTTPBadRequestAttachmentsPublishDisallowed
  488. }
  489. contentType := http.DetectContentType(body.PeakedBytes)
  490. exts, err := mime.ExtensionsByType(contentType)
  491. if err != nil {
  492. return err
  493. }
  494. ext := ".bin"
  495. if len(exts) > 0 {
  496. ext = exts[0]
  497. }
  498. filename := fmt.Sprintf("attachment%s", ext)
  499. file := filepath.Join(s.config.AttachmentCacheDir, m.ID)
  500. f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
  501. if err != nil {
  502. return err
  503. }
  504. defer f.Close()
  505. fileSizeLimiter := util.NewLimiter(s.config.AttachmentSizeLimit)
  506. limitWriter := util.NewLimitWriter(f, fileSizeLimiter)
  507. if _, err := io.Copy(limitWriter, body); err != nil {
  508. os.Remove(file)
  509. if err == util.ErrLimitReached {
  510. return errHTTPBadRequestMessageTooLarge
  511. }
  512. return err
  513. }
  514. if err := f.Close(); err != nil {
  515. os.Remove(file)
  516. return err
  517. }
  518. m.Message = fmt.Sprintf("You received a file: %s", filename)
  519. m.Attachment = &attachment{
  520. Name: filename,
  521. Type: contentType,
  522. URL: fmt.Sprintf("%s/file/%s%s", s.config.BaseURL, m.ID, ext),
  523. }
  524. return nil
  525. }
  526. func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error {
  527. encoder := func(msg *message) (string, error) {
  528. var buf bytes.Buffer
  529. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  530. return "", err
  531. }
  532. return buf.String(), nil
  533. }
  534. return s.handleSubscribe(w, r, v, "json", "application/x-ndjson", encoder)
  535. }
  536. func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error {
  537. encoder := func(msg *message) (string, error) {
  538. var buf bytes.Buffer
  539. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  540. return "", err
  541. }
  542. if msg.Event != messageEvent {
  543. return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this!
  544. }
  545. return fmt.Sprintf("data: %s\n", buf.String()), nil
  546. }
  547. return s.handleSubscribe(w, r, v, "sse", "text/event-stream", encoder)
  548. }
  549. func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error {
  550. encoder := func(msg *message) (string, error) {
  551. if msg.Event == messageEvent { // only handle default events
  552. return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil
  553. }
  554. return "\n", nil // "keepalive" and "open" events just send an empty line
  555. }
  556. return s.handleSubscribe(w, r, v, "raw", "text/plain", encoder)
  557. }
  558. func (s *Server) handleSubscribe(w http.ResponseWriter, r *http.Request, v *visitor, format string, contentType string, encoder messageEncoder) error {
  559. if err := v.SubscriptionAllowed(); err != nil {
  560. return errHTTPTooManyRequestsLimitSubscriptions
  561. }
  562. defer v.RemoveSubscription()
  563. topicsStr := strings.TrimSuffix(r.URL.Path[1:], "/"+format) // Hack
  564. topicIDs := util.SplitNoEmpty(topicsStr, ",")
  565. topics, err := s.topicsFromIDs(topicIDs...)
  566. if err != nil {
  567. return err
  568. }
  569. poll := readParam(r, "x-poll", "poll", "po") == "1"
  570. scheduled := readParam(r, "x-scheduled", "scheduled", "sched") == "1"
  571. since, err := parseSince(r, poll)
  572. if err != nil {
  573. return err
  574. }
  575. messageFilter, titleFilter, priorityFilter, tagsFilter, err := parseQueryFilters(r)
  576. if err != nil {
  577. return err
  578. }
  579. var wlock sync.Mutex
  580. sub := func(msg *message) error {
  581. if !passesQueryFilter(msg, messageFilter, titleFilter, priorityFilter, tagsFilter) {
  582. return nil
  583. }
  584. m, err := encoder(msg)
  585. if err != nil {
  586. return err
  587. }
  588. wlock.Lock()
  589. defer wlock.Unlock()
  590. if _, err := w.Write([]byte(m)); err != nil {
  591. return err
  592. }
  593. if fl, ok := w.(http.Flusher); ok {
  594. fl.Flush()
  595. }
  596. return nil
  597. }
  598. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  599. w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset!
  600. if poll {
  601. return s.sendOldMessages(topics, since, scheduled, sub)
  602. }
  603. subscriberIDs := make([]int, 0)
  604. for _, t := range topics {
  605. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  606. }
  607. defer func() {
  608. for i, subscriberID := range subscriberIDs {
  609. topics[i].Unsubscribe(subscriberID) // Order!
  610. }
  611. }()
  612. if err := sub(newOpenMessage(topicsStr)); err != nil { // Send out open message
  613. return err
  614. }
  615. if err := s.sendOldMessages(topics, since, scheduled, sub); err != nil {
  616. return err
  617. }
  618. for {
  619. select {
  620. case <-r.Context().Done():
  621. return nil
  622. case <-time.After(s.config.KeepaliveInterval):
  623. v.Keepalive()
  624. if err := sub(newKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message
  625. return err
  626. }
  627. }
  628. }
  629. }
  630. func parseQueryFilters(r *http.Request) (messageFilter string, titleFilter string, priorityFilter []int, tagsFilter []string, err error) {
  631. messageFilter = readParam(r, "x-message", "message", "m")
  632. titleFilter = readParam(r, "x-title", "title", "t")
  633. tagsFilter = util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  634. priorityFilter = make([]int, 0)
  635. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  636. priority, err := util.ParsePriority(p)
  637. if err != nil {
  638. return "", "", nil, nil, err
  639. }
  640. priorityFilter = append(priorityFilter, priority)
  641. }
  642. return
  643. }
  644. func passesQueryFilter(msg *message, messageFilter string, titleFilter string, priorityFilter []int, tagsFilter []string) bool {
  645. if msg.Event != messageEvent {
  646. return true // filters only apply to messages
  647. }
  648. if messageFilter != "" && msg.Message != messageFilter {
  649. return false
  650. }
  651. if titleFilter != "" && msg.Title != titleFilter {
  652. return false
  653. }
  654. messagePriority := msg.Priority
  655. if messagePriority == 0 {
  656. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  657. }
  658. if len(priorityFilter) > 0 && !util.InIntList(priorityFilter, messagePriority) {
  659. return false
  660. }
  661. if len(tagsFilter) > 0 && !util.InStringListAll(msg.Tags, tagsFilter) {
  662. return false
  663. }
  664. return true
  665. }
  666. func (s *Server) sendOldMessages(topics []*topic, since sinceTime, scheduled bool, sub subscriber) error {
  667. if since.IsNone() {
  668. return nil
  669. }
  670. for _, t := range topics {
  671. messages, err := s.cache.Messages(t.ID, since, scheduled)
  672. if err != nil {
  673. return err
  674. }
  675. for _, m := range messages {
  676. if err := sub(m); err != nil {
  677. return err
  678. }
  679. }
  680. }
  681. return nil
  682. }
  683. // parseSince returns a timestamp identifying the time span from which cached messages should be received.
  684. //
  685. // Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), or
  686. // "all" for all messages.
  687. func parseSince(r *http.Request, poll bool) (sinceTime, error) {
  688. since := readParam(r, "x-since", "since", "si")
  689. if since == "" {
  690. if poll {
  691. return sinceAllMessages, nil
  692. }
  693. return sinceNoMessages, nil
  694. }
  695. if since == "all" {
  696. return sinceAllMessages, nil
  697. } else if s, err := strconv.ParseInt(since, 10, 64); err == nil {
  698. return sinceTime(time.Unix(s, 0)), nil
  699. } else if d, err := time.ParseDuration(since); err == nil {
  700. return sinceTime(time.Now().Add(-1 * d)), nil
  701. }
  702. return sinceNoMessages, errHTTPBadRequestSinceInvalid
  703. }
  704. func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request) error {
  705. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  706. w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST")
  707. return nil
  708. }
  709. func (s *Server) topicFromPath(path string) (*topic, error) {
  710. parts := strings.Split(path, "/")
  711. if len(parts) < 2 {
  712. return nil, errHTTPBadRequestTopicInvalid
  713. }
  714. topics, err := s.topicsFromIDs(parts[1])
  715. if err != nil {
  716. return nil, err
  717. }
  718. return topics[0], nil
  719. }
  720. func (s *Server) topicsFromIDs(ids ...string) ([]*topic, error) {
  721. s.mu.Lock()
  722. defer s.mu.Unlock()
  723. topics := make([]*topic, 0)
  724. for _, id := range ids {
  725. if util.InStringList(disallowedTopics, id) {
  726. return nil, errHTTPBadRequestTopicDisallowed
  727. }
  728. if _, ok := s.topics[id]; !ok {
  729. if len(s.topics) >= s.config.TotalTopicLimit {
  730. return nil, errHTTPTooManyRequestsLimitGlobalTopics
  731. }
  732. s.topics[id] = newTopic(id)
  733. }
  734. topics = append(topics, s.topics[id])
  735. }
  736. return topics, nil
  737. }
  738. func (s *Server) updateStatsAndPrune() {
  739. s.mu.Lock()
  740. defer s.mu.Unlock()
  741. // Expire visitors from rate visitors map
  742. for ip, v := range s.visitors {
  743. if v.Stale() {
  744. delete(s.visitors, ip)
  745. }
  746. }
  747. // Prune message cache
  748. olderThan := time.Now().Add(-1 * s.config.CacheDuration)
  749. if err := s.cache.Prune(olderThan); err != nil {
  750. log.Printf("error pruning cache: %s", err.Error())
  751. }
  752. // Prune old topics, remove subscriptions without subscribers
  753. var subscribers, messages int
  754. for _, t := range s.topics {
  755. subs := t.Subscribers()
  756. msgs, err := s.cache.MessageCount(t.ID)
  757. if err != nil {
  758. log.Printf("cannot get stats for topic %s: %s", t.ID, err.Error())
  759. continue
  760. }
  761. if msgs == 0 && subs == 0 {
  762. delete(s.topics, t.ID)
  763. continue
  764. }
  765. subscribers += subs
  766. messages += msgs
  767. }
  768. // Mail stats
  769. var mailSuccess, mailFailure int64
  770. if s.smtpBackend != nil {
  771. mailSuccess, mailFailure = s.smtpBackend.Counts()
  772. }
  773. // Print stats
  774. log.Printf("Stats: %d message(s) published, %d in cache, %d successful mails, %d failed, %d topic(s) active, %d subscriber(s), %d visitor(s)",
  775. s.messages, messages, mailSuccess, mailFailure, len(s.topics), subscribers, len(s.visitors))
  776. }
  777. func (s *Server) runSMTPServer() error {
  778. sub := func(m *message) error {
  779. url := fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic)
  780. req, err := http.NewRequest("PUT", url, strings.NewReader(m.Message))
  781. if err != nil {
  782. return err
  783. }
  784. if m.Title != "" {
  785. req.Header.Set("Title", m.Title)
  786. }
  787. rr := httptest.NewRecorder()
  788. s.handle(rr, req)
  789. if rr.Code != http.StatusOK {
  790. return errors.New("error: " + rr.Body.String())
  791. }
  792. return nil
  793. }
  794. s.smtpBackend = newMailBackend(s.config, sub)
  795. s.smtpServer = smtp.NewServer(s.smtpBackend)
  796. s.smtpServer.Addr = s.config.SMTPServerListen
  797. s.smtpServer.Domain = s.config.SMTPServerDomain
  798. s.smtpServer.ReadTimeout = 10 * time.Second
  799. s.smtpServer.WriteTimeout = 10 * time.Second
  800. s.smtpServer.MaxMessageBytes = 1024 * 1024 // Must be much larger than message size (headers, multipart, etc.)
  801. s.smtpServer.MaxRecipients = 1
  802. s.smtpServer.AllowInsecureAuth = true
  803. return s.smtpServer.ListenAndServe()
  804. }
  805. func (s *Server) runManager() {
  806. for {
  807. select {
  808. case <-time.After(s.config.ManagerInterval):
  809. s.updateStatsAndPrune()
  810. case <-s.closeChan:
  811. return
  812. }
  813. }
  814. }
  815. func (s *Server) runAtSender() {
  816. for {
  817. select {
  818. case <-time.After(s.config.AtSenderInterval):
  819. if err := s.sendDelayedMessages(); err != nil {
  820. log.Printf("error sending scheduled messages: %s", err.Error())
  821. }
  822. case <-s.closeChan:
  823. return
  824. }
  825. }
  826. }
  827. func (s *Server) runFirebaseKeepliver() {
  828. if s.firebase == nil {
  829. return
  830. }
  831. for {
  832. select {
  833. case <-time.After(s.config.FirebaseKeepaliveInterval):
  834. if err := s.firebase(newKeepaliveMessage(firebaseControlTopic)); err != nil {
  835. log.Printf("error sending Firebase keepalive message: %s", err.Error())
  836. }
  837. case <-s.closeChan:
  838. return
  839. }
  840. }
  841. }
  842. func (s *Server) sendDelayedMessages() error {
  843. s.mu.Lock()
  844. defer s.mu.Unlock()
  845. messages, err := s.cache.MessagesDue()
  846. if err != nil {
  847. return err
  848. }
  849. for _, m := range messages {
  850. t, ok := s.topics[m.Topic] // If no subscribers, just mark message as published
  851. if ok {
  852. if err := t.Publish(m); err != nil {
  853. log.Printf("unable to publish message %s to topic %s: %v", m.ID, m.Topic, err.Error())
  854. }
  855. if s.firebase != nil {
  856. if err := s.firebase(m); err != nil {
  857. log.Printf("unable to publish to Firebase: %v", err.Error())
  858. }
  859. }
  860. // TODO delayed email sending
  861. }
  862. if err := s.cache.MarkPublished(m); err != nil {
  863. return err
  864. }
  865. }
  866. return nil
  867. }
  868. func (s *Server) withRateLimit(w http.ResponseWriter, r *http.Request, handler func(w http.ResponseWriter, r *http.Request, v *visitor) error) error {
  869. v := s.visitor(r)
  870. if err := v.RequestAllowed(); err != nil {
  871. return errHTTPTooManyRequestsLimitRequests
  872. }
  873. return handler(w, r, v)
  874. }
  875. // visitor creates or retrieves a rate.Limiter for the given visitor.
  876. // This function was taken from https://www.alexedwards.net/blog/how-to-rate-limit-http-requests (MIT).
  877. func (s *Server) visitor(r *http.Request) *visitor {
  878. s.mu.Lock()
  879. defer s.mu.Unlock()
  880. remoteAddr := r.RemoteAddr
  881. ip, _, err := net.SplitHostPort(remoteAddr)
  882. if err != nil {
  883. ip = remoteAddr // This should not happen in real life; only in tests.
  884. }
  885. if s.config.BehindProxy && r.Header.Get("X-Forwarded-For") != "" {
  886. ip = r.Header.Get("X-Forwarded-For")
  887. }
  888. v, exists := s.visitors[ip]
  889. if !exists {
  890. s.visitors[ip] = newVisitor(s.config, ip)
  891. return s.visitors[ip]
  892. }
  893. v.Keepalive()
  894. return v
  895. }
  896. func (s *Server) inc(counter *int64) {
  897. s.mu.Lock()
  898. defer s.mu.Unlock()
  899. *counter++
  900. }