server.go 67 KB

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