server.go 76 KB

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