serve_linux.go 17 KB

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