server.go 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  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. "github.com/emersion/go-smtp"
  12. "github.com/gorilla/websocket"
  13. "github.com/prometheus/client_golang/prometheus/promhttp"
  14. "golang.org/x/sync/errgroup"
  15. "heckel.io/ntfy/log"
  16. "heckel.io/ntfy/user"
  17. "heckel.io/ntfy/util"
  18. "io"
  19. "net"
  20. "net/http"
  21. "net/http/pprof"
  22. "net/netip"
  23. "net/url"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "regexp"
  28. "sort"
  29. "strconv"
  30. "strings"
  31. "sync"
  32. "time"
  33. "unicode/utf8"
  34. )
  35. // Server is the main server, providing the UI and API for ntfy
  36. type Server struct {
  37. config *Config
  38. httpServer *http.Server
  39. httpsServer *http.Server
  40. httpMetricsServer *http.Server
  41. httpProfileServer *http.Server
  42. unixListener net.Listener
  43. smtpServer *smtp.Server
  44. smtpServerBackend *smtpBackend
  45. smtpSender mailer
  46. topics map[string]*topic
  47. visitors map[string]*visitor // ip:<ip> or user:<user>
  48. firebaseClient *firebaseClient
  49. messages int64 // Total number of messages (persisted if messageCache enabled)
  50. messagesHistory []int64 // Last n values of the messages counter, used to determine rate
  51. userManager *user.Manager // Might be nil!
  52. messageCache *messageCache // Database that stores the messages
  53. fileCache *fileCache // File system based cache that stores attachments
  54. stripe stripeAPI // Stripe API, can be replaced with a mock
  55. priceCache *util.LookupCache[map[string]int64] // Stripe price ID -> price as cents (USD implied!)
  56. metricsHandler http.Handler // Handles /metrics if enable-metrics set, and listen-metrics-http not set
  57. closeChan chan bool
  58. mu sync.RWMutex
  59. }
  60. // handleFunc extends the normal http.HandlerFunc to be able to easily return errors
  61. type handleFunc func(http.ResponseWriter, *http.Request, *visitor) error
  62. var (
  63. // If changed, don't forget to update Android App and auth_sqlite.go
  64. topicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No /!
  65. topicPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}$`) // Regex must match JS & Android app!
  66. externalTopicPathRegex = regexp.MustCompile(`^/[^/]+\.[^/]+/[-_A-Za-z0-9]{1,64}$`) // Extended topic path, for web-app, e.g. /example.com/mytopic
  67. jsonPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/json$`)
  68. ssePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/sse$`)
  69. rawPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/raw$`)
  70. wsPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/ws$`)
  71. authPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/auth$`)
  72. publishPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/(publish|send|trigger)$`)
  73. webConfigPath = "/config.js"
  74. accountPath = "/account"
  75. matrixPushPath = "/_matrix/push/v1/notify"
  76. metricsPath = "/metrics"
  77. apiHealthPath = "/v1/health"
  78. apiStatsPath = "/v1/stats"
  79. apiTiersPath = "/v1/tiers"
  80. apiUsersPath = "/v1/users"
  81. apiUsersAccessPath = "/v1/users/access"
  82. apiAccountPath = "/v1/account"
  83. apiAccountTokenPath = "/v1/account/token"
  84. apiAccountPasswordPath = "/v1/account/password"
  85. apiAccountSettingsPath = "/v1/account/settings"
  86. apiAccountSubscriptionPath = "/v1/account/subscription"
  87. apiAccountReservationPath = "/v1/account/reservation"
  88. apiAccountPhonePath = "/v1/account/phone"
  89. apiAccountPhoneVerifyPath = "/v1/account/phone/verify"
  90. apiAccountBillingPortalPath = "/v1/account/billing/portal"
  91. apiAccountBillingWebhookPath = "/v1/account/billing/webhook"
  92. apiAccountBillingSubscriptionPath = "/v1/account/billing/subscription"
  93. apiAccountBillingSubscriptionCheckoutSuccessTemplate = "/v1/account/billing/subscription/success/{CHECKOUT_SESSION_ID}"
  94. apiAccountBillingSubscriptionCheckoutSuccessRegex = regexp.MustCompile(`/v1/account/billing/subscription/success/(.+)$`)
  95. apiAccountReservationSingleRegex = regexp.MustCompile(`/v1/account/reservation/([-_A-Za-z0-9]{1,64})$`)
  96. staticRegex = regexp.MustCompile(`^/static/.+`)
  97. docsRegex = regexp.MustCompile(`^/docs(|/.*)$`)
  98. fileRegex = regexp.MustCompile(`^/file/([-_A-Za-z0-9]{1,64})(?:\.[A-Za-z0-9]{1,16})?$`)
  99. urlRegex = regexp.MustCompile(`^https?://`)
  100. phoneNumberRegex = regexp.MustCompile(`^\+\d{1,100}$`)
  101. //go:embed site
  102. webFs embed.FS
  103. webFsCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: webFs}
  104. webSiteDir = "/site"
  105. webAppIndex = "/app.html" // React app
  106. //go:embed docs
  107. docsStaticFs embed.FS
  108. docsStaticCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: docsStaticFs}
  109. )
  110. const (
  111. firebaseControlTopic = "~control" // See Android if changed
  112. firebasePollTopic = "~poll" // See iOS if changed
  113. emptyMessageBody = "triggered" // Used if message body is empty
  114. newMessageBody = "New message" // Used in poll requests as generic message
  115. defaultAttachmentMessage = "You received a file: %s" // Used if message body is empty, and there is an attachment
  116. encodingBase64 = "base64" // Used mainly for binary UnifiedPush messages
  117. jsonBodyBytesLimit = 16384 // Max number of bytes for a JSON request body
  118. unifiedPushTopicPrefix = "up" // Temporarily, we rate limit all "up*" topics based on the subscriber
  119. unifiedPushTopicLength = 14 // Length of UnifiedPush topics, including the "up" part
  120. messagesHistoryMax = 10 // Number of message count values to keep in memory
  121. )
  122. // WebSocket constants
  123. const (
  124. wsWriteWait = 2 * time.Second
  125. wsBufferSize = 1024
  126. wsReadLimit = 64 // We only ever receive PINGs
  127. wsPongWait = 15 * time.Second
  128. )
  129. // New instantiates a new Server. It creates the cache and adds a Firebase
  130. // subscriber (if configured).
  131. func New(conf *Config) (*Server, error) {
  132. var mailer mailer
  133. if conf.SMTPSenderAddr != "" {
  134. mailer = &smtpSender{config: conf}
  135. }
  136. var stripe stripeAPI
  137. if conf.StripeSecretKey != "" {
  138. stripe = newStripeAPI()
  139. }
  140. messageCache, err := createMessageCache(conf)
  141. if err != nil {
  142. return nil, err
  143. }
  144. topics, err := messageCache.Topics()
  145. if err != nil {
  146. return nil, err
  147. }
  148. messages, err := messageCache.Stats()
  149. if err != nil {
  150. return nil, err
  151. }
  152. var fileCache *fileCache
  153. if conf.AttachmentCacheDir != "" {
  154. fileCache, err = newFileCache(conf.AttachmentCacheDir, conf.AttachmentTotalSizeLimit)
  155. if err != nil {
  156. return nil, err
  157. }
  158. }
  159. var userManager *user.Manager
  160. if conf.AuthFile != "" {
  161. userManager, err = user.NewManager(conf.AuthFile, conf.AuthStartupQueries, conf.AuthDefault, conf.AuthBcryptCost, conf.AuthStatsQueueWriterInterval)
  162. if err != nil {
  163. return nil, err
  164. }
  165. }
  166. var firebaseClient *firebaseClient
  167. if conf.FirebaseKeyFile != "" {
  168. sender, err := newFirebaseSender(conf.FirebaseKeyFile)
  169. if err != nil {
  170. return nil, err
  171. }
  172. // This awkward logic is required because Go is weird about nil types and interfaces.
  173. // See issue #641, and https://go.dev/play/p/uur1flrv1t3 for an example
  174. var auther user.Auther
  175. if userManager != nil {
  176. auther = userManager
  177. }
  178. firebaseClient = newFirebaseClient(sender, auther)
  179. }
  180. s := &Server{
  181. config: conf,
  182. messageCache: messageCache,
  183. fileCache: fileCache,
  184. firebaseClient: firebaseClient,
  185. smtpSender: mailer,
  186. topics: topics,
  187. userManager: userManager,
  188. messages: messages,
  189. messagesHistory: []int64{messages},
  190. visitors: make(map[string]*visitor),
  191. stripe: stripe,
  192. }
  193. s.priceCache = util.NewLookupCache(s.fetchStripePrices, conf.StripePriceCacheDuration)
  194. return s, nil
  195. }
  196. func createMessageCache(conf *Config) (*messageCache, error) {
  197. if conf.CacheDuration == 0 {
  198. return newNopCache()
  199. } else if conf.CacheFile != "" {
  200. return newSqliteCache(conf.CacheFile, conf.CacheStartupQueries, conf.CacheDuration, conf.CacheBatchSize, conf.CacheBatchTimeout, false)
  201. }
  202. return newMemCache()
  203. }
  204. // Run executes the main server. It listens on HTTP (+ HTTPS, if configured), and starts
  205. // a manager go routine to print stats and prune messages.
  206. func (s *Server) Run() error {
  207. var listenStr string
  208. if s.config.ListenHTTP != "" {
  209. listenStr += fmt.Sprintf(" %s[http]", s.config.ListenHTTP)
  210. }
  211. if s.config.ListenHTTPS != "" {
  212. listenStr += fmt.Sprintf(" %s[https]", s.config.ListenHTTPS)
  213. }
  214. if s.config.ListenUnix != "" {
  215. listenStr += fmt.Sprintf(" %s[unix]", s.config.ListenUnix)
  216. }
  217. if s.config.SMTPServerListen != "" {
  218. listenStr += fmt.Sprintf(" %s[smtp]", s.config.SMTPServerListen)
  219. }
  220. if s.config.MetricsListenHTTP != "" {
  221. listenStr += fmt.Sprintf(" %s[http/metrics]", s.config.MetricsListenHTTP)
  222. }
  223. if s.config.ProfileListenHTTP != "" {
  224. listenStr += fmt.Sprintf(" %s[http/profile]", s.config.ProfileListenHTTP)
  225. }
  226. log.Tag(tagStartup).Info("Listening on%s, ntfy %s, log level is %s", listenStr, s.config.Version, log.CurrentLevel().String())
  227. if log.IsFile() {
  228. fmt.Fprintf(os.Stderr, "Listening on%s, ntfy %s\n", listenStr, s.config.Version)
  229. fmt.Fprintf(os.Stderr, "Logs are written to %s\n", log.File())
  230. }
  231. mux := http.NewServeMux()
  232. mux.HandleFunc("/", s.handle)
  233. errChan := make(chan error)
  234. s.mu.Lock()
  235. s.closeChan = make(chan bool)
  236. if s.config.ListenHTTP != "" {
  237. s.httpServer = &http.Server{Addr: s.config.ListenHTTP, Handler: mux}
  238. go func() {
  239. errChan <- s.httpServer.ListenAndServe()
  240. }()
  241. }
  242. if s.config.ListenHTTPS != "" {
  243. s.httpsServer = &http.Server{Addr: s.config.ListenHTTPS, Handler: mux}
  244. go func() {
  245. errChan <- s.httpsServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile)
  246. }()
  247. }
  248. if s.config.ListenUnix != "" {
  249. go func() {
  250. var err error
  251. s.mu.Lock()
  252. os.Remove(s.config.ListenUnix)
  253. s.unixListener, err = net.Listen("unix", s.config.ListenUnix)
  254. if err != nil {
  255. s.mu.Unlock()
  256. errChan <- err
  257. return
  258. }
  259. defer s.unixListener.Close()
  260. if s.config.ListenUnixMode > 0 {
  261. if err := os.Chmod(s.config.ListenUnix, s.config.ListenUnixMode); err != nil {
  262. s.mu.Unlock()
  263. errChan <- err
  264. return
  265. }
  266. }
  267. s.mu.Unlock()
  268. httpServer := &http.Server{Handler: mux}
  269. errChan <- httpServer.Serve(s.unixListener)
  270. }()
  271. }
  272. if s.config.MetricsListenHTTP != "" {
  273. initMetrics()
  274. s.httpMetricsServer = &http.Server{Addr: s.config.MetricsListenHTTP, Handler: promhttp.Handler()}
  275. go func() {
  276. errChan <- s.httpMetricsServer.ListenAndServe()
  277. }()
  278. } else if s.config.EnableMetrics {
  279. initMetrics()
  280. s.metricsHandler = promhttp.Handler()
  281. }
  282. if s.config.ProfileListenHTTP != "" {
  283. profileMux := http.NewServeMux()
  284. profileMux.HandleFunc("/debug/pprof/", pprof.Index)
  285. profileMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
  286. profileMux.HandleFunc("/debug/pprof/profile", pprof.Profile)
  287. profileMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
  288. profileMux.HandleFunc("/debug/pprof/trace", pprof.Trace)
  289. s.httpProfileServer = &http.Server{Addr: s.config.ProfileListenHTTP, Handler: profileMux}
  290. go func() {
  291. errChan <- s.httpProfileServer.ListenAndServe()
  292. }()
  293. }
  294. if s.config.SMTPServerListen != "" {
  295. go func() {
  296. errChan <- s.runSMTPServer()
  297. }()
  298. }
  299. s.mu.Unlock()
  300. go s.runManager()
  301. go s.runStatsResetter()
  302. go s.runDelayedSender()
  303. go s.runFirebaseKeepaliver()
  304. return <-errChan
  305. }
  306. // Stop stops HTTP (+HTTPS) server and all managers
  307. func (s *Server) Stop() {
  308. s.mu.Lock()
  309. defer s.mu.Unlock()
  310. if s.httpServer != nil {
  311. s.httpServer.Close()
  312. }
  313. if s.httpsServer != nil {
  314. s.httpsServer.Close()
  315. }
  316. if s.unixListener != nil {
  317. s.unixListener.Close()
  318. }
  319. if s.smtpServer != nil {
  320. s.smtpServer.Close()
  321. }
  322. s.closeDatabases()
  323. close(s.closeChan)
  324. }
  325. func (s *Server) closeDatabases() {
  326. if s.userManager != nil {
  327. s.userManager.Close()
  328. }
  329. s.messageCache.Close()
  330. }
  331. // handle is the main entry point for all HTTP requests
  332. func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
  333. v, err := s.maybeAuthenticate(r) // Note: Always returns v, even when error is returned
  334. if err != nil {
  335. s.handleError(w, r, v, err)
  336. return
  337. }
  338. ev := logvr(v, r)
  339. if ev.IsTrace() {
  340. ev.Field("http_request", renderHTTPRequest(r)).Trace("HTTP request started")
  341. } else if logvr(v, r).IsDebug() {
  342. ev.Debug("HTTP request started")
  343. }
  344. logvr(v, r).
  345. Timing(func() {
  346. if err := s.handleInternal(w, r, v); err != nil {
  347. s.handleError(w, r, v, err)
  348. return
  349. }
  350. if metricHTTPRequests != nil {
  351. metricHTTPRequests.WithLabelValues("200", "20000", r.Method).Inc()
  352. }
  353. }).
  354. Debug("HTTP request finished")
  355. }
  356. func (s *Server) handleError(w http.ResponseWriter, r *http.Request, v *visitor, err error) {
  357. httpErr, ok := err.(*errHTTP)
  358. if !ok {
  359. httpErr = errHTTPInternalError
  360. }
  361. if metricHTTPRequests != nil {
  362. metricHTTPRequests.WithLabelValues(fmt.Sprintf("%d", httpErr.HTTPCode), fmt.Sprintf("%d", httpErr.Code), r.Method).Inc()
  363. }
  364. isRateLimiting := util.Contains(rateLimitingErrorCodes, httpErr.HTTPCode)
  365. isNormalError := strings.Contains(err.Error(), "i/o timeout") || util.Contains(normalErrorCodes, httpErr.HTTPCode)
  366. ev := logvr(v, r).Err(err)
  367. if websocket.IsWebSocketUpgrade(r) {
  368. ev.Tag(tagWebsocket).Fields(websocketErrorContext(err))
  369. if isNormalError {
  370. ev.Debug("WebSocket error (this error is okay, it happens a lot): %s", err.Error())
  371. } else {
  372. ev.Info("WebSocket error: %s", err.Error())
  373. }
  374. return // Do not attempt to write to upgraded connection
  375. }
  376. if isNormalError {
  377. ev.Debug("Connection closed with HTTP %d (ntfy error %d)", httpErr.HTTPCode, httpErr.Code)
  378. } else {
  379. ev.Info("Connection closed with HTTP %d (ntfy error %d)", httpErr.HTTPCode, httpErr.Code)
  380. }
  381. if isRateLimiting && s.config.StripeSecretKey != "" {
  382. u := v.User()
  383. if u == nil || u.Tier == nil {
  384. httpErr = httpErr.Wrap("increase your limits with a paid plan, see %s", s.config.BaseURL)
  385. }
  386. }
  387. w.Header().Set("Content-Type", "application/json")
  388. w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests
  389. w.WriteHeader(httpErr.HTTPCode)
  390. io.WriteString(w, httpErr.JSON()+"\n")
  391. }
  392. func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request, v *visitor) error {
  393. if r.Method == http.MethodGet && r.URL.Path == "/" && s.config.WebRoot == "/" {
  394. return s.ensureWebEnabled(s.handleRoot)(w, r, v)
  395. } else if r.Method == http.MethodHead && r.URL.Path == "/" {
  396. return s.ensureWebEnabled(s.handleEmpty)(w, r, v)
  397. } else if r.Method == http.MethodGet && r.URL.Path == apiHealthPath {
  398. return s.handleHealth(w, r, v)
  399. } else if r.Method == http.MethodGet && r.URL.Path == webConfigPath {
  400. return s.ensureWebEnabled(s.handleWebConfig)(w, r, v)
  401. } else if r.Method == http.MethodGet && r.URL.Path == apiUsersPath {
  402. return s.ensureAdmin(s.handleUsersGet)(w, r, v)
  403. } else if r.Method == http.MethodPut && r.URL.Path == apiUsersPath {
  404. return s.ensureAdmin(s.handleUsersAdd)(w, r, v)
  405. } else if r.Method == http.MethodDelete && r.URL.Path == apiUsersPath {
  406. return s.ensureAdmin(s.handleUsersDelete)(w, r, v)
  407. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && r.URL.Path == apiUsersAccessPath {
  408. return s.ensureAdmin(s.handleAccessAllow)(w, r, v)
  409. } else if r.Method == http.MethodDelete && r.URL.Path == apiUsersAccessPath {
  410. return s.ensureAdmin(s.handleAccessReset)(w, r, v)
  411. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountPath {
  412. return s.ensureUserManager(s.handleAccountCreate)(w, r, v)
  413. } else if r.Method == http.MethodGet && r.URL.Path == apiAccountPath {
  414. return s.handleAccountGet(w, r, v) // Allowed by anonymous
  415. } else if r.Method == http.MethodDelete && r.URL.Path == apiAccountPath {
  416. return s.ensureUser(s.withAccountSync(s.handleAccountDelete))(w, r, v)
  417. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountPasswordPath {
  418. return s.ensureUser(s.handleAccountPasswordChange)(w, r, v)
  419. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountTokenPath {
  420. return s.ensureUser(s.withAccountSync(s.handleAccountTokenCreate))(w, r, v)
  421. } else if r.Method == http.MethodPatch && r.URL.Path == apiAccountTokenPath {
  422. return s.ensureUser(s.withAccountSync(s.handleAccountTokenUpdate))(w, r, v)
  423. } else if r.Method == http.MethodDelete && r.URL.Path == apiAccountTokenPath {
  424. return s.ensureUser(s.withAccountSync(s.handleAccountTokenDelete))(w, r, v)
  425. } else if r.Method == http.MethodPatch && r.URL.Path == apiAccountSettingsPath {
  426. return s.ensureUser(s.withAccountSync(s.handleAccountSettingsChange))(w, r, v)
  427. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountSubscriptionPath {
  428. return s.ensureUser(s.withAccountSync(s.handleAccountSubscriptionAdd))(w, r, v)
  429. } else if r.Method == http.MethodPatch && r.URL.Path == apiAccountSubscriptionPath {
  430. return s.ensureUser(s.withAccountSync(s.handleAccountSubscriptionChange))(w, r, v)
  431. } else if r.Method == http.MethodDelete && r.URL.Path == apiAccountSubscriptionPath {
  432. return s.ensureUser(s.withAccountSync(s.handleAccountSubscriptionDelete))(w, r, v)
  433. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountReservationPath {
  434. return s.ensureUser(s.withAccountSync(s.handleAccountReservationAdd))(w, r, v)
  435. } else if r.Method == http.MethodDelete && apiAccountReservationSingleRegex.MatchString(r.URL.Path) {
  436. return s.ensureUser(s.withAccountSync(s.handleAccountReservationDelete))(w, r, v)
  437. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountBillingSubscriptionPath {
  438. return s.ensurePaymentsEnabled(s.ensureUser(s.handleAccountBillingSubscriptionCreate))(w, r, v) // Account sync via incoming Stripe webhook
  439. } else if r.Method == http.MethodGet && apiAccountBillingSubscriptionCheckoutSuccessRegex.MatchString(r.URL.Path) {
  440. return s.ensurePaymentsEnabled(s.ensureUserManager(s.handleAccountBillingSubscriptionCreateSuccess))(w, r, v) // No user context!
  441. } else if r.Method == http.MethodPut && r.URL.Path == apiAccountBillingSubscriptionPath {
  442. return s.ensurePaymentsEnabled(s.ensureStripeCustomer(s.handleAccountBillingSubscriptionUpdate))(w, r, v) // Account sync via incoming Stripe webhook
  443. } else if r.Method == http.MethodDelete && r.URL.Path == apiAccountBillingSubscriptionPath {
  444. return s.ensurePaymentsEnabled(s.ensureStripeCustomer(s.handleAccountBillingSubscriptionDelete))(w, r, v) // Account sync via incoming Stripe webhook
  445. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountBillingPortalPath {
  446. return s.ensurePaymentsEnabled(s.ensureStripeCustomer(s.handleAccountBillingPortalSessionCreate))(w, r, v)
  447. } else if r.Method == http.MethodPost && r.URL.Path == apiAccountBillingWebhookPath {
  448. return s.ensurePaymentsEnabled(s.ensureUserManager(s.handleAccountBillingWebhook))(w, r, v) // This request comes from Stripe!
  449. } else if r.Method == http.MethodPut && r.URL.Path == apiAccountPhoneVerifyPath {
  450. return s.ensureUser(s.ensureCallsEnabled(s.withAccountSync(s.handleAccountPhoneNumberVerify)))(w, r, v)
  451. } else if r.Method == http.MethodPut && r.URL.Path == apiAccountPhonePath {
  452. return s.ensureUser(s.ensureCallsEnabled(s.withAccountSync(s.handleAccountPhoneNumberAdd)))(w, r, v)
  453. } else if r.Method == http.MethodDelete && r.URL.Path == apiAccountPhonePath {
  454. return s.ensureUser(s.ensureCallsEnabled(s.withAccountSync(s.handleAccountPhoneNumberDelete)))(w, r, v)
  455. } else if r.Method == http.MethodGet && r.URL.Path == apiStatsPath {
  456. return s.handleStats(w, r, v)
  457. } else if r.Method == http.MethodGet && r.URL.Path == apiTiersPath {
  458. return s.ensurePaymentsEnabled(s.handleBillingTiersGet)(w, r, v)
  459. } else if r.Method == http.MethodGet && r.URL.Path == matrixPushPath {
  460. return s.handleMatrixDiscovery(w)
  461. } else if r.Method == http.MethodGet && r.URL.Path == metricsPath && s.metricsHandler != nil {
  462. return s.handleMetrics(w, r, v)
  463. } else if r.Method == http.MethodGet && staticRegex.MatchString(r.URL.Path) {
  464. return s.ensureWebEnabled(s.handleStatic)(w, r, v)
  465. } else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) {
  466. return s.ensureWebEnabled(s.handleDocs)(w, r, v)
  467. } else if (r.Method == http.MethodGet || r.Method == http.MethodHead) && fileRegex.MatchString(r.URL.Path) && s.config.AttachmentCacheDir != "" {
  468. return s.limitRequests(s.handleFile)(w, r, v)
  469. } else if r.Method == http.MethodOptions {
  470. return s.limitRequests(s.handleOptions)(w, r, v) // Should work even if the web app is not enabled, see #598
  471. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && r.URL.Path == "/" {
  472. return s.transformBodyJSON(s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublish)))(w, r, v)
  473. } else if r.Method == http.MethodPost && r.URL.Path == matrixPushPath {
  474. return s.transformMatrixJSON(s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublishMatrix)))(w, r, v)
  475. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicPathRegex.MatchString(r.URL.Path) {
  476. return s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublish))(w, r, v)
  477. } else if r.Method == http.MethodGet && publishPathRegex.MatchString(r.URL.Path) {
  478. return s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublish))(w, r, v)
  479. } else if r.Method == http.MethodGet && jsonPathRegex.MatchString(r.URL.Path) {
  480. return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeJSON))(w, r, v)
  481. } else if r.Method == http.MethodGet && ssePathRegex.MatchString(r.URL.Path) {
  482. return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeSSE))(w, r, v)
  483. } else if r.Method == http.MethodGet && rawPathRegex.MatchString(r.URL.Path) {
  484. return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeRaw))(w, r, v)
  485. } else if r.Method == http.MethodGet && wsPathRegex.MatchString(r.URL.Path) {
  486. return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeWS))(w, r, v)
  487. } else if r.Method == http.MethodGet && authPathRegex.MatchString(r.URL.Path) {
  488. return s.limitRequests(s.authorizeTopicRead(s.handleTopicAuth))(w, r, v)
  489. } else if r.Method == http.MethodGet && (topicPathRegex.MatchString(r.URL.Path) || externalTopicPathRegex.MatchString(r.URL.Path)) {
  490. return s.ensureWebEnabled(s.handleTopic)(w, r, v)
  491. }
  492. return errHTTPNotFound
  493. }
  494. func (s *Server) handleRoot(w http.ResponseWriter, r *http.Request, v *visitor) error {
  495. r.URL.Path = webAppIndex
  496. return s.handleStatic(w, r, v)
  497. }
  498. func (s *Server) handleTopic(w http.ResponseWriter, r *http.Request, v *visitor) error {
  499. unifiedpush := readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see PUT/POST too!
  500. if unifiedpush {
  501. w.Header().Set("Content-Type", "application/json")
  502. w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests
  503. _, err := io.WriteString(w, `{"unifiedpush":{"version":1}}`+"\n")
  504. return err
  505. }
  506. r.URL.Path = webAppIndex
  507. return s.handleStatic(w, r, v)
  508. }
  509. func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request, _ *visitor) error {
  510. return nil
  511. }
  512. func (s *Server) handleTopicAuth(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  513. return s.writeJSON(w, newSuccessResponse())
  514. }
  515. func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  516. response := &apiHealthResponse{
  517. Healthy: true,
  518. }
  519. return s.writeJSON(w, response)
  520. }
  521. func (s *Server) handleWebConfig(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  522. response := &apiConfigResponse{
  523. BaseURL: "", // Will translate to window.location.origin
  524. AppRoot: s.config.WebRoot,
  525. EnableLogin: s.config.EnableLogin,
  526. EnableSignup: s.config.EnableSignup,
  527. EnablePayments: s.config.StripeSecretKey != "",
  528. EnableCalls: s.config.TwilioAccount != "",
  529. EnableEmails: s.config.SMTPSenderFrom != "",
  530. EnableReservations: s.config.EnableReservations,
  531. BillingContact: s.config.BillingContact,
  532. DisallowedTopics: s.config.DisallowedTopics,
  533. }
  534. b, err := json.MarshalIndent(response, "", " ")
  535. if err != nil {
  536. return err
  537. }
  538. w.Header().Set("Content-Type", "text/javascript")
  539. _, err = io.WriteString(w, fmt.Sprintf("// Generated server configuration\nvar config = %s;\n", string(b)))
  540. return err
  541. }
  542. // handleMetrics returns Prometheus metrics. This endpoint is only called if enable-metrics is set,
  543. // and listen-metrics-http is not set.
  544. func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  545. s.metricsHandler.ServeHTTP(w, r)
  546. return nil
  547. }
  548. // handleStatic returns all static resources (excluding the docs), including the web app
  549. func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  550. r.URL.Path = webSiteDir + r.URL.Path
  551. util.Gzip(http.FileServer(http.FS(webFsCached))).ServeHTTP(w, r)
  552. return nil
  553. }
  554. // handleDocs returns static resources related to the docs
  555. func (s *Server) handleDocs(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  556. util.Gzip(http.FileServer(http.FS(docsStaticCached))).ServeHTTP(w, r)
  557. return nil
  558. }
  559. // handleStats returns the publicly available server stats
  560. func (s *Server) handleStats(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  561. s.mu.RLock()
  562. messages, n, rate := s.messages, len(s.messagesHistory), float64(0)
  563. if n > 1 {
  564. rate = float64(s.messagesHistory[n-1]-s.messagesHistory[0]) / (float64(n-1) * s.config.ManagerInterval.Seconds())
  565. }
  566. s.mu.RUnlock()
  567. response := &apiStatsResponse{
  568. Messages: messages,
  569. MessagesRate: rate,
  570. }
  571. return s.writeJSON(w, response)
  572. }
  573. // handleFile processes the download of attachment files. The method handles GET and HEAD requests against a file.
  574. // Before streaming the file to a client, it locates uploader (m.Sender or m.User) in the message cache, so it
  575. // can associate the download bandwidth with the uploader.
  576. func (s *Server) handleFile(w http.ResponseWriter, r *http.Request, v *visitor) error {
  577. if s.config.AttachmentCacheDir == "" {
  578. return errHTTPInternalError
  579. }
  580. matches := fileRegex.FindStringSubmatch(r.URL.Path)
  581. if len(matches) != 2 {
  582. return errHTTPInternalErrorInvalidPath
  583. }
  584. messageID := matches[1]
  585. file := filepath.Join(s.config.AttachmentCacheDir, messageID)
  586. stat, err := os.Stat(file)
  587. if err != nil {
  588. return errHTTPNotFound.Fields(log.Context{
  589. "message_id": messageID,
  590. "error_context": "filesystem",
  591. })
  592. }
  593. w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests
  594. w.Header().Set("Content-Length", fmt.Sprintf("%d", stat.Size()))
  595. if r.Method == http.MethodHead {
  596. return nil
  597. }
  598. // Find message in database, and associate bandwidth to the uploader user
  599. // This is an easy way to
  600. // - avoid abuse (e.g. 1 uploader, 1k downloaders)
  601. // - and also uses the higher bandwidth limits of a paying user
  602. m, err := s.messageCache.Message(messageID)
  603. if err == errMessageNotFound {
  604. if s.config.CacheBatchTimeout > 0 {
  605. // Strange edge case: If we immediately after upload request the file (the web app does this for images),
  606. // and messages are persisted asynchronously, retry fetching from the database
  607. m, err = util.Retry(func() (*message, error) {
  608. return s.messageCache.Message(messageID)
  609. }, s.config.CacheBatchTimeout, 100*time.Millisecond, 300*time.Millisecond, 600*time.Millisecond)
  610. }
  611. if err != nil {
  612. return errHTTPNotFound.Fields(log.Context{
  613. "message_id": messageID,
  614. "error_context": "message_cache",
  615. })
  616. }
  617. } else if err != nil {
  618. return err
  619. }
  620. bandwidthVisitor := v
  621. if s.userManager != nil && m.User != "" {
  622. u, err := s.userManager.UserByID(m.User)
  623. if err != nil {
  624. return err
  625. }
  626. bandwidthVisitor = s.visitor(v.IP(), u)
  627. } else if m.Sender.IsValid() {
  628. bandwidthVisitor = s.visitor(m.Sender, nil)
  629. }
  630. if !bandwidthVisitor.BandwidthAllowed(stat.Size()) {
  631. return errHTTPTooManyRequestsLimitAttachmentBandwidth.With(m)
  632. }
  633. // Actually send file
  634. f, err := os.Open(file)
  635. if err != nil {
  636. return err
  637. }
  638. defer f.Close()
  639. if m.Attachment.Name != "" {
  640. w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(m.Attachment.Name))
  641. }
  642. _, err = io.Copy(util.NewContentTypeWriter(w, r.URL.Path), f)
  643. return err
  644. }
  645. func (s *Server) handleMatrixDiscovery(w http.ResponseWriter) error {
  646. if s.config.BaseURL == "" {
  647. return errHTTPInternalErrorMissingBaseURL
  648. }
  649. return writeMatrixDiscoveryResponse(w)
  650. }
  651. func (s *Server) handlePublishInternal(r *http.Request, v *visitor) (*message, error) {
  652. start := time.Now()
  653. t, err := fromContext[*topic](r, contextTopic)
  654. if err != nil {
  655. return nil, err
  656. }
  657. vrate, err := fromContext[*visitor](r, contextRateVisitor)
  658. if err != nil {
  659. return nil, err
  660. }
  661. body, err := util.Peek(r.Body, s.config.MessageLimit)
  662. if err != nil {
  663. return nil, err
  664. }
  665. m := newDefaultMessage(t.ID, "")
  666. cache, firebase, email, call, unifiedpush, e := s.parsePublishParams(r, m)
  667. if e != nil {
  668. return nil, e.With(t)
  669. }
  670. if unifiedpush && s.config.VisitorSubscriberRateLimiting && t.RateVisitor() == nil {
  671. // UnifiedPush clients must subscribe before publishing to allow proper subscriber-based rate limiting (see
  672. // Rate-Topics header). The 5xx response is because some app servers (in particular Mastodon) will remove
  673. // the subscription as invalid if any 400-499 code (except 429/408) is returned.
  674. // See https://github.com/mastodon/mastodon/blob/730bb3e211a84a2f30e3e2bbeae3f77149824a68/app/workers/web/push_notification_worker.rb#L35-L46
  675. return nil, errHTTPInsufficientStorageUnifiedPush.With(t)
  676. } else if !util.ContainsIP(s.config.VisitorRequestExemptIPAddrs, v.ip) && !vrate.MessageAllowed() {
  677. return nil, errHTTPTooManyRequestsLimitMessages.With(t)
  678. } else if email != "" && !vrate.EmailAllowed() {
  679. return nil, errHTTPTooManyRequestsLimitEmails.With(t)
  680. } else if call != "" {
  681. var httpErr *errHTTP
  682. call, httpErr = s.convertPhoneNumber(v.User(), call)
  683. if httpErr != nil {
  684. return nil, httpErr.With(t)
  685. } else if !vrate.CallAllowed() {
  686. return nil, errHTTPTooManyRequestsLimitCalls.With(t)
  687. }
  688. }
  689. if m.PollID != "" {
  690. m = newPollRequestMessage(t.ID, m.PollID)
  691. }
  692. m.Sender = v.IP()
  693. m.User = v.MaybeUserID()
  694. if cache {
  695. m.Expires = time.Unix(m.Time, 0).Add(v.Limits().MessageExpiryDuration).Unix()
  696. }
  697. if err := s.handlePublishBody(r, v, m, body, unifiedpush); err != nil {
  698. return nil, err
  699. }
  700. if m.Message == "" {
  701. m.Message = emptyMessageBody
  702. }
  703. delayed := m.Time > time.Now().Unix()
  704. ev := logvrm(v, r, m).
  705. Tag(tagPublish).
  706. With(t).
  707. Fields(log.Context{
  708. "message_delayed": delayed,
  709. "message_firebase": firebase,
  710. "message_unifiedpush": unifiedpush,
  711. "message_email": email,
  712. "message_call": call,
  713. })
  714. if ev.IsTrace() {
  715. ev.Field("message_body", util.MaybeMarshalJSON(m)).Trace("Received message")
  716. } else if ev.IsDebug() {
  717. ev.Debug("Received message")
  718. }
  719. if !delayed {
  720. if err := t.Publish(v, m); err != nil {
  721. return nil, err
  722. }
  723. if s.firebaseClient != nil && firebase {
  724. go s.sendToFirebase(v, m)
  725. }
  726. if s.smtpSender != nil && email != "" {
  727. go s.sendEmail(v, m, email)
  728. }
  729. if s.config.TwilioAccount != "" && call != "" {
  730. go s.callPhone(v, r, m, call)
  731. }
  732. if s.config.UpstreamBaseURL != "" && !unifiedpush { // UP messages are not sent to upstream
  733. go s.forwardPollRequest(v, m)
  734. }
  735. } else {
  736. logvrm(v, r, m).Tag(tagPublish).Debug("Message delayed, will process later")
  737. }
  738. if cache {
  739. logvrm(v, r, m).Tag(tagPublish).Debug("Adding message to cache")
  740. if err := s.messageCache.AddMessage(m); err != nil {
  741. return nil, err
  742. }
  743. }
  744. u := v.User()
  745. if s.userManager != nil && u != nil && u.Tier != nil {
  746. go s.userManager.EnqueueUserStats(u.ID, v.Stats())
  747. }
  748. s.mu.Lock()
  749. s.messages++
  750. s.mu.Unlock()
  751. if unifiedpush {
  752. minc(metricUnifiedPushPublishedSuccess)
  753. }
  754. mset(metricMessagePublishDurationMillis, time.Since(start).Milliseconds())
  755. return m, nil
  756. }
  757. func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, v *visitor) error {
  758. m, err := s.handlePublishInternal(r, v)
  759. if err != nil {
  760. minc(metricMessagesPublishedFailure)
  761. return err
  762. }
  763. minc(metricMessagesPublishedSuccess)
  764. return s.writeJSON(w, m)
  765. }
  766. func (s *Server) handlePublishMatrix(w http.ResponseWriter, r *http.Request, v *visitor) error {
  767. _, err := s.handlePublishInternal(r, v)
  768. if err != nil {
  769. minc(metricMessagesPublishedFailure)
  770. minc(metricMatrixPublishedFailure)
  771. if e, ok := err.(*errHTTP); ok && e.HTTPCode == errHTTPInsufficientStorageUnifiedPush.HTTPCode {
  772. topic, err := fromContext[*topic](r, contextTopic)
  773. if err != nil {
  774. return err
  775. }
  776. pushKey, err := fromContext[string](r, contextMatrixPushKey)
  777. if err != nil {
  778. return err
  779. }
  780. if time.Since(topic.LastAccess()) > matrixRejectPushKeyForUnifiedPushTopicWithoutRateVisitorAfter {
  781. return writeMatrixResponse(w, pushKey)
  782. }
  783. }
  784. return err
  785. }
  786. minc(metricMessagesPublishedSuccess)
  787. minc(metricMatrixPublishedSuccess)
  788. return writeMatrixSuccess(w)
  789. }
  790. func (s *Server) sendToFirebase(v *visitor, m *message) {
  791. logvm(v, m).Tag(tagFirebase).Debug("Publishing to Firebase")
  792. if err := s.firebaseClient.Send(v, m); err != nil {
  793. minc(metricFirebasePublishedFailure)
  794. if err == errFirebaseTemporarilyBanned {
  795. logvm(v, m).Tag(tagFirebase).Err(err).Debug("Unable to publish to Firebase: %v", err.Error())
  796. } else {
  797. logvm(v, m).Tag(tagFirebase).Err(err).Warn("Unable to publish to Firebase: %v", err.Error())
  798. }
  799. return
  800. }
  801. minc(metricFirebasePublishedSuccess)
  802. }
  803. func (s *Server) sendEmail(v *visitor, m *message, email string) {
  804. logvm(v, m).Tag(tagEmail).Field("email", email).Debug("Sending email to %s", email)
  805. if err := s.smtpSender.Send(v, m, email); err != nil {
  806. logvm(v, m).Tag(tagEmail).Field("email", email).Err(err).Warn("Unable to send email to %s: %v", email, err.Error())
  807. minc(metricEmailsPublishedFailure)
  808. return
  809. }
  810. minc(metricEmailsPublishedSuccess)
  811. }
  812. func (s *Server) forwardPollRequest(v *visitor, m *message) {
  813. topicURL := fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic)
  814. topicHash := fmt.Sprintf("%x", sha256.Sum256([]byte(topicURL)))
  815. forwardURL := fmt.Sprintf("%s/%s", s.config.UpstreamBaseURL, topicHash)
  816. logvm(v, m).Debug("Publishing poll request to %s", forwardURL)
  817. req, err := http.NewRequest("POST", forwardURL, strings.NewReader(""))
  818. if err != nil {
  819. logvm(v, m).Err(err).Warn("Unable to publish poll request")
  820. return
  821. }
  822. req.Header.Set("User-Agent", "ntfy/"+s.config.Version)
  823. req.Header.Set("X-Poll-ID", m.ID)
  824. if s.config.UpstreamAccessToken != "" {
  825. req.Header.Set("Authorization", util.BearerAuth(s.config.UpstreamAccessToken))
  826. }
  827. var httpClient = &http.Client{
  828. Timeout: time.Second * 10,
  829. }
  830. response, err := httpClient.Do(req)
  831. if err != nil {
  832. logvm(v, m).Err(err).Warn("Unable to publish poll request")
  833. return
  834. } else if response.StatusCode != http.StatusOK {
  835. if response.StatusCode == http.StatusTooManyRequests {
  836. logvm(v, m).Err(err).Warn("Unable to publish poll request, the upstream server %s responded with HTTP %s; you may solve this by sending fewer daily messages, or by configuring upstream-access-token (assuming you have an account with higher rate limits) ", s.config.UpstreamBaseURL, response.Status)
  837. } else {
  838. logvm(v, m).Err(err).Warn("Unable to publish poll request, the upstream server %s responded with HTTP %s", s.config.UpstreamBaseURL, response.Status)
  839. }
  840. return
  841. }
  842. }
  843. func (s *Server) parsePublishParams(r *http.Request, m *message) (cache bool, firebase bool, email, call string, unifiedpush bool, err *errHTTP) {
  844. cache = readBoolParam(r, true, "x-cache", "cache")
  845. firebase = readBoolParam(r, true, "x-firebase", "firebase")
  846. m.Title = readParam(r, "x-title", "title", "t")
  847. m.Click = readParam(r, "x-click", "click")
  848. icon := readParam(r, "x-icon", "icon")
  849. filename := readParam(r, "x-filename", "filename", "file", "f")
  850. attach := readParam(r, "x-attach", "attach", "a")
  851. if attach != "" || filename != "" {
  852. m.Attachment = &attachment{}
  853. }
  854. if filename != "" {
  855. m.Attachment.Name = filename
  856. }
  857. if attach != "" {
  858. if !urlRegex.MatchString(attach) {
  859. return false, false, "", "", false, errHTTPBadRequestAttachmentURLInvalid
  860. }
  861. m.Attachment.URL = attach
  862. if m.Attachment.Name == "" {
  863. u, err := url.Parse(m.Attachment.URL)
  864. if err == nil {
  865. m.Attachment.Name = path.Base(u.Path)
  866. if m.Attachment.Name == "." || m.Attachment.Name == "/" {
  867. m.Attachment.Name = ""
  868. }
  869. }
  870. }
  871. if m.Attachment.Name == "" {
  872. m.Attachment.Name = "attachment"
  873. }
  874. }
  875. if icon != "" {
  876. if !urlRegex.MatchString(icon) {
  877. return false, false, "", "", false, errHTTPBadRequestIconURLInvalid
  878. }
  879. m.Icon = icon
  880. }
  881. email = readParam(r, "x-email", "x-e-mail", "email", "e-mail", "mail", "e")
  882. if s.smtpSender == nil && email != "" {
  883. return false, false, "", "", false, errHTTPBadRequestEmailDisabled
  884. }
  885. call = readParam(r, "x-call", "call")
  886. if call != "" && (s.config.TwilioAccount == "" || s.userManager == nil) {
  887. return false, false, "", "", false, errHTTPBadRequestPhoneCallsDisabled
  888. } else if call != "" && !isBoolValue(call) && !phoneNumberRegex.MatchString(call) {
  889. return false, false, "", "", false, errHTTPBadRequestPhoneNumberInvalid
  890. }
  891. messageStr := strings.ReplaceAll(readParam(r, "x-message", "message", "m"), "\\n", "\n")
  892. if messageStr != "" {
  893. m.Message = messageStr
  894. }
  895. var e error
  896. m.Priority, e = util.ParsePriority(readParam(r, "x-priority", "priority", "prio", "p"))
  897. if e != nil {
  898. return false, false, "", "", false, errHTTPBadRequestPriorityInvalid
  899. }
  900. m.Tags = readCommaSeparatedParam(r, "x-tags", "tags", "tag", "ta")
  901. delayStr := readParam(r, "x-delay", "delay", "x-at", "at", "x-in", "in")
  902. if delayStr != "" {
  903. if !cache {
  904. return false, false, "", "", false, errHTTPBadRequestDelayNoCache
  905. }
  906. if email != "" {
  907. return false, false, "", "", false, errHTTPBadRequestDelayNoEmail // we cannot store the email address (yet)
  908. }
  909. if call != "" {
  910. return false, false, "", "", false, errHTTPBadRequestDelayNoCall // we cannot store the phone number (yet)
  911. }
  912. delay, err := util.ParseFutureTime(delayStr, time.Now())
  913. if err != nil {
  914. return false, false, "", "", false, errHTTPBadRequestDelayCannotParse
  915. } else if delay.Unix() < time.Now().Add(s.config.MinDelay).Unix() {
  916. return false, false, "", "", false, errHTTPBadRequestDelayTooSmall
  917. } else if delay.Unix() > time.Now().Add(s.config.MaxDelay).Unix() {
  918. return false, false, "", "", false, errHTTPBadRequestDelayTooLarge
  919. }
  920. m.Time = delay.Unix()
  921. }
  922. actionsStr := readParam(r, "x-actions", "actions", "action")
  923. if actionsStr != "" {
  924. m.Actions, e = parseActions(actionsStr)
  925. if e != nil {
  926. return false, false, "", "", false, errHTTPBadRequestActionsInvalid.Wrap(e.Error())
  927. }
  928. }
  929. unifiedpush = readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see GET too!
  930. if unifiedpush {
  931. firebase = false
  932. unifiedpush = true
  933. }
  934. m.PollID = readParam(r, "x-poll-id", "poll-id")
  935. if m.PollID != "" {
  936. unifiedpush = false
  937. cache = false
  938. email = ""
  939. }
  940. return cache, firebase, email, call, unifiedpush, nil
  941. }
  942. // handlePublishBody consumes the PUT/POST body and decides whether the body is an attachment or the message.
  943. //
  944. // 1. curl -X POST -H "Poll: 1234" ntfy.sh/...
  945. // If a message is flagged as poll request, the body does not matter and is discarded
  946. // 2. curl -T somebinarydata.bin "ntfy.sh/mytopic?up=1"
  947. // If body is binary, encode as base64, if not do not encode
  948. // 3. curl -H "Attach: http://example.com/file.jpg" ntfy.sh/mytopic
  949. // Body must be a message, because we attached an external URL
  950. // 4. curl -T short.txt -H "Filename: short.txt" ntfy.sh/mytopic
  951. // Body must be attachment, because we passed a filename
  952. // 5. curl -T file.txt ntfy.sh/mytopic
  953. // If file.txt is <= 4096 (message limit) and valid UTF-8, treat it as a message
  954. // 6. curl -T file.txt ntfy.sh/mytopic
  955. // If file.txt is > message limit, treat it as an attachment
  956. func (s *Server) handlePublishBody(r *http.Request, v *visitor, m *message, body *util.PeekedReadCloser, unifiedpush bool) error {
  957. if m.Event == pollRequestEvent { // Case 1
  958. return s.handleBodyDiscard(body)
  959. } else if unifiedpush {
  960. return s.handleBodyAsMessageAutoDetect(m, body) // Case 2
  961. } else if m.Attachment != nil && m.Attachment.URL != "" {
  962. return s.handleBodyAsTextMessage(m, body) // Case 3
  963. } else if m.Attachment != nil && m.Attachment.Name != "" {
  964. return s.handleBodyAsAttachment(r, v, m, body) // Case 4
  965. } else if !body.LimitReached && utf8.Valid(body.PeekedBytes) {
  966. return s.handleBodyAsTextMessage(m, body) // Case 5
  967. }
  968. return s.handleBodyAsAttachment(r, v, m, body) // Case 6
  969. }
  970. func (s *Server) handleBodyDiscard(body *util.PeekedReadCloser) error {
  971. _, err := io.Copy(io.Discard, body)
  972. _ = body.Close()
  973. return err
  974. }
  975. func (s *Server) handleBodyAsMessageAutoDetect(m *message, body *util.PeekedReadCloser) error {
  976. if utf8.Valid(body.PeekedBytes) {
  977. m.Message = string(body.PeekedBytes) // Do not trim
  978. } else {
  979. m.Message = base64.StdEncoding.EncodeToString(body.PeekedBytes)
  980. m.Encoding = encodingBase64
  981. }
  982. return nil
  983. }
  984. func (s *Server) handleBodyAsTextMessage(m *message, body *util.PeekedReadCloser) error {
  985. if !utf8.Valid(body.PeekedBytes) {
  986. return errHTTPBadRequestMessageNotUTF8.With(m)
  987. }
  988. if len(body.PeekedBytes) > 0 { // Empty body should not override message (publish via GET!)
  989. m.Message = strings.TrimSpace(string(body.PeekedBytes)) // Truncates the message to the peek limit if required
  990. }
  991. if m.Attachment != nil && m.Attachment.Name != "" && m.Message == "" {
  992. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  993. }
  994. return nil
  995. }
  996. func (s *Server) handleBodyAsAttachment(r *http.Request, v *visitor, m *message, body *util.PeekedReadCloser) error {
  997. if s.fileCache == nil || s.config.BaseURL == "" || s.config.AttachmentCacheDir == "" {
  998. return errHTTPBadRequestAttachmentsDisallowed.With(m)
  999. }
  1000. vinfo, err := v.Info()
  1001. if err != nil {
  1002. return err
  1003. }
  1004. attachmentExpiry := time.Now().Add(vinfo.Limits.AttachmentExpiryDuration).Unix()
  1005. if m.Time > attachmentExpiry {
  1006. return errHTTPBadRequestAttachmentsExpiryBeforeDelivery.With(m)
  1007. }
  1008. contentLengthStr := r.Header.Get("Content-Length")
  1009. if contentLengthStr != "" { // Early "do-not-trust" check, hard limit see below
  1010. contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
  1011. if err == nil && (contentLength > vinfo.Stats.AttachmentTotalSizeRemaining || contentLength > vinfo.Limits.AttachmentFileSizeLimit) {
  1012. return errHTTPEntityTooLargeAttachment.With(m).Fields(log.Context{
  1013. "message_content_length": contentLength,
  1014. "attachment_total_size_remaining": vinfo.Stats.AttachmentTotalSizeRemaining,
  1015. "attachment_file_size_limit": vinfo.Limits.AttachmentFileSizeLimit,
  1016. })
  1017. }
  1018. }
  1019. if m.Attachment == nil {
  1020. m.Attachment = &attachment{}
  1021. }
  1022. var ext string
  1023. m.Attachment.Expires = attachmentExpiry
  1024. m.Attachment.Type, ext = util.DetectContentType(body.PeekedBytes, m.Attachment.Name)
  1025. m.Attachment.URL = fmt.Sprintf("%s/file/%s%s", s.config.BaseURL, m.ID, ext)
  1026. if m.Attachment.Name == "" {
  1027. m.Attachment.Name = fmt.Sprintf("attachment%s", ext)
  1028. }
  1029. if m.Message == "" {
  1030. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  1031. }
  1032. limiters := []util.Limiter{
  1033. v.BandwidthLimiter(),
  1034. util.NewFixedLimiter(vinfo.Limits.AttachmentFileSizeLimit),
  1035. util.NewFixedLimiter(vinfo.Stats.AttachmentTotalSizeRemaining),
  1036. }
  1037. m.Attachment.Size, err = s.fileCache.Write(m.ID, body, limiters...)
  1038. if err == util.ErrLimitReached {
  1039. return errHTTPEntityTooLargeAttachment.With(m)
  1040. } else if err != nil {
  1041. return err
  1042. }
  1043. return nil
  1044. }
  1045. func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1046. encoder := func(msg *message) (string, error) {
  1047. var buf bytes.Buffer
  1048. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  1049. return "", err
  1050. }
  1051. return buf.String(), nil
  1052. }
  1053. return s.handleSubscribeHTTP(w, r, v, "application/x-ndjson", encoder)
  1054. }
  1055. func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1056. encoder := func(msg *message) (string, error) {
  1057. var buf bytes.Buffer
  1058. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  1059. return "", err
  1060. }
  1061. if msg.Event != messageEvent {
  1062. return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this!
  1063. }
  1064. return fmt.Sprintf("data: %s\n", buf.String()), nil
  1065. }
  1066. return s.handleSubscribeHTTP(w, r, v, "text/event-stream", encoder)
  1067. }
  1068. func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1069. encoder := func(msg *message) (string, error) {
  1070. if msg.Event == messageEvent { // only handle default events
  1071. return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil
  1072. }
  1073. return "\n", nil // "keepalive" and "open" events just send an empty line
  1074. }
  1075. return s.handleSubscribeHTTP(w, r, v, "text/plain", encoder)
  1076. }
  1077. func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request, v *visitor, contentType string, encoder messageEncoder) error {
  1078. logvr(v, r).Tag(tagSubscribe).Debug("HTTP stream connection opened")
  1079. defer logvr(v, r).Tag(tagSubscribe).Debug("HTTP stream connection closed")
  1080. if !v.SubscriptionAllowed() {
  1081. return errHTTPTooManyRequestsLimitSubscriptions
  1082. }
  1083. defer v.RemoveSubscription()
  1084. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  1085. if err != nil {
  1086. return err
  1087. }
  1088. poll, since, scheduled, filters, rateTopics, err := parseSubscribeParams(r)
  1089. if err != nil {
  1090. return err
  1091. }
  1092. var wlock sync.Mutex
  1093. defer func() {
  1094. // Hack: This is the fix for a horrible data race that I have not been able to figure out in quite some time.
  1095. // It appears to be happening when the Go HTTP code reads from the socket when closing the request (i.e. AFTER
  1096. // this function returns), and causes a data race with the ResponseWriter. Locking wlock here silences the
  1097. // data race detector. See https://github.com/binwiederhier/ntfy/issues/338#issuecomment-1163425889.
  1098. wlock.TryLock()
  1099. }()
  1100. sub := func(v *visitor, msg *message) error {
  1101. if !filters.Pass(msg) {
  1102. return nil
  1103. }
  1104. m, err := encoder(msg)
  1105. if err != nil {
  1106. return err
  1107. }
  1108. wlock.Lock()
  1109. defer wlock.Unlock()
  1110. if _, err := w.Write([]byte(m)); err != nil {
  1111. return err
  1112. }
  1113. if fl, ok := w.(http.Flusher); ok {
  1114. fl.Flush()
  1115. }
  1116. return nil
  1117. }
  1118. if err := s.maybeSetRateVisitors(r, v, topics, rateTopics); err != nil {
  1119. return err
  1120. }
  1121. w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests
  1122. w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset!
  1123. if poll {
  1124. for _, t := range topics {
  1125. t.Keepalive()
  1126. }
  1127. return s.sendOldMessages(topics, since, scheduled, v, sub)
  1128. }
  1129. ctx, cancel := context.WithCancel(context.Background())
  1130. defer cancel()
  1131. subscriberIDs := make([]int, 0)
  1132. for _, t := range topics {
  1133. subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v.MaybeUserID(), cancel))
  1134. }
  1135. defer func() {
  1136. for i, subscriberID := range subscriberIDs {
  1137. topics[i].Unsubscribe(subscriberID) // Order!
  1138. }
  1139. }()
  1140. if err := sub(v, newOpenMessage(topicsStr)); err != nil { // Send out open message
  1141. return err
  1142. }
  1143. if err := s.sendOldMessages(topics, since, scheduled, v, sub); err != nil {
  1144. return err
  1145. }
  1146. for {
  1147. select {
  1148. case <-ctx.Done():
  1149. return nil
  1150. case <-r.Context().Done():
  1151. return nil
  1152. case <-time.After(s.config.KeepaliveInterval):
  1153. ev := logvr(v, r).Tag(tagSubscribe)
  1154. if len(topics) == 1 {
  1155. ev.With(topics[0]).Trace("Sending keepalive message to %s", topics[0].ID)
  1156. } else {
  1157. ev.Trace("Sending keepalive message to %d topics", len(topics))
  1158. }
  1159. v.Keepalive()
  1160. for _, t := range topics {
  1161. t.Keepalive()
  1162. }
  1163. if err := sub(v, newKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message
  1164. return err
  1165. }
  1166. }
  1167. }
  1168. }
  1169. func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1170. if strings.ToLower(r.Header.Get("Upgrade")) != "websocket" {
  1171. return errHTTPBadRequestWebSocketsUpgradeHeaderMissing
  1172. }
  1173. if !v.SubscriptionAllowed() {
  1174. return errHTTPTooManyRequestsLimitSubscriptions
  1175. }
  1176. defer v.RemoveSubscription()
  1177. logvr(v, r).Tag(tagWebsocket).Debug("WebSocket connection opened")
  1178. defer logvr(v, r).Tag(tagWebsocket).Debug("WebSocket connection closed")
  1179. topics, topicsStr, err := s.topicsFromPath(r.URL.Path)
  1180. if err != nil {
  1181. return err
  1182. }
  1183. poll, since, scheduled, filters, rateTopics, err := parseSubscribeParams(r)
  1184. if err != nil {
  1185. return err
  1186. }
  1187. upgrader := &websocket.Upgrader{
  1188. ReadBufferSize: wsBufferSize,
  1189. WriteBufferSize: wsBufferSize,
  1190. CheckOrigin: func(r *http.Request) bool {
  1191. return true // We're open for business!
  1192. },
  1193. }
  1194. conn, err := upgrader.Upgrade(w, r, nil)
  1195. if err != nil {
  1196. return err
  1197. }
  1198. defer conn.Close()
  1199. // Subscription connections can be canceled externally, see topic.CancelSubscribersExceptUser
  1200. cancelCtx, cancel := context.WithCancel(context.Background())
  1201. defer cancel()
  1202. // Use errgroup to run WebSocket reader and writer in Go routines
  1203. var wlock sync.Mutex
  1204. g, gctx := errgroup.WithContext(cancelCtx)
  1205. g.Go(func() error {
  1206. pongWait := s.config.KeepaliveInterval + wsPongWait
  1207. conn.SetReadLimit(wsReadLimit)
  1208. if err := conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
  1209. return err
  1210. }
  1211. conn.SetPongHandler(func(appData string) error {
  1212. logvr(v, r).Tag(tagWebsocket).Trace("Received WebSocket pong")
  1213. return conn.SetReadDeadline(time.Now().Add(pongWait))
  1214. })
  1215. for {
  1216. _, _, err := conn.NextReader()
  1217. if err != nil {
  1218. return err
  1219. }
  1220. select {
  1221. case <-gctx.Done():
  1222. return nil
  1223. default:
  1224. }
  1225. }
  1226. })
  1227. g.Go(func() error {
  1228. ping := func() error {
  1229. wlock.Lock()
  1230. defer wlock.Unlock()
  1231. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  1232. return err
  1233. }
  1234. logvr(v, r).Tag(tagWebsocket).Trace("Sending WebSocket ping")
  1235. return conn.WriteMessage(websocket.PingMessage, nil)
  1236. }
  1237. for {
  1238. select {
  1239. case <-gctx.Done():
  1240. return nil
  1241. case <-cancelCtx.Done():
  1242. logvr(v, r).Tag(tagWebsocket).Trace("Cancel received, closing subscriber connection")
  1243. conn.Close()
  1244. return &websocket.CloseError{Code: websocket.CloseNormalClosure, Text: "subscription was canceled"}
  1245. case <-time.After(s.config.KeepaliveInterval):
  1246. v.Keepalive()
  1247. for _, t := range topics {
  1248. t.Keepalive()
  1249. }
  1250. if err := ping(); err != nil {
  1251. return err
  1252. }
  1253. }
  1254. }
  1255. })
  1256. sub := func(v *visitor, msg *message) error {
  1257. if !filters.Pass(msg) {
  1258. return nil
  1259. }
  1260. wlock.Lock()
  1261. defer wlock.Unlock()
  1262. if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil {
  1263. return err
  1264. }
  1265. return conn.WriteJSON(msg)
  1266. }
  1267. if err := s.maybeSetRateVisitors(r, v, topics, rateTopics); err != nil {
  1268. return err
  1269. }
  1270. w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests
  1271. if poll {
  1272. for _, t := range topics {
  1273. t.Keepalive()
  1274. }
  1275. return s.sendOldMessages(topics, since, scheduled, v, sub)
  1276. }
  1277. subscriberIDs := make([]int, 0)
  1278. for _, t := range topics {
  1279. subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v.MaybeUserID(), cancel))
  1280. }
  1281. defer func() {
  1282. for i, subscriberID := range subscriberIDs {
  1283. topics[i].Unsubscribe(subscriberID) // Order!
  1284. }
  1285. }()
  1286. if err := sub(v, newOpenMessage(topicsStr)); err != nil { // Send out open message
  1287. return err
  1288. }
  1289. if err := s.sendOldMessages(topics, since, scheduled, v, sub); err != nil {
  1290. return err
  1291. }
  1292. err = g.Wait()
  1293. if err != nil && websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseAbnormalClosure, websocket.CloseNoStatusReceived) {
  1294. logvr(v, r).Tag(tagWebsocket).Err(err).Fields(websocketErrorContext(err)).Trace("WebSocket connection closed")
  1295. return nil // Normal closures are not errors; note: "1006 (abnormal closure)" is treated as normal, because people disconnect a lot
  1296. }
  1297. return err
  1298. }
  1299. func parseSubscribeParams(r *http.Request) (poll bool, since sinceMarker, scheduled bool, filters *queryFilter, rateTopics []string, err error) {
  1300. poll = readBoolParam(r, false, "x-poll", "poll", "po")
  1301. scheduled = readBoolParam(r, false, "x-scheduled", "scheduled", "sched")
  1302. since, err = parseSince(r, poll)
  1303. if err != nil {
  1304. return
  1305. }
  1306. filters, err = parseQueryFilters(r)
  1307. if err != nil {
  1308. return
  1309. }
  1310. rateTopics = readCommaSeparatedParam(r, "x-rate-topics", "rate-topics")
  1311. return
  1312. }
  1313. // maybeSetRateVisitors sets the rate visitor on a topic (v.SetRateVisitor), indicating that all messages published
  1314. // to that topic will be rate limited against the rate visitor instead of the publishing visitor.
  1315. //
  1316. // Setting the rate visitor is ony allowed if the `visitor-subscriber-rate-limiting` setting is enabled, AND
  1317. // - auth-file is not set (everything is open by default)
  1318. // - or the topic is reserved, and v.user is the owner
  1319. // - or the topic is not reserved, and v.user has write access
  1320. //
  1321. // Note: This TEMPORARILY also registers all topics starting with "up" (= UnifiedPush). This is to ease the transition
  1322. // until the Android app will send the "Rate-Topics" header.
  1323. func (s *Server) maybeSetRateVisitors(r *http.Request, v *visitor, topics []*topic, rateTopics []string) error {
  1324. // Bail out if not enabled
  1325. if !s.config.VisitorSubscriberRateLimiting {
  1326. return nil
  1327. }
  1328. // Make a list of topics that we'll actually set the RateVisitor on
  1329. eligibleRateTopics := make([]*topic, 0)
  1330. for _, t := range topics {
  1331. if (strings.HasPrefix(t.ID, unifiedPushTopicPrefix) && len(t.ID) == unifiedPushTopicLength) || util.Contains(rateTopics, t.ID) {
  1332. eligibleRateTopics = append(eligibleRateTopics, t)
  1333. }
  1334. }
  1335. if len(eligibleRateTopics) == 0 {
  1336. return nil
  1337. }
  1338. // If access controls are turned off, v has access to everything, and we can set the rate visitor
  1339. if s.userManager == nil {
  1340. return s.setRateVisitors(r, v, eligibleRateTopics)
  1341. }
  1342. // If access controls are enabled, only set rate visitor if
  1343. // - topic is reserved, and v.user is the owner
  1344. // - topic is not reserved, and v.user has write access
  1345. writableRateTopics := make([]*topic, 0)
  1346. for _, t := range topics {
  1347. ownerUserID, err := s.userManager.ReservationOwner(t.ID)
  1348. if err != nil {
  1349. return err
  1350. }
  1351. if ownerUserID == "" {
  1352. if err := s.userManager.Authorize(v.User(), t.ID, user.PermissionWrite); err == nil {
  1353. writableRateTopics = append(writableRateTopics, t)
  1354. }
  1355. } else if ownerUserID == v.MaybeUserID() {
  1356. writableRateTopics = append(writableRateTopics, t)
  1357. }
  1358. }
  1359. return s.setRateVisitors(r, v, writableRateTopics)
  1360. }
  1361. func (s *Server) setRateVisitors(r *http.Request, v *visitor, rateTopics []*topic) error {
  1362. for _, t := range rateTopics {
  1363. logvr(v, r).
  1364. Tag(tagSubscribe).
  1365. With(t).
  1366. Debug("Setting visitor as rate visitor for topic %s", t.ID)
  1367. t.SetRateVisitor(v)
  1368. }
  1369. return nil
  1370. }
  1371. // sendOldMessages selects old messages from the messageCache and calls sub for each of them. It uses since as the
  1372. // marker, returning only messages that are newer than the marker.
  1373. func (s *Server) sendOldMessages(topics []*topic, since sinceMarker, scheduled bool, v *visitor, sub subscriber) error {
  1374. if since.IsNone() {
  1375. return nil
  1376. }
  1377. messages := make([]*message, 0)
  1378. for _, t := range topics {
  1379. topicMessages, err := s.messageCache.Messages(t.ID, since, scheduled)
  1380. if err != nil {
  1381. return err
  1382. }
  1383. messages = append(messages, topicMessages...)
  1384. }
  1385. sort.Slice(messages, func(i, j int) bool {
  1386. return messages[i].Time < messages[j].Time
  1387. })
  1388. for _, m := range messages {
  1389. if err := sub(v, m); err != nil {
  1390. return err
  1391. }
  1392. }
  1393. return nil
  1394. }
  1395. // parseSince returns a timestamp identifying the time span from which cached messages should be received.
  1396. //
  1397. // Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), or
  1398. // "all" for all messages.
  1399. func parseSince(r *http.Request, poll bool) (sinceMarker, error) {
  1400. since := readParam(r, "x-since", "since", "si")
  1401. // Easy cases (empty, all, none)
  1402. if since == "" {
  1403. if poll {
  1404. return sinceAllMessages, nil
  1405. }
  1406. return sinceNoMessages, nil
  1407. } else if since == "all" {
  1408. return sinceAllMessages, nil
  1409. } else if since == "none" {
  1410. return sinceNoMessages, nil
  1411. }
  1412. // ID, timestamp, duration
  1413. if validMessageID(since) {
  1414. return newSinceID(since), nil
  1415. } else if s, err := strconv.ParseInt(since, 10, 64); err == nil {
  1416. return newSinceTime(s), nil
  1417. } else if d, err := time.ParseDuration(since); err == nil {
  1418. return newSinceTime(time.Now().Add(-1 * d).Unix()), nil
  1419. }
  1420. return sinceNoMessages, errHTTPBadRequestSinceInvalid
  1421. }
  1422. func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request, _ *visitor) error {
  1423. w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, PATCH, DELETE")
  1424. w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests
  1425. w.Header().Set("Access-Control-Allow-Headers", "*") // CORS, allow auth via JS // FIXME is this terrible?
  1426. return nil
  1427. }
  1428. // topicFromPath returns the topic from a root path (e.g. /mytopic), creating it if it doesn't exist.
  1429. func (s *Server) topicFromPath(path string) (*topic, error) {
  1430. parts := strings.Split(path, "/")
  1431. if len(parts) < 2 {
  1432. return nil, errHTTPBadRequestTopicInvalid
  1433. }
  1434. return s.topicFromID(parts[1])
  1435. }
  1436. // topicsFromPath returns the topic from a root path (e.g. /mytopic,mytopic2), creating it if it doesn't exist.
  1437. func (s *Server) topicsFromPath(path string) ([]*topic, string, error) {
  1438. parts := strings.Split(path, "/")
  1439. if len(parts) < 2 {
  1440. return nil, "", errHTTPBadRequestTopicInvalid
  1441. }
  1442. topicIDs := util.SplitNoEmpty(parts[1], ",")
  1443. topics, err := s.topicsFromIDs(topicIDs...)
  1444. if err != nil {
  1445. return nil, "", errHTTPBadRequestTopicInvalid
  1446. }
  1447. return topics, parts[1], nil
  1448. }
  1449. // topicsFromIDs returns the topics with the given IDs, creating them if they don't exist.
  1450. func (s *Server) topicsFromIDs(ids ...string) ([]*topic, error) {
  1451. s.mu.Lock()
  1452. defer s.mu.Unlock()
  1453. topics := make([]*topic, 0)
  1454. for _, id := range ids {
  1455. if util.Contains(s.config.DisallowedTopics, id) {
  1456. return nil, errHTTPBadRequestTopicDisallowed
  1457. }
  1458. if _, ok := s.topics[id]; !ok {
  1459. if len(s.topics) >= s.config.TotalTopicLimit {
  1460. return nil, errHTTPTooManyRequestsLimitTotalTopics
  1461. }
  1462. s.topics[id] = newTopic(id)
  1463. }
  1464. topics = append(topics, s.topics[id])
  1465. }
  1466. return topics, nil
  1467. }
  1468. // topicFromID returns the topic with the given ID, creating it if it doesn't exist.
  1469. func (s *Server) topicFromID(id string) (*topic, error) {
  1470. topics, err := s.topicsFromIDs(id)
  1471. if err != nil {
  1472. return nil, err
  1473. }
  1474. return topics[0], nil
  1475. }
  1476. // topicsFromPattern returns a list of topics matching the given pattern, but it does not create them.
  1477. func (s *Server) topicsFromPattern(pattern string) ([]*topic, error) {
  1478. s.mu.RLock()
  1479. defer s.mu.RUnlock()
  1480. patternRegexp, err := regexp.Compile("^" + strings.ReplaceAll(pattern, "*", ".*") + "$")
  1481. if err != nil {
  1482. return nil, err
  1483. }
  1484. topics := make([]*topic, 0)
  1485. for _, t := range s.topics {
  1486. if patternRegexp.MatchString(t.ID) {
  1487. topics = append(topics, t)
  1488. }
  1489. }
  1490. return topics, nil
  1491. }
  1492. func (s *Server) runSMTPServer() error {
  1493. s.smtpServerBackend = newMailBackend(s.config, s.handle)
  1494. s.smtpServer = smtp.NewServer(s.smtpServerBackend)
  1495. s.smtpServer.Addr = s.config.SMTPServerListen
  1496. s.smtpServer.Domain = s.config.SMTPServerDomain
  1497. s.smtpServer.ReadTimeout = 10 * time.Second
  1498. s.smtpServer.WriteTimeout = 10 * time.Second
  1499. s.smtpServer.MaxMessageBytes = 1024 * 1024 // Must be much larger than message size (headers, multipart, etc.)
  1500. s.smtpServer.MaxRecipients = 1
  1501. s.smtpServer.AllowInsecureAuth = true
  1502. return s.smtpServer.ListenAndServe()
  1503. }
  1504. func (s *Server) runManager() {
  1505. for {
  1506. select {
  1507. case <-time.After(s.config.ManagerInterval):
  1508. log.
  1509. Tag(tagManager).
  1510. Timing(s.execManager).
  1511. Debug("Manager finished")
  1512. case <-s.closeChan:
  1513. return
  1514. }
  1515. }
  1516. }
  1517. // runStatsResetter runs once a day (usually midnight UTC) to reset all the visitor's message and
  1518. // email counters. The stats are used to display the counters in the web app, as well as for rate limiting.
  1519. func (s *Server) runStatsResetter() {
  1520. for {
  1521. runAt := util.NextOccurrenceUTC(s.config.VisitorStatsResetTime, time.Now())
  1522. timer := time.NewTimer(time.Until(runAt))
  1523. log.Tag(tagResetter).Debug("Waiting until %v to reset visitor stats", runAt)
  1524. select {
  1525. case <-timer.C:
  1526. log.Tag(tagResetter).Debug("Running stats resetter")
  1527. s.resetStats()
  1528. case <-s.closeChan:
  1529. log.Tag(tagResetter).Debug("Stopping stats resetter")
  1530. timer.Stop()
  1531. return
  1532. }
  1533. }
  1534. }
  1535. func (s *Server) resetStats() {
  1536. log.Info("Resetting all visitor stats (daily task)")
  1537. s.mu.Lock()
  1538. defer s.mu.Unlock() // Includes the database query to avoid races with other processes
  1539. for _, v := range s.visitors {
  1540. v.ResetStats()
  1541. }
  1542. if s.userManager != nil {
  1543. if err := s.userManager.ResetStats(); err != nil {
  1544. log.Tag(tagResetter).Warn("Failed to write to database: %s", err.Error())
  1545. }
  1546. }
  1547. }
  1548. func (s *Server) runFirebaseKeepaliver() {
  1549. if s.firebaseClient == nil {
  1550. return
  1551. }
  1552. v := newVisitor(s.config, s.messageCache, s.userManager, netip.IPv4Unspecified(), nil) // Background process, not a real visitor, uses IP 0.0.0.0
  1553. for {
  1554. select {
  1555. case <-time.After(s.config.FirebaseKeepaliveInterval):
  1556. s.sendToFirebase(v, newKeepaliveMessage(firebaseControlTopic))
  1557. /*
  1558. FIXME: Disable iOS polling entirely for now due to thundering herd problem (see #677)
  1559. To solve this, we'd have to shard the iOS poll topics to spread out the polling evenly.
  1560. Given that it's not really necessary to poll, turning it off for now should not have any impact.
  1561. case <-time.After(s.config.FirebasePollInterval):
  1562. s.sendToFirebase(v, newKeepaliveMessage(firebasePollTopic))
  1563. */
  1564. case <-s.closeChan:
  1565. return
  1566. }
  1567. }
  1568. }
  1569. func (s *Server) runDelayedSender() {
  1570. for {
  1571. select {
  1572. case <-time.After(s.config.DelayedSenderInterval):
  1573. if err := s.sendDelayedMessages(); err != nil {
  1574. log.Tag(tagPublish).Err(err).Warn("Error sending delayed messages")
  1575. }
  1576. case <-s.closeChan:
  1577. return
  1578. }
  1579. }
  1580. }
  1581. func (s *Server) sendDelayedMessages() error {
  1582. messages, err := s.messageCache.MessagesDue()
  1583. if err != nil {
  1584. return err
  1585. }
  1586. for _, m := range messages {
  1587. var u *user.User
  1588. if s.userManager != nil && m.User != "" {
  1589. u, err = s.userManager.UserByID(m.User)
  1590. if err != nil {
  1591. log.With(m).Err(err).Warn("Error sending delayed message")
  1592. continue
  1593. }
  1594. }
  1595. v := s.visitor(m.Sender, u)
  1596. if err := s.sendDelayedMessage(v, m); err != nil {
  1597. logvm(v, m).Err(err).Warn("Error sending delayed message")
  1598. }
  1599. }
  1600. return nil
  1601. }
  1602. func (s *Server) sendDelayedMessage(v *visitor, m *message) error {
  1603. logvm(v, m).Debug("Sending delayed message")
  1604. s.mu.RLock()
  1605. t, ok := s.topics[m.Topic] // If no subscribers, just mark message as published
  1606. s.mu.RUnlock()
  1607. if ok {
  1608. go func() {
  1609. // We do not rate-limit messages here, since we've rate limited them in the PUT/POST handler
  1610. if err := t.Publish(v, m); err != nil {
  1611. logvm(v, m).Err(err).Warn("Unable to publish message")
  1612. }
  1613. }()
  1614. }
  1615. if s.firebaseClient != nil { // Firebase subscribers may not show up in topics map
  1616. go s.sendToFirebase(v, m)
  1617. }
  1618. if s.config.UpstreamBaseURL != "" {
  1619. go s.forwardPollRequest(v, m)
  1620. }
  1621. if err := s.messageCache.MarkPublished(m); err != nil {
  1622. return err
  1623. }
  1624. return nil
  1625. }
  1626. // transformBodyJSON peeks the request body, reads the JSON, and converts it to headers
  1627. // before passing it on to the next handler. This is meant to be used in combination with handlePublish.
  1628. func (s *Server) transformBodyJSON(next handleFunc) handleFunc {
  1629. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1630. m, err := readJSONWithLimit[publishMessage](r.Body, s.config.MessageLimit*2, false) // 2x to account for JSON format overhead
  1631. if err != nil {
  1632. return err
  1633. }
  1634. if !topicRegex.MatchString(m.Topic) {
  1635. return errHTTPBadRequestTopicInvalid
  1636. }
  1637. if m.Message == "" {
  1638. m.Message = emptyMessageBody
  1639. }
  1640. r.URL.Path = "/" + m.Topic
  1641. r.Body = io.NopCloser(strings.NewReader(m.Message))
  1642. if m.Title != "" {
  1643. r.Header.Set("X-Title", m.Title)
  1644. }
  1645. if m.Priority != 0 {
  1646. r.Header.Set("X-Priority", fmt.Sprintf("%d", m.Priority))
  1647. }
  1648. if m.Tags != nil && len(m.Tags) > 0 {
  1649. r.Header.Set("X-Tags", strings.Join(m.Tags, ","))
  1650. }
  1651. if m.Attach != "" {
  1652. r.Header.Set("X-Attach", m.Attach)
  1653. }
  1654. if m.Filename != "" {
  1655. r.Header.Set("X-Filename", m.Filename)
  1656. }
  1657. if m.Click != "" {
  1658. r.Header.Set("X-Click", m.Click)
  1659. }
  1660. if m.Icon != "" {
  1661. r.Header.Set("X-Icon", m.Icon)
  1662. }
  1663. if len(m.Actions) > 0 {
  1664. actionsStr, err := json.Marshal(m.Actions)
  1665. if err != nil {
  1666. return errHTTPBadRequestMessageJSONInvalid
  1667. }
  1668. r.Header.Set("X-Actions", string(actionsStr))
  1669. }
  1670. if m.Email != "" {
  1671. r.Header.Set("X-Email", m.Email)
  1672. }
  1673. if m.Delay != "" {
  1674. r.Header.Set("X-Delay", m.Delay)
  1675. }
  1676. if m.Call != "" {
  1677. r.Header.Set("X-Call", m.Call)
  1678. }
  1679. return next(w, r, v)
  1680. }
  1681. }
  1682. func (s *Server) transformMatrixJSON(next handleFunc) handleFunc {
  1683. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1684. newRequest, err := newRequestFromMatrixJSON(r, s.config.BaseURL, s.config.MessageLimit)
  1685. if err != nil {
  1686. logvr(v, r).Tag(tagMatrix).Err(err).Debug("Invalid Matrix request")
  1687. if e, ok := err.(*errMatrixPushkeyRejected); ok {
  1688. return writeMatrixResponse(w, e.rejectedPushKey)
  1689. }
  1690. return err
  1691. }
  1692. if err := next(w, newRequest, v); err != nil {
  1693. logvr(v, r).Tag(tagMatrix).Err(err).Debug("Error handling Matrix request")
  1694. return err
  1695. }
  1696. return nil
  1697. }
  1698. }
  1699. func (s *Server) authorizeTopicWrite(next handleFunc) handleFunc {
  1700. return s.autorizeTopic(next, user.PermissionWrite)
  1701. }
  1702. func (s *Server) authorizeTopicRead(next handleFunc) handleFunc {
  1703. return s.autorizeTopic(next, user.PermissionRead)
  1704. }
  1705. func (s *Server) autorizeTopic(next handleFunc, perm user.Permission) handleFunc {
  1706. return func(w http.ResponseWriter, r *http.Request, v *visitor) error {
  1707. if s.userManager == nil {
  1708. return next(w, r, v)
  1709. }
  1710. topics, _, err := s.topicsFromPath(r.URL.Path)
  1711. if err != nil {
  1712. return err
  1713. }
  1714. u := v.User()
  1715. for _, t := range topics {
  1716. if err := s.userManager.Authorize(u, t.ID, perm); err != nil {
  1717. logvr(v, r).With(t).Err(err).Debug("Access to topic %s not authorized", t.ID)
  1718. return errHTTPForbidden.With(t)
  1719. }
  1720. }
  1721. return next(w, r, v)
  1722. }
  1723. }
  1724. // maybeAuthenticate reads the "Authorization" header and will try to authenticate the user
  1725. // if it is set.
  1726. //
  1727. // - If auth-file is not configured, immediately return an IP-based visitor
  1728. // - If the header is not set or not supported (anything non-Basic and non-Bearer),
  1729. // an IP-based visitor is returned
  1730. // - If the header is set, authenticate will be called to check the username/password (Basic auth),
  1731. // or the token (Bearer auth), and read the user from the database
  1732. //
  1733. // This function will ALWAYS return a visitor, even if an error occurs (e.g. unauthorized), so
  1734. // that subsequent logging calls still have a visitor context.
  1735. func (s *Server) maybeAuthenticate(r *http.Request) (*visitor, error) {
  1736. // Read "Authorization" header value, and exit out early if it's not set
  1737. ip := extractIPAddress(r, s.config.BehindProxy)
  1738. vip := s.visitor(ip, nil)
  1739. if s.userManager == nil {
  1740. return vip, nil
  1741. }
  1742. header, err := readAuthHeader(r)
  1743. if err != nil {
  1744. return vip, err
  1745. } else if !supportedAuthHeader(header) {
  1746. return vip, nil
  1747. }
  1748. // If we're trying to auth, check the rate limiter first
  1749. if !vip.AuthAllowed() {
  1750. return vip, errHTTPTooManyRequestsLimitAuthFailure // Always return visitor, even when error occurs!
  1751. }
  1752. u, err := s.authenticate(r, header)
  1753. if err != nil {
  1754. vip.AuthFailed()
  1755. logr(r).Err(err).Debug("Authentication failed")
  1756. return vip, errHTTPUnauthorized // Always return visitor, even when error occurs!
  1757. }
  1758. // Authentication with user was successful
  1759. return s.visitor(ip, u), nil
  1760. }
  1761. // authenticate a user based on basic auth username/password (Authorization: Basic ...), or token auth (Authorization: Bearer ...).
  1762. // The Authorization header can be passed as a header or the ?auth=... query param. The latter is required only to
  1763. // support the WebSocket JavaScript class, which does not support passing headers during the initial request. The auth
  1764. // query param is effectively doubly base64 encoded. Its format is base64(Basic base64(user:pass)).
  1765. func (s *Server) authenticate(r *http.Request, header string) (user *user.User, err error) {
  1766. if strings.HasPrefix(header, "Bearer") {
  1767. return s.authenticateBearerAuth(r, strings.TrimSpace(strings.TrimPrefix(header, "Bearer")))
  1768. }
  1769. return s.authenticateBasicAuth(r, header)
  1770. }
  1771. // readAuthHeader reads the raw value of the Authorization header, either from the actual HTTP header,
  1772. // or from the ?auth... query parameter
  1773. func readAuthHeader(r *http.Request) (string, error) {
  1774. value := strings.TrimSpace(r.Header.Get("Authorization"))
  1775. queryParam := readQueryParam(r, "authorization", "auth")
  1776. if queryParam != "" {
  1777. a, err := base64.RawURLEncoding.DecodeString(queryParam)
  1778. if err != nil {
  1779. return "", err
  1780. }
  1781. value = strings.TrimSpace(string(a))
  1782. }
  1783. return value, nil
  1784. }
  1785. // supportedAuthHeader returns true only if the Authorization header value starts
  1786. // with "Basic" or "Bearer". In particular, an empty value is not supported, and neither
  1787. // are things like "WebPush", or "vapid" (see #629).
  1788. func supportedAuthHeader(value string) bool {
  1789. value = strings.ToLower(value)
  1790. return strings.HasPrefix(value, "basic ") || strings.HasPrefix(value, "bearer ")
  1791. }
  1792. func (s *Server) authenticateBasicAuth(r *http.Request, value string) (user *user.User, err error) {
  1793. r.Header.Set("Authorization", value)
  1794. username, password, ok := r.BasicAuth()
  1795. if !ok {
  1796. return nil, errors.New("invalid basic auth")
  1797. } else if username == "" {
  1798. return s.authenticateBearerAuth(r, password) // Treat password as token
  1799. }
  1800. return s.userManager.Authenticate(username, password)
  1801. }
  1802. func (s *Server) authenticateBearerAuth(r *http.Request, token string) (*user.User, error) {
  1803. u, err := s.userManager.AuthenticateToken(token)
  1804. if err != nil {
  1805. return nil, err
  1806. }
  1807. ip := extractIPAddress(r, s.config.BehindProxy)
  1808. go s.userManager.EnqueueTokenUpdate(token, &user.TokenUpdate{
  1809. LastAccess: time.Now(),
  1810. LastOrigin: ip,
  1811. })
  1812. return u, nil
  1813. }
  1814. func (s *Server) visitor(ip netip.Addr, user *user.User) *visitor {
  1815. s.mu.Lock()
  1816. defer s.mu.Unlock()
  1817. id := visitorID(ip, user)
  1818. v, exists := s.visitors[id]
  1819. if !exists {
  1820. s.visitors[id] = newVisitor(s.config, s.messageCache, s.userManager, ip, user)
  1821. return s.visitors[id]
  1822. }
  1823. v.Keepalive()
  1824. v.SetUser(user) // Always update with the latest user, may be nil!
  1825. return v
  1826. }
  1827. func (s *Server) writeJSON(w http.ResponseWriter, v any) error {
  1828. w.Header().Set("Content-Type", "application/json")
  1829. w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests
  1830. if err := json.NewEncoder(w).Encode(v); err != nil {
  1831. return err
  1832. }
  1833. return nil
  1834. }
  1835. func (s *Server) updateAndWriteStats(messagesCount int64) {
  1836. s.mu.Lock()
  1837. s.messagesHistory = append(s.messagesHistory, messagesCount)
  1838. if len(s.messagesHistory) > messagesHistoryMax {
  1839. s.messagesHistory = s.messagesHistory[1:]
  1840. }
  1841. s.mu.Unlock()
  1842. go func() {
  1843. if err := s.messageCache.UpdateStats(messagesCount); err != nil {
  1844. log.Tag(tagManager).Err(err).Warn("Cannot write messages stats")
  1845. }
  1846. }()
  1847. }