server.go 62 KB

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