server.go 57 KB

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