server.go 75 KB

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