server.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "embed"
  6. "encoding/json"
  7. "errors"
  8. firebase "firebase.google.com/go"
  9. "firebase.google.com/go/messaging"
  10. "fmt"
  11. "github.com/emersion/go-smtp"
  12. "google.golang.org/api/option"
  13. "heckel.io/ntfy/util"
  14. "html/template"
  15. "io"
  16. "log"
  17. "net"
  18. "net/http"
  19. "net/http/httptest"
  20. "os"
  21. "path/filepath"
  22. "regexp"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "unicode/utf8"
  28. )
  29. // TODO add "max messages in a topic" limit
  30. // TODO implement "since=<ID>"
  31. // Server is the main server, providing the UI and API for ntfy
  32. type Server struct {
  33. config *Config
  34. httpServer *http.Server
  35. httpsServer *http.Server
  36. smtpServer *smtp.Server
  37. smtpBackend *smtpBackend
  38. topics map[string]*topic
  39. visitors map[string]*visitor
  40. firebase subscriber
  41. mailer mailer
  42. messages int64
  43. cache cache
  44. fileCache *fileCache
  45. closeChan chan bool
  46. mu sync.Mutex
  47. }
  48. // errHTTP is a generic HTTP error for any non-200 HTTP error
  49. type errHTTP struct {
  50. Code int `json:"code,omitempty"`
  51. HTTPCode int `json:"http"`
  52. Message string `json:"error"`
  53. Link string `json:"link,omitempty"`
  54. }
  55. func (e errHTTP) Error() string {
  56. return e.Message
  57. }
  58. func (e errHTTP) JSON() string {
  59. b, _ := json.Marshal(&e)
  60. return string(b)
  61. }
  62. type indexPage struct {
  63. Topic string
  64. CacheDuration time.Duration
  65. }
  66. type sinceTime time.Time
  67. func (t sinceTime) IsAll() bool {
  68. return t == sinceAllMessages
  69. }
  70. func (t sinceTime) IsNone() bool {
  71. return t == sinceNoMessages
  72. }
  73. func (t sinceTime) Time() time.Time {
  74. return time.Time(t)
  75. }
  76. var (
  77. sinceAllMessages = sinceTime(time.Unix(0, 0))
  78. sinceNoMessages = sinceTime(time.Unix(1, 0))
  79. )
  80. var (
  81. topicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No /!
  82. topicPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}$`) // Regex must match JS & Android app!
  83. jsonPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/json$`)
  84. ssePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/sse$`)
  85. rawPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/raw$`)
  86. publishPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/(publish|send|trigger)$`)
  87. staticRegex = regexp.MustCompile(`^/static/.+`)
  88. docsRegex = regexp.MustCompile(`^/docs(|/.*)$`)
  89. fileRegex = regexp.MustCompile(`^/file/([-_A-Za-z0-9]{1,64})(?:\.[A-Za-z0-9]{1,16})?$`)
  90. disallowedTopics = []string{"docs", "static", "file"}
  91. attachURLRegex = regexp.MustCompile(`^https?://`)
  92. templateFnMap = template.FuncMap{
  93. "durationToHuman": util.DurationToHuman,
  94. }
  95. //go:embed "index.gohtml"
  96. indexSource string
  97. indexTemplate = template.Must(template.New("index").Funcs(templateFnMap).Parse(indexSource))
  98. //go:embed "example.html"
  99. exampleSource string
  100. //go:embed static
  101. webStaticFs embed.FS
  102. webStaticFsCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: webStaticFs}
  103. //go:embed docs
  104. docsStaticFs embed.FS
  105. docsStaticCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: docsStaticFs}
  106. errHTTPNotFound = &errHTTP{40401, http.StatusNotFound, "page not found", ""}
  107. errHTTPTooManyRequestsLimitRequests = &errHTTP{42901, http.StatusTooManyRequests, "limit reached: too many requests, please be nice", "https://ntfy.sh/docs/publish/#limitations"}
  108. errHTTPTooManyRequestsLimitEmails = &errHTTP{42902, http.StatusTooManyRequests, "limit reached: too many emails, please be nice", "https://ntfy.sh/docs/publish/#limitations"}
  109. errHTTPTooManyRequestsLimitSubscriptions = &errHTTP{42903, http.StatusTooManyRequests, "limit reached: too many active subscriptions, please be nice", "https://ntfy.sh/docs/publish/#limitations"}
  110. errHTTPTooManyRequestsLimitGlobalTopics = &errHTTP{42904, http.StatusTooManyRequests, "limit reached: the total number of topics on the server has been reached, please contact the admin", "https://ntfy.sh/docs/publish/#limitations"}
  111. errHTTPBadRequestEmailDisabled = &errHTTP{40001, http.StatusBadRequest, "e-mail notifications are not enabled", "https://ntfy.sh/docs/config/#e-mail-notifications"}
  112. errHTTPBadRequestDelayNoCache = &errHTTP{40002, http.StatusBadRequest, "cannot disable cache for delayed message", ""}
  113. errHTTPBadRequestDelayNoEmail = &errHTTP{40003, http.StatusBadRequest, "delayed e-mail notifications are not supported", ""}
  114. errHTTPBadRequestDelayCannotParse = &errHTTP{40004, http.StatusBadRequest, "invalid delay parameter: unable to parse delay", "https://ntfy.sh/docs/publish/#scheduled-delivery"}
  115. errHTTPBadRequestDelayTooSmall = &errHTTP{40005, http.StatusBadRequest, "invalid delay parameter: too small, please refer to the docs", "https://ntfy.sh/docs/publish/#scheduled-delivery"}
  116. errHTTPBadRequestDelayTooLarge = &errHTTP{40006, http.StatusBadRequest, "invalid delay parameter: too large, please refer to the docs", "https://ntfy.sh/docs/publish/#scheduled-delivery"}
  117. errHTTPBadRequestPriorityInvalid = &errHTTP{40007, http.StatusBadRequest, "invalid priority parameter", "https://ntfy.sh/docs/publish/#message-priority"}
  118. errHTTPBadRequestSinceInvalid = &errHTTP{40008, http.StatusBadRequest, "invalid since parameter", "https://ntfy.sh/docs/subscribe/api/#fetch-cached-messages"}
  119. errHTTPBadRequestTopicInvalid = &errHTTP{40009, http.StatusBadRequest, "invalid topic: path invalid", ""}
  120. errHTTPBadRequestTopicDisallowed = &errHTTP{40010, http.StatusBadRequest, "invalid topic: topic name is disallowed", ""}
  121. errHTTPBadRequestMessageNotUTF8 = &errHTTP{40011, http.StatusBadRequest, "invalid message: message must be UTF-8 encoded", ""}
  122. errHTTPBadRequestMessageTooLarge = &errHTTP{40012, http.StatusBadRequest, "invalid message: too large", ""}
  123. errHTTPBadRequestAttachmentURLInvalid = &errHTTP{40013, http.StatusBadRequest, "invalid request: attachment URL is invalid", ""}
  124. errHTTPBadRequestAttachmentURLPeakGeneral = &errHTTP{40014, http.StatusBadRequest, "invalid request: attachment URL peak failed", ""}
  125. errHTTPBadRequestAttachmentURLPeakNon2xx = &errHTTP{40015, http.StatusBadRequest, "invalid request: attachment URL peak failed with non-2xx status code", ""}
  126. errHTTPBadRequestAttachmentsDisallowed = &errHTTP{40016, http.StatusBadRequest, "invalid request: attachments not allowed", ""}
  127. errHTTPBadRequestAttachmentsExpiryBeforeDelivery = &errHTTP{40017, http.StatusBadRequest, "invalid request: attachment expiry before delayed delivery date", ""}
  128. errHTTPInternalError = &errHTTP{50001, http.StatusInternalServerError, "internal server error", ""}
  129. errHTTPInternalErrorInvalidFilePath = &errHTTP{50002, http.StatusInternalServerError, "internal server error: invalid file path", ""}
  130. )
  131. const (
  132. firebaseControlTopic = "~control" // See Android if changed
  133. emptyMessageBody = "triggered"
  134. fcmMessageLimit = 4000 // see maybeTruncateFCMMessage for details
  135. defaultAttachmentMessage = "You received a file: %s"
  136. )
  137. // New instantiates a new Server. It creates the cache and adds a Firebase
  138. // subscriber (if configured).
  139. func New(conf *Config) (*Server, error) {
  140. var firebaseSubscriber subscriber
  141. if conf.FirebaseKeyFile != "" {
  142. var err error
  143. firebaseSubscriber, err = createFirebaseSubscriber(conf)
  144. if err != nil {
  145. return nil, err
  146. }
  147. }
  148. var mailer mailer
  149. if conf.SMTPSenderAddr != "" {
  150. mailer = &smtpSender{config: conf}
  151. }
  152. cache, err := createCache(conf)
  153. if err != nil {
  154. return nil, err
  155. }
  156. topics, err := cache.Topics()
  157. if err != nil {
  158. return nil, err
  159. }
  160. var fileCache *fileCache
  161. if conf.AttachmentCacheDir != "" {
  162. fileCache, err = newFileCache(conf.AttachmentCacheDir, conf.AttachmentTotalSizeLimit, conf.AttachmentFileSizeLimit)
  163. if err != nil {
  164. return nil, err
  165. }
  166. }
  167. return &Server{
  168. config: conf,
  169. cache: cache,
  170. fileCache: fileCache,
  171. firebase: firebaseSubscriber,
  172. mailer: mailer,
  173. topics: topics,
  174. visitors: make(map[string]*visitor),
  175. }, nil
  176. }
  177. func createCache(conf *Config) (cache, error) {
  178. if conf.CacheDuration == 0 {
  179. return newNopCache(), nil
  180. } else if conf.CacheFile != "" {
  181. return newSqliteCache(conf.CacheFile)
  182. }
  183. return newMemCache(), nil
  184. }
  185. func createFirebaseSubscriber(conf *Config) (subscriber, error) {
  186. fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(conf.FirebaseKeyFile))
  187. if err != nil {
  188. return nil, err
  189. }
  190. msg, err := fb.Messaging(context.Background())
  191. if err != nil {
  192. return nil, err
  193. }
  194. return func(m *message) error {
  195. var data map[string]string // Matches https://ntfy.sh/docs/subscribe/api/#json-message-format
  196. switch m.Event {
  197. case keepaliveEvent, openEvent:
  198. data = map[string]string{
  199. "id": m.ID,
  200. "time": fmt.Sprintf("%d", m.Time),
  201. "event": m.Event,
  202. "topic": m.Topic,
  203. }
  204. case messageEvent:
  205. data = map[string]string{
  206. "id": m.ID,
  207. "time": fmt.Sprintf("%d", m.Time),
  208. "event": m.Event,
  209. "topic": m.Topic,
  210. "priority": fmt.Sprintf("%d", m.Priority),
  211. "tags": strings.Join(m.Tags, ","),
  212. "click": m.Click,
  213. "title": m.Title,
  214. "message": m.Message,
  215. }
  216. if m.Attachment != nil {
  217. data["attachment_name"] = m.Attachment.Name
  218. data["attachment_type"] = m.Attachment.Type
  219. data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
  220. data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
  221. data["attachment_url"] = m.Attachment.URL
  222. }
  223. }
  224. var androidConfig *messaging.AndroidConfig
  225. if m.Priority >= 4 {
  226. androidConfig = &messaging.AndroidConfig{
  227. Priority: "high",
  228. }
  229. }
  230. _, err := msg.Send(context.Background(), maybeTruncateFCMMessage(&messaging.Message{
  231. Topic: m.Topic,
  232. Data: data,
  233. Android: androidConfig,
  234. }))
  235. return err
  236. }, nil
  237. }
  238. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  239. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  240. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  241. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  242. s, err := json.Marshal(m)
  243. if err != nil {
  244. return m
  245. }
  246. if len(s) > fcmMessageLimit {
  247. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  248. message, ok := m.Data["message"]
  249. if ok && len(message) > over {
  250. m.Data["truncated"] = "1"
  251. m.Data["message"] = message[:len(message)-over]
  252. }
  253. }
  254. return m
  255. }
  256. // Run executes the main server. It listens on HTTP (+ HTTPS, if configured), and starts
  257. // a manager go routine to print stats and prune messages.
  258. func (s *Server) Run() error {
  259. listenStr := fmt.Sprintf("%s/http", s.config.ListenHTTP)
  260. if s.config.ListenHTTPS != "" {
  261. listenStr += fmt.Sprintf(" %s/https", s.config.ListenHTTPS)
  262. }
  263. if s.config.SMTPServerListen != "" {
  264. listenStr += fmt.Sprintf(" %s/smtp", s.config.SMTPServerListen)
  265. }
  266. log.Printf("Listening on %s", listenStr)
  267. mux := http.NewServeMux()
  268. mux.HandleFunc("/", s.handle)
  269. errChan := make(chan error)
  270. s.mu.Lock()
  271. s.closeChan = make(chan bool)
  272. s.httpServer = &http.Server{Addr: s.config.ListenHTTP, Handler: mux}
  273. go func() {
  274. errChan <- s.httpServer.ListenAndServe()
  275. }()
  276. if s.config.ListenHTTPS != "" {
  277. s.httpsServer = &http.Server{Addr: s.config.ListenHTTPS, Handler: mux}
  278. go func() {
  279. errChan <- s.httpsServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile)
  280. }()
  281. }
  282. if s.config.SMTPServerListen != "" {
  283. go func() {
  284. errChan <- s.runSMTPServer()
  285. }()
  286. }
  287. s.mu.Unlock()
  288. go s.runManager()
  289. go s.runAtSender()
  290. go s.runFirebaseKeepliver()
  291. return <-errChan
  292. }
  293. // Stop stops HTTP (+HTTPS) server and all managers
  294. func (s *Server) Stop() {
  295. s.mu.Lock()
  296. defer s.mu.Unlock()
  297. if s.httpServer != nil {
  298. s.httpServer.Close()
  299. }
  300. if s.httpsServer != nil {
  301. s.httpsServer.Close()
  302. }
  303. if s.smtpServer != nil {
  304. s.smtpServer.Close()
  305. }
  306. close(s.closeChan)
  307. }
  308. func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
  309. if err := s.handleInternal(w, r); err != nil {
  310. var e *errHTTP
  311. var ok bool
  312. if e, ok = err.(*errHTTP); !ok {
  313. e = errHTTPInternalError
  314. }
  315. log.Printf("[%s] %s - %d - %s", r.RemoteAddr, r.Method, e.HTTPCode, err.Error())
  316. w.Header().Set("Content-Type", "application/json")
  317. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  318. w.WriteHeader(e.HTTPCode)
  319. io.WriteString(w, e.JSON()+"\n")
  320. }
  321. }
  322. func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request) error {
  323. if r.Method == http.MethodGet && r.URL.Path == "/" {
  324. return s.handleHome(w, r)
  325. } else if r.Method == http.MethodGet && r.URL.Path == "/example.html" {
  326. return s.handleExample(w, r)
  327. } else if r.Method == http.MethodHead && r.URL.Path == "/" {
  328. return s.handleEmpty(w, r)
  329. } else if r.Method == http.MethodGet && staticRegex.MatchString(r.URL.Path) {
  330. return s.handleStatic(w, r)
  331. } else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) {
  332. return s.handleDocs(w, r)
  333. } else if r.Method == http.MethodGet && fileRegex.MatchString(r.URL.Path) && s.config.AttachmentCacheDir != "" {
  334. return s.withRateLimit(w, r, s.handleFile)
  335. } else if r.Method == http.MethodOptions {
  336. return s.handleOptions(w, r)
  337. } else if r.Method == http.MethodGet && topicPathRegex.MatchString(r.URL.Path) {
  338. return s.handleTopic(w, r)
  339. } else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicPathRegex.MatchString(r.URL.Path) {
  340. return s.withRateLimit(w, r, s.handlePublish)
  341. } else if r.Method == http.MethodGet && publishPathRegex.MatchString(r.URL.Path) {
  342. return s.withRateLimit(w, r, s.handlePublish)
  343. } else if r.Method == http.MethodGet && jsonPathRegex.MatchString(r.URL.Path) {
  344. return s.withRateLimit(w, r, s.handleSubscribeJSON)
  345. } else if r.Method == http.MethodGet && ssePathRegex.MatchString(r.URL.Path) {
  346. return s.withRateLimit(w, r, s.handleSubscribeSSE)
  347. } else if r.Method == http.MethodGet && rawPathRegex.MatchString(r.URL.Path) {
  348. return s.withRateLimit(w, r, s.handleSubscribeRaw)
  349. }
  350. return errHTTPNotFound
  351. }
  352. func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) error {
  353. return indexTemplate.Execute(w, &indexPage{
  354. Topic: r.URL.Path[1:],
  355. CacheDuration: s.config.CacheDuration,
  356. })
  357. }
  358. func (s *Server) handleTopic(w http.ResponseWriter, r *http.Request) error {
  359. unifiedpush := readParam(r, "x-unifiedpush", "unifiedpush", "up") == "1" // see PUT/POST too!
  360. if unifiedpush {
  361. w.Header().Set("Content-Type", "application/json")
  362. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  363. _, err := io.WriteString(w, `{"unifiedpush":{"version":1}}`+"\n")
  364. return err
  365. }
  366. return s.handleHome(w, r)
  367. }
  368. func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request) error {
  369. return nil
  370. }
  371. func (s *Server) handleExample(w http.ResponseWriter, _ *http.Request) error {
  372. _, err := io.WriteString(w, exampleSource)
  373. return err
  374. }
  375. func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request) error {
  376. http.FileServer(http.FS(webStaticFsCached)).ServeHTTP(w, r)
  377. return nil
  378. }
  379. func (s *Server) handleDocs(w http.ResponseWriter, r *http.Request) error {
  380. http.FileServer(http.FS(docsStaticCached)).ServeHTTP(w, r)
  381. return nil
  382. }
  383. func (s *Server) handleFile(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  384. if s.config.AttachmentCacheDir == "" {
  385. return errHTTPInternalError
  386. }
  387. matches := fileRegex.FindStringSubmatch(r.URL.Path)
  388. if len(matches) != 2 {
  389. return errHTTPInternalErrorInvalidFilePath
  390. }
  391. messageID := matches[1]
  392. file := filepath.Join(s.config.AttachmentCacheDir, messageID)
  393. stat, err := os.Stat(file)
  394. if err != nil {
  395. return errHTTPNotFound
  396. }
  397. w.Header().Set("Length", fmt.Sprintf("%d", stat.Size()))
  398. f, err := os.Open(file)
  399. if err != nil {
  400. return err
  401. }
  402. defer f.Close()
  403. _, err = io.Copy(util.NewContentTypeWriter(w, r.URL.Path), f)
  404. return err
  405. }
  406. func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, v *visitor) error {
  407. t, err := s.topicFromPath(r.URL.Path)
  408. if err != nil {
  409. return err
  410. }
  411. body, err := util.Peak(r.Body, s.config.MessageLimit)
  412. if err != nil {
  413. return err
  414. }
  415. m := newDefaultMessage(t.ID, "")
  416. cache, firebase, email, err := s.parsePublishParams(r, v, m)
  417. if err != nil {
  418. return err
  419. }
  420. if err := maybePeakAttachmentURL(m); err != nil {
  421. return err
  422. }
  423. if err := s.handlePublishBody(v, m, body); err != nil {
  424. return err
  425. }
  426. if m.Message == "" {
  427. m.Message = emptyMessageBody
  428. }
  429. delayed := m.Time > time.Now().Unix()
  430. if !delayed {
  431. if err := t.Publish(m); err != nil {
  432. return err
  433. }
  434. }
  435. if s.firebase != nil && firebase && !delayed {
  436. go func() {
  437. if err := s.firebase(m); err != nil {
  438. log.Printf("Unable to publish to Firebase: %v", err.Error())
  439. }
  440. }()
  441. }
  442. if s.mailer != nil && email != "" && !delayed {
  443. go func() {
  444. if err := s.mailer.Send(v.ip, email, m); err != nil {
  445. log.Printf("Unable to send email: %v", err.Error())
  446. }
  447. }()
  448. }
  449. if cache {
  450. if err := s.cache.AddMessage(m); err != nil {
  451. return err
  452. }
  453. }
  454. w.Header().Set("Content-Type", "application/json")
  455. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  456. if err := json.NewEncoder(w).Encode(m); err != nil {
  457. return err
  458. }
  459. s.inc(&s.messages)
  460. return nil
  461. }
  462. func (s *Server) parsePublishParams(r *http.Request, v *visitor, m *message) (cache bool, firebase bool, email string, err error) {
  463. cache = readParam(r, "x-cache", "cache") != "no"
  464. firebase = readParam(r, "x-firebase", "firebase") != "no"
  465. m.Title = readParam(r, "x-title", "title", "t")
  466. m.Click = readParam(r, "x-click", "click")
  467. attach := readParam(r, "x-attachment", "attachment", "attach", "a")
  468. filename := readParam(r, "x-filename", "filename", "file", "f")
  469. if attach != "" || filename != "" {
  470. m.Attachment = &attachment{}
  471. }
  472. if attach != "" {
  473. if !attachURLRegex.MatchString(attach) {
  474. return false, false, "", errHTTPBadRequestAttachmentURLInvalid
  475. }
  476. m.Attachment.URL = attach
  477. }
  478. if filename != "" {
  479. m.Attachment.Name = filename
  480. }
  481. email = readParam(r, "x-email", "x-e-mail", "email", "e-mail", "mail", "e")
  482. if email != "" {
  483. if err := v.EmailAllowed(); err != nil {
  484. return false, false, "", errHTTPTooManyRequestsLimitEmails
  485. }
  486. }
  487. if s.mailer == nil && email != "" {
  488. return false, false, "", errHTTPBadRequestEmailDisabled
  489. }
  490. messageStr := readParam(r, "x-message", "message", "m")
  491. if messageStr != "" {
  492. m.Message = messageStr
  493. }
  494. m.Priority, err = util.ParsePriority(readParam(r, "x-priority", "priority", "prio", "p"))
  495. if err != nil {
  496. return false, false, "", errHTTPBadRequestPriorityInvalid
  497. }
  498. tagsStr := readParam(r, "x-tags", "tags", "tag", "ta")
  499. if tagsStr != "" {
  500. m.Tags = make([]string, 0)
  501. for _, s := range util.SplitNoEmpty(tagsStr, ",") {
  502. m.Tags = append(m.Tags, strings.TrimSpace(s))
  503. }
  504. }
  505. delayStr := readParam(r, "x-delay", "delay", "x-at", "at", "x-in", "in")
  506. if delayStr != "" {
  507. if !cache {
  508. return false, false, "", errHTTPBadRequestDelayNoCache
  509. }
  510. if email != "" {
  511. return false, false, "", errHTTPBadRequestDelayNoEmail // we cannot store the email address (yet)
  512. }
  513. delay, err := util.ParseFutureTime(delayStr, time.Now())
  514. if err != nil {
  515. return false, false, "", errHTTPBadRequestDelayCannotParse
  516. } else if delay.Unix() < time.Now().Add(s.config.MinDelay).Unix() {
  517. return false, false, "", errHTTPBadRequestDelayTooSmall
  518. } else if delay.Unix() > time.Now().Add(s.config.MaxDelay).Unix() {
  519. return false, false, "", errHTTPBadRequestDelayTooLarge
  520. }
  521. m.Time = delay.Unix()
  522. }
  523. unifiedpush := readParam(r, "x-unifiedpush", "unifiedpush", "up") == "1" // see GET too!
  524. if unifiedpush {
  525. firebase = false
  526. }
  527. return cache, firebase, email, nil
  528. }
  529. func readParam(r *http.Request, names ...string) string {
  530. for _, name := range names {
  531. value := r.Header.Get(name)
  532. if value != "" {
  533. return strings.TrimSpace(value)
  534. }
  535. }
  536. for _, name := range names {
  537. value := r.URL.Query().Get(strings.ToLower(name))
  538. if value != "" {
  539. return strings.TrimSpace(value)
  540. }
  541. }
  542. return ""
  543. }
  544. // handlePublishBody consumes the PUT/POST body and decides whether the body is an attachment or the message.
  545. //
  546. // 1. curl -H "Attach: http://example.com/file.jpg" ntfy.sh/mytopic
  547. // Body must be a message, because we attached an external URL
  548. // 2. curl -T short.txt -H "Filename: short.txt" ntfy.sh/mytopic
  549. // Body must be attachment, because we passed a filename
  550. // 3. curl -T file.txt ntfy.sh/mytopic
  551. // If file.txt is <= 4096 (message limit) and valid UTF-8, treat it as a message
  552. // 4. curl -T file.txt ntfy.sh/mytopic
  553. // If file.txt is > message limit, treat it as an attachment
  554. func (s *Server) handlePublishBody(v *visitor, m *message, body *util.PeakedReadCloser) error {
  555. if m.Attachment != nil && m.Attachment.URL != "" {
  556. return s.handleBodyAsMessage(m, body) // Case 1
  557. } else if m.Attachment != nil && m.Attachment.Name != "" {
  558. return s.handleBodyAsAttachment(v, m, body) // Case 2
  559. } else if !body.LimitReached && utf8.Valid(body.PeakedBytes) {
  560. return s.handleBodyAsMessage(m, body) // Case 3
  561. }
  562. return s.handleBodyAsAttachment(v, m, body) // Case 4
  563. }
  564. func (s *Server) handleBodyAsMessage(m *message, body *util.PeakedReadCloser) error {
  565. if !utf8.Valid(body.PeakedBytes) {
  566. return errHTTPBadRequestMessageNotUTF8
  567. }
  568. if len(body.PeakedBytes) > 0 { // Empty body should not override message (publish via GET!)
  569. m.Message = strings.TrimSpace(string(body.PeakedBytes)) // Truncates the message to the peak limit if required
  570. }
  571. if m.Attachment != nil && m.Attachment.Name != "" && m.Message == "" {
  572. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  573. }
  574. return nil
  575. }
  576. func (s *Server) handleBodyAsAttachment(v *visitor, m *message, body *util.PeakedReadCloser) error {
  577. if s.fileCache == nil {
  578. return errHTTPBadRequestAttachmentsDisallowed
  579. } else if m.Time > time.Now().Add(s.config.AttachmentExpiryDuration).Unix() {
  580. return errHTTPBadRequestAttachmentsExpiryBeforeDelivery
  581. }
  582. if m.Attachment == nil {
  583. m.Attachment = &attachment{}
  584. }
  585. var err error
  586. var ext string
  587. m.Attachment.Owner = v.ip // Important for attachment rate limiting
  588. m.Attachment.Expires = time.Now().Add(s.config.AttachmentExpiryDuration).Unix()
  589. m.Attachment.Type, ext = util.DetectContentType(body.PeakedBytes, m.Attachment.Name)
  590. m.Attachment.URL = fmt.Sprintf("%s/file/%s%s", s.config.BaseURL, m.ID, ext)
  591. if m.Attachment.Name == "" {
  592. m.Attachment.Name = fmt.Sprintf("attachment%s", ext)
  593. }
  594. if m.Message == "" {
  595. m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name)
  596. }
  597. // TODO do not allowed delayed delivery for attachments
  598. visitorAttachmentsSize, err := s.cache.AttachmentsSize(v.ip)
  599. if err != nil {
  600. return err
  601. }
  602. remainingVisitorAttachmentSize := s.config.VisitorAttachmentTotalSizeLimit - visitorAttachmentsSize
  603. m.Attachment.Size, err = s.fileCache.Write(m.ID, body, util.NewLimiter(remainingVisitorAttachmentSize))
  604. if err == util.ErrLimitReached {
  605. return errHTTPBadRequestMessageTooLarge
  606. } else if err != nil {
  607. return err
  608. }
  609. return nil
  610. }
  611. func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error {
  612. encoder := func(msg *message) (string, error) {
  613. var buf bytes.Buffer
  614. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  615. return "", err
  616. }
  617. return buf.String(), nil
  618. }
  619. return s.handleSubscribe(w, r, v, "json", "application/x-ndjson", encoder)
  620. }
  621. func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error {
  622. encoder := func(msg *message) (string, error) {
  623. var buf bytes.Buffer
  624. if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
  625. return "", err
  626. }
  627. if msg.Event != messageEvent {
  628. return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this!
  629. }
  630. return fmt.Sprintf("data: %s\n", buf.String()), nil
  631. }
  632. return s.handleSubscribe(w, r, v, "sse", "text/event-stream", encoder)
  633. }
  634. func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error {
  635. encoder := func(msg *message) (string, error) {
  636. if msg.Event == messageEvent { // only handle default events
  637. return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil
  638. }
  639. return "\n", nil // "keepalive" and "open" events just send an empty line
  640. }
  641. return s.handleSubscribe(w, r, v, "raw", "text/plain", encoder)
  642. }
  643. func (s *Server) handleSubscribe(w http.ResponseWriter, r *http.Request, v *visitor, format string, contentType string, encoder messageEncoder) error {
  644. if err := v.SubscriptionAllowed(); err != nil {
  645. return errHTTPTooManyRequestsLimitSubscriptions
  646. }
  647. defer v.RemoveSubscription()
  648. topicsStr := strings.TrimSuffix(r.URL.Path[1:], "/"+format) // Hack
  649. topicIDs := util.SplitNoEmpty(topicsStr, ",")
  650. topics, err := s.topicsFromIDs(topicIDs...)
  651. if err != nil {
  652. return err
  653. }
  654. poll := readParam(r, "x-poll", "poll", "po") == "1"
  655. scheduled := readParam(r, "x-scheduled", "scheduled", "sched") == "1"
  656. since, err := parseSince(r, poll)
  657. if err != nil {
  658. return err
  659. }
  660. messageFilter, titleFilter, priorityFilter, tagsFilter, err := parseQueryFilters(r)
  661. if err != nil {
  662. return err
  663. }
  664. var wlock sync.Mutex
  665. sub := func(msg *message) error {
  666. if !passesQueryFilter(msg, messageFilter, titleFilter, priorityFilter, tagsFilter) {
  667. return nil
  668. }
  669. m, err := encoder(msg)
  670. if err != nil {
  671. return err
  672. }
  673. wlock.Lock()
  674. defer wlock.Unlock()
  675. if _, err := w.Write([]byte(m)); err != nil {
  676. return err
  677. }
  678. if fl, ok := w.(http.Flusher); ok {
  679. fl.Flush()
  680. }
  681. return nil
  682. }
  683. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  684. w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset!
  685. if poll {
  686. return s.sendOldMessages(topics, since, scheduled, sub)
  687. }
  688. subscriberIDs := make([]int, 0)
  689. for _, t := range topics {
  690. subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
  691. }
  692. defer func() {
  693. for i, subscriberID := range subscriberIDs {
  694. topics[i].Unsubscribe(subscriberID) // Order!
  695. }
  696. }()
  697. if err := sub(newOpenMessage(topicsStr)); err != nil { // Send out open message
  698. return err
  699. }
  700. if err := s.sendOldMessages(topics, since, scheduled, sub); err != nil {
  701. return err
  702. }
  703. for {
  704. select {
  705. case <-r.Context().Done():
  706. return nil
  707. case <-time.After(s.config.KeepaliveInterval):
  708. v.Keepalive()
  709. if err := sub(newKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message
  710. return err
  711. }
  712. }
  713. }
  714. }
  715. func parseQueryFilters(r *http.Request) (messageFilter string, titleFilter string, priorityFilter []int, tagsFilter []string, err error) {
  716. messageFilter = readParam(r, "x-message", "message", "m")
  717. titleFilter = readParam(r, "x-title", "title", "t")
  718. tagsFilter = util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  719. priorityFilter = make([]int, 0)
  720. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  721. priority, err := util.ParsePriority(p)
  722. if err != nil {
  723. return "", "", nil, nil, err
  724. }
  725. priorityFilter = append(priorityFilter, priority)
  726. }
  727. return
  728. }
  729. func passesQueryFilter(msg *message, messageFilter string, titleFilter string, priorityFilter []int, tagsFilter []string) bool {
  730. if msg.Event != messageEvent {
  731. return true // filters only apply to messages
  732. }
  733. if messageFilter != "" && msg.Message != messageFilter {
  734. return false
  735. }
  736. if titleFilter != "" && msg.Title != titleFilter {
  737. return false
  738. }
  739. messagePriority := msg.Priority
  740. if messagePriority == 0 {
  741. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  742. }
  743. if len(priorityFilter) > 0 && !util.InIntList(priorityFilter, messagePriority) {
  744. return false
  745. }
  746. if len(tagsFilter) > 0 && !util.InStringListAll(msg.Tags, tagsFilter) {
  747. return false
  748. }
  749. return true
  750. }
  751. func (s *Server) sendOldMessages(topics []*topic, since sinceTime, scheduled bool, sub subscriber) error {
  752. if since.IsNone() {
  753. return nil
  754. }
  755. for _, t := range topics {
  756. messages, err := s.cache.Messages(t.ID, since, scheduled)
  757. if err != nil {
  758. return err
  759. }
  760. for _, m := range messages {
  761. if err := sub(m); err != nil {
  762. return err
  763. }
  764. }
  765. }
  766. return nil
  767. }
  768. // parseSince returns a timestamp identifying the time span from which cached messages should be received.
  769. //
  770. // Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), or
  771. // "all" for all messages.
  772. func parseSince(r *http.Request, poll bool) (sinceTime, error) {
  773. since := readParam(r, "x-since", "since", "si")
  774. if since == "" {
  775. if poll {
  776. return sinceAllMessages, nil
  777. }
  778. return sinceNoMessages, nil
  779. }
  780. if since == "all" {
  781. return sinceAllMessages, nil
  782. } else if s, err := strconv.ParseInt(since, 10, 64); err == nil {
  783. return sinceTime(time.Unix(s, 0)), nil
  784. } else if d, err := time.ParseDuration(since); err == nil {
  785. return sinceTime(time.Now().Add(-1 * d)), nil
  786. }
  787. return sinceNoMessages, errHTTPBadRequestSinceInvalid
  788. }
  789. func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request) error {
  790. w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
  791. w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST")
  792. return nil
  793. }
  794. func (s *Server) topicFromPath(path string) (*topic, error) {
  795. parts := strings.Split(path, "/")
  796. if len(parts) < 2 {
  797. return nil, errHTTPBadRequestTopicInvalid
  798. }
  799. topics, err := s.topicsFromIDs(parts[1])
  800. if err != nil {
  801. return nil, err
  802. }
  803. return topics[0], nil
  804. }
  805. func (s *Server) topicsFromIDs(ids ...string) ([]*topic, error) {
  806. s.mu.Lock()
  807. defer s.mu.Unlock()
  808. topics := make([]*topic, 0)
  809. for _, id := range ids {
  810. if util.InStringList(disallowedTopics, id) {
  811. return nil, errHTTPBadRequestTopicDisallowed
  812. }
  813. if _, ok := s.topics[id]; !ok {
  814. if len(s.topics) >= s.config.TotalTopicLimit {
  815. return nil, errHTTPTooManyRequestsLimitGlobalTopics
  816. }
  817. s.topics[id] = newTopic(id)
  818. }
  819. topics = append(topics, s.topics[id])
  820. }
  821. return topics, nil
  822. }
  823. func (s *Server) updateStatsAndPrune() {
  824. s.mu.Lock()
  825. defer s.mu.Unlock()
  826. // Expire visitors from rate visitors map
  827. for ip, v := range s.visitors {
  828. if v.Stale() {
  829. delete(s.visitors, ip)
  830. }
  831. }
  832. // Delete expired attachments
  833. if s.fileCache != nil {
  834. ids, err := s.cache.AttachmentsExpired()
  835. if err == nil {
  836. if err := s.fileCache.Remove(ids...); err != nil {
  837. log.Printf("error while deleting attachments: %s", err.Error())
  838. }
  839. } else {
  840. log.Printf("error retrieving expired attachments: %s", err.Error())
  841. }
  842. }
  843. // Prune message cache
  844. olderThan := time.Now().Add(-1 * s.config.CacheDuration)
  845. if err := s.cache.Prune(olderThan); err != nil {
  846. log.Printf("error pruning cache: %s", err.Error())
  847. }
  848. // Prune old topics, remove subscriptions without subscribers
  849. var subscribers, messages int
  850. for _, t := range s.topics {
  851. subs := t.Subscribers()
  852. msgs, err := s.cache.MessageCount(t.ID)
  853. if err != nil {
  854. log.Printf("cannot get stats for topic %s: %s", t.ID, err.Error())
  855. continue
  856. }
  857. if msgs == 0 && subs == 0 {
  858. delete(s.topics, t.ID)
  859. continue
  860. }
  861. subscribers += subs
  862. messages += msgs
  863. }
  864. // Mail stats
  865. var mailSuccess, mailFailure int64
  866. if s.smtpBackend != nil {
  867. mailSuccess, mailFailure = s.smtpBackend.Counts()
  868. }
  869. // Print stats
  870. log.Printf("Stats: %d message(s) published, %d in cache, %d successful mails, %d failed, %d topic(s) active, %d subscriber(s), %d visitor(s)",
  871. s.messages, messages, mailSuccess, mailFailure, len(s.topics), subscribers, len(s.visitors))
  872. }
  873. func (s *Server) runSMTPServer() error {
  874. sub := func(m *message) error {
  875. url := fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic)
  876. req, err := http.NewRequest("PUT", url, strings.NewReader(m.Message))
  877. if err != nil {
  878. return err
  879. }
  880. if m.Title != "" {
  881. req.Header.Set("Title", m.Title)
  882. }
  883. rr := httptest.NewRecorder()
  884. s.handle(rr, req)
  885. if rr.Code != http.StatusOK {
  886. return errors.New("error: " + rr.Body.String())
  887. }
  888. return nil
  889. }
  890. s.smtpBackend = newMailBackend(s.config, sub)
  891. s.smtpServer = smtp.NewServer(s.smtpBackend)
  892. s.smtpServer.Addr = s.config.SMTPServerListen
  893. s.smtpServer.Domain = s.config.SMTPServerDomain
  894. s.smtpServer.ReadTimeout = 10 * time.Second
  895. s.smtpServer.WriteTimeout = 10 * time.Second
  896. s.smtpServer.MaxMessageBytes = 1024 * 1024 // Must be much larger than message size (headers, multipart, etc.)
  897. s.smtpServer.MaxRecipients = 1
  898. s.smtpServer.AllowInsecureAuth = true
  899. return s.smtpServer.ListenAndServe()
  900. }
  901. func (s *Server) runManager() {
  902. for {
  903. select {
  904. case <-time.After(s.config.ManagerInterval):
  905. s.updateStatsAndPrune()
  906. case <-s.closeChan:
  907. return
  908. }
  909. }
  910. }
  911. func (s *Server) runAtSender() {
  912. for {
  913. select {
  914. case <-time.After(s.config.AtSenderInterval):
  915. if err := s.sendDelayedMessages(); err != nil {
  916. log.Printf("error sending scheduled messages: %s", err.Error())
  917. }
  918. case <-s.closeChan:
  919. return
  920. }
  921. }
  922. }
  923. func (s *Server) runFirebaseKeepliver() {
  924. if s.firebase == nil {
  925. return
  926. }
  927. for {
  928. select {
  929. case <-time.After(s.config.FirebaseKeepaliveInterval):
  930. if err := s.firebase(newKeepaliveMessage(firebaseControlTopic)); err != nil {
  931. log.Printf("error sending Firebase keepalive message: %s", err.Error())
  932. }
  933. case <-s.closeChan:
  934. return
  935. }
  936. }
  937. }
  938. func (s *Server) sendDelayedMessages() error {
  939. s.mu.Lock()
  940. defer s.mu.Unlock()
  941. messages, err := s.cache.MessagesDue()
  942. if err != nil {
  943. return err
  944. }
  945. for _, m := range messages {
  946. t, ok := s.topics[m.Topic] // If no subscribers, just mark message as published
  947. if ok {
  948. if err := t.Publish(m); err != nil {
  949. log.Printf("unable to publish message %s to topic %s: %v", m.ID, m.Topic, err.Error())
  950. }
  951. if s.firebase != nil {
  952. if err := s.firebase(m); err != nil {
  953. log.Printf("unable to publish to Firebase: %v", err.Error())
  954. }
  955. }
  956. }
  957. if err := s.cache.MarkPublished(m); err != nil {
  958. return err
  959. }
  960. }
  961. return nil
  962. }
  963. func (s *Server) withRateLimit(w http.ResponseWriter, r *http.Request, handler func(w http.ResponseWriter, r *http.Request, v *visitor) error) error {
  964. v := s.visitor(r)
  965. if err := v.RequestAllowed(); err != nil {
  966. return errHTTPTooManyRequestsLimitRequests
  967. }
  968. return handler(w, r, v)
  969. }
  970. // visitor creates or retrieves a rate.Limiter for the given visitor.
  971. // This function was taken from https://www.alexedwards.net/blog/how-to-rate-limit-http-requests (MIT).
  972. func (s *Server) visitor(r *http.Request) *visitor {
  973. s.mu.Lock()
  974. defer s.mu.Unlock()
  975. remoteAddr := r.RemoteAddr
  976. ip, _, err := net.SplitHostPort(remoteAddr)
  977. if err != nil {
  978. ip = remoteAddr // This should not happen in real life; only in tests.
  979. }
  980. if s.config.BehindProxy && r.Header.Get("X-Forwarded-For") != "" {
  981. ip = r.Header.Get("X-Forwarded-For")
  982. }
  983. v, exists := s.visitors[ip]
  984. if !exists {
  985. s.visitors[ip] = newVisitor(s.config, ip)
  986. return s.visitors[ip]
  987. }
  988. v.Keepalive()
  989. return v
  990. }
  991. func (s *Server) inc(counter *int64) {
  992. s.mu.Lock()
  993. defer s.mu.Unlock()
  994. *counter++
  995. }