server.go 75 KB

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