server.go 75 KB

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