server.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "embed"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "net"
  13. "net/http"
  14. "net/http/httptest"
  15. "net/url"
  16. "os"
  17. "path"
  18. "path/filepath"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. "unicode/utf8"
  25. "github.com/emersion/go-smtp"
  26. "github.com/gorilla/websocket"
  27. "golang.org/x/sync/errgroup"
  28. "heckel.io/ntfy/auth"
  29. "heckel.io/ntfy/util"
  30. )
  31. // Server is the main server, providing the UI and API for ntfy
  32. type Server struct {
  33. config *Config
  34. httpServer *http.Server
  35. httpsServer *http.Server
  36. unixListener net.Listener
  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. auth auth.Auther
  45. messageCache *messageCache
  46. fileCache *fileCache
  47. closeChan chan bool
  48. mu sync.Mutex
  49. }
  50. // handleFunc extends the normal http.HandlerFunc to be able to easily return errors
  51. type handleFunc func(http.ResponseWriter, *http.Request, *visitor) error
  52. var (
  53. // If changed, don't forget to update Android App and auth_sqlite.go
  54. topicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No /!
  55. topicPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}$`) // Regex must match JS & Android app!
  56. updatePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/[^/]+$`)
  57. externalTopicPathRegex = regexp.MustCompile(`^/[^/]+\.[^/]+/[-_A-Za-z0-9]{1,64}$`) // Extended topic path, for web-app, e.g. /example.com/mytopic
  58. jsonPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/json$`)
  59. ssePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/sse$`)
  60. rawPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/raw$`)
  61. wsPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/ws$`)
  62. authPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/auth$`)
  63. publishPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/(publish|send|trigger)$`)
  64. webConfigPath = "/config.js"
  65. userStatsPath = "/user/stats"
  66. staticRegex = regexp.MustCompile(`^/static/.+`)
  67. docsRegex = regexp.MustCompile(`^/docs(|/.*)$`)
  68. fileRegex = regexp.MustCompile(`^/file/([-_A-Za-z0-9]{1,64})(?:\.[A-Za-z0-9]{1,16})?$`)
  69. disallowedTopics = []string{"docs", "static", "file", "app", "settings"} // If updated, also update in Android app
  70. attachURLRegex = regexp.MustCompile(`^https?://`)
  71. //go:embed "example.html"
  72. exampleSource string
  73. //go:embed site
  74. webFs embed.FS
  75. webFsCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: webFs}
  76. webSiteDir = "/site"
  77. webHomeIndex = "/home.html" // Landing page, only if "web-root: home"
  78. webAppIndex = "/app.html" // React app
  79. //go:embed docs
  80. docsStaticFs embed.FS
  81. docsStaticCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: docsStaticFs}
  82. )
  83. const (
  84. firebaseControlTopic = "~control" // See Android if changed
  85. emptyMessageBody = "triggered" // Used if message body is empty
  86. defaultAttachmentMessage = "You received a file: %s" // Used if message body is empty, and there is an attachment
  87. encodingBase64 = "base64"
  88. )
  89. // WebSocket constants
  90. const (
  91. wsWriteWait = 2 * time.Second
  92. wsBufferSize = 1024
  93. wsReadLimit = 64 // We only ever receive PINGs
  94. wsPongWait = 15 * time.Second
  95. )
  96. // New instantiates a new Server. It creates the cache and adds a Firebase
  97. // subscriber (if configured).
  98. func New(conf *Config) (*Server, error) {
  99. var mailer mailer
  100. if conf.SMTPSenderAddr != "" {
  101. mailer = &smtpSender{config: conf}
  102. }
  103. messageCache, err := createMessageCache(conf)
  104. if err != nil {
  105. return nil, err
  106. }
  107. topics, err := messageCache.Topics()
  108. if err != nil {
  109. return nil, err
  110. }
  111. var fileCache *fileCache
  112. if conf.AttachmentCacheDir != "" {
  113. fileCache, err = newFileCache(conf.AttachmentCacheDir, conf.AttachmentTotalSizeLimit, conf.AttachmentFileSizeLimit)
  114. if err != nil {
  115. return nil, err
  116. }
  117. }
  118. var auther auth.Auther
  119. if conf.AuthFile != "" {
  120. auther, err = auth.NewSQLiteAuth(conf.AuthFile, conf.AuthDefaultRead, conf.AuthDefaultWrite)
  121. if err != nil {
  122. return nil, err
  123. }
  124. }
  125. var firebaseSubscriber subscriber
  126. if conf.FirebaseKeyFile != "" {
  127. var err error
  128. firebaseSubscriber, err = createFirebaseSubscriber(conf.FirebaseKeyFile, auther)
  129. if err != nil {
  130. return nil, err
  131. }
  132. }
  133. return &Server{
  134. config: conf,
  135. messageCache: messageCache,
  136. fileCache: fileCache,
  137. firebase: firebaseSubscriber,
  138. mailer: mailer,
  139. topics: topics,
  140. auth: auther,
  141. visitors: make(map[string]*visitor),
  142. }, nil
  143. }
  144. func createMessageCache(conf *Config) (*messageCache, error) {
  145. if conf.CacheDuration == 0 {
  146. return newNopCache()
  147. } else if conf.CacheFile != "" {
  148. return newSqliteCache(conf.CacheFile, false)
  149. }
  150. return newMemCache()
  151. }
  152. // Run executes the main server. It listens on HTTP (+ HTTPS, if configured), and starts
  153. // a manager go routine to print stats and prune messages.
  154. func (s *Server) Run() error {
  155. var listenStr string
  156. if s.config.ListenHTTP != "" {
  157. listenStr += fmt.Sprintf(" %s[http]", s.config.ListenHTTP)
  158. }
  159. if s.config.ListenHTTPS != "" {
  160. listenStr += fmt.Sprintf(" %s[https]", s.config.ListenHTTPS)
  161. }
  162. if s.config.ListenUnix != "" {
  163. listenStr += fmt.Sprintf(" %s[unix]", s.config.ListenUnix)
  164. }
  165. if s.config.SMTPServerListen != "" {
  166. listenStr += fmt.Sprintf(" %s[smtp]", s.config.SMTPServerListen)
  167. }
  168. log.Printf("Listening on%s", listenStr)
  169. mux := http.NewServeMux()
  170. mux.HandleFunc("/", s.handle)
  171. errChan := make(chan error)
  172. s.mu.Lock()
  173. s.closeChan = make(chan bool)
  174. if s.config.ListenHTTP != "" {
  175. s.httpServer = &http.Server{Addr: s.config.ListenHTTP, Handler: mux}
  176. go func() {
  177. errChan <- s.httpServer.ListenAndServe()
  178. }()
  179. }
  180. if s.config.ListenHTTPS != "" {
  181. s.httpsServer = &http.Server{Addr: s.config.ListenHTTPS, Handler: mux}
  182. go func() {
  183. errChan <- s.httpsServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile)
  184. }()
  185. }
  186. if s.config.ListenUnix != "" {
  187. go func() {
  188. var err error
  189. s.mu.Lock()
  190. os.Remove(s.config.ListenUnix)
  191. s.unixListener, err = net.Listen("unix", s.config.ListenUnix)
  192. if err != nil {
  193. errChan <- err
  194. return
  195. }
  196. s.mu.Unlock()
  197. httpServer := &http.Server{Handler: mux}
  198. errChan <- httpServer.Serve(s.unixListener)
  199. }()
  200. }
  201. if s.config.SMTPServerListen != "" {
  202. go func() {
  203. errChan <- s.runSMTPServer()
  204. }()
  205. }
  206. s.mu.Unlock()
  207. go s.runManager()
  208. go s.runAtSender()
  209. go s.runFirebaseKeepaliver()
  210. return <-errChan
  211. }
  212. // Stop stops HTTP (+HTTPS) server and all managers
  213. func (s *Server) Stop() {
  214. s.mu.Lock()
  215. defer s.mu.Unlock()
  216. if s.httpServer != nil {
  217. s.httpServer.Close()
  218. }
  219. if s.httpsServer != nil {
  220. s.httpsServer.Close()
  221. }
  222. if s.unixListener != nil {
  223. s.unixListener.Close()
  224. }
  225. if s.smtpServer != nil {
  226. s.smtpServer.Close()
  227. }
  228. close(s.closeChan)
  229. }
  230. func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
  231. v := s.visitor(r)
  232. if err := s.handleInternal(w, r, v); err != nil {
  233. if websocket.IsWebSocketUpgrade(r) {
  234. log.Printf("[%s] WS %s %s - %s", v.ip, r.Method, r.URL.Path, err.Error())
  235. return // Do not attempt to write to upgraded connection
  236. }
  237. httpErr, ok := err.(*errHTTP)
  238. if !ok {
  239. httpErr = errHTTPInternalError
  240. }
  241. log.Printf("[%s] HTTP %s %s - %d - %d - %s", v.ip, r.Method, r.URL.Path, httpErr.HTTPCode, httpErr.Code, err.Error())
  242. w.Header().Set("Content-Type", "application/json")
  243. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  244. w.WriteHeader(httpErr.HTTPCode)
  245. io.WriteString(w, httpErr.JSON()+"\n")
  246. }
  247. }
  248. func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request, v *visitor) error {
  249. if r.Method == http.MethodGet && r.URL.Path == "/" {
  250. return s.ensureWebEnabled(s.handleHome)(w, r, v)
  251. } else if r.Method == http.MethodGet && r.URL.Path == "/example.html" {
  252. return s.ensureWebEnabled(s.handleExample)(w, r, v)
  253. } else if r.Method == http.MethodHead && r.URL.Path == "/" {
  254. return s.ensureWebEnabled(s.handleEmpty)(w, r, v)
  255. } else if r.Method == http.MethodGet && r.URL.Path == webConfigPath {
  256. return s.ensureWebEnabled(s.handleWebConfig)(w, r, v)
  257. } else if r.Method == http.MethodGet && r.URL.Path == userStatsPath {
  258. return s.handleUserStats(w, r, v)
  259. } else if r.Method == http.MethodGet && staticRegex.MatchString(r.URL.Path) {
  260. return s.ensureWebEnabled(s.handleStatic)(w, r, v)
  261. } else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) {
  262. return s.ensureWebEnabled(s.handleDocs)(w, r, v)
  263. } else if r.Method == http.MethodGet && fileRegex.MatchString(r.URL.Path) && s.config.AttachmentCacheDir != "" {
  264. return s.limitRequests(s.handleFile)(w, r, v)
  265. } else if r.Method == http.MethodOptions {
  266. return s.ensureWebEnabled(s.handleOptions)(w, r, v)
  267. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && r.URL.Path == "/" {
  268. return s.limitRequests(s.transformBodyJSON(s.authWrite(s.handlePublish)))(w, r, v)
  269. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicPathRegex.MatchString(r.URL.Path) {
  270. return s.limitRequests(s.authWrite(s.handlePublish))(w, r, v)
  271. } else if r.Method == http.MethodGet && publishPathRegex.MatchString(r.URL.Path) {
  272. return s.limitRequests(s.authWrite(s.handlePublish))(w, r, v)
  273. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && updatePathRegex.MatchString(r.URL.Path) {
  274. return s.limitRequests(s.authWrite(s.handleUpdate))(w, r, v)
  275. } else if r.Method == http.MethodGet && jsonPathRegex.MatchString(r.URL.Path) {
  276. return s.limitRequests(s.authRead(s.handleSubscribeJSON))(w, r, v)
  277. } else if r.Method == http.MethodGet && ssePathRegex.MatchString(r.URL.Path) {
  278. return s.limitRequests(s.authRead(s.handleSubscribeSSE))(w, r, v)
  279. } else if r.Method == http.MethodGet && rawPathRegex.MatchString(r.URL.Path) {
  280. return s.limitRequests(s.authRead(s.handleSubscribeRaw))(w, r, v)
  281. } else if r.Method == http.MethodGet && wsPathRegex.MatchString(r.URL.Path) {
  282. return s.limitRequests(s.authRead(s.handleSubscribeWS))(w, r, v)
  283. } else if r.Method == http.MethodGet && authPathRegex.MatchString(r.URL.Path) {
  284. return s.limitRequests(s.authRead(s.handleTopicAuth))(w, r, v)
  285. } else if r.Method == http.MethodGet && (topicPathRegex.MatchString(r.URL.Path) || externalTopicPathRegex.MatchString(r.URL.Path)) {
  286. return s.ensureWebEnabled(s.handleTopic)(w, r, v)
  287. }
  288. return errHTTPNotFound
  289. }
  290. func (s *Server) handleHome(w http.ResponseWriter, r *http.Request, v *visitor) error {
  291. if s.config.WebRootIsApp {
  292. r.URL.Path = webAppIndex
  293. } else {
  294. r.URL.Path = webHomeIndex
  295. }
  296. return s.handleStatic(w, r, v)
  297. }
  298. func (s *Server) handleTopic(w http.ResponseWriter, r *http.Request, v *visitor) error {
  299. unifiedpush := readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see PUT/POST too!
  300. if unifiedpush {
  301. w.Header().Set("Content-Type", "application/json")
  302. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  303. _, err := io.WriteString(w, `{"unifiedpush":{"version":1}}`+"\n")
  304. return err
  305. }
  306. r.URL.Path = webAppIndex
  307. return s.handleStatic(w, r, v)
  308. }
  309. func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request, _ *visitor) error {
  310. return nil
  311. }
  312. func (s *Server) handleTopicAuth(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  313. w.Header().Set("Content-Type", "application/json")
  314. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  315. _, err := io.WriteString(w, `{"success":true}`+"\n")
  316. return err
  317. }
  318. func (s *Server) handleExample(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  319. _, err := io.WriteString(w, exampleSource)
  320. return err
  321. }
  322. func (s *Server) handleWebConfig(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  323. appRoot := "/"
  324. if !s.config.WebRootIsApp {
  325. appRoot = "/app"
  326. }
  327. disallowedTopicsStr := `"` + strings.Join(disallowedTopics, `", "`) + `"`
  328. w.Header().Set("Content-Type", "text/javascript")
  329. _, err := io.WriteString(w, fmt.Sprintf(`// Generated server configuration
  330. var config = {
  331. appRoot: "%s",
  332. disallowedTopics: [%s]
  333. };`, appRoot, disallowedTopicsStr))
  334. return err
  335. }
  336. func (s *Server) handleUserStats(w http.ResponseWriter, r *http.Request, v *visitor) error {
  337. stats, err := v.Stats()
  338. if err != nil {
  339. return err
  340. }
  341. w.Header().Set("Content-Type", "text/json")
  342. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  343. if err := json.NewEncoder(w).Encode(stats); err != nil {
  344. return err
  345. }
  346. return nil
  347. }
  348. func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  349. r.URL.Path = webSiteDir + r.URL.Path
  350. util.Gzip(http.FileServer(http.FS(webFsCached))).ServeHTTP(w, r)
  351. return nil
  352. }
  353. func (s *Server) handleDocs(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  354. util.Gzip(http.FileServer(http.FS(docsStaticCached))).ServeHTTP(w, r)
  355. return nil
  356. }
  357. func (s *Server) handleFile(w http.ResponseWriter, r *http.Request, v *visitor) error {
  358. if s.config.AttachmentCacheDir == "" {
  359. return errHTTPInternalError
  360. }
  361. matches := fileRegex.FindStringSubmatch(r.URL.Path)
  362. if len(matches) != 2 {
  363. return errHTTPInternalErrorInvalidFilePath
  364. }
  365. messageID := matches[1]
  366. file := filepath.Join(s.config.AttachmentCacheDir, messageID)
  367. stat, err := os.Stat(file)
  368. if err != nil {
  369. return errHTTPNotFound
  370. }
  371. if err := v.BandwidthLimiter().Allow(stat.Size()); err != nil {
  372. return errHTTPTooManyRequestsAttachmentBandwidthLimit
  373. }
  374. w.Header().Set("Content-Length", fmt.Sprintf("%d", stat.Size()))
  375. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  376. f, err := os.Open(file)
  377. if err != nil {
  378. return err
  379. }
  380. defer f.Close()
  381. _, err = io.Copy(util.NewContentTypeWriter(w, r.URL.Path), f)
  382. return err
  383. }
  384. func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, v *visitor) error {
  385. t, err := s.topicFromPath(r.URL.Path)
  386. if err != nil {
  387. return err
  388. }
  389. body, err := util.Peek(r.Body, s.config.MessageLimit)
  390. if err != nil {
  391. return err
  392. }
  393. m := newDefaultMessage(t.ID, "")
  394. cache, firebase, email, unifiedpush, err := s.parsePublishParams(r, v, m)
  395. if err != nil {
  396. return err
  397. }
  398. if err := s.handlePublishBody(r, v, m, body, unifiedpush); err != nil {
  399. return err
  400. }
  401. if m.Message == "" {
  402. m.Message = emptyMessageBody
  403. }
  404. delayed := m.Time > time.Now().Unix()
  405. if !delayed {
  406. if err := t.Publish(m); err != nil {
  407. return err
  408. }
  409. }
  410. if s.firebase != nil && firebase && !delayed {
  411. go func() {
  412. if err := s.firebase(m); err != nil {
  413. log.Printf("[%s] FB - Unable to publish to Firebase: %v", v.ip, err.Error())
  414. }
  415. }()
  416. }
  417. if s.mailer != nil && email != "" && !delayed {
  418. go func() {
  419. if err := s.mailer.Send(v.ip, email, m); err != nil {
  420. log.Printf("[%s] MAIL - Unable to send email: %v", v.ip, err.Error())
  421. }
  422. }()
  423. }
  424. if cache {
  425. if err := s.messageCache.AddMessage(m); err != nil {
  426. return err
  427. }
  428. }
  429. w.Header().Set("Content-Type", "application/json")
  430. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  431. if err := json.NewEncoder(w).Encode(m); err != nil {
  432. return err
  433. }
  434. s.mu.Lock()
  435. s.messages++
  436. s.mu.Unlock()
  437. return nil
  438. }
  439. func (s *Server) parsePublishParams(r *http.Request, v *visitor, m *message) (cache bool, firebase bool, email string, unifiedpush bool, err error) {
  440. cache = readBoolParam(r, true, "x-cache", "cache")
  441. firebase = readBoolParam(r, true, "x-firebase", "firebase")
  442. m.Title = readParam(r, "x-title", "title", "t")
  443. m.Click = readParam(r, "x-click", "click")
  444. filename := readParam(r, "x-filename", "filename", "file", "f")
  445. attach := readParam(r, "x-attach", "attach", "a")
  446. if attach != "" || filename != "" {
  447. m.Attachment = &attachment{}
  448. }
  449. if filename != "" {
  450. m.Attachment.Name = filename
  451. }
  452. if attach != "" {
  453. if !attachURLRegex.MatchString(attach) {
  454. return false, false, "", false, errHTTPBadRequestAttachmentURLInvalid
  455. }
  456. m.Attachment.URL = attach
  457. if m.Attachment.Name == "" {
  458. u, err := url.Parse(m.Attachment.URL)
  459. if err == nil {
  460. m.Attachment.Name = path.Base(u.Path)
  461. if m.Attachment.Name == "." || m.Attachment.Name == "/" {
  462. m.Attachment.Name = ""
  463. }
  464. }
  465. }
  466. if m.Attachment.Name == "" {
  467. m.Attachment.Name = "attachment"
  468. }
  469. }
  470. email = readParam(r, "x-email", "x-e-mail", "email", "e-mail", "mail", "e")
  471. if email != "" {
  472. if err := v.EmailAllowed(); err != nil {
  473. return false, false, "", false, errHTTPTooManyRequestsLimitEmails
  474. }
  475. }
  476. if s.mailer == nil && email != "" {
  477. return false, false, "", false, errHTTPBadRequestEmailDisabled
  478. }
  479. messageStr := strings.ReplaceAll(readParam(r, "x-message", "message", "m"), "\\n", "\n")
  480. if messageStr != "" {
  481. m.Message = messageStr
  482. }
  483. m.Priority, err = util.ParsePriority(readParam(r, "x-priority", "priority", "prio", "p"))
  484. if err != nil {
  485. return false, false, "", false, errHTTPBadRequestPriorityInvalid
  486. }
  487. tagsStr := readParam(r, "x-tags", "tags", "tag", "ta")
  488. if tagsStr != "" {
  489. m.Tags = make([]string, 0)
  490. for _, s := range util.SplitNoEmpty(tagsStr, ",") {
  491. m.Tags = append(m.Tags, strings.TrimSpace(s))
  492. }
  493. }
  494. delayStr := readDelayParam(r)
  495. if delayStr != "" {
  496. if !cache {
  497. return false, false, "", false, errHTTPBadRequestDelayNoCache
  498. }
  499. if email != "" {
  500. return false, false, "", false, errHTTPBadRequestDelayNoEmail // we cannot store the email address (yet)
  501. }
  502. futureTime, err := s.parseDelay(delayStr)
  503. if err != nil {
  504. return false, false, "", false, err
  505. }
  506. m.Time = futureTime
  507. }
  508. actionsStr := readParam(r, "x-actions", "actions", "action")
  509. if actionsStr != "" {
  510. m.Actions, err = parseActions(actionsStr)
  511. if err != nil {
  512. return false, false, "", false, wrapErrHTTP(errHTTPBadRequestActionsInvalid, err.Error())
  513. }
  514. }
  515. unifiedpush = readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see GET too!
  516. if unifiedpush {
  517. firebase = false
  518. unifiedpush = true
  519. }
  520. return cache, firebase, email, unifiedpush, nil
  521. }
  522. func readDelayParam(r *http.Request) string {
  523. return readParam(r, "x-delay", "delay", "x-at", "at", "x-in", "in")
  524. }
  525. func (s *Server) parseDelay(delayStr string) (int64, error) {
  526. futureTime, err := util.ParseFutureTime(delayStr, time.Now())
  527. if err != nil {
  528. return 0, errHTTPBadRequestDelayCannotParse
  529. } else if futureTime.Unix() < time.Now().Add(s.config.MinDelay).Unix() {
  530. return 0, errHTTPBadRequestDelayTooSmall
  531. } else if futureTime.Unix() > time.Now().Add(s.config.MaxDelay).Unix() {
  532. return 0, errHTTPBadRequestDelayTooLarge
  533. }
  534. return futureTime.Unix(), nil
  535. }
  536. // handlePublishBody consumes the PUT/POST body and decides whether the body is an attachment or the message.
  537. //
  538. // 1. curl -T somebinarydata.bin "ntfy.sh/mytopic?up=1"
  539. // If body is binary, encode as base64, if not do not encode
  540. // 2. curl -H "Attach: http://example.com/file.jpg" ntfy.sh/mytopic
  541. // Body must be a message, because we attached an external URL
  542. // 3. curl -T short.txt -H "Filename: short.txt" ntfy.sh/mytopic
  543. // Body must be attachment, because we passed a filename
  544. // 4. curl -T file.txt ntfy.sh/mytopic
  545. // If file.txt is <= 4096 (message limit) and valid UTF-8, treat it as a message
  546. // 5. curl -T file.txt ntfy.sh/mytopic
  547. // If file.txt is > message limit, treat it as an attachment
  548. func (s *Server) handlePublishBody(r *http.Request, v *visitor, m *message, body *util.PeekedReadCloser, unifiedpush bool) error {
  549. if unifiedpush {
  550. return s.handleBodyAsMessageAutoDetect(m, body) // Case 1
  551. } else if m.Attachment != nil && m.Attachment.URL != "" {
  552. return s.handleBodyAsTextMessage(m, body) // Case 2
  553. } else if m.Attachment != nil && m.Attachment.Name != "" {
  554. return s.handleBodyAsAttachment(r, v, m, body) // Case 3
  555. } else if !body.LimitReached && utf8.Valid(body.PeekedBytes) {
  556. return s.handleBodyAsTextMessage(m, body) // Case 4
  557. }
  558. return s.handleBodyAsAttachment(r, v, m, body) // Case 5
  559. }
  560. func (s *Server) handleBodyAsMessageAutoDetect(m *message, body *util.PeekedReadCloser) error {
  561. if utf8.Valid(body.PeekedBytes) {
  562. m.Message = string(body.PeekedBytes) // Do not trim
  563. } else {
  564. m.Message = base64.StdEncoding.EncodeToString(body.PeekedBytes)
  565. m.Encoding = encodingBase64
  566. }
  567. return nil
  568. }
  569. func (s *Server) handleBodyAsTextMessage(m *message, body *util.PeekedReadCloser) error {
  570. if !utf8.Valid(body.PeekedBytes) {
  571. return errHTTPBadRequestMessageNotUTF8
  572. }
  573. if len(body.PeekedBytes) > 0 { // Empty body should not override message (publish via GET!)
  574. m.Message = strings.TrimSpace(string(body.PeekedBytes)) // Truncates the message to the peek limit if required
  575. }
  576. if m.Attachment != nil && m.Attachment.Name != "" && m.Message == "" {
  577. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  578. }
  579. return nil
  580. }
  581. func (s *Server) handleBodyAsAttachment(r *http.Request, v *visitor, m *message, body *util.PeekedReadCloser) error {
  582. if s.fileCache == nil || s.config.BaseURL == "" || s.config.AttachmentCacheDir == "" {
  583. return errHTTPBadRequestAttachmentsDisallowed
  584. } else if m.Time > time.Now().Add(s.config.AttachmentExpiryDuration).Unix() {
  585. return errHTTPBadRequestAttachmentsExpiryBeforeDelivery
  586. }
  587. visitorStats, err := v.Stats()
  588. if err != nil {
  589. return err
  590. }
  591. contentLengthStr := r.Header.Get("Content-Length")
  592. if contentLengthStr != "" { // Early "do-not-trust" check, hard limit see below
  593. contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
  594. if err == nil && (contentLength > visitorStats.VisitorAttachmentBytesRemaining || contentLength > s.config.AttachmentFileSizeLimit) {
  595. return errHTTPEntityTooLargeAttachmentTooLarge
  596. }
  597. }
  598. if m.Attachment == nil {
  599. m.Attachment = &attachment{}
  600. }
  601. var ext string
  602. m.Attachment.Owner = v.ip // Important for attachment rate limiting
  603. m.Attachment.Expires = time.Now().Add(s.config.AttachmentExpiryDuration).Unix()
  604. m.Attachment.Type, ext = util.DetectContentType(body.PeekedBytes, m.Attachment.Name)
  605. m.Attachment.URL = fmt.Sprintf("%s/file/%s%s", s.config.BaseURL, m.ID, ext)
  606. if m.Attachment.Name == "" {
  607. m.Attachment.Name = fmt.Sprintf("attachment%s", ext)
  608. }
  609. if m.Message == "" {
  610. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  611. }
  612. m.Attachment.Size, err = s.fileCache.Write(m.ID, body, v.BandwidthLimiter(), util.NewFixedLimiter(visitorStats.VisitorAttachmentBytesRemaining))
  613. if err == util.ErrLimitReached {
  614. return errHTTPEntityTooLargeAttachmentTooLarge
  615. } else if err != nil {
  616. return err
  617. }
  618. return nil
  619. }
  620. func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  621. // Parse updatable params
  622. parts := strings.Split(r.URL.Path, "/")
  623. if len(parts) < 3 {
  624. return errHTTPBadRequestTopicInvalid
  625. }
  626. t := parts[1]
  627. selector := parts[2]
  628. delayStr := readDelayParam(r)
  629. if delayStr == "" {
  630. return errHTTPBadRequestDelayExpected
  631. }
  632. futureTime, err := s.parseDelay(delayStr)
  633. if err != nil {
  634. return err
  635. }
  636. // Update matching message(s) and print them
  637. messages, err := s.messageCache.MessagesScheduledByTagOrID(t, selector)
  638. if err != nil {
  639. return err
  640. } else if len(messages) == 0 {
  641. return s.handlePublish(w, r, v) // If no messages found, publish a new one!
  642. }
  643. for _, m := range messages {
  644. m.Time = futureTime
  645. if err := s.messageCache.UpdateMessage(m); err != nil {
  646. return err
  647. }
  648. }
  649. w.Header().Set("Content-Type", "application/json")
  650. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  651. for _, m := range messages {
  652. if err := json.NewEncoder(w).Encode(m); err != nil {
  653. return err
  654. }
  655. }
  656. return nil
  657. }
  658. func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error {
  659. encoder := func(msg *message) (string, error) {
  660. var buf bytes.Buffer
  661. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  662. return "", err
  663. }
  664. return buf.String(), nil
  665. }
  666. return s.handleSubscribeHTTP(w, r, v, "application/x-ndjson", encoder)
  667. }
  668. func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error {
  669. encoder := func(msg *message) (string, error) {
  670. var buf bytes.Buffer
  671. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  672. return "", err
  673. }
  674. if msg.Event != messageEvent {
  675. return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this!
  676. }
  677. return fmt.Sprintf("data: %s\n", buf.String()), nil
  678. }
  679. return s.handleSubscribeHTTP(w, r, v, "text/event-stream", encoder)
  680. }
  681. func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error {
  682. encoder := func(msg *message) (string, error) {
  683. if msg.Event == messageEvent { // only handle default events
  684. return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil
  685. }
  686. return "\n", nil // "keepalive" and "open" events just send an empty line
  687. }
  688. return s.handleSubscribeHTTP(w, r, v, "text/plain", encoder)
  689. }
  690. func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request, v *visitor, contentType string, encoder messageEncoder) error {
  691. if err := v.SubscriptionAllowed(); err != nil {
  692. return errHTTPTooManyRequestsLimitSubscriptions
  693. }
  694. defer v.RemoveSubscription()
  695. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  696. if err != nil {
  697. return err
  698. }
  699. poll, since, scheduled, filters, err := parseSubscribeParams(r)
  700. if err != nil {
  701. return err
  702. }
  703. var wlock sync.Mutex
  704. sub := func(msg *message) error {
  705. if !filters.Pass(msg) {
  706. return nil
  707. }
  708. m, err := encoder(msg)
  709. if err != nil {
  710. return err
  711. }
  712. wlock.Lock()
  713. defer wlock.Unlock()
  714. if _, err := w.Write([]byte(m)); err != nil {
  715. return err
  716. }
  717. if fl, ok := w.(http.Flusher); ok {
  718. fl.Flush()
  719. }
  720. return nil
  721. }
  722. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  723. w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset!
  724. if poll {
  725. return s.sendOldMessages(topics, since, scheduled, sub)
  726. }
  727. subscriberIDs := make([]int, 0)
  728. for _, t := range topics {
  729. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  730. }
  731. defer func() {
  732. for i, subscriberID := range subscriberIDs {
  733. topics[i].Unsubscribe(subscriberID) // Order!
  734. }
  735. }()
  736. if err := sub(newOpenMessage(topicsStr)); err != nil { // Send out open message
  737. return err
  738. }
  739. if err := s.sendOldMessages(topics, since, scheduled, sub); err != nil {
  740. return err
  741. }
  742. for {
  743. select {
  744. case <-r.Context().Done():
  745. return nil
  746. case <-time.After(s.config.KeepaliveInterval):
  747. v.Keepalive()
  748. if err := sub(newKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message
  749. return err
  750. }
  751. }
  752. }
  753. }
  754. func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request, v *visitor) error {
  755. if strings.ToLower(r.Header.Get("Upgrade")) != "websocket" {
  756. return errHTTPBadRequestWebSocketsUpgradeHeaderMissing
  757. }
  758. if err := v.SubscriptionAllowed(); err != nil {
  759. return errHTTPTooManyRequestsLimitSubscriptions
  760. }
  761. defer v.RemoveSubscription()
  762. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  763. if err != nil {
  764. return err
  765. }
  766. poll, since, scheduled, filters, err := parseSubscribeParams(r)
  767. if err != nil {
  768. return err
  769. }
  770. upgrader := &websocket.Upgrader{
  771. ReadBufferSize: wsBufferSize,
  772. WriteBufferSize: wsBufferSize,
  773. CheckOrigin: func(r *http.Request) bool {
  774. return true // We're open for business!
  775. },
  776. }
  777. conn, err := upgrader.Upgrade(w, r, nil)
  778. if err != nil {
  779. return err
  780. }
  781. defer conn.Close()
  782. var wlock sync.Mutex
  783. g, ctx := errgroup.WithContext(context.Background())
  784. g.Go(func() error {
  785. pongWait := s.config.KeepaliveInterval + wsPongWait
  786. conn.SetReadLimit(wsReadLimit)
  787. if err := conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
  788. return err
  789. }
  790. conn.SetPongHandler(func(appData string) error {
  791. return conn.SetReadDeadline(time.Now().Add(pongWait))
  792. })
  793. for {
  794. _, _, err := conn.NextReader()
  795. if err != nil {
  796. return err
  797. }
  798. }
  799. })
  800. g.Go(func() error {
  801. ping := func() error {
  802. wlock.Lock()
  803. defer wlock.Unlock()
  804. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  805. return err
  806. }
  807. return conn.WriteMessage(websocket.PingMessage, nil)
  808. }
  809. for {
  810. select {
  811. case <-ctx.Done():
  812. return nil
  813. case <-time.After(s.config.KeepaliveInterval):
  814. v.Keepalive()
  815. if err := ping(); err != nil {
  816. return err
  817. }
  818. }
  819. }
  820. })
  821. sub := func(msg *message) error {
  822. if !filters.Pass(msg) {
  823. return nil
  824. }
  825. wlock.Lock()
  826. defer wlock.Unlock()
  827. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  828. return err
  829. }
  830. return conn.WriteJSON(msg)
  831. }
  832. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  833. if poll {
  834. return s.sendOldMessages(topics, since, scheduled, sub)
  835. }
  836. subscriberIDs := make([]int, 0)
  837. for _, t := range topics {
  838. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  839. }
  840. defer func() {
  841. for i, subscriberID := range subscriberIDs {
  842. topics[i].Unsubscribe(subscriberID) // Order!
  843. }
  844. }()
  845. if err := sub(newOpenMessage(topicsStr)); err != nil { // Send out open message
  846. return err
  847. }
  848. if err := s.sendOldMessages(topics, since, scheduled, sub); err != nil {
  849. return err
  850. }
  851. err = g.Wait()
  852. if err != nil && websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
  853. return nil // Normal closures are not errors
  854. }
  855. return err
  856. }
  857. func parseSubscribeParams(r *http.Request) (poll bool, since sinceMarker, scheduled bool, filters *queryFilter, err error) {
  858. poll = readBoolParam(r, false, "x-poll", "poll", "po")
  859. scheduled = readBoolParam(r, false, "x-scheduled", "scheduled", "sched")
  860. since, err = parseSince(r, poll)
  861. if err != nil {
  862. return
  863. }
  864. filters, err = parseQueryFilters(r)
  865. if err != nil {
  866. return
  867. }
  868. return
  869. }
  870. func (s *Server) sendOldMessages(topics []*topic, since sinceMarker, scheduled bool, sub subscriber) error {
  871. if since.IsNone() {
  872. return nil
  873. }
  874. for _, t := range topics {
  875. messages, err := s.messageCache.Messages(t.ID, since, scheduled)
  876. if err != nil {
  877. return err
  878. }
  879. for _, m := range messages {
  880. if err := sub(m); err != nil {
  881. return err
  882. }
  883. }
  884. }
  885. return nil
  886. }
  887. // parseSince returns a timestamp identifying the time span from which cached messages should be received.
  888. //
  889. // Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), or
  890. // "all" for all messages.
  891. func parseSince(r *http.Request, poll bool) (sinceMarker, error) {
  892. since := readParam(r, "x-since", "since", "si")
  893. // Easy cases (empty, all, none)
  894. if since == "" {
  895. if poll {
  896. return sinceAllMessages, nil
  897. }
  898. return sinceNoMessages, nil
  899. } else if since == "all" {
  900. return sinceAllMessages, nil
  901. } else if since == "none" {
  902. return sinceNoMessages, nil
  903. }
  904. // ID, timestamp, duration
  905. if validMessageID(since) {
  906. return newSinceID(since), nil
  907. } else if s, err := strconv.ParseInt(since, 10, 64); err == nil {
  908. return newSinceTime(s), nil
  909. } else if d, err := time.ParseDuration(since); err == nil {
  910. return newSinceTime(time.Now().Add(-1 * d).Unix()), nil
  911. }
  912. return sinceNoMessages, errHTTPBadRequestSinceInvalid
  913. }
  914. func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  915. w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST")
  916. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  917. w.Header().Set("Access-Control-Allow-Headers", "*") // CORS, allow auth via JS // FIXME is this terrible?
  918. return nil
  919. }
  920. func (s *Server) topicFromPath(path string) (*topic, error) {
  921. parts := strings.Split(path, "/")
  922. if len(parts) < 2 {
  923. return nil, errHTTPBadRequestTopicInvalid
  924. }
  925. topics, err := s.topicsFromIDs(parts[1])
  926. if err != nil {
  927. return nil, err
  928. }
  929. return topics[0], nil
  930. }
  931. func (s *Server) topicsFromPath(path string) ([]*topic, string, error) {
  932. parts := strings.Split(path, "/")
  933. if len(parts) < 2 {
  934. return nil, "", errHTTPBadRequestTopicInvalid
  935. }
  936. topicIDs := util.SplitNoEmpty(parts[1], ",")
  937. topics, err := s.topicsFromIDs(topicIDs...)
  938. if err != nil {
  939. return nil, "", errHTTPBadRequestTopicInvalid
  940. }
  941. return topics, parts[1], nil
  942. }
  943. func (s *Server) topicsFromIDs(ids ...string) ([]*topic, error) {
  944. s.mu.Lock()
  945. defer s.mu.Unlock()
  946. topics := make([]*topic, 0)
  947. for _, id := range ids {
  948. if util.InStringList(disallowedTopics, id) {
  949. return nil, errHTTPBadRequestTopicDisallowed
  950. }
  951. if _, ok := s.topics[id]; !ok {
  952. if len(s.topics) >= s.config.TotalTopicLimit {
  953. return nil, errHTTPTooManyRequestsLimitTotalTopics
  954. }
  955. s.topics[id] = newTopic(id)
  956. }
  957. topics = append(topics, s.topics[id])
  958. }
  959. return topics, nil
  960. }
  961. func (s *Server) updateStatsAndPrune() {
  962. s.mu.Lock()
  963. defer s.mu.Unlock()
  964. // Expire visitors from rate visitors map
  965. for ip, v := range s.visitors {
  966. if v.Stale() {
  967. delete(s.visitors, ip)
  968. }
  969. }
  970. // Delete expired attachments
  971. if s.fileCache != nil {
  972. ids, err := s.messageCache.AttachmentsExpired()
  973. if err == nil {
  974. if err := s.fileCache.Remove(ids...); err != nil {
  975. log.Printf("error while deleting attachments: %s", err.Error())
  976. }
  977. } else {
  978. log.Printf("error retrieving expired attachments: %s", err.Error())
  979. }
  980. }
  981. // Prune message cache
  982. olderThan := time.Now().Add(-1 * s.config.CacheDuration)
  983. if err := s.messageCache.Prune(olderThan); err != nil {
  984. log.Printf("error pruning cache: %s", err.Error())
  985. }
  986. // Prune old topics, remove subscriptions without subscribers
  987. var subscribers, messages int
  988. for _, t := range s.topics {
  989. subs := t.Subscribers()
  990. msgs, err := s.messageCache.MessageCount(t.ID)
  991. if err != nil {
  992. log.Printf("cannot get stats for topic %s: %s", t.ID, err.Error())
  993. continue
  994. }
  995. if msgs == 0 && subs == 0 {
  996. delete(s.topics, t.ID)
  997. continue
  998. }
  999. subscribers += subs
  1000. messages += msgs
  1001. }
  1002. // Mail stats
  1003. var mailSuccess, mailFailure int64
  1004. if s.smtpBackend != nil {
  1005. mailSuccess, mailFailure = s.smtpBackend.Counts()
  1006. }
  1007. // Print stats
  1008. 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)",
  1009. s.messages, messages, mailSuccess, mailFailure, len(s.topics), subscribers, len(s.visitors))
  1010. }
  1011. func (s *Server) runSMTPServer() error {
  1012. sub := func(m *message) error {
  1013. url := fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic)
  1014. req, err := http.NewRequest("PUT", url, strings.NewReader(m.Message))
  1015. if err != nil {
  1016. return err
  1017. }
  1018. if m.Title != "" {
  1019. req.Header.Set("Title", m.Title)
  1020. }
  1021. rr := httptest.NewRecorder()
  1022. s.handle(rr, req)
  1023. if rr.Code != http.StatusOK {
  1024. return errors.New("error: " + rr.Body.String())
  1025. }
  1026. return nil
  1027. }
  1028. s.smtpBackend = newMailBackend(s.config, sub)
  1029. s.smtpServer = smtp.NewServer(s.smtpBackend)
  1030. s.smtpServer.Addr = s.config.SMTPServerListen
  1031. s.smtpServer.Domain = s.config.SMTPServerDomain
  1032. s.smtpServer.ReadTimeout = 10 * time.Second
  1033. s.smtpServer.WriteTimeout = 10 * time.Second
  1034. s.smtpServer.MaxMessageBytes = 1024 * 1024 // Must be much larger than message size (headers, multipart, etc.)
  1035. s.smtpServer.MaxRecipients = 1
  1036. s.smtpServer.AllowInsecureAuth = true
  1037. return s.smtpServer.ListenAndServe()
  1038. }
  1039. func (s *Server) runManager() {
  1040. for {
  1041. select {
  1042. case <-time.After(s.config.ManagerInterval):
  1043. s.updateStatsAndPrune()
  1044. case <-s.closeChan:
  1045. return
  1046. }
  1047. }
  1048. }
  1049. func (s *Server) runAtSender() {
  1050. for {
  1051. select {
  1052. case <-time.After(s.config.AtSenderInterval):
  1053. if err := s.sendDelayedMessages(); err != nil {
  1054. log.Printf("error sending scheduled messages: %s", err.Error())
  1055. }
  1056. case <-s.closeChan:
  1057. return
  1058. }
  1059. }
  1060. }
  1061. func (s *Server) runFirebaseKeepaliver() {
  1062. if s.firebase == nil {
  1063. return
  1064. }
  1065. for {
  1066. select {
  1067. case <-time.After(s.config.FirebaseKeepaliveInterval):
  1068. if err := s.firebase(newKeepaliveMessage(firebaseControlTopic)); err != nil {
  1069. log.Printf("error sending Firebase keepalive message: %s", err.Error())
  1070. }
  1071. case <-s.closeChan:
  1072. return
  1073. }
  1074. }
  1075. }
  1076. func (s *Server) sendDelayedMessages() error {
  1077. s.mu.Lock()
  1078. defer s.mu.Unlock()
  1079. messages, err := s.messageCache.MessagesDue()
  1080. if err != nil {
  1081. return err
  1082. }
  1083. for _, m := range messages {
  1084. t, ok := s.topics[m.Topic] // If no subscribers, just mark message as published
  1085. if ok {
  1086. if err := t.Publish(m); err != nil {
  1087. log.Printf("unable to publish message %s to topic %s: %v", m.ID, m.Topic, err.Error())
  1088. }
  1089. }
  1090. if s.firebase != nil { // Firebase subscribers may not show up in topics map
  1091. if err := s.firebase(m); err != nil {
  1092. log.Printf("unable to publish to Firebase: %v", err.Error())
  1093. }
  1094. }
  1095. if err := s.messageCache.MarkPublished(m); err != nil {
  1096. return err
  1097. }
  1098. }
  1099. return nil
  1100. }
  1101. func (s *Server) limitRequests(next handleFunc) handleFunc {
  1102. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1103. if util.InStringList(s.config.VisitorRequestExemptIPAddrs, v.ip) {
  1104. return next(w, r, v)
  1105. } else if err := v.RequestAllowed(); err != nil {
  1106. return errHTTPTooManyRequestsLimitRequests
  1107. }
  1108. return next(w, r, v)
  1109. }
  1110. }
  1111. func (s *Server) ensureWebEnabled(next handleFunc) handleFunc {
  1112. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1113. if !s.config.EnableWeb {
  1114. return errHTTPNotFound
  1115. }
  1116. return next(w, r, v)
  1117. }
  1118. }
  1119. // transformBodyJSON peeks the request body, reads the JSON, and converts it to headers
  1120. // before passing it on to the next handler. This is meant to be used in combination with handlePublish.
  1121. func (s *Server) transformBodyJSON(next handleFunc) handleFunc {
  1122. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1123. body, err := util.Peek(r.Body, s.config.MessageLimit)
  1124. if err != nil {
  1125. return err
  1126. }
  1127. defer r.Body.Close()
  1128. var m publishMessage
  1129. if err := json.NewDecoder(body).Decode(&m); err != nil {
  1130. return errHTTPBadRequestJSONInvalid
  1131. }
  1132. if !topicRegex.MatchString(m.Topic) {
  1133. return errHTTPBadRequestTopicInvalid
  1134. }
  1135. if m.Message == "" {
  1136. m.Message = emptyMessageBody
  1137. }
  1138. r.URL.Path = "/" + m.Topic
  1139. r.Body = io.NopCloser(strings.NewReader(m.Message))
  1140. if m.Title != "" {
  1141. r.Header.Set("X-Title", m.Title)
  1142. }
  1143. if m.Priority != 0 {
  1144. r.Header.Set("X-Priority", fmt.Sprintf("%d", m.Priority))
  1145. }
  1146. if m.Tags != nil && len(m.Tags) > 0 {
  1147. r.Header.Set("X-Tags", strings.Join(m.Tags, ","))
  1148. }
  1149. if m.Attach != "" {
  1150. r.Header.Set("X-Attach", m.Attach)
  1151. }
  1152. if m.Filename != "" {
  1153. r.Header.Set("X-Filename", m.Filename)
  1154. }
  1155. if m.Click != "" {
  1156. r.Header.Set("X-Click", m.Click)
  1157. }
  1158. if len(m.Actions) > 0 {
  1159. actionsStr, err := json.Marshal(m.Actions)
  1160. if err != nil {
  1161. return errHTTPBadRequestJSONInvalid
  1162. }
  1163. r.Header.Set("X-Actions", string(actionsStr))
  1164. }
  1165. if m.Email != "" {
  1166. r.Header.Set("X-Email", m.Email)
  1167. }
  1168. if m.Delay != "" {
  1169. r.Header.Set("X-Delay", m.Delay)
  1170. }
  1171. return next(w, r, v)
  1172. }
  1173. }
  1174. func (s *Server) authWrite(next handleFunc) handleFunc {
  1175. return s.withAuth(next, auth.PermissionWrite)
  1176. }
  1177. func (s *Server) authRead(next handleFunc) handleFunc {
  1178. return s.withAuth(next, auth.PermissionRead)
  1179. }
  1180. func (s *Server) withAuth(next handleFunc, perm auth.Permission) handleFunc {
  1181. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1182. if s.auth == nil {
  1183. return next(w, r, v)
  1184. }
  1185. topics, _, err := s.topicsFromPath(r.URL.Path)
  1186. if err != nil {
  1187. return err
  1188. }
  1189. var user *auth.User // may stay nil if no auth header!
  1190. username, password, ok := extractUserPass(r)
  1191. if ok {
  1192. if user, err = s.auth.Authenticate(username, password); err != nil {
  1193. log.Printf("authentication failed: %s", err.Error())
  1194. return errHTTPUnauthorized
  1195. }
  1196. }
  1197. for _, t := range topics {
  1198. if err := s.auth.Authorize(user, t.ID, perm); err != nil {
  1199. log.Printf("unauthorized: %s", err.Error())
  1200. return errHTTPForbidden
  1201. }
  1202. }
  1203. return next(w, r, v)
  1204. }
  1205. }
  1206. // extractUserPass reads the username/password from the basic auth header (Authorization: Basic ...),
  1207. // or from the ?auth=... query param. The latter is required only to support the WebSocket JavaScript
  1208. // class, which does not support passing headers during the initial request. The auth query param
  1209. // is effectively double base64 encoded. Its format is base64(Basic base64(user:pass)).
  1210. func extractUserPass(r *http.Request) (username string, password string, ok bool) {
  1211. username, password, ok = r.BasicAuth()
  1212. if ok {
  1213. return
  1214. }
  1215. authParam := readQueryParam(r, "authorization", "auth")
  1216. if authParam != "" {
  1217. a, err := base64.RawURLEncoding.DecodeString(authParam)
  1218. if err != nil {
  1219. return
  1220. }
  1221. r.Header.Set("Authorization", string(a))
  1222. return r.BasicAuth()
  1223. }
  1224. return
  1225. }
  1226. // visitor creates or retrieves a rate.Limiter for the given visitor.
  1227. // This function was taken from https://www.alexedwards.net/blog/how-to-rate-limit-http-requests (MIT).
  1228. func (s *Server) visitor(r *http.Request) *visitor {
  1229. s.mu.Lock()
  1230. defer s.mu.Unlock()
  1231. remoteAddr := r.RemoteAddr
  1232. ip, _, err := net.SplitHostPort(remoteAddr)
  1233. if err != nil {
  1234. ip = remoteAddr // This should not happen in real life; only in tests.
  1235. }
  1236. if s.config.BehindProxy && r.Header.Get("X-Forwarded-For") != "" {
  1237. ip = r.Header.Get("X-Forwarded-For")
  1238. }
  1239. v, exists := s.visitors[ip]
  1240. if !exists {
  1241. s.visitors[ip] = newVisitor(s.config, s.messageCache, ip)
  1242. return s.visitors[ip]
  1243. }
  1244. v.Keepalive()
  1245. return v
  1246. }