serve.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. package cmd
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/urfave/cli/v2"
  6. "github.com/urfave/cli/v2/altsrc"
  7. "heckel.io/ntfy/server"
  8. "heckel.io/ntfy/util"
  9. "log"
  10. "math"
  11. "net"
  12. "strings"
  13. "time"
  14. )
  15. var flagsServe = []cli.Flag{
  16. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: "/etc/ntfy/server.yml", DefaultText: "/etc/ntfy/server.yml", Usage: "config file"},
  17. altsrc.NewStringFlag(&cli.StringFlag{Name: "base-url", Aliases: []string{"B"}, EnvVars: []string{"NTFY_BASE_URL"}, Usage: "externally visible base URL for this host (e.g. https://ntfy.sh)"}),
  18. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-http", Aliases: []string{"l"}, EnvVars: []string{"NTFY_LISTEN_HTTP"}, Value: server.DefaultListenHTTP, Usage: "ip:port used to as HTTP listen address"}),
  19. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-https", Aliases: []string{"L"}, EnvVars: []string{"NTFY_LISTEN_HTTPS"}, Usage: "ip:port used to as HTTPS listen address"}),
  20. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-unix", Aliases: []string{"U"}, EnvVars: []string{"NTFY_LISTEN_UNIX"}, Usage: "listen on unix socket path"}),
  21. altsrc.NewStringFlag(&cli.StringFlag{Name: "key-file", Aliases: []string{"K"}, EnvVars: []string{"NTFY_KEY_FILE"}, Usage: "private key file, if listen-https is set"}),
  22. altsrc.NewStringFlag(&cli.StringFlag{Name: "cert-file", Aliases: []string{"E"}, EnvVars: []string{"NTFY_CERT_FILE"}, Usage: "certificate file, if listen-https is set"}),
  23. altsrc.NewStringFlag(&cli.StringFlag{Name: "firebase-key-file", Aliases: []string{"F"}, EnvVars: []string{"NTFY_FIREBASE_KEY_FILE"}, Usage: "Firebase credentials file; if set additionally publish to FCM topic"}),
  24. altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-file", Aliases: []string{"C"}, EnvVars: []string{"NTFY_CACHE_FILE"}, Usage: "cache file used for message caching"}),
  25. altsrc.NewDurationFlag(&cli.DurationFlag{Name: "cache-duration", Aliases: []string{"b"}, EnvVars: []string{"NTFY_CACHE_DURATION"}, Value: server.DefaultCacheDuration, Usage: "buffer messages for this time to allow `since` requests"}),
  26. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-file", Aliases: []string{"H"}, EnvVars: []string{"NTFY_AUTH_FILE"}, Usage: "auth database file used for access control"}),
  27. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-default-access", Aliases: []string{"p"}, EnvVars: []string{"NTFY_AUTH_DEFAULT_ACCESS"}, Value: "read-write", Usage: "default permissions if no matching entries in the auth database are found"}),
  28. altsrc.NewStringFlag(&cli.StringFlag{Name: "attachment-cache-dir", EnvVars: []string{"NTFY_ATTACHMENT_CACHE_DIR"}, Usage: "cache directory for attached files"}),
  29. altsrc.NewStringFlag(&cli.StringFlag{Name: "attachment-total-size-limit", Aliases: []string{"A"}, EnvVars: []string{"NTFY_ATTACHMENT_TOTAL_SIZE_LIMIT"}, DefaultText: "5G", Usage: "limit of the on-disk attachment cache"}),
  30. altsrc.NewStringFlag(&cli.StringFlag{Name: "attachment-file-size-limit", Aliases: []string{"Y"}, EnvVars: []string{"NTFY_ATTACHMENT_FILE_SIZE_LIMIT"}, DefaultText: "15M", Usage: "per-file attachment size limit (e.g. 300k, 2M, 100M)"}),
  31. altsrc.NewDurationFlag(&cli.DurationFlag{Name: "attachment-expiry-duration", Aliases: []string{"X"}, EnvVars: []string{"NTFY_ATTACHMENT_EXPIRY_DURATION"}, Value: server.DefaultAttachmentExpiryDuration, DefaultText: "3h", Usage: "duration after which uploaded attachments will be deleted (e.g. 3h, 20h)"}),
  32. altsrc.NewDurationFlag(&cli.DurationFlag{Name: "keepalive-interval", Aliases: []string{"k"}, EnvVars: []string{"NTFY_KEEPALIVE_INTERVAL"}, Value: server.DefaultKeepaliveInterval, Usage: "interval of keepalive messages"}),
  33. altsrc.NewDurationFlag(&cli.DurationFlag{Name: "manager-interval", Aliases: []string{"m"}, EnvVars: []string{"NTFY_MANAGER_INTERVAL"}, Value: server.DefaultManagerInterval, Usage: "interval of for message pruning and stats printing"}),
  34. altsrc.NewStringFlag(&cli.StringFlag{Name: "web-root", EnvVars: []string{"NTFY_WEB_ROOT"}, Value: "app", Usage: "sets web root to landing page (home) or web app (app)"}),
  35. altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-addr", EnvVars: []string{"NTFY_SMTP_SENDER_ADDR"}, Usage: "SMTP server address (host:port) for outgoing emails"}),
  36. altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-user", EnvVars: []string{"NTFY_SMTP_SENDER_USER"}, Usage: "SMTP user (if e-mail sending is enabled)"}),
  37. altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-pass", EnvVars: []string{"NTFY_SMTP_SENDER_PASS"}, Usage: "SMTP password (if e-mail sending is enabled)"}),
  38. altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-from", EnvVars: []string{"NTFY_SMTP_SENDER_FROM"}, Usage: "SMTP sender address (if e-mail sending is enabled)"}),
  39. altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-server-listen", EnvVars: []string{"NTFY_SMTP_SERVER_LISTEN"}, Usage: "SMTP server address (ip:port) for incoming emails, e.g. :25"}),
  40. altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-server-domain", EnvVars: []string{"NTFY_SMTP_SERVER_DOMAIN"}, Usage: "SMTP domain for incoming e-mail, e.g. ntfy.sh"}),
  41. altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-server-addr-prefix", EnvVars: []string{"NTFY_SMTP_SERVER_ADDR_PREFIX"}, Usage: "SMTP email address prefix for topics to prevent spam (e.g. 'ntfy-')"}),
  42. altsrc.NewIntFlag(&cli.IntFlag{Name: "global-topic-limit", Aliases: []string{"T"}, EnvVars: []string{"NTFY_GLOBAL_TOPIC_LIMIT"}, Value: server.DefaultTotalTopicLimit, Usage: "total number of topics allowed"}),
  43. altsrc.NewIntFlag(&cli.IntFlag{Name: "visitor-subscription-limit", EnvVars: []string{"NTFY_VISITOR_SUBSCRIPTION_LIMIT"}, Value: server.DefaultVisitorSubscriptionLimit, Usage: "number of subscriptions per visitor"}),
  44. altsrc.NewStringFlag(&cli.StringFlag{Name: "visitor-attachment-total-size-limit", EnvVars: []string{"NTFY_VISITOR_ATTACHMENT_TOTAL_SIZE_LIMIT"}, Value: "100M", Usage: "total storage limit used for attachments per visitor"}),
  45. altsrc.NewStringFlag(&cli.StringFlag{Name: "visitor-attachment-daily-bandwidth-limit", EnvVars: []string{"NTFY_VISITOR_ATTACHMENT_DAILY_BANDWIDTH_LIMIT"}, Value: "500M", Usage: "total daily attachment download/upload bandwidth limit per visitor"}),
  46. altsrc.NewIntFlag(&cli.IntFlag{Name: "visitor-request-limit-burst", EnvVars: []string{"NTFY_VISITOR_REQUEST_LIMIT_BURST"}, Value: server.DefaultVisitorRequestLimitBurst, Usage: "initial limit of requests per visitor"}),
  47. altsrc.NewDurationFlag(&cli.DurationFlag{Name: "visitor-request-limit-replenish", EnvVars: []string{"NTFY_VISITOR_REQUEST_LIMIT_REPLENISH"}, Value: server.DefaultVisitorRequestLimitReplenish, Usage: "interval at which burst limit is replenished (one per x)"}),
  48. altsrc.NewStringFlag(&cli.StringFlag{Name: "visitor-request-limit-exempt-hosts", EnvVars: []string{"NTFY_VISITOR_REQUEST_LIMIT_EXEMPT_HOSTS"}, Value: "", Usage: "hostnames and/or IP addresses of hosts that will be exempt from the visitor request limit"}),
  49. altsrc.NewIntFlag(&cli.IntFlag{Name: "visitor-email-limit-burst", EnvVars: []string{"NTFY_VISITOR_EMAIL_LIMIT_BURST"}, Value: server.DefaultVisitorEmailLimitBurst, Usage: "initial limit of e-mails per visitor"}),
  50. altsrc.NewDurationFlag(&cli.DurationFlag{Name: "visitor-email-limit-replenish", EnvVars: []string{"NTFY_VISITOR_EMAIL_LIMIT_REPLENISH"}, Value: server.DefaultVisitorEmailLimitReplenish, Usage: "interval at which burst limit is replenished (one per x)"}),
  51. altsrc.NewBoolFlag(&cli.BoolFlag{Name: "behind-proxy", Aliases: []string{"P"}, EnvVars: []string{"NTFY_BEHIND_PROXY"}, Value: false, Usage: "if set, use X-Forwarded-For header to determine visitor IP address (for rate limiting)"}),
  52. }
  53. var cmdServe = &cli.Command{
  54. Name: "serve",
  55. Usage: "Run the ntfy server",
  56. UsageText: "ntfy serve [OPTIONS..]",
  57. Action: execServe,
  58. Category: categoryServer,
  59. Flags: flagsServe,
  60. Before: initConfigFileInputSource("config", flagsServe),
  61. Description: `Run the ntfy server and listen for incoming requests
  62. The command will load the configuration from /etc/ntfy/server.yml. Config options can
  63. be overridden using the command line options.
  64. Examples:
  65. ntfy serve # Starts server in the foreground (on port 80)
  66. ntfy serve --listen-http :8080 # Starts server with alternate port`,
  67. }
  68. func execServe(c *cli.Context) error {
  69. if c.NArg() > 0 {
  70. return errors.New("no arguments expected, see 'ntfy serve --help' for help")
  71. }
  72. // Read all the options
  73. baseURL := c.String("base-url")
  74. listenHTTP := c.String("listen-http")
  75. listenHTTPS := c.String("listen-https")
  76. listenUnix := c.String("listen-unix")
  77. keyFile := c.String("key-file")
  78. certFile := c.String("cert-file")
  79. firebaseKeyFile := c.String("firebase-key-file")
  80. cacheFile := c.String("cache-file")
  81. cacheDuration := c.Duration("cache-duration")
  82. authFile := c.String("auth-file")
  83. authDefaultAccess := c.String("auth-default-access")
  84. attachmentCacheDir := c.String("attachment-cache-dir")
  85. attachmentTotalSizeLimitStr := c.String("attachment-total-size-limit")
  86. attachmentFileSizeLimitStr := c.String("attachment-file-size-limit")
  87. attachmentExpiryDuration := c.Duration("attachment-expiry-duration")
  88. keepaliveInterval := c.Duration("keepalive-interval")
  89. managerInterval := c.Duration("manager-interval")
  90. webRoot := c.String("web-root")
  91. smtpSenderAddr := c.String("smtp-sender-addr")
  92. smtpSenderUser := c.String("smtp-sender-user")
  93. smtpSenderPass := c.String("smtp-sender-pass")
  94. smtpSenderFrom := c.String("smtp-sender-from")
  95. smtpServerListen := c.String("smtp-server-listen")
  96. smtpServerDomain := c.String("smtp-server-domain")
  97. smtpServerAddrPrefix := c.String("smtp-server-addr-prefix")
  98. totalTopicLimit := c.Int("global-topic-limit")
  99. visitorSubscriptionLimit := c.Int("visitor-subscription-limit")
  100. visitorAttachmentTotalSizeLimitStr := c.String("visitor-attachment-total-size-limit")
  101. visitorAttachmentDailyBandwidthLimitStr := c.String("visitor-attachment-daily-bandwidth-limit")
  102. visitorRequestLimitBurst := c.Int("visitor-request-limit-burst")
  103. visitorRequestLimitReplenish := c.Duration("visitor-request-limit-replenish")
  104. visitorRequestLimitExemptHosts := util.SplitNoEmpty(c.String("visitor-request-limit-exempt-hosts"), ",")
  105. visitorEmailLimitBurst := c.Int("visitor-email-limit-burst")
  106. visitorEmailLimitReplenish := c.Duration("visitor-email-limit-replenish")
  107. behindProxy := c.Bool("behind-proxy")
  108. // Check values
  109. if firebaseKeyFile != "" && !util.FileExists(firebaseKeyFile) {
  110. return errors.New("if set, FCM key file must exist")
  111. } else if keepaliveInterval < 5*time.Second {
  112. return errors.New("keepalive interval cannot be lower than five seconds")
  113. } else if managerInterval < 5*time.Second {
  114. return errors.New("manager interval cannot be lower than five seconds")
  115. } else if cacheDuration > 0 && cacheDuration < managerInterval {
  116. return errors.New("cache duration cannot be lower than manager interval")
  117. } else if keyFile != "" && !util.FileExists(keyFile) {
  118. return errors.New("if set, key file must exist")
  119. } else if certFile != "" && !util.FileExists(certFile) {
  120. return errors.New("if set, certificate file must exist")
  121. } else if listenHTTPS != "" && (keyFile == "" || certFile == "") {
  122. return errors.New("if listen-https is set, both key-file and cert-file must be set")
  123. } else if smtpSenderAddr != "" && (baseURL == "" || smtpSenderUser == "" || smtpSenderPass == "" || smtpSenderFrom == "") {
  124. return errors.New("if smtp-sender-addr is set, base-url, smtp-sender-user, smtp-sender-pass and smtp-sender-from must also be set")
  125. } else if smtpServerListen != "" && smtpServerDomain == "" {
  126. return errors.New("if smtp-server-listen is set, smtp-server-domain must also be set")
  127. } else if attachmentCacheDir != "" && baseURL == "" {
  128. return errors.New("if attachment-cache-dir is set, base-url must also be set")
  129. } else if baseURL != "" && !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") {
  130. return errors.New("if set, base-url must start with http:// or https://")
  131. } else if !util.InStringList([]string{"read-write", "read-only", "write-only", "deny-all"}, authDefaultAccess) {
  132. return errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  133. } else if !util.InStringList([]string{"app", "home"}, webRoot) {
  134. return errors.New("if set, web-root must be 'home' or 'app'")
  135. }
  136. // Default auth permissions
  137. webRootIsApp := webRoot == "app"
  138. authDefaultRead := authDefaultAccess == "read-write" || authDefaultAccess == "read-only"
  139. authDefaultWrite := authDefaultAccess == "read-write" || authDefaultAccess == "write-only"
  140. // Special case: Unset default
  141. if listenHTTP == "-" {
  142. listenHTTP = ""
  143. }
  144. // Convert sizes to bytes
  145. attachmentTotalSizeLimit, err := parseSize(attachmentTotalSizeLimitStr, server.DefaultAttachmentTotalSizeLimit)
  146. if err != nil {
  147. return err
  148. }
  149. attachmentFileSizeLimit, err := parseSize(attachmentFileSizeLimitStr, server.DefaultAttachmentFileSizeLimit)
  150. if err != nil {
  151. return err
  152. }
  153. visitorAttachmentTotalSizeLimit, err := parseSize(visitorAttachmentTotalSizeLimitStr, server.DefaultVisitorAttachmentTotalSizeLimit)
  154. if err != nil {
  155. return err
  156. }
  157. visitorAttachmentDailyBandwidthLimit, err := parseSize(visitorAttachmentDailyBandwidthLimitStr, server.DefaultVisitorAttachmentDailyBandwidthLimit)
  158. if err != nil {
  159. return err
  160. } else if visitorAttachmentDailyBandwidthLimit > math.MaxInt {
  161. return fmt.Errorf("config option visitor-attachment-daily-bandwidth-limit must be lower than %d", math.MaxInt)
  162. }
  163. // Resolve hosts
  164. visitorRequestLimitExemptIPs := make([]string, 0)
  165. for _, host := range visitorRequestLimitExemptHosts {
  166. ips, err := net.LookupIP(host)
  167. if err != nil {
  168. log.Printf("cannot resolve host %s: %s, ignoring visitor request exemption", host, err.Error())
  169. continue
  170. }
  171. for _, ip := range ips {
  172. visitorRequestLimitExemptIPs = append(visitorRequestLimitExemptIPs, ip.String())
  173. }
  174. }
  175. // Run server
  176. conf := server.NewConfig()
  177. conf.BaseURL = baseURL
  178. conf.ListenHTTP = listenHTTP
  179. conf.ListenHTTPS = listenHTTPS
  180. conf.ListenUnix = listenUnix
  181. conf.KeyFile = keyFile
  182. conf.CertFile = certFile
  183. conf.FirebaseKeyFile = firebaseKeyFile
  184. conf.CacheFile = cacheFile
  185. conf.CacheDuration = cacheDuration
  186. conf.AuthFile = authFile
  187. conf.AuthDefaultRead = authDefaultRead
  188. conf.AuthDefaultWrite = authDefaultWrite
  189. conf.AttachmentCacheDir = attachmentCacheDir
  190. conf.AttachmentTotalSizeLimit = attachmentTotalSizeLimit
  191. conf.AttachmentFileSizeLimit = attachmentFileSizeLimit
  192. conf.AttachmentExpiryDuration = attachmentExpiryDuration
  193. conf.KeepaliveInterval = keepaliveInterval
  194. conf.ManagerInterval = managerInterval
  195. conf.WebRootIsApp = webRootIsApp
  196. conf.SMTPSenderAddr = smtpSenderAddr
  197. conf.SMTPSenderUser = smtpSenderUser
  198. conf.SMTPSenderPass = smtpSenderPass
  199. conf.SMTPSenderFrom = smtpSenderFrom
  200. conf.SMTPServerListen = smtpServerListen
  201. conf.SMTPServerDomain = smtpServerDomain
  202. conf.SMTPServerAddrPrefix = smtpServerAddrPrefix
  203. conf.TotalTopicLimit = totalTopicLimit
  204. conf.VisitorSubscriptionLimit = visitorSubscriptionLimit
  205. conf.VisitorAttachmentTotalSizeLimit = visitorAttachmentTotalSizeLimit
  206. conf.VisitorAttachmentDailyBandwidthLimit = int(visitorAttachmentDailyBandwidthLimit)
  207. conf.VisitorRequestLimitBurst = visitorRequestLimitBurst
  208. conf.VisitorRequestLimitReplenish = visitorRequestLimitReplenish
  209. conf.VisitorRequestExemptIPAddrs = visitorRequestLimitExemptIPs
  210. conf.VisitorEmailLimitBurst = visitorEmailLimitBurst
  211. conf.VisitorEmailLimitReplenish = visitorEmailLimitReplenish
  212. conf.BehindProxy = behindProxy
  213. s, err := server.New(conf)
  214. if err != nil {
  215. log.Fatalln(err)
  216. }
  217. if err := s.Run(); err != nil {
  218. log.Fatalln(err)
  219. }
  220. log.Printf("Exiting.")
  221. return nil
  222. }
  223. func parseSize(s string, defaultValue int64) (v int64, err error) {
  224. if s == "" {
  225. return defaultValue, nil
  226. }
  227. v, err = util.ParseSize(s)
  228. if err != nil {
  229. return 0, err
  230. }
  231. return v, nil
  232. }