server.go 35 KB

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