server.go 39 KB

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