server.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. "github.com/tidwall/gjson"
  13. "golang.org/x/sync/errgroup"
  14. "heckel.io/ntfy/auth"
  15. "heckel.io/ntfy/util"
  16. "io"
  17. "log"
  18. "net"
  19. "net/http"
  20. "net/http/httptest"
  21. "net/url"
  22. "os"
  23. "path"
  24. "path/filepath"
  25. "regexp"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "time"
  30. "unicode/utf8"
  31. )
  32. // Server is the main server, providing the UI and API for ntfy
  33. type Server struct {
  34. config *Config
  35. httpServer *http.Server
  36. httpsServer *http.Server
  37. unixListener net.Listener
  38. smtpServer *smtp.Server
  39. smtpBackend *smtpBackend
  40. topics map[string]*topic
  41. visitors map[string]*visitor
  42. firebase subscriber
  43. mailer mailer
  44. messages int64
  45. auth auth.Auther
  46. messageCache *messageCache
  47. fileCache *fileCache
  48. closeChan chan bool
  49. mu sync.Mutex
  50. }
  51. // handleFunc extends the normal http.HandlerFunc to be able to easily return errors
  52. type handleFunc func(http.ResponseWriter, *http.Request, *visitor) error
  53. var (
  54. // If changed, don't forget to update Android App and auth_sqlite.go
  55. topicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No /!
  56. topicPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}$`) // Regex must match JS & Android app!
  57. extTopicPathRegex = 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}(,[-_A-Za-z0-9]{1,64})*/(publish|send|trigger)$`)
  64. webConfigPath = "/config.js"
  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 && staticRegex.MatchString(r.URL.Path) {
  257. return s.handleStatic(w, r)
  258. } else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) {
  259. return s.handleDocs(w, r)
  260. } else if r.Method == http.MethodGet && fileRegex.MatchString(r.URL.Path) && s.config.AttachmentCacheDir != "" {
  261. return s.limitRequests(s.handleFile)(w, r, v)
  262. } else if r.Method == http.MethodOptions {
  263. return s.handleOptions(w, r)
  264. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicPathRegex.MatchString(r.URL.Path) {
  265. return s.limitRequests(s.authWrite(s.handlePublish))(w, r, v)
  266. } else if r.Method == http.MethodGet && publishPathRegex.MatchString(r.URL.Path) {
  267. return s.limitRequests(s.authWrite(s.handlePublish))(w, r, v)
  268. } else if r.Method == http.MethodGet && jsonPathRegex.MatchString(r.URL.Path) {
  269. return s.limitRequests(s.authRead(s.handleSubscribeJSON))(w, r, v)
  270. } else if r.Method == http.MethodGet && ssePathRegex.MatchString(r.URL.Path) {
  271. return s.limitRequests(s.authRead(s.handleSubscribeSSE))(w, r, v)
  272. } else if r.Method == http.MethodGet && rawPathRegex.MatchString(r.URL.Path) {
  273. return s.limitRequests(s.authRead(s.handleSubscribeRaw))(w, r, v)
  274. } else if r.Method == http.MethodGet && wsPathRegex.MatchString(r.URL.Path) {
  275. return s.limitRequests(s.authRead(s.handleSubscribeWS))(w, r, v)
  276. } else if r.Method == http.MethodGet && authPathRegex.MatchString(r.URL.Path) {
  277. return s.limitRequests(s.authRead(s.handleTopicAuth))(w, r, v)
  278. } else if r.Method == http.MethodGet && (topicPathRegex.MatchString(r.URL.Path) || extTopicPathRegex.MatchString(r.URL.Path)) {
  279. return s.handleTopic(w, r)
  280. }
  281. return errHTTPNotFound
  282. }
  283. func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) error {
  284. if s.config.WebRootIsApp {
  285. r.URL.Path = webAppIndex
  286. } else {
  287. r.URL.Path = webHomeIndex
  288. }
  289. return s.handleStatic(w, r)
  290. }
  291. func (s *Server) handleTopic(w http.ResponseWriter, r *http.Request) error {
  292. unifiedpush := readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see PUT/POST too!
  293. if unifiedpush {
  294. w.Header().Set("Content-Type", "application/json")
  295. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  296. _, err := io.WriteString(w, `{"unifiedpush":{"version":1}}`+"\n")
  297. return err
  298. }
  299. r.URL.Path = webAppIndex
  300. return s.handleStatic(w, r)
  301. }
  302. func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request, _ *visitor) error {
  303. return nil
  304. }
  305. func (s *Server) handleTopicAuth(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  306. w.Header().Set("Content-Type", "application/json")
  307. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  308. _, err := io.WriteString(w, `{"success":true}`+"\n")
  309. return err
  310. }
  311. func (s *Server) handleExample(w http.ResponseWriter, _ *http.Request) error {
  312. _, err := io.WriteString(w, exampleSource)
  313. return err
  314. }
  315. func (s *Server) handleWebConfig(w http.ResponseWriter, r *http.Request) error {
  316. appRoot := "/"
  317. if !s.config.WebRootIsApp {
  318. appRoot = "/app"
  319. }
  320. disallowedTopicsStr := `"` + strings.Join(disallowedTopics, `", "`) + `"`
  321. w.Header().Set("Content-Type", "text/javascript")
  322. _, err := io.WriteString(w, fmt.Sprintf(`// Generated server configuration
  323. var config = {
  324. appRoot: "%s",
  325. disallowedTopics: [%s]
  326. };`, appRoot, disallowedTopicsStr))
  327. return err
  328. }
  329. func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request) error {
  330. r.URL.Path = webSiteDir + r.URL.Path
  331. util.Gzip(http.FileServer(http.FS(webFsCached))).ServeHTTP(w, r)
  332. return nil
  333. }
  334. func (s *Server) handleDocs(w http.ResponseWriter, r *http.Request) error {
  335. util.Gzip(http.FileServer(http.FS(docsStaticCached))).ServeHTTP(w, r)
  336. return nil
  337. }
  338. func (s *Server) handleFile(w http.ResponseWriter, r *http.Request, v *visitor) error {
  339. if s.config.AttachmentCacheDir == "" {
  340. return errHTTPInternalError
  341. }
  342. matches := fileRegex.FindStringSubmatch(r.URL.Path)
  343. if len(matches) != 2 {
  344. return errHTTPInternalErrorInvalidFilePath
  345. }
  346. messageID := matches[1]
  347. file := filepath.Join(s.config.AttachmentCacheDir, messageID)
  348. stat, err := os.Stat(file)
  349. if err != nil {
  350. return errHTTPNotFound
  351. }
  352. if err := v.BandwidthLimiter().Allow(stat.Size()); err != nil {
  353. return errHTTPTooManyRequestsAttachmentBandwidthLimit
  354. }
  355. w.Header().Set("Content-Length", fmt.Sprintf("%d", stat.Size()))
  356. f, err := os.Open(file)
  357. if err != nil {
  358. return err
  359. }
  360. defer f.Close()
  361. _, err = io.Copy(util.NewContentTypeWriter(w, r.URL.Path), f)
  362. return err
  363. }
  364. func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, v *visitor) error {
  365. t, err := s.topicFromPath(r.URL.Path)
  366. if err != nil {
  367. return err
  368. }
  369. body, err := util.Peak(r.Body, s.config.MessageLimit)
  370. if err != nil {
  371. return err
  372. }
  373. m := newDefaultMessage(t.ID, "")
  374. cache, firebase, email, template, unifiedpush, err := s.parsePublishParams(r, v, m)
  375. if err != nil {
  376. return err
  377. }
  378. if err := s.handlePublishBody(r, v, m, body, template, unifiedpush); err != nil {
  379. return err
  380. }
  381. if m.Message == "" {
  382. m.Message = emptyMessageBody
  383. }
  384. delayed := m.Time > time.Now().Unix()
  385. if !delayed {
  386. if err := t.Publish(m); err != nil {
  387. return err
  388. }
  389. }
  390. if s.firebase != nil && firebase && !delayed {
  391. go func() {
  392. if err := s.firebase(m); err != nil {
  393. log.Printf("[%s] FB - Unable to publish to Firebase: %v", v.ip, err.Error())
  394. }
  395. }()
  396. }
  397. if s.mailer != nil && email != "" && !delayed {
  398. go func() {
  399. if err := s.mailer.Send(v.ip, email, m); err != nil {
  400. log.Printf("[%s] MAIL - Unable to send email: %v", v.ip, err.Error())
  401. }
  402. }()
  403. }
  404. if cache {
  405. if err := s.messageCache.AddMessage(m); err != nil {
  406. return err
  407. }
  408. }
  409. w.Header().Set("Content-Type", "application/json")
  410. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  411. if err := json.NewEncoder(w).Encode(m); err != nil {
  412. return err
  413. }
  414. s.mu.Lock()
  415. s.messages++
  416. s.mu.Unlock()
  417. return nil
  418. }
  419. func (s *Server) parsePublishParams(r *http.Request, v *visitor, m *message) (cache bool, firebase bool, email string, template string, unifiedpush bool, err error) {
  420. cache = readBoolParam(r, true, "x-cache", "cache")
  421. firebase = readBoolParam(r, true, "x-firebase", "firebase")
  422. m.Title = readParam(r, "x-title", "title", "t")
  423. m.Click = readParam(r, "x-click", "click")
  424. filename := readParam(r, "x-filename", "filename", "file", "f")
  425. attach := readParam(r, "x-attach", "attach", "a")
  426. if attach != "" || filename != "" {
  427. m.Attachment = &attachment{}
  428. }
  429. if filename != "" {
  430. m.Attachment.Name = filename
  431. }
  432. if attach != "" {
  433. if !attachURLRegex.MatchString(attach) {
  434. return false, false, "", "", false, errHTTPBadRequestAttachmentURLInvalid
  435. }
  436. m.Attachment.URL = attach
  437. if m.Attachment.Name == "" {
  438. u, err := url.Parse(m.Attachment.URL)
  439. if err == nil {
  440. m.Attachment.Name = path.Base(u.Path)
  441. if m.Attachment.Name == "." || m.Attachment.Name == "/" {
  442. m.Attachment.Name = ""
  443. }
  444. }
  445. }
  446. if m.Attachment.Name == "" {
  447. m.Attachment.Name = "attachment"
  448. }
  449. }
  450. email = readParam(r, "x-email", "x-e-mail", "email", "e-mail", "mail", "e")
  451. if email != "" {
  452. if err := v.EmailAllowed(); err != nil {
  453. return false, false, "", "", false, errHTTPTooManyRequestsLimitEmails
  454. }
  455. }
  456. if s.mailer == nil && email != "" {
  457. return false, false, "", "", false, errHTTPBadRequestEmailDisabled
  458. }
  459. messageStr := strings.ReplaceAll(readParam(r, "x-message", "message", "m"), "\\n", "\n")
  460. if messageStr != "" {
  461. m.Message = messageStr
  462. }
  463. m.Priority, err = util.ParsePriority(readParam(r, "x-priority", "priority", "prio", "p"))
  464. if err != nil {
  465. return false, false, "", "", false, errHTTPBadRequestPriorityInvalid
  466. }
  467. tagsStr := readParam(r, "x-tags", "tags", "tag", "ta")
  468. if tagsStr != "" {
  469. m.Tags = make([]string, 0)
  470. for _, s := range util.SplitNoEmpty(tagsStr, ",") {
  471. m.Tags = append(m.Tags, strings.TrimSpace(s))
  472. }
  473. }
  474. delayStr := readParam(r, "x-delay", "delay", "x-at", "at", "x-in", "in")
  475. if delayStr != "" {
  476. if !cache {
  477. return false, false, "", "", false, errHTTPBadRequestDelayNoCache
  478. }
  479. if email != "" {
  480. return false, false, "", "", false, errHTTPBadRequestDelayNoEmail // we cannot store the email address (yet)
  481. }
  482. delay, err := util.ParseFutureTime(delayStr, time.Now())
  483. if err != nil {
  484. return false, false, "", "", false, errHTTPBadRequestDelayCannotParse
  485. } else if delay.Unix() < time.Now().Add(s.config.MinDelay).Unix() {
  486. return false, false, "", "", false, errHTTPBadRequestDelayTooSmall
  487. } else if delay.Unix() > time.Now().Add(s.config.MaxDelay).Unix() {
  488. return false, false, "", "", false, errHTTPBadRequestDelayTooLarge
  489. }
  490. m.Time = delay.Unix()
  491. }
  492. template = readParam(r, "x-template", "template", "tpl")
  493. if template != "" {
  494. if template != "json" {
  495. return false, false, "", "", false, errors.New("invalid template")
  496. }
  497. }
  498. unifiedpush = readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see GET too!
  499. if unifiedpush {
  500. firebase = false
  501. unifiedpush = true
  502. }
  503. return cache, firebase, email, template, unifiedpush, nil
  504. }
  505. // handlePublishBody consumes the PUT/POST body and decides whether the body is an attachment or the message.
  506. //
  507. // 1. curl -T somebinarydata.bin "ntfy.sh/mytopic?up=1"
  508. // If body is binary, encode as base64, if not do not encode
  509. // 2. curl -H "Attach: http://example.com/file.jpg" ntfy.sh/mytopic
  510. // Body must be a message, because we attached an external URL
  511. // 3. curl -T short.txt -H "Filename: short.txt" ntfy.sh/mytopic
  512. // Body must be attachment, because we passed a filename
  513. // 4. curl -T file.txt ntfy.sh/mytopic
  514. // If file.txt is <= 4096 (message limit) and valid UTF-8, treat it as a message
  515. // 5. curl -T file.txt ntfy.sh/mytopic
  516. // If file.txt is > message limit, treat it as an attachment
  517. func (s *Server) handlePublishBody(r *http.Request, v *visitor, m *message, body *util.PeakedReadCloser, template string, unifiedpush bool) error {
  518. if unifiedpush {
  519. return s.handleBodyAsMessageAutoDetect(m, body) // Case 1
  520. } else if m.Attachment != nil && m.Attachment.URL != "" {
  521. return s.handleBodyAsTextMessage(m, body, template) // Case 2
  522. } else if m.Attachment != nil && m.Attachment.Name != "" {
  523. return s.handleBodyAsAttachment(r, v, m, body) // Case 3
  524. } else if !body.LimitReached && utf8.Valid(body.PeakedBytes) {
  525. return s.handleBodyAsTextMessage(m, body, template) // Case 4
  526. }
  527. return s.handleBodyAsAttachment(r, v, m, body) // Case 5
  528. }
  529. func (s *Server) handleBodyAsMessageAutoDetect(m *message, body *util.PeakedReadCloser) error {
  530. if utf8.Valid(body.PeakedBytes) {
  531. m.Message = string(body.PeakedBytes) // Do not trim
  532. } else {
  533. m.Message = base64.StdEncoding.EncodeToString(body.PeakedBytes)
  534. m.Encoding = encodingBase64
  535. }
  536. return nil
  537. }
  538. func (s *Server) handleBodyAsTextMessage(m *message, body *util.PeakedReadCloser, template string) error {
  539. if !utf8.Valid(body.PeakedBytes) {
  540. return errHTTPBadRequestMessageNotUTF8
  541. }
  542. if len(body.PeakedBytes) > 0 { // Empty body should not override message (publish via GET!)
  543. peakedBody := strings.TrimSpace(string(body.PeakedBytes)) // Truncates the message to the peak limit if required
  544. if template == "json" && gjson.Valid(peakedBody) {
  545. r := regexp.MustCompile(`\${([^}]+)}`)
  546. matches := r.FindAllStringSubmatch(m.Message, -1)
  547. for _, v := range matches {
  548. query := v[1]
  549. result := gjson.Get(peakedBody, query)
  550. if result.Exists() {
  551. m.Message = strings.ReplaceAll(m.Message, fmt.Sprintf("${%s}", query), result.String())
  552. }
  553. }
  554. matches = r.FindAllStringSubmatch(m.Title, -1)
  555. for _, v := range matches {
  556. query := v[1]
  557. result := gjson.Get(peakedBody, query)
  558. if result.Exists() {
  559. m.Title = strings.ReplaceAll(m.Title, fmt.Sprintf("${%s}", query), result.String())
  560. }
  561. }
  562. } else {
  563. m.Message = peakedBody
  564. }
  565. }
  566. if m.Attachment != nil && m.Attachment.Name != "" && m.Message == "" {
  567. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  568. }
  569. return nil
  570. }
  571. func (s *Server) handleBodyAsAttachment(r *http.Request, v *visitor, m *message, body *util.PeakedReadCloser) error {
  572. if s.fileCache == nil || s.config.BaseURL == "" || s.config.AttachmentCacheDir == "" {
  573. return errHTTPBadRequestAttachmentsDisallowed
  574. } else if m.Time > time.Now().Add(s.config.AttachmentExpiryDuration).Unix() {
  575. return errHTTPBadRequestAttachmentsExpiryBeforeDelivery
  576. }
  577. visitorAttachmentsSize, err := s.messageCache.AttachmentsSize(v.ip)
  578. if err != nil {
  579. return err
  580. }
  581. remainingVisitorAttachmentSize := s.config.VisitorAttachmentTotalSizeLimit - visitorAttachmentsSize
  582. contentLengthStr := r.Header.Get("Content-Length")
  583. if contentLengthStr != "" { // Early "do-not-trust" check, hard limit see below
  584. contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
  585. if err == nil && (contentLength > remainingVisitorAttachmentSize || contentLength > s.config.AttachmentFileSizeLimit) {
  586. return errHTTPBadRequestAttachmentTooLarge
  587. }
  588. }
  589. if m.Attachment == nil {
  590. m.Attachment = &attachment{}
  591. }
  592. var ext string
  593. m.Attachment.Owner = v.ip // Important for attachment rate limiting
  594. m.Attachment.Expires = time.Now().Add(s.config.AttachmentExpiryDuration).Unix()
  595. m.Attachment.Type, ext = util.DetectContentType(body.PeakedBytes, m.Attachment.Name)
  596. m.Attachment.URL = fmt.Sprintf("%s/file/%s%s", s.config.BaseURL, m.ID, ext)
  597. if m.Attachment.Name == "" {
  598. m.Attachment.Name = fmt.Sprintf("attachment%s", ext)
  599. }
  600. if m.Message == "" {
  601. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  602. }
  603. m.Attachment.Size, err = s.fileCache.Write(m.ID, body, v.BandwidthLimiter(), util.NewFixedLimiter(remainingVisitorAttachmentSize))
  604. if err == util.ErrLimitReached {
  605. return errHTTPBadRequestAttachmentTooLarge
  606. } else if err != nil {
  607. return err
  608. }
  609. return nil
  610. }
  611. func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error {
  612. encoder := func(msg *message) (string, error) {
  613. var buf bytes.Buffer
  614. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  615. return "", err
  616. }
  617. return buf.String(), nil
  618. }
  619. return s.handleSubscribeHTTP(w, r, v, "application/x-ndjson", encoder)
  620. }
  621. func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error {
  622. encoder := func(msg *message) (string, error) {
  623. var buf bytes.Buffer
  624. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  625. return "", err
  626. }
  627. if msg.Event != messageEvent {
  628. return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this!
  629. }
  630. return fmt.Sprintf("data: %s\n", buf.String()), nil
  631. }
  632. return s.handleSubscribeHTTP(w, r, v, "text/event-stream", encoder)
  633. }
  634. func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error {
  635. encoder := func(msg *message) (string, error) {
  636. if msg.Event == messageEvent { // only handle default events
  637. return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil
  638. }
  639. return "\n", nil // "keepalive" and "open" events just send an empty line
  640. }
  641. return s.handleSubscribeHTTP(w, r, v, "text/plain", encoder)
  642. }
  643. func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request, v *visitor, contentType string, encoder messageEncoder) error {
  644. if err := v.SubscriptionAllowed(); err != nil {
  645. return errHTTPTooManyRequestsLimitSubscriptions
  646. }
  647. defer v.RemoveSubscription()
  648. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  649. if err != nil {
  650. return err
  651. }
  652. poll, since, scheduled, filters, err := parseSubscribeParams(r)
  653. if err != nil {
  654. return err
  655. }
  656. var wlock sync.Mutex
  657. sub := func(msg *message) error {
  658. if !filters.Pass(msg) {
  659. return nil
  660. }
  661. m, err := encoder(msg)
  662. if err != nil {
  663. return err
  664. }
  665. wlock.Lock()
  666. defer wlock.Unlock()
  667. if _, err := w.Write([]byte(m)); err != nil {
  668. return err
  669. }
  670. if fl, ok := w.(http.Flusher); ok {
  671. fl.Flush()
  672. }
  673. return nil
  674. }
  675. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  676. w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset!
  677. if poll {
  678. return s.sendOldMessages(topics, since, scheduled, sub)
  679. }
  680. subscriberIDs := make([]int, 0)
  681. for _, t := range topics {
  682. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  683. }
  684. defer func() {
  685. for i, subscriberID := range subscriberIDs {
  686. topics[i].Unsubscribe(subscriberID) // Order!
  687. }
  688. }()
  689. if err := sub(newOpenMessage(topicsStr)); err != nil { // Send out open message
  690. return err
  691. }
  692. if err := s.sendOldMessages(topics, since, scheduled, sub); err != nil {
  693. return err
  694. }
  695. for {
  696. select {
  697. case <-r.Context().Done():
  698. return nil
  699. case <-time.After(s.config.KeepaliveInterval):
  700. v.Keepalive()
  701. if err := sub(newKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message
  702. return err
  703. }
  704. }
  705. }
  706. }
  707. func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request, v *visitor) error {
  708. if r.Header.Get("Upgrade") != "websocket" {
  709. return errHTTPBadRequestWebSocketsUpgradeHeaderMissing
  710. }
  711. if err := v.SubscriptionAllowed(); err != nil {
  712. return errHTTPTooManyRequestsLimitSubscriptions
  713. }
  714. defer v.RemoveSubscription()
  715. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  716. if err != nil {
  717. return err
  718. }
  719. poll, since, scheduled, filters, err := parseSubscribeParams(r)
  720. if err != nil {
  721. return err
  722. }
  723. upgrader := &websocket.Upgrader{
  724. ReadBufferSize: wsBufferSize,
  725. WriteBufferSize: wsBufferSize,
  726. CheckOrigin: func(r *http.Request) bool {
  727. return true // We're open for business!
  728. },
  729. }
  730. conn, err := upgrader.Upgrade(w, r, nil)
  731. if err != nil {
  732. return err
  733. }
  734. defer conn.Close()
  735. var wlock sync.Mutex
  736. g, ctx := errgroup.WithContext(context.Background())
  737. g.Go(func() error {
  738. pongWait := s.config.KeepaliveInterval + wsPongWait
  739. conn.SetReadLimit(wsReadLimit)
  740. if err := conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
  741. return err
  742. }
  743. conn.SetPongHandler(func(appData string) error {
  744. return conn.SetReadDeadline(time.Now().Add(pongWait))
  745. })
  746. for {
  747. _, _, err := conn.NextReader()
  748. if err != nil {
  749. return err
  750. }
  751. }
  752. })
  753. g.Go(func() error {
  754. ping := func() error {
  755. wlock.Lock()
  756. defer wlock.Unlock()
  757. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  758. return err
  759. }
  760. return conn.WriteMessage(websocket.PingMessage, nil)
  761. }
  762. for {
  763. select {
  764. case <-ctx.Done():
  765. return nil
  766. case <-time.After(s.config.KeepaliveInterval):
  767. v.Keepalive()
  768. if err := ping(); err != nil {
  769. return err
  770. }
  771. }
  772. }
  773. })
  774. sub := func(msg *message) error {
  775. if !filters.Pass(msg) {
  776. return nil
  777. }
  778. wlock.Lock()
  779. defer wlock.Unlock()
  780. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  781. return err
  782. }
  783. return conn.WriteJSON(msg)
  784. }
  785. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  786. if poll {
  787. return s.sendOldMessages(topics, since, scheduled, sub)
  788. }
  789. subscriberIDs := make([]int, 0)
  790. for _, t := range topics {
  791. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  792. }
  793. defer func() {
  794. for i, subscriberID := range subscriberIDs {
  795. topics[i].Unsubscribe(subscriberID) // Order!
  796. }
  797. }()
  798. if err := sub(newOpenMessage(topicsStr)); err != nil { // Send out open message
  799. return err
  800. }
  801. if err := s.sendOldMessages(topics, since, scheduled, sub); err != nil {
  802. return err
  803. }
  804. err = g.Wait()
  805. if err != nil && websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
  806. return nil // Normal closures are not errors
  807. }
  808. return err
  809. }
  810. func parseSubscribeParams(r *http.Request) (poll bool, since sinceMarker, scheduled bool, filters *queryFilter, err error) {
  811. poll = readBoolParam(r, false, "x-poll", "poll", "po")
  812. scheduled = readBoolParam(r, false, "x-scheduled", "scheduled", "sched")
  813. since, err = parseSince(r, poll)
  814. if err != nil {
  815. return
  816. }
  817. filters, err = parseQueryFilters(r)
  818. if err != nil {
  819. return
  820. }
  821. return
  822. }
  823. func (s *Server) sendOldMessages(topics []*topic, since sinceMarker, scheduled bool, sub subscriber) error {
  824. if since.IsNone() {
  825. return nil
  826. }
  827. for _, t := range topics {
  828. messages, err := s.messageCache.Messages(t.ID, since, scheduled)
  829. if err != nil {
  830. return err
  831. }
  832. for _, m := range messages {
  833. if err := sub(m); err != nil {
  834. return err
  835. }
  836. }
  837. }
  838. return nil
  839. }
  840. // parseSince returns a timestamp identifying the time span from which cached messages should be received.
  841. //
  842. // Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), or
  843. // "all" for all messages.
  844. func parseSince(r *http.Request, poll bool) (sinceMarker, error) {
  845. since := readParam(r, "x-since", "since", "si")
  846. // Easy cases (empty, all, none)
  847. if since == "" {
  848. if poll {
  849. return sinceAllMessages, nil
  850. }
  851. return sinceNoMessages, nil
  852. } else if since == "all" {
  853. return sinceAllMessages, nil
  854. } else if since == "none" {
  855. return sinceNoMessages, nil
  856. }
  857. // ID, timestamp, duration
  858. if validMessageID(since) {
  859. return newSinceID(since), nil
  860. } else if s, err := strconv.ParseInt(since, 10, 64); err == nil {
  861. return newSinceTime(s), nil
  862. } else if d, err := time.ParseDuration(since); err == nil {
  863. return newSinceTime(time.Now().Add(-1 * d).Unix()), nil
  864. }
  865. return sinceNoMessages, errHTTPBadRequestSinceInvalid
  866. }
  867. func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request) error {
  868. w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST")
  869. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  870. w.Header().Set("Access-Control-Allow-Headers", "*") // CORS, allow auth via JS // FIXME is this terrible?
  871. return nil
  872. }
  873. func (s *Server) topicFromPath(path string) (*topic, error) {
  874. parts := strings.Split(path, "/")
  875. if len(parts) < 2 {
  876. return nil, errHTTPBadRequestTopicInvalid
  877. }
  878. topics, err := s.topicsFromIDs(parts[1])
  879. if err != nil {
  880. return nil, err
  881. }
  882. return topics[0], nil
  883. }
  884. func (s *Server) topicsFromPath(path string) ([]*topic, string, error) {
  885. parts := strings.Split(path, "/")
  886. if len(parts) < 2 {
  887. return nil, "", errHTTPBadRequestTopicInvalid
  888. }
  889. topicIDs := util.SplitNoEmpty(parts[1], ",")
  890. topics, err := s.topicsFromIDs(topicIDs...)
  891. if err != nil {
  892. return nil, "", errHTTPBadRequestTopicInvalid
  893. }
  894. return topics, parts[1], nil
  895. }
  896. func (s *Server) topicsFromIDs(ids ...string) ([]*topic, error) {
  897. s.mu.Lock()
  898. defer s.mu.Unlock()
  899. topics := make([]*topic, 0)
  900. for _, id := range ids {
  901. if util.InStringList(disallowedTopics, id) {
  902. return nil, errHTTPBadRequestTopicDisallowed
  903. }
  904. if _, ok := s.topics[id]; !ok {
  905. if len(s.topics) >= s.config.TotalTopicLimit {
  906. return nil, errHTTPTooManyRequestsLimitTotalTopics
  907. }
  908. s.topics[id] = newTopic(id)
  909. }
  910. topics = append(topics, s.topics[id])
  911. }
  912. return topics, nil
  913. }
  914. func (s *Server) updateStatsAndPrune() {
  915. s.mu.Lock()
  916. defer s.mu.Unlock()
  917. // Expire visitors from rate visitors map
  918. for ip, v := range s.visitors {
  919. if v.Stale() {
  920. delete(s.visitors, ip)
  921. }
  922. }
  923. // Delete expired attachments
  924. if s.fileCache != nil {
  925. ids, err := s.messageCache.AttachmentsExpired()
  926. if err == nil {
  927. if err := s.fileCache.Remove(ids...); err != nil {
  928. log.Printf("error while deleting attachments: %s", err.Error())
  929. }
  930. } else {
  931. log.Printf("error retrieving expired attachments: %s", err.Error())
  932. }
  933. }
  934. // Prune message cache
  935. olderThan := time.Now().Add(-1 * s.config.CacheDuration)
  936. if err := s.messageCache.Prune(olderThan); err != nil {
  937. log.Printf("error pruning cache: %s", err.Error())
  938. }
  939. // Prune old topics, remove subscriptions without subscribers
  940. var subscribers, messages int
  941. for _, t := range s.topics {
  942. subs := t.Subscribers()
  943. msgs, err := s.messageCache.MessageCount(t.ID)
  944. if err != nil {
  945. log.Printf("cannot get stats for topic %s: %s", t.ID, err.Error())
  946. continue
  947. }
  948. if msgs == 0 && subs == 0 {
  949. delete(s.topics, t.ID)
  950. continue
  951. }
  952. subscribers += subs
  953. messages += msgs
  954. }
  955. // Mail stats
  956. var mailSuccess, mailFailure int64
  957. if s.smtpBackend != nil {
  958. mailSuccess, mailFailure = s.smtpBackend.Counts()
  959. }
  960. // Print stats
  961. 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)",
  962. s.messages, messages, mailSuccess, mailFailure, len(s.topics), subscribers, len(s.visitors))
  963. }
  964. func (s *Server) runSMTPServer() error {
  965. sub := func(m *message) error {
  966. url := fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic)
  967. req, err := http.NewRequest("PUT", url, strings.NewReader(m.Message))
  968. if err != nil {
  969. return err
  970. }
  971. if m.Title != "" {
  972. req.Header.Set("Title", m.Title)
  973. }
  974. rr := httptest.NewRecorder()
  975. s.handle(rr, req)
  976. if rr.Code != http.StatusOK {
  977. return errors.New("error: " + rr.Body.String())
  978. }
  979. return nil
  980. }
  981. s.smtpBackend = newMailBackend(s.config, sub)
  982. s.smtpServer = smtp.NewServer(s.smtpBackend)
  983. s.smtpServer.Addr = s.config.SMTPServerListen
  984. s.smtpServer.Domain = s.config.SMTPServerDomain
  985. s.smtpServer.ReadTimeout = 10 * time.Second
  986. s.smtpServer.WriteTimeout = 10 * time.Second
  987. s.smtpServer.MaxMessageBytes = 1024 * 1024 // Must be much larger than message size (headers, multipart, etc.)
  988. s.smtpServer.MaxRecipients = 1
  989. s.smtpServer.AllowInsecureAuth = true
  990. return s.smtpServer.ListenAndServe()
  991. }
  992. func (s *Server) runManager() {
  993. for {
  994. select {
  995. case <-time.After(s.config.ManagerInterval):
  996. s.updateStatsAndPrune()
  997. case <-s.closeChan:
  998. return
  999. }
  1000. }
  1001. }
  1002. func (s *Server) runAtSender() {
  1003. for {
  1004. select {
  1005. case <-time.After(s.config.AtSenderInterval):
  1006. if err := s.sendDelayedMessages(); err != nil {
  1007. log.Printf("error sending scheduled messages: %s", err.Error())
  1008. }
  1009. case <-s.closeChan:
  1010. return
  1011. }
  1012. }
  1013. }
  1014. func (s *Server) runFirebaseKeepaliver() {
  1015. if s.firebase == nil {
  1016. return
  1017. }
  1018. for {
  1019. select {
  1020. case <-time.After(s.config.FirebaseKeepaliveInterval):
  1021. if err := s.firebase(newKeepaliveMessage(firebaseControlTopic)); err != nil {
  1022. log.Printf("error sending Firebase keepalive message: %s", err.Error())
  1023. }
  1024. case <-s.closeChan:
  1025. return
  1026. }
  1027. }
  1028. }
  1029. func (s *Server) sendDelayedMessages() error {
  1030. s.mu.Lock()
  1031. defer s.mu.Unlock()
  1032. messages, err := s.messageCache.MessagesDue()
  1033. if err != nil {
  1034. return err
  1035. }
  1036. for _, m := range messages {
  1037. t, ok := s.topics[m.Topic] // If no subscribers, just mark message as published
  1038. if ok {
  1039. if err := t.Publish(m); err != nil {
  1040. log.Printf("unable to publish message %s to topic %s: %v", m.ID, m.Topic, err.Error())
  1041. }
  1042. }
  1043. if s.firebase != nil { // Firebase subscribers may not show up in topics map
  1044. if err := s.firebase(m); err != nil {
  1045. log.Printf("unable to publish to Firebase: %v", err.Error())
  1046. }
  1047. }
  1048. if err := s.messageCache.MarkPublished(m); err != nil {
  1049. return err
  1050. }
  1051. }
  1052. return nil
  1053. }
  1054. func (s *Server) limitRequests(next handleFunc) handleFunc {
  1055. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1056. if util.InStringList(s.config.VisitorRequestExemptIPAddrs, v.ip) {
  1057. return next(w, r, v)
  1058. } else if err := v.RequestAllowed(); err != nil {
  1059. return errHTTPTooManyRequestsLimitRequests
  1060. }
  1061. return next(w, r, v)
  1062. }
  1063. }
  1064. func (s *Server) authWrite(next handleFunc) handleFunc {
  1065. return s.withAuth(next, auth.PermissionWrite)
  1066. }
  1067. func (s *Server) authRead(next handleFunc) handleFunc {
  1068. return s.withAuth(next, auth.PermissionRead)
  1069. }
  1070. func (s *Server) withAuth(next handleFunc, perm auth.Permission) handleFunc {
  1071. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1072. if s.auth == nil {
  1073. return next(w, r, v)
  1074. }
  1075. topics, _, err := s.topicsFromPath(r.URL.Path)
  1076. if err != nil {
  1077. return err
  1078. }
  1079. var user *auth.User // may stay nil if no auth header!
  1080. username, password, ok := extractUserPass(r)
  1081. if ok {
  1082. if user, err = s.auth.Authenticate(username, password); err != nil {
  1083. log.Printf("authentication failed: %s", err.Error())
  1084. return errHTTPUnauthorized
  1085. }
  1086. }
  1087. for _, t := range topics {
  1088. if err := s.auth.Authorize(user, t.ID, perm); err != nil {
  1089. log.Printf("unauthorized: %s", err.Error())
  1090. return errHTTPForbidden
  1091. }
  1092. }
  1093. return next(w, r, v)
  1094. }
  1095. }
  1096. // extractUserPass reads the username/password from the basic auth header (Authorization: Basic ...),
  1097. // or from the ?auth=... query param. The latter is required only to support the WebSocket JavaScript
  1098. // class, which does not support passing headers during the initial request. The auth query param
  1099. // is effectively double base64 encoded. Its format is base64(Basic base64(user:pass)).
  1100. func extractUserPass(r *http.Request) (username string, password string, ok bool) {
  1101. username, password, ok = r.BasicAuth()
  1102. if ok {
  1103. return
  1104. }
  1105. authParam := readQueryParam(r, "authorization", "auth")
  1106. if authParam != "" {
  1107. a, err := base64.RawURLEncoding.DecodeString(authParam)
  1108. if err != nil {
  1109. return
  1110. }
  1111. r.Header.Set("Authorization", string(a))
  1112. return r.BasicAuth()
  1113. }
  1114. return
  1115. }
  1116. // visitor creates or retrieves a rate.Limiter for the given visitor.
  1117. // This function was taken from https://www.alexedwards.net/blog/how-to-rate-limit-http-requests (MIT).
  1118. func (s *Server) visitor(r *http.Request) *visitor {
  1119. s.mu.Lock()
  1120. defer s.mu.Unlock()
  1121. remoteAddr := r.RemoteAddr
  1122. ip, _, err := net.SplitHostPort(remoteAddr)
  1123. if err != nil {
  1124. ip = remoteAddr // This should not happen in real life; only in tests.
  1125. }
  1126. if s.config.BehindProxy && r.Header.Get("X-Forwarded-For") != "" {
  1127. ip = r.Header.Get("X-Forwarded-For")
  1128. }
  1129. v, exists := s.visitors[ip]
  1130. if !exists {
  1131. s.visitors[ip] = newVisitor(s.config, ip)
  1132. return s.visitors[ip]
  1133. }
  1134. v.Keepalive()
  1135. return v
  1136. }