server.go 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "embed"
  7. "encoding/base64"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "regexp"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. "unicode/utf8"
  25. "heckel.io/ntfy/log"
  26. "github.com/emersion/go-smtp"
  27. "github.com/gorilla/websocket"
  28. "golang.org/x/sync/errgroup"
  29. "heckel.io/ntfy/auth"
  30. "heckel.io/ntfy/util"
  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. smtpServerBackend *smtpBackend
  40. smtpSender mailer
  41. topics map[string]*topic
  42. visitors map[string]*visitor
  43. firebaseClient *firebaseClient
  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. externalTopicPathRegex = regexp.MustCompile(`^/[^/]+\.[^/]+/[-_A-Za-z0-9]{1,64}$`) // Extended topic path, for web-app, e.g. /example.com/mytopic
  58. jsonPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/json$`)
  59. ssePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/sse$`)
  60. rawPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/raw$`)
  61. wsPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/ws$`)
  62. authPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/auth$`)
  63. publishPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/(publish|send|trigger)$`)
  64. webConfigPath = "/config.js"
  65. userStatsPath = "/user/stats"
  66. matrixPushPath = "/_matrix/push/v1/notify"
  67. staticRegex = regexp.MustCompile(`^/static/.+`)
  68. docsRegex = regexp.MustCompile(`^/docs(|/.*)$`)
  69. fileRegex = regexp.MustCompile(`^/file/([-_A-Za-z0-9]{1,64})(?:\.[A-Za-z0-9]{1,16})?$`)
  70. disallowedTopics = []string{"docs", "static", "file", "app", "settings"} // If updated, also update in Android app
  71. urlRegex = regexp.MustCompile(`^https?://`)
  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. firebasePollTopic = "~poll" // See iOS if changed
  85. emptyMessageBody = "triggered" // Used if message body is empty
  86. newMessageBody = "New message" // Used in poll requests as generic message
  87. defaultAttachmentMessage = "You received a file: %s" // Used if message body is empty, and there is an attachment
  88. encodingBase64 = "base64"
  89. encodingJWE = "jwe"
  90. multipartFieldMessage = "message"
  91. multipartFieldAttachment = "attachment"
  92. )
  93. // WebSocket constants
  94. const (
  95. wsWriteWait = 2 * time.Second
  96. wsBufferSize = 1024
  97. wsReadLimit = 64 // We only ever receive PINGs
  98. wsPongWait = 15 * time.Second
  99. )
  100. // New instantiates a new Server. It creates the cache and adds a Firebase
  101. // subscriber (if configured).
  102. func New(conf *Config) (*Server, error) {
  103. var mailer mailer
  104. if conf.SMTPSenderAddr != "" {
  105. mailer = &smtpSender{config: conf}
  106. }
  107. messageCache, err := createMessageCache(conf)
  108. if err != nil {
  109. return nil, err
  110. }
  111. topics, err := messageCache.Topics()
  112. if err != nil {
  113. return nil, err
  114. }
  115. var fileCache *fileCache
  116. if conf.AttachmentCacheDir != "" {
  117. fileCache, err = newFileCache(conf.AttachmentCacheDir, conf.AttachmentTotalSizeLimit, conf.AttachmentFileSizeLimit)
  118. if err != nil {
  119. return nil, err
  120. }
  121. }
  122. var auther auth.Auther
  123. if conf.AuthFile != "" {
  124. auther, err = auth.NewSQLiteAuth(conf.AuthFile, conf.AuthDefaultRead, conf.AuthDefaultWrite)
  125. if err != nil {
  126. return nil, err
  127. }
  128. }
  129. var firebaseClient *firebaseClient
  130. if conf.FirebaseKeyFile != "" {
  131. sender, err := newFirebaseSender(conf.FirebaseKeyFile)
  132. if err != nil {
  133. return nil, err
  134. }
  135. firebaseClient = newFirebaseClient(sender, auther)
  136. }
  137. return &Server{
  138. config: conf,
  139. messageCache: messageCache,
  140. fileCache: fileCache,
  141. firebaseClient: firebaseClient,
  142. smtpSender: mailer,
  143. topics: topics,
  144. auth: auther,
  145. visitors: make(map[string]*visitor),
  146. }, nil
  147. }
  148. func createMessageCache(conf *Config) (*messageCache, error) {
  149. if conf.CacheDuration == 0 {
  150. return newNopCache()
  151. } else if conf.CacheFile != "" {
  152. return newSqliteCache(conf.CacheFile, conf.CacheStartupQueries, false)
  153. }
  154. return newMemCache()
  155. }
  156. // Run executes the main server. It listens on HTTP (+ HTTPS, if configured), and starts
  157. // a manager go routine to print stats and prune messages.
  158. func (s *Server) Run() error {
  159. var listenStr string
  160. if s.config.ListenHTTP != "" {
  161. listenStr += fmt.Sprintf(" %s[http]", s.config.ListenHTTP)
  162. }
  163. if s.config.ListenHTTPS != "" {
  164. listenStr += fmt.Sprintf(" %s[https]", s.config.ListenHTTPS)
  165. }
  166. if s.config.ListenUnix != "" {
  167. listenStr += fmt.Sprintf(" %s[unix]", s.config.ListenUnix)
  168. }
  169. if s.config.SMTPServerListen != "" {
  170. listenStr += fmt.Sprintf(" %s[smtp]", s.config.SMTPServerListen)
  171. }
  172. log.Info("Listening on%s, ntfy %s, log level is %s", listenStr, s.config.Version, log.CurrentLevel().String())
  173. mux := http.NewServeMux()
  174. mux.HandleFunc("/", s.handle)
  175. errChan := make(chan error)
  176. s.mu.Lock()
  177. s.closeChan = make(chan bool)
  178. if s.config.ListenHTTP != "" {
  179. s.httpServer = &http.Server{Addr: s.config.ListenHTTP, Handler: mux}
  180. go func() {
  181. errChan <- s.httpServer.ListenAndServe()
  182. }()
  183. }
  184. if s.config.ListenHTTPS != "" {
  185. s.httpsServer = &http.Server{Addr: s.config.ListenHTTPS, Handler: mux}
  186. go func() {
  187. errChan <- s.httpsServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile)
  188. }()
  189. }
  190. if s.config.ListenUnix != "" {
  191. go func() {
  192. var err error
  193. s.mu.Lock()
  194. os.Remove(s.config.ListenUnix)
  195. s.unixListener, err = net.Listen("unix", s.config.ListenUnix)
  196. if err != nil {
  197. s.mu.Unlock()
  198. errChan <- err
  199. return
  200. }
  201. defer s.unixListener.Close()
  202. if s.config.ListenUnixMode > 0 {
  203. if err := os.Chmod(s.config.ListenUnix, s.config.ListenUnixMode); err != nil {
  204. s.mu.Unlock()
  205. errChan <- err
  206. return
  207. }
  208. }
  209. s.mu.Unlock()
  210. httpServer := &http.Server{Handler: mux}
  211. errChan <- httpServer.Serve(s.unixListener)
  212. }()
  213. }
  214. if s.config.SMTPServerListen != "" {
  215. go func() {
  216. errChan <- s.runSMTPServer()
  217. }()
  218. }
  219. s.mu.Unlock()
  220. go s.runManager()
  221. go s.runDelayedSender()
  222. go s.runFirebaseKeepaliver()
  223. return <-errChan
  224. }
  225. // Stop stops HTTP (+HTTPS) server and all managers
  226. func (s *Server) Stop() {
  227. s.mu.Lock()
  228. defer s.mu.Unlock()
  229. if s.httpServer != nil {
  230. s.httpServer.Close()
  231. }
  232. if s.httpsServer != nil {
  233. s.httpsServer.Close()
  234. }
  235. if s.unixListener != nil {
  236. s.unixListener.Close()
  237. }
  238. if s.smtpServer != nil {
  239. s.smtpServer.Close()
  240. }
  241. close(s.closeChan)
  242. }
  243. func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
  244. v := s.visitor(r)
  245. log.Debug("%s Dispatching request", logHTTPPrefix(v, r))
  246. if log.IsTrace() {
  247. log.Trace("%s Entire request (headers and body):\n%s", logHTTPPrefix(v, r), renderHTTPRequest(r))
  248. }
  249. if err := s.handleInternal(w, r, v); err != nil {
  250. if websocket.IsWebSocketUpgrade(r) {
  251. isNormalError := strings.Contains(err.Error(), "i/o timeout")
  252. if isNormalError {
  253. log.Debug("%s WebSocket error (this error is okay, it happens a lot): %s", logHTTPPrefix(v, r), err.Error())
  254. } else {
  255. log.Info("%s WebSocket error: %s", logHTTPPrefix(v, r), err.Error())
  256. }
  257. return // Do not attempt to write to upgraded connection
  258. }
  259. if matrixErr, ok := err.(*errMatrix); ok {
  260. writeMatrixError(w, r, v, matrixErr)
  261. return
  262. }
  263. httpErr, ok := err.(*errHTTP)
  264. if !ok {
  265. httpErr = errHTTPInternalError
  266. }
  267. isNormalError := httpErr.HTTPCode == http.StatusNotFound || httpErr.HTTPCode == http.StatusBadRequest
  268. if isNormalError {
  269. log.Debug("%s Connection closed with HTTP %d (ntfy error %d): %s", logHTTPPrefix(v, r), httpErr.HTTPCode, httpErr.Code, err.Error())
  270. } else {
  271. log.Info("%s Connection closed with HTTP %d (ntfy error %d): %s", logHTTPPrefix(v, r), httpErr.HTTPCode, httpErr.Code, err.Error())
  272. }
  273. w.Header().Set("Content-Type", "application/json")
  274. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  275. w.WriteHeader(httpErr.HTTPCode)
  276. io.WriteString(w, httpErr.JSON()+"\n")
  277. }
  278. }
  279. func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request, v *visitor) error {
  280. if r.Method == http.MethodGet && r.URL.Path == "/" {
  281. return s.ensureWebEnabled(s.handleHome)(w, r, v)
  282. } else if r.Method == http.MethodHead && r.URL.Path == "/" {
  283. return s.ensureWebEnabled(s.handleEmpty)(w, r, v)
  284. } else if r.Method == http.MethodGet && r.URL.Path == webConfigPath {
  285. return s.ensureWebEnabled(s.handleWebConfig)(w, r, v)
  286. } else if r.Method == http.MethodGet && r.URL.Path == userStatsPath {
  287. return s.handleUserStats(w, r, v)
  288. } else if r.Method == http.MethodGet && r.URL.Path == matrixPushPath {
  289. return s.handleMatrixDiscovery(w)
  290. } else if r.Method == http.MethodGet && staticRegex.MatchString(r.URL.Path) {
  291. return s.ensureWebEnabled(s.handleStatic)(w, r, v)
  292. } else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) {
  293. return s.ensureWebEnabled(s.handleDocs)(w, r, v)
  294. } else if (r.Method == http.MethodGet || r.Method == http.MethodHead) && fileRegex.MatchString(r.URL.Path) && s.config.AttachmentCacheDir != "" {
  295. return s.limitRequests(s.handleFile)(w, r, v)
  296. } else if r.Method == http.MethodOptions {
  297. return s.ensureWebEnabled(s.handleOptions)(w, r, v)
  298. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && (r.URL.Path == "/" || topicPathRegex.MatchString(r.URL.Path)) {
  299. return s.limitRequests(s.handlePublishAll)(w, r, v)
  300. } else if r.Method == http.MethodPost && r.URL.Path == matrixPushPath {
  301. return s.limitRequests(s.transformMatrixJSON(s.authWrite(s.handlePublishMatrix)))(w, r, v)
  302. } else if r.Method == http.MethodGet && publishPathRegex.MatchString(r.URL.Path) {
  303. return s.limitRequests(s.authWrite(s.handlePublish))(w, r, v)
  304. } else if r.Method == http.MethodGet && jsonPathRegex.MatchString(r.URL.Path) {
  305. return s.limitRequests(s.authRead(s.handleSubscribeJSON))(w, r, v)
  306. } else if r.Method == http.MethodGet && ssePathRegex.MatchString(r.URL.Path) {
  307. return s.limitRequests(s.authRead(s.handleSubscribeSSE))(w, r, v)
  308. } else if r.Method == http.MethodGet && rawPathRegex.MatchString(r.URL.Path) {
  309. return s.limitRequests(s.authRead(s.handleSubscribeRaw))(w, r, v)
  310. } else if r.Method == http.MethodGet && wsPathRegex.MatchString(r.URL.Path) {
  311. return s.limitRequests(s.authRead(s.handleSubscribeWS))(w, r, v)
  312. } else if r.Method == http.MethodGet && authPathRegex.MatchString(r.URL.Path) {
  313. return s.limitRequests(s.authRead(s.handleTopicAuth))(w, r, v)
  314. } else if r.Method == http.MethodGet && (topicPathRegex.MatchString(r.URL.Path) || externalTopicPathRegex.MatchString(r.URL.Path)) {
  315. return s.ensureWebEnabled(s.handleTopic)(w, r, v)
  316. }
  317. return errHTTPNotFound
  318. }
  319. func (s *Server) handleHome(w http.ResponseWriter, r *http.Request, v *visitor) error {
  320. if s.config.WebRootIsApp {
  321. r.URL.Path = webAppIndex
  322. } else {
  323. r.URL.Path = webHomeIndex
  324. }
  325. return s.handleStatic(w, r, v)
  326. }
  327. func (s *Server) handleTopic(w http.ResponseWriter, r *http.Request, v *visitor) error {
  328. unifiedpush := readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see PUT/POST too!
  329. if unifiedpush {
  330. w.Header().Set("Content-Type", "application/json")
  331. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  332. _, err := io.WriteString(w, `{"unifiedpush":{"version":1}}`+"\n")
  333. return err
  334. }
  335. r.URL.Path = webAppIndex
  336. return s.handleStatic(w, r, v)
  337. }
  338. func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request, _ *visitor) error {
  339. return nil
  340. }
  341. func (s *Server) handleTopicAuth(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  342. w.Header().Set("Content-Type", "application/json")
  343. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  344. _, err := io.WriteString(w, `{"success":true}`+"\n")
  345. return err
  346. }
  347. func (s *Server) handleWebConfig(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  348. appRoot := "/"
  349. if !s.config.WebRootIsApp {
  350. appRoot = "/app"
  351. }
  352. disallowedTopicsStr := `"` + strings.Join(disallowedTopics, `", "`) + `"`
  353. w.Header().Set("Content-Type", "text/javascript")
  354. _, err := io.WriteString(w, fmt.Sprintf(`// Generated server configuration
  355. var config = {
  356. appRoot: "%s",
  357. disallowedTopics: [%s]
  358. };`, appRoot, disallowedTopicsStr))
  359. return err
  360. }
  361. func (s *Server) handleUserStats(w http.ResponseWriter, r *http.Request, v *visitor) error {
  362. stats, err := v.Stats()
  363. if err != nil {
  364. return err
  365. }
  366. w.Header().Set("Content-Type", "text/json")
  367. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  368. if err := json.NewEncoder(w).Encode(stats); err != nil {
  369. return err
  370. }
  371. return nil
  372. }
  373. func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  374. r.URL.Path = webSiteDir + r.URL.Path
  375. util.Gzip(http.FileServer(http.FS(webFsCached))).ServeHTTP(w, r)
  376. return nil
  377. }
  378. func (s *Server) handleDocs(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  379. util.Gzip(http.FileServer(http.FS(docsStaticCached))).ServeHTTP(w, r)
  380. return nil
  381. }
  382. func (s *Server) handleFile(w http.ResponseWriter, r *http.Request, v *visitor) error {
  383. if s.config.AttachmentCacheDir == "" {
  384. return errHTTPInternalError
  385. }
  386. matches := fileRegex.FindStringSubmatch(r.URL.Path)
  387. if len(matches) != 2 {
  388. return errHTTPInternalErrorInvalidFilePath
  389. }
  390. messageID := matches[1]
  391. file := filepath.Join(s.config.AttachmentCacheDir, messageID)
  392. stat, err := os.Stat(file) // TODO: Why is this here and not in fileCache?!
  393. if err != nil {
  394. return errHTTPNotFound
  395. }
  396. if r.Method == http.MethodGet {
  397. if err := v.BandwidthLimiter().Allow(stat.Size()); err != nil {
  398. return errHTTPTooManyRequestsAttachmentBandwidthLimit
  399. }
  400. }
  401. w.Header().Set("Content-Length", fmt.Sprintf("%d", stat.Size()))
  402. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  403. if r.Method == http.MethodGet {
  404. f, err := os.Open(file)
  405. if err != nil {
  406. return err
  407. }
  408. defer f.Close()
  409. _, err = io.Copy(util.NewContentTypeWriter(w, r.URL.Path), f)
  410. return err
  411. }
  412. return nil
  413. }
  414. func (s *Server) handleMatrixDiscovery(w http.ResponseWriter) error {
  415. if s.config.BaseURL == "" {
  416. return errHTTPInternalErrorMissingBaseURL
  417. }
  418. return writeMatrixDiscoveryResponse(w)
  419. }
  420. func (s *Server) handlePublishInternal(r *http.Request, v *visitor) (*message, error) {
  421. t, err := s.topicFromPath(r.URL.Path)
  422. if err != nil {
  423. return nil, err
  424. }
  425. m := newDefaultMessage(t.ID, "")
  426. cache, firebase, email, unifiedpush, err := s.parsePublishParams(r, v, m)
  427. if err != nil {
  428. return nil, err
  429. }
  430. var body *util.PeekedReadCloser
  431. if m.Encoding == encodingJWE {
  432. m = newEncryptedMessage(t.ID, im.M)
  433. if body, err = s.handlePublishEncrypted(r, m); err != nil {
  434. return nil, err
  435. }
  436. } else {
  437. if body, err = util.Peek(r.Body, s.config.MessageLimit); err != nil {
  438. return nil, err
  439. }
  440. }
  441. if m.PollID != "" {
  442. m = newPollRequestMessage(t.ID, m.PollID)
  443. }
  444. if err := s.handlePublishBody(r, v, m, body, unifiedpush); err != nil {
  445. return nil, err
  446. }
  447. if m.Message == "" {
  448. m.Message = emptyMessageBody
  449. }
  450. delayed := m.Time > time.Now().Unix()
  451. log.Debug("%s Received message: event=%s, body=%d byte(s), delayed=%t, firebase=%t, cache=%t, up=%t, email=%s",
  452. logMessagePrefix(v, m), m.Event, len(m.Message), delayed, firebase, cache, unifiedpush, email)
  453. if log.IsTrace() {
  454. log.Trace("%s Message body: %s", logMessagePrefix(v, m), util.MaybeMarshalJSON(m))
  455. }
  456. if !delayed {
  457. if err := t.Publish(v, m); err != nil {
  458. return nil, err
  459. }
  460. if s.firebaseClient != nil && firebase {
  461. go s.sendToFirebase(v, m)
  462. }
  463. if s.smtpSender != nil && email != "" {
  464. go s.sendEmail(v, m, email)
  465. }
  466. if s.config.UpstreamBaseURL != "" {
  467. go s.forwardPollRequest(v, m)
  468. }
  469. } else {
  470. log.Debug("%s Message delayed, will process later", logMessagePrefix(v, m))
  471. }
  472. if cache {
  473. if err := s.messageCache.AddMessage(m); err != nil {
  474. return nil, err
  475. }
  476. }
  477. s.mu.Lock()
  478. s.messages++
  479. s.mu.Unlock()
  480. return m, nil
  481. }
  482. type inputMessage struct {
  483. PublishMessage
  484. AttachmentBody io.ReadCloser
  485. Cache bool
  486. Firebase bool
  487. UnifiedPush bool
  488. PollID string
  489. Encoding string
  490. }
  491. func (s *Server) handlePublishAll(w http.ResponseWriter, r *http.Request, v *visitor) error {
  492. // TODO authWrite
  493. im, err := s.parsePublishInputMessage(r, v)
  494. if err != nil {
  495. return err
  496. }
  497. t, err := s.topicsFromID(im.Topic)
  498. if err != nil {
  499. return err
  500. }
  501. m, err := s.checkAndConvertPublishMessage(v, im)
  502. if err != nil {
  503. return err
  504. }
  505. var body *util.PeekedReadCloser
  506. if err := s.handlePublishBody(r, v, m, body, unifiedpush); err != nil {
  507. return err
  508. }
  509. if m.Message == "" {
  510. m.Message = emptyMessageBody
  511. }
  512. delayed := m.Time > time.Now().Unix()
  513. log.Debug("%s Received message: event=%s, body=%d byte(s), delayed=%t, firebase=%t, cache=%t, up=%t, email=%s",
  514. logMessagePrefix(v, m), m.Event, len(m.Message), delayed, im.Firebase, im.Cache, im.UnifiedPush, im.Email)
  515. if log.IsTrace() {
  516. log.Trace("%s Message body: %s", logMessagePrefix(v, m), util.MaybeMarshalJSON(m))
  517. }
  518. if !delayed {
  519. if err := t.Publish(v, m); err != nil {
  520. return err
  521. }
  522. if s.firebaseClient != nil && im.Firebase {
  523. go s.sendToFirebase(v, m)
  524. }
  525. if s.smtpSender != nil && im.Email != "" {
  526. go s.sendEmail(v, m, im.Email)
  527. }
  528. if s.config.UpstreamBaseURL != "" {
  529. go s.forwardPollRequest(v, m)
  530. }
  531. } else {
  532. log.Debug("%s Message delayed, will process later", logMessagePrefix(v, m))
  533. }
  534. if im.Cache {
  535. if err := s.messageCache.AddMessage(m); err != nil {
  536. return err
  537. }
  538. }
  539. s.mu.Lock()
  540. s.messages++
  541. s.mu.Unlock()
  542. return nil
  543. }
  544. func (s *Server) parsePublishInputMessage(r *http.Request, v *visitor) (im *inputMessage, err error) {
  545. im = &inputMessage{}
  546. encrypted := readParam(r, "x-encoding", "encoding") == encodingJWE
  547. multipart := strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/")
  548. isJSON := r.URL.Path == "/"
  549. if err := s.parsePublishParams(r, im); err != nil {
  550. return nil, err
  551. }
  552. parts := strings.Split(r.URL.Path, "/")
  553. if len(parts) < 2 {
  554. return nil, errHTTPBadRequestTopicInvalid
  555. }
  556. im.Topic = parts[1]
  557. if multipart {
  558. im.Message, im.AttachmentBody, err = s.readMultipart(r)
  559. if err != nil {
  560. return nil, err
  561. }
  562. if !encrypted && isJSON {
  563. if err := json.NewDecoder(strings.NewReader(im.Message)).Decode(&im.PublishMessage); err != nil {
  564. return nil, errHTTPBadRequestJSONInvalid
  565. }
  566. }
  567. } else {
  568. body, err := util.Peek(r.Body, s.config.MessageLimit)
  569. if err != nil {
  570. return nil, err
  571. }
  572. if encrypted {
  573. if body.LimitReached {
  574. return nil, errHTTPEntityTooLargeMessageTooLarge
  575. }
  576. im.Message = string(body.PeekedBytes)
  577. } else if body.LimitReached {
  578. im.AttachmentBody = body
  579. } else if isJSON {
  580. if err := json.NewDecoder(strings.NewReader(im.Message)).Decode(&im.PublishMessage); err != nil {
  581. return nil, errHTTPBadRequestJSONInvalid
  582. }
  583. } else {
  584. im.Message = string(body.PeekedBytes)
  585. }
  586. }
  587. return im, nil
  588. }
  589. func (s *Server) readMultipart(r *http.Request) (message string, attachment io.ReadCloser, err error) {
  590. mp, err := r.MultipartReader()
  591. if err != nil {
  592. return "", nil, err
  593. }
  594. p, err := mp.NextPart()
  595. if err != nil {
  596. return "", nil, err
  597. } else if p.FormName() != multipartFieldMessage {
  598. return "", nil, wrapErrHTTP(errHTTPBadRequestUnexpectedMultipartField, "expected '%s', got '%s'", multipartFieldMessage, p.FormName())
  599. }
  600. messageBody, err := util.PeekLimit(p, s.config.MessageLimit)
  601. if err == util.ErrLimitReached {
  602. return "", nil, errHTTPEntityTooLargeMessageTooLarge
  603. } else if err != nil {
  604. return "", nil, err
  605. }
  606. message = string(messageBody.PeekedBytes)
  607. attachment, err = mp.NextPart()
  608. if err != nil {
  609. return "", nil, err
  610. } else if p.FormName() != multipartFieldAttachment {
  611. return "", nil, wrapErrHTTP(errHTTPBadRequestUnexpectedMultipartField, "expected '%s', got '%s'", multipartFieldAttachment, p.FormName())
  612. }
  613. return message, attachment, nil
  614. }
  615. func (s *Server) checkAndConvertPublishMessage(v *visitor, im *inputMessage) (m *message, err error) {
  616. if m.PollID != "" {
  617. im.Cache = false
  618. im.Email = ""
  619. im.UnifiedPush = false
  620. return newPollRequestMessage(im.Topic, m.PollID), nil
  621. } else if im.Encoding == encodingJWE {
  622. im.Email = ""
  623. im.UnifiedPush = false
  624. return newEncryptedMessage(im.Topic, im.Message), nil
  625. }
  626. m = newDefaultMessage(im.Topic, im.Message)
  627. m.Title = im.Title
  628. m.Priority = im.Priority
  629. m.Tags = im.Tags
  630. m.Click = im.Click
  631. m.Actions = im.Actions
  632. if im.Attach != "" || im.Filename != "" {
  633. m.Attachment = &attachment{}
  634. }
  635. if im.Filename != "" {
  636. m.Attachment.Name = im.Filename
  637. }
  638. if im.Attach != "" {
  639. if !urlRegex.MatchString(im.Attach) {
  640. return nil, errHTTPBadRequestAttachmentURLInvalid
  641. }
  642. if im.AttachmentBody != nil {
  643. return nil, errors.New("cannot attach and send attachment body") // TODO test for this
  644. }
  645. m.Attachment.URL = im.Attach
  646. if im.Filename == "" {
  647. u, err := url.Parse(m.Attachment.URL)
  648. if err == nil {
  649. m.Attachment.Name = path.Base(u.Path)
  650. if m.Attachment.Name == "." || m.Attachment.Name == "/" {
  651. m.Attachment.Name = ""
  652. }
  653. }
  654. }
  655. if m.Attachment.Name == "" {
  656. m.Attachment.Name = "attachment"
  657. }
  658. }
  659. if im.Icon != "" {
  660. if !urlRegex.MatchString(im.Icon) {
  661. return nil, errHTTPBadRequestIconURLInvalid
  662. }
  663. m.Icon = im.Icon
  664. }
  665. if im.Email != "" {
  666. if err := v.EmailAllowed(); err != nil {
  667. return nil, errHTTPTooManyRequestsLimitEmails
  668. }
  669. }
  670. if s.smtpSender == nil && im.Email != "" {
  671. return nil, errHTTPBadRequestEmailDisabled
  672. }
  673. if im.Delay != "" {
  674. if !im.Cache {
  675. return nil, errHTTPBadRequestDelayNoCache
  676. }
  677. if im.Email != "" {
  678. return nil, errHTTPBadRequestDelayNoEmail // we cannot store the email address (yet)
  679. }
  680. delay, err := util.ParseFutureTime(im.Delay, time.Now())
  681. if err != nil {
  682. return nil, errHTTPBadRequestDelayCannotParse
  683. } else if delay.Unix() < time.Now().Add(s.config.MinDelay).Unix() {
  684. return nil, errHTTPBadRequestDelayTooSmall
  685. } else if delay.Unix() > time.Now().Add(s.config.MaxDelay).Unix() {
  686. return nil, errHTTPBadRequestDelayTooLarge
  687. }
  688. m.Time = delay.Unix()
  689. m.Sender = v.ip // Important for rate limiting
  690. }
  691. if im.UnifiedPush {
  692. im.Firebase = false
  693. im.UnifiedPush = true
  694. }
  695. return m, nil
  696. }
  697. func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, v *visitor) error {
  698. m, err := s.handlePublishInternal(r, v)
  699. if err != nil {
  700. return err
  701. }
  702. w.Header().Set("Content-Type", "application/json")
  703. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  704. if err := json.NewEncoder(w).Encode(m); err != nil {
  705. return err
  706. }
  707. return nil
  708. }
  709. func (s *Server) handlePublishMatrix(w http.ResponseWriter, r *http.Request, v *visitor) error {
  710. _, err := s.handlePublishInternal(r, v)
  711. if err != nil {
  712. return &errMatrix{pushKey: r.Header.Get(matrixPushKeyHeader), err: err}
  713. }
  714. return writeMatrixSuccess(w)
  715. }
  716. func (s *Server) sendToFirebase(v *visitor, m *message) {
  717. log.Debug("%s Publishing to Firebase", logMessagePrefix(v, m))
  718. if err := s.firebaseClient.Send(v, m); err != nil {
  719. if err == errFirebaseTemporarilyBanned {
  720. log.Debug("%s Unable to publish to Firebase: %v", logMessagePrefix(v, m), err.Error())
  721. } else {
  722. log.Warn("%s Unable to publish to Firebase: %v", logMessagePrefix(v, m), err.Error())
  723. }
  724. }
  725. }
  726. func (s *Server) sendEmail(v *visitor, m *message, email string) {
  727. log.Debug("%s Sending email to %s", logMessagePrefix(v, m), email)
  728. if err := s.smtpSender.Send(v, m, email); err != nil {
  729. log.Warn("%s Unable to send email to %s: %v", logMessagePrefix(v, m), email, err.Error())
  730. }
  731. }
  732. func (s *Server) forwardPollRequest(v *visitor, m *message) {
  733. topicURL := fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic)
  734. topicHash := fmt.Sprintf("%x", sha256.Sum256([]byte(topicURL)))
  735. forwardURL := fmt.Sprintf("%s/%s", s.config.UpstreamBaseURL, topicHash)
  736. log.Debug("%s Publishing poll request to %s", logMessagePrefix(v, m), forwardURL)
  737. req, err := http.NewRequest("POST", forwardURL, strings.NewReader(""))
  738. if err != nil {
  739. log.Warn("%s Unable to publish poll request: %v", logMessagePrefix(v, m), err.Error())
  740. return
  741. }
  742. req.Header.Set("X-Poll-ID", m.ID)
  743. var httpClient = &http.Client{
  744. Timeout: time.Second * 10,
  745. }
  746. response, err := httpClient.Do(req)
  747. if err != nil {
  748. log.Warn("%s Unable to publish poll request: %v", logMessagePrefix(v, m), err.Error())
  749. return
  750. } else if response.StatusCode != http.StatusOK {
  751. log.Warn("%s Unable to publish poll request, unexpected HTTP status: %d", logMessagePrefix(v, m), response.StatusCode)
  752. return
  753. }
  754. }
  755. func (s *Server) parsePublishParams(r *http.Request, m *inputMessage) error {
  756. m.Message = strings.ReplaceAll(readParam(r, "x-message", "message", "m"), "\\n", "\n")
  757. m.Title = readParam(r, "x-title", "title", "t")
  758. m.Click = readParam(r, "x-click", "click")
  759. m.Icon = readParam(r, "x-icon", "icon")
  760. m.Filename = readParam(r, "x-filename", "filename", "file", "f")
  761. m.Attach = readParam(r, "x-attach", "attach", "a")
  762. m.Email = readParam(r, "x-email", "x-e-mail", "email", "e-mail", "mail", "e")
  763. m.Delay = readParam(r, "x-delay", "delay", "x-at", "at", "x-in", "in")
  764. m.Encoding = readParam(r, "x-encoding", "encoding")
  765. m.UnifiedPush = readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see GET too!
  766. m.Cache = readBoolParam(r, true, "x-cache", "cache")
  767. m.Firebase = readBoolParam(r, true, "x-firebase", "firebase")
  768. m.PollID = readParam(r, "x-poll-id", "poll-id")
  769. var err error
  770. m.Priority, err = util.ParsePriority(readParam(r, "x-priority", "priority", "prio", "p"))
  771. if err != nil {
  772. return errHTTPBadRequestPriorityInvalid
  773. }
  774. tagsStr := readParam(r, "x-tags", "tags", "tag", "ta")
  775. if tagsStr != "" {
  776. m.Tags = make([]string, 0)
  777. for _, s := range util.SplitNoEmpty(tagsStr, ",") {
  778. m.Tags = append(m.Tags, strings.TrimSpace(s))
  779. }
  780. }
  781. actionsStr := readParam(r, "x-actions", "actions", "action")
  782. if actionsStr != "" {
  783. m.Actions, err = parseActions(actionsStr)
  784. if err != nil {
  785. return wrapErrHTTP(errHTTPBadRequestActionsInvalid, err.Error())
  786. }
  787. }
  788. return nil
  789. }
  790. // handlePublishBody consumes the PUT/POST body and decides whether the body is an attachment or the message.
  791. //
  792. // 1. curl -X POST -H "Poll: 1234" ntfy.sh/...
  793. // If a message is flagged as poll request, the body does not matter and is discarded
  794. // 2. curl -T somebinarydata.bin "ntfy.sh/mytopic?up=1"
  795. // If body is binary, encode as base64, if not do not encode
  796. // 3. curl -H "Attach: http://example.com/file.jpg" ntfy.sh/mytopic
  797. // Body must be a message, because we attached an external URL
  798. // 4. curl -T short.txt -H "Filename: short.txt" ntfy.sh/mytopic
  799. // Body must be attachment, because we passed a filename
  800. // 5. curl -T file.txt ntfy.sh/mytopic
  801. // If file.txt is <= 4096 (message limit) and valid UTF-8, treat it as a message
  802. // 6. curl -T file.txt ntfy.sh/mytopic
  803. // If file.txt is > message limit, treat it as an attachment
  804. func (s *Server) handlePublishBody(r *http.Request, v *visitor, m *message, body *util.PeekedReadCloser, unifiedpush bool) error {
  805. if m.Event == pollRequestEvent { // Case 1
  806. return s.handleBodyDiscard(body)
  807. } else if unifiedpush {
  808. return s.handleBodyAsMessageAutoDetect(m, body) // Case 2
  809. } else if m.Attachment != nil && m.Attachment.URL != "" {
  810. return s.handleBodyAsTextMessage(m, body) // Case 3
  811. } else if m.Attachment != nil && m.Attachment.Name != "" {
  812. return s.handleBodyAsAttachment(r, v, m, body) // Case 4
  813. } else if !body.LimitReached && utf8.Valid(body.PeekedBytes) {
  814. return s.handleBodyAsTextMessage(m, body) // Case 5
  815. }
  816. return s.handleBodyAsAttachment(r, v, m, body) // Case 6
  817. }
  818. func (s *Server) handleBodyDiscard(body *util.PeekedReadCloser) error {
  819. _, err := io.Copy(io.Discard, body)
  820. _ = body.Close()
  821. return err
  822. }
  823. func (s *Server) handleBodyAsMessageAutoDetect(m *message, body *util.PeekedReadCloser) error {
  824. if utf8.Valid(body.PeekedBytes) {
  825. m.Message = string(body.PeekedBytes) // Do not trim
  826. } else {
  827. m.Message = base64.StdEncoding.EncodeToString(body.PeekedBytes)
  828. m.Encoding = encodingBase64
  829. }
  830. return nil
  831. }
  832. func (s *Server) handleBodyAsTextMessage(m *message, body *util.PeekedReadCloser) error {
  833. if !utf8.Valid(body.PeekedBytes) {
  834. return errHTTPBadRequestMessageNotUTF8
  835. }
  836. if len(body.PeekedBytes) > 0 { // Empty body should not override message (publish via GET!)
  837. m.Message = strings.TrimSpace(string(body.PeekedBytes)) // Truncates the message to the peek limit if required
  838. }
  839. if m.Attachment != nil && m.Attachment.Name != "" && m.Message == "" {
  840. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  841. }
  842. return nil
  843. }
  844. func (s *Server) handleBodyAsAttachment(r *http.Request, v *visitor, m *message, body *util.PeekedReadCloser) error {
  845. if s.fileCache == nil || s.config.BaseURL == "" || s.config.AttachmentCacheDir == "" {
  846. return errHTTPBadRequestAttachmentsDisallowed
  847. } else if m.Time > time.Now().Add(s.config.AttachmentExpiryDuration).Unix() {
  848. return errHTTPBadRequestAttachmentsExpiryBeforeDelivery
  849. }
  850. visitorStats, err := v.Stats()
  851. if err != nil {
  852. return err
  853. }
  854. contentLengthStr := r.Header.Get("Content-Length")
  855. if contentLengthStr != "" { // Early "do-not-trust" check, hard limit see below
  856. contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
  857. if err == nil && (contentLength > visitorStats.VisitorAttachmentBytesRemaining || contentLength > s.config.AttachmentFileSizeLimit) {
  858. return errHTTPEntityTooLargeAttachmentTooLarge
  859. }
  860. }
  861. if m.Attachment == nil {
  862. m.Attachment = &attachment{}
  863. }
  864. var ext string
  865. m.Sender = v.ip // Important for attachment rate limiting
  866. m.Attachment.Expires = time.Now().Add(s.config.AttachmentExpiryDuration).Unix()
  867. m.Attachment.Type, ext = util.DetectContentType(body.PeekedBytes, m.Attachment.Name)
  868. m.Attachment.URL = fmt.Sprintf("%s/file/%s%s", s.config.BaseURL, m.ID, ext)
  869. if m.Attachment.Name == "" {
  870. m.Attachment.Name = fmt.Sprintf("attachment%s", ext)
  871. }
  872. if m.Message == "" {
  873. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  874. }
  875. m.Attachment.Size, err = s.fileCache.Write(m.ID, body, v.BandwidthLimiter(), util.NewFixedLimiter(visitorStats.VisitorAttachmentBytesRemaining))
  876. if err == util.ErrLimitReached {
  877. return errHTTPEntityTooLargeAttachmentTooLarge
  878. } else if err != nil {
  879. return err
  880. }
  881. return nil
  882. }
  883. func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error {
  884. encoder := func(msg *message) (string, error) {
  885. var buf bytes.Buffer
  886. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  887. return "", err
  888. }
  889. return buf.String(), nil
  890. }
  891. return s.handleSubscribeHTTP(w, r, v, "application/x-ndjson", encoder)
  892. }
  893. func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error {
  894. encoder := func(msg *message) (string, error) {
  895. var buf bytes.Buffer
  896. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  897. return "", err
  898. }
  899. if msg.Event != messageEvent {
  900. return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this!
  901. }
  902. return fmt.Sprintf("data: %s\n", buf.String()), nil
  903. }
  904. return s.handleSubscribeHTTP(w, r, v, "text/event-stream", encoder)
  905. }
  906. func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error {
  907. encoder := func(msg *message) (string, error) {
  908. if msg.Event == messageEvent { // only handle default events
  909. return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil
  910. }
  911. return "\n", nil // "keepalive" and "open" events just send an empty line
  912. }
  913. return s.handleSubscribeHTTP(w, r, v, "text/plain", encoder)
  914. }
  915. func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request, v *visitor, contentType string, encoder messageEncoder) error {
  916. log.Debug("%s HTTP stream connection opened", logHTTPPrefix(v, r))
  917. defer log.Debug("%s HTTP stream connection closed", logHTTPPrefix(v, r))
  918. if err := v.SubscriptionAllowed(); err != nil {
  919. return errHTTPTooManyRequestsLimitSubscriptions
  920. }
  921. defer v.RemoveSubscription()
  922. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  923. if err != nil {
  924. return err
  925. }
  926. poll, since, scheduled, filters, err := parseSubscribeParams(r)
  927. if err != nil {
  928. return err
  929. }
  930. var wlock sync.Mutex
  931. defer func() {
  932. // Hack: This is the fix for a horrible data race that I have not been able to figure out in quite some time.
  933. // It appears to be happening when the Go HTTP code reads from the socket when closing the request (i.e. AFTER
  934. // this function returns), and causes a data race with the ResponseWriter. Locking wlock here silences the
  935. // data race detector. See https://github.com/binwiederhier/ntfy/issues/338#issuecomment-1163425889.
  936. wlock.TryLock()
  937. }()
  938. sub := func(v *visitor, msg *message) error {
  939. if !filters.Pass(msg) {
  940. return nil
  941. }
  942. m, err := encoder(msg)
  943. if err != nil {
  944. return err
  945. }
  946. wlock.Lock()
  947. defer wlock.Unlock()
  948. if _, err := w.Write([]byte(m)); err != nil {
  949. return err
  950. }
  951. if fl, ok := w.(http.Flusher); ok {
  952. fl.Flush()
  953. }
  954. return nil
  955. }
  956. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  957. w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset!
  958. if poll {
  959. return s.sendOldMessages(topics, since, scheduled, v, sub)
  960. }
  961. subscriberIDs := make([]int, 0)
  962. for _, t := range topics {
  963. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  964. }
  965. defer func() {
  966. for i, subscriberID := range subscriberIDs {
  967. topics[i].Unsubscribe(subscriberID) // Order!
  968. }
  969. }()
  970. if err := sub(v, newOpenMessage(topicsStr)); err != nil { // Send out open message
  971. return err
  972. }
  973. if err := s.sendOldMessages(topics, since, scheduled, v, sub); err != nil {
  974. return err
  975. }
  976. for {
  977. select {
  978. case <-r.Context().Done():
  979. return nil
  980. case <-time.After(s.config.KeepaliveInterval):
  981. log.Trace("%s Sending keepalive message", logHTTPPrefix(v, r))
  982. v.Keepalive()
  983. if err := sub(v, newKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message
  984. return err
  985. }
  986. }
  987. }
  988. }
  989. func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request, v *visitor) error {
  990. if strings.ToLower(r.Header.Get("Upgrade")) != "websocket" {
  991. return errHTTPBadRequestWebSocketsUpgradeHeaderMissing
  992. }
  993. if err := v.SubscriptionAllowed(); err != nil {
  994. return errHTTPTooManyRequestsLimitSubscriptions
  995. }
  996. defer v.RemoveSubscription()
  997. log.Debug("%s WebSocket connection opened", logHTTPPrefix(v, r))
  998. defer log.Debug("%s WebSocket connection closed", logHTTPPrefix(v, r))
  999. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  1000. if err != nil {
  1001. return err
  1002. }
  1003. poll, since, scheduled, filters, err := parseSubscribeParams(r)
  1004. if err != nil {
  1005. return err
  1006. }
  1007. upgrader := &websocket.Upgrader{
  1008. ReadBufferSize: wsBufferSize,
  1009. WriteBufferSize: wsBufferSize,
  1010. CheckOrigin: func(r *http.Request) bool {
  1011. return true // We're open for business!
  1012. },
  1013. }
  1014. conn, err := upgrader.Upgrade(w, r, nil)
  1015. if err != nil {
  1016. return err
  1017. }
  1018. defer conn.Close()
  1019. var wlock sync.Mutex
  1020. g, ctx := errgroup.WithContext(context.Background())
  1021. g.Go(func() error {
  1022. pongWait := s.config.KeepaliveInterval + wsPongWait
  1023. conn.SetReadLimit(wsReadLimit)
  1024. if err := conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
  1025. return err
  1026. }
  1027. conn.SetPongHandler(func(appData string) error {
  1028. log.Trace("%s Received WebSocket pong", logHTTPPrefix(v, r))
  1029. return conn.SetReadDeadline(time.Now().Add(pongWait))
  1030. })
  1031. for {
  1032. _, _, err := conn.NextReader()
  1033. if err != nil {
  1034. return err
  1035. }
  1036. }
  1037. })
  1038. g.Go(func() error {
  1039. ping := func() error {
  1040. wlock.Lock()
  1041. defer wlock.Unlock()
  1042. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  1043. return err
  1044. }
  1045. log.Trace("%s Sending WebSocket ping", logHTTPPrefix(v, r))
  1046. return conn.WriteMessage(websocket.PingMessage, nil)
  1047. }
  1048. for {
  1049. select {
  1050. case <-ctx.Done():
  1051. return nil
  1052. case <-time.After(s.config.KeepaliveInterval):
  1053. v.Keepalive()
  1054. if err := ping(); err != nil {
  1055. return err
  1056. }
  1057. }
  1058. }
  1059. })
  1060. sub := func(v *visitor, msg *message) error {
  1061. if !filters.Pass(msg) {
  1062. return nil
  1063. }
  1064. wlock.Lock()
  1065. defer wlock.Unlock()
  1066. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  1067. return err
  1068. }
  1069. return conn.WriteJSON(msg)
  1070. }
  1071. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  1072. if poll {
  1073. return s.sendOldMessages(topics, since, scheduled, v, sub)
  1074. }
  1075. subscriberIDs := make([]int, 0)
  1076. for _, t := range topics {
  1077. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  1078. }
  1079. defer func() {
  1080. for i, subscriberID := range subscriberIDs {
  1081. topics[i].Unsubscribe(subscriberID) // Order!
  1082. }
  1083. }()
  1084. if err := sub(v, newOpenMessage(topicsStr)); err != nil { // Send out open message
  1085. return err
  1086. }
  1087. if err := s.sendOldMessages(topics, since, scheduled, v, sub); err != nil {
  1088. return err
  1089. }
  1090. err = g.Wait()
  1091. if err != nil && websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
  1092. log.Trace("%s WebSocket connection closed: %s", logHTTPPrefix(v, r), err.Error())
  1093. return nil // Normal closures are not errors; note: "1006 (abnormal closure)" is treated as normal, because people disconnect a lot
  1094. }
  1095. return err
  1096. }
  1097. func parseSubscribeParams(r *http.Request) (poll bool, since sinceMarker, scheduled bool, filters *queryFilter, err error) {
  1098. poll = readBoolParam(r, false, "x-poll", "poll", "po")
  1099. scheduled = readBoolParam(r, false, "x-scheduled", "scheduled", "sched")
  1100. since, err = parseSince(r, poll)
  1101. if err != nil {
  1102. return
  1103. }
  1104. filters, err = parseQueryFilters(r)
  1105. if err != nil {
  1106. return
  1107. }
  1108. return
  1109. }
  1110. // sendOldMessages selects old messages from the messageCache and calls sub for each of them. It uses since as the
  1111. // marker, returning only messages that are newer than the marker.
  1112. func (s *Server) sendOldMessages(topics []*topic, since sinceMarker, scheduled bool, v *visitor, sub subscriber) error {
  1113. if since.IsNone() {
  1114. return nil
  1115. }
  1116. messages := make([]*message, 0)
  1117. for _, t := range topics {
  1118. topicMessages, err := s.messageCache.Messages(t.ID, since, scheduled)
  1119. if err != nil {
  1120. return err
  1121. }
  1122. messages = append(messages, topicMessages...)
  1123. }
  1124. sort.Slice(messages, func(i, j int) bool {
  1125. return messages[i].Time < messages[j].Time
  1126. })
  1127. for _, m := range messages {
  1128. if err := sub(v, m); err != nil {
  1129. return err
  1130. }
  1131. }
  1132. return nil
  1133. }
  1134. // parseSince returns a timestamp identifying the time span from which cached messages should be received.
  1135. //
  1136. // Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), or
  1137. // "all" for all messages.
  1138. func parseSince(r *http.Request, poll bool) (sinceMarker, error) {
  1139. since := readParam(r, "x-since", "since", "si")
  1140. // Easy cases (empty, all, none)
  1141. if since == "" {
  1142. if poll {
  1143. return sinceAllMessages, nil
  1144. }
  1145. return sinceNoMessages, nil
  1146. } else if since == "all" {
  1147. return sinceAllMessages, nil
  1148. } else if since == "none" {
  1149. return sinceNoMessages, nil
  1150. }
  1151. // ID, timestamp, duration
  1152. if validMessageID(since) {
  1153. return newSinceID(since), nil
  1154. } else if s, err := strconv.ParseInt(since, 10, 64); err == nil {
  1155. return newSinceTime(s), nil
  1156. } else if d, err := time.ParseDuration(since); err == nil {
  1157. return newSinceTime(time.Now().Add(-1 * d).Unix()), nil
  1158. }
  1159. return sinceNoMessages, errHTTPBadRequestSinceInvalid
  1160. }
  1161. func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  1162. w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST")
  1163. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  1164. w.Header().Set("Access-Control-Allow-Headers", "*") // CORS, allow auth via JS // FIXME is this terrible?
  1165. return nil
  1166. }
  1167. func (s *Server) topicFromPath(path string) (*topic, error) {
  1168. parts := strings.Split(path, "/")
  1169. if len(parts) < 2 {
  1170. return nil, errHTTPBadRequestTopicInvalid
  1171. }
  1172. topics, err := s.topicsFromIDs(parts[1])
  1173. if err != nil {
  1174. return nil, err
  1175. }
  1176. return topics[0], nil
  1177. }
  1178. func (s *Server) topicsFromPath(path string) ([]*topic, string, error) {
  1179. parts := strings.Split(path, "/")
  1180. if len(parts) < 2 {
  1181. return nil, "", errHTTPBadRequestTopicInvalid
  1182. }
  1183. topicIDs := util.SplitNoEmpty(parts[1], ",")
  1184. topics, err := s.topicsFromIDs(topicIDs...)
  1185. if err != nil {
  1186. return nil, "", errHTTPBadRequestTopicInvalid
  1187. }
  1188. return topics, parts[1], nil
  1189. }
  1190. func (s *Server) topicsFromID(id string) (*topic, error) {
  1191. t, err := s.topicsFromIDs(id)
  1192. if err != nil {
  1193. return nil, err
  1194. } else if len(t) == 0 {
  1195. return nil, errHTTPBadRequestTopicDisallowed
  1196. }
  1197. return t[0], nil
  1198. }
  1199. func (s *Server) topicsFromIDs(ids ...string) ([]*topic, error) {
  1200. s.mu.Lock()
  1201. defer s.mu.Unlock()
  1202. topics := make([]*topic, 0)
  1203. for _, id := range ids {
  1204. if util.Contains(disallowedTopics, id) {
  1205. return nil, errHTTPBadRequestTopicDisallowed
  1206. }
  1207. if _, ok := s.topics[id]; !ok {
  1208. if len(s.topics) >= s.config.TotalTopicLimit {
  1209. return nil, errHTTPTooManyRequestsLimitTotalTopics
  1210. }
  1211. s.topics[id] = newTopic(id)
  1212. }
  1213. topics = append(topics, s.topics[id])
  1214. }
  1215. return topics, nil
  1216. }
  1217. func (s *Server) updateStatsAndPrune() {
  1218. log.Debug("Manager: Starting")
  1219. defer log.Debug("Manager: Finished")
  1220. // WARNING: Make sure to only selectively lock with the mutex, and be aware that this
  1221. // there is no mutex for the entire function.
  1222. // Expire visitors from rate visitors map
  1223. s.mu.Lock()
  1224. staleVisitors := 0
  1225. for ip, v := range s.visitors {
  1226. if v.Stale() {
  1227. log.Trace("Deleting stale visitor %s", v.ip)
  1228. delete(s.visitors, ip)
  1229. staleVisitors++
  1230. }
  1231. }
  1232. s.mu.Unlock()
  1233. log.Debug("Manager: Deleted %d stale visitor(s)", staleVisitors)
  1234. // Delete expired attachments
  1235. if s.fileCache != nil && s.config.AttachmentExpiryDuration > 0 {
  1236. olderThan := time.Now().Add(-1 * s.config.AttachmentExpiryDuration)
  1237. ids, err := s.fileCache.Expired(olderThan)
  1238. if err != nil {
  1239. log.Warn("Error retrieving expired attachments: %s", err.Error())
  1240. } else if len(ids) > 0 {
  1241. log.Debug("Manager: Deleting expired attachments: %v", ids)
  1242. if err := s.fileCache.Remove(ids...); err != nil {
  1243. log.Warn("Error deleting attachments: %s", err.Error())
  1244. }
  1245. } else {
  1246. log.Debug("Manager: No expired attachments to delete")
  1247. }
  1248. }
  1249. // Prune message cache
  1250. olderThan := time.Now().Add(-1 * s.config.CacheDuration)
  1251. log.Debug("Manager: Pruning messages older than %s", olderThan.Format("2006-01-02 15:04:05"))
  1252. if err := s.messageCache.Prune(olderThan); err != nil {
  1253. log.Warn("Manager: Error pruning cache: %s", err.Error())
  1254. }
  1255. // Message count per topic
  1256. var messages int
  1257. messageCounts, err := s.messageCache.MessageCounts()
  1258. if err != nil {
  1259. log.Warn("Manager: Cannot get message counts: %s", err.Error())
  1260. messageCounts = make(map[string]int) // Empty, so we can continue
  1261. }
  1262. for _, count := range messageCounts {
  1263. messages += count
  1264. }
  1265. // Remove subscriptions without subscribers
  1266. s.mu.Lock()
  1267. var subscribers int
  1268. for _, t := range s.topics {
  1269. subs := t.SubscribersCount()
  1270. msgs, exists := messageCounts[t.ID]
  1271. if subs == 0 && (!exists || msgs == 0) {
  1272. log.Trace("Deleting empty topic %s", t.ID)
  1273. delete(s.topics, t.ID)
  1274. continue
  1275. }
  1276. subscribers += subs
  1277. }
  1278. s.mu.Unlock()
  1279. // Mail stats
  1280. var receivedMailTotal, receivedMailSuccess, receivedMailFailure int64
  1281. if s.smtpServerBackend != nil {
  1282. receivedMailTotal, receivedMailSuccess, receivedMailFailure = s.smtpServerBackend.Counts()
  1283. }
  1284. var sentMailTotal, sentMailSuccess, sentMailFailure int64
  1285. if s.smtpSender != nil {
  1286. sentMailTotal, sentMailSuccess, sentMailFailure = s.smtpSender.Counts()
  1287. }
  1288. // Print stats
  1289. s.mu.Lock()
  1290. messagesCount, topicsCount, visitorsCount := s.messages, len(s.topics), len(s.visitors)
  1291. s.mu.Unlock()
  1292. log.Info("Stats: %d messages published, %d in cache, %d topic(s) active, %d subscriber(s), %d visitor(s), %d mails received (%d successful, %d failed), %d mails sent (%d successful, %d failed)",
  1293. messagesCount, messages, topicsCount, subscribers, visitorsCount,
  1294. receivedMailTotal, receivedMailSuccess, receivedMailFailure,
  1295. sentMailTotal, sentMailSuccess, sentMailFailure)
  1296. }
  1297. func (s *Server) runSMTPServer() error {
  1298. s.smtpServerBackend = newMailBackend(s.config, s.handle)
  1299. s.smtpServer = smtp.NewServer(s.smtpServerBackend)
  1300. s.smtpServer.Addr = s.config.SMTPServerListen
  1301. s.smtpServer.Domain = s.config.SMTPServerDomain
  1302. s.smtpServer.ReadTimeout = 10 * time.Second
  1303. s.smtpServer.WriteTimeout = 10 * time.Second
  1304. s.smtpServer.MaxMessageBytes = 1024 * 1024 // Must be much larger than message size (headers, multipart, etc.)
  1305. s.smtpServer.MaxRecipients = 1
  1306. s.smtpServer.AllowInsecureAuth = true
  1307. return s.smtpServer.ListenAndServe()
  1308. }
  1309. func (s *Server) runManager() {
  1310. for {
  1311. select {
  1312. case <-time.After(s.config.ManagerInterval):
  1313. s.updateStatsAndPrune()
  1314. case <-s.closeChan:
  1315. return
  1316. }
  1317. }
  1318. }
  1319. func (s *Server) runFirebaseKeepaliver() {
  1320. if s.firebaseClient == nil {
  1321. return
  1322. }
  1323. v := newVisitor(s.config, s.messageCache, "0.0.0.0") // Background process, not a real visitor
  1324. for {
  1325. select {
  1326. case <-time.After(s.config.FirebaseKeepaliveInterval):
  1327. s.sendToFirebase(v, newKeepaliveMessage(firebaseControlTopic))
  1328. case <-time.After(s.config.FirebasePollInterval):
  1329. s.sendToFirebase(v, newKeepaliveMessage(firebasePollTopic))
  1330. case <-s.closeChan:
  1331. return
  1332. }
  1333. }
  1334. }
  1335. func (s *Server) runDelayedSender() {
  1336. for {
  1337. select {
  1338. case <-time.After(s.config.DelayedSenderInterval):
  1339. if err := s.sendDelayedMessages(); err != nil {
  1340. log.Warn("Error sending delayed messages: %s", err.Error())
  1341. }
  1342. case <-s.closeChan:
  1343. return
  1344. }
  1345. }
  1346. }
  1347. func (s *Server) sendDelayedMessages() error {
  1348. messages, err := s.messageCache.MessagesDue()
  1349. if err != nil {
  1350. return err
  1351. }
  1352. for _, m := range messages {
  1353. v := s.visitorFromIP(m.Sender)
  1354. if err := s.sendDelayedMessage(v, m); err != nil {
  1355. log.Warn("%s Error sending delayed message: %s", logMessagePrefix(v, m), err.Error())
  1356. }
  1357. }
  1358. return nil
  1359. }
  1360. func (s *Server) sendDelayedMessage(v *visitor, m *message) error {
  1361. log.Debug("%s Sending delayed message", logMessagePrefix(v, m))
  1362. s.mu.Lock()
  1363. t, ok := s.topics[m.Topic] // If no subscribers, just mark message as published
  1364. s.mu.Unlock()
  1365. if ok {
  1366. go func() {
  1367. // We do not rate-limit messages here, since we've rate limited them in the PUT/POST handler
  1368. if err := t.Publish(v, m); err != nil {
  1369. log.Warn("%s Unable to publish message: %v", logMessagePrefix(v, m), err.Error())
  1370. }
  1371. }()
  1372. }
  1373. if s.firebaseClient != nil { // Firebase subscribers may not show up in topics map
  1374. go s.sendToFirebase(v, m)
  1375. }
  1376. if s.config.UpstreamBaseURL != "" {
  1377. go s.forwardPollRequest(v, m)
  1378. }
  1379. if err := s.messageCache.MarkPublished(m); err != nil {
  1380. return err
  1381. }
  1382. return nil
  1383. }
  1384. func (s *Server) limitRequests(next handleFunc) handleFunc {
  1385. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1386. if util.Contains(s.config.VisitorRequestExemptIPAddrs, v.ip) {
  1387. return next(w, r, v)
  1388. } else if err := v.RequestAllowed(); err != nil {
  1389. return errHTTPTooManyRequestsLimitRequests
  1390. }
  1391. return next(w, r, v)
  1392. }
  1393. }
  1394. func (s *Server) ensureWebEnabled(next handleFunc) handleFunc {
  1395. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1396. if !s.config.EnableWeb {
  1397. return errHTTPNotFound
  1398. }
  1399. return next(w, r, v)
  1400. }
  1401. }
  1402. func (s *Server) transformMatrixJSON(next handleFunc) handleFunc {
  1403. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1404. newRequest, err := newRequestFromMatrixJSON(r, s.config.BaseURL, s.config.MessageLimit)
  1405. if err != nil {
  1406. return err
  1407. }
  1408. if err := next(w, newRequest, v); err != nil {
  1409. return &errMatrix{pushKey: newRequest.Header.Get(matrixPushKeyHeader), err: err}
  1410. }
  1411. return nil
  1412. }
  1413. }
  1414. func (s *Server) authWrite(next handleFunc) handleFunc {
  1415. return s.withAuth(next, auth.PermissionWrite)
  1416. }
  1417. func (s *Server) authRead(next handleFunc) handleFunc {
  1418. return s.withAuth(next, auth.PermissionRead)
  1419. }
  1420. func (s *Server) withAuth(next handleFunc, perm auth.Permission) handleFunc {
  1421. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1422. if s.auth == nil {
  1423. return next(w, r, v)
  1424. }
  1425. topics, _, err := s.topicsFromPath(r.URL.Path)
  1426. if err != nil {
  1427. return err
  1428. }
  1429. var user *auth.User // may stay nil if no auth header!
  1430. username, password, ok := extractUserPass(r)
  1431. if ok {
  1432. if user, err = s.auth.Authenticate(username, password); err != nil {
  1433. log.Info("authentication failed: %s", err.Error())
  1434. return errHTTPUnauthorized
  1435. }
  1436. }
  1437. for _, t := range topics {
  1438. if err := s.auth.Authorize(user, t.ID, perm); err != nil {
  1439. log.Info("unauthorized: %s", err.Error())
  1440. return errHTTPForbidden
  1441. }
  1442. }
  1443. return next(w, r, v)
  1444. }
  1445. }
  1446. // extractUserPass reads the username/password from the basic auth header (Authorization: Basic ...),
  1447. // or from the ?auth=... query param. The latter is required only to support the WebSocket JavaScript
  1448. // class, which does not support passing headers during the initial request. The auth query param
  1449. // is effectively double base64 encoded. Its format is base64(Basic base64(user:pass)).
  1450. func extractUserPass(r *http.Request) (username string, password string, ok bool) {
  1451. username, password, ok = r.BasicAuth()
  1452. if ok {
  1453. return
  1454. }
  1455. authParam := readQueryParam(r, "authorization", "auth")
  1456. if authParam != "" {
  1457. a, err := base64.RawURLEncoding.DecodeString(authParam)
  1458. if err != nil {
  1459. return
  1460. }
  1461. r.Header.Set("Authorization", string(a))
  1462. return r.BasicAuth()
  1463. }
  1464. return
  1465. }
  1466. // visitor creates or retrieves a rate.Limiter for the given visitor.
  1467. // This function was taken from https://www.alexedwards.net/blog/how-to-rate-limit-http-requests (MIT).
  1468. func (s *Server) visitor(r *http.Request) *visitor {
  1469. remoteAddr := r.RemoteAddr
  1470. ip, _, err := net.SplitHostPort(remoteAddr)
  1471. if err != nil {
  1472. ip = remoteAddr // This should not happen in real life; only in tests.
  1473. }
  1474. if s.config.BehindProxy && strings.TrimSpace(r.Header.Get("X-Forwarded-For")) != "" {
  1475. // X-Forwarded-For can contain multiple addresses (see #328). If we are behind a proxy,
  1476. // only the right-most address can be trusted (as this is the one added by our proxy server).
  1477. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For for details.
  1478. ips := util.SplitNoEmpty(r.Header.Get("X-Forwarded-For"), ",")
  1479. ip = strings.TrimSpace(util.LastString(ips, remoteAddr))
  1480. }
  1481. return s.visitorFromIP(ip)
  1482. }
  1483. func (s *Server) visitorFromIP(ip string) *visitor {
  1484. s.mu.Lock()
  1485. defer s.mu.Unlock()
  1486. v, exists := s.visitors[ip]
  1487. if !exists {
  1488. s.visitors[ip] = newVisitor(s.config, s.messageCache, ip)
  1489. return s.visitors[ip]
  1490. }
  1491. v.Keepalive()
  1492. return v
  1493. }