server.go 75 KB

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