serve.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //go:build !noserver
  2. package cmd
  3. import (
  4. "errors"
  5. "fmt"
  6. "github.com/stripe/stripe-go/v74"
  7. "heckel.io/ntfy/user"
  8. "io/fs"
  9. "math"
  10. "net"
  11. "net/netip"
  12. "os"
  13. "os/signal"
  14. "strings"
  15. "syscall"
  16. "time"
  17. "heckel.io/ntfy/log"
  18. "github.com/urfave/cli/v2"
  19. "github.com/urfave/cli/v2/altsrc"
  20. "heckel.io/ntfy/server"
  21. "heckel.io/ntfy/util"
  22. )
  23. func init() {
  24. commands = append(commands, cmdServe)
  25. }
  26. const (
  27. defaultServerConfigFile = "/etc/ntfy/server.yml"
  28. )
  29. var flagsServe = append(
  30. append([]cli.Flag{}, flagsDefault...),
  31. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: defaultServerConfigFile, DefaultText: defaultServerConfigFile, Usage: "config file"},
  32. 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)"}),
  33. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-http", Aliases: []string{"listen_http", "l"}, EnvVars: []string{"NTFY_LISTEN_HTTP"}, Value: server.DefaultListenHTTP, Usage: "ip:port used as HTTP listen address"}),
  34. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-https", Aliases: []string{"listen_https", "L"}, EnvVars: []string{"NTFY_LISTEN_HTTPS"}, Usage: "ip:port used as HTTPS listen address"}),
  35. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-unix", Aliases: []string{"listen_unix", "U"}, EnvVars: []string{"NTFY_LISTEN_UNIX"}, Usage: "listen on unix socket path"}),
  36. altsrc.NewIntFlag(&cli.IntFlag{Name: "listen-unix-mode", Aliases: []string{"listen_unix_mode"}, EnvVars: []string{"NTFY_LISTEN_UNIX_MODE"}, DefaultText: "system default", Usage: "file permissions of unix socket, e.g. 0700"}),
  37. 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"}),
  38. 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"}),
  39. 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"}),
  40. altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-file", Aliases: []string{"cache_file", "C"}, EnvVars: []string{"NTFY_CACHE_FILE"}, Usage: "cache file used for message caching"}),
  41. 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"}),
  42. altsrc.NewIntFlag(&cli.IntFlag{Name: "cache-batch-size", Aliases: []string{"cache_batch_size"}, EnvVars: []string{"NTFY_BATCH_SIZE"}, Usage: "max size of messages to batch together when writing to message cache (if zero, writes are synchronous)"}),
  43. altsrc.NewDurationFlag(&cli.DurationFlag{Name: "cache-batch-timeout", Aliases: []string{"cache_batch_timeout"}, EnvVars: []string{"NTFY_CACHE_BATCH_TIMEOUT"}, Usage: "timeout for batched async writes to the message cache (if zero, writes are synchronous)"}),
  44. altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-startup-queries", Aliases: []string{"cache_startup_queries"}, EnvVars: []string{"NTFY_CACHE_STARTUP_QUERIES"}, Usage: "queries run when the cache database is initialized"}),
  45. 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"}),
  46. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-startup-queries", Aliases: []string{"auth_startup_queries"}, EnvVars: []string{"NTFY_AUTH_STARTUP_QUERIES"}, Usage: "queries run when the auth database is initialized"}),
  47. 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"}),
  48. 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"}),
  49. 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"}),
  50. 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)"}),
  51. 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)"}),
  52. 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"}),
  53. 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"}),
  54. altsrc.NewStringSliceFlag(&cli.StringSliceFlag{Name: "disallowed-topics", Aliases: []string{"disallowed_topics"}, EnvVars: []string{"NTFY_DISALLOWED_TOPICS"}, Usage: "topics that are not allowed to be used"}),
  55. altsrc.NewStringFlag(&cli.StringFlag{Name: "web-root", Aliases: []string{"web_root"}, EnvVars: []string{"NTFY_WEB_ROOT"}, Value: "/", Usage: "sets root of the web app (e.g. /, or /app), or disables it (disable)"}),
  56. altsrc.NewBoolFlag(&cli.BoolFlag{Name: "enable-signup", Aliases: []string{"enable_signup"}, EnvVars: []string{"NTFY_ENABLE_SIGNUP"}, Value: false, Usage: "allows users to sign up via the web app, or API"}),
  57. altsrc.NewBoolFlag(&cli.BoolFlag{Name: "enable-login", Aliases: []string{"enable_login"}, EnvVars: []string{"NTFY_ENABLE_LOGIN"}, Value: false, Usage: "allows users to log in via the web app, or API"}),
  58. altsrc.NewBoolFlag(&cli.BoolFlag{Name: "enable-reservations", Aliases: []string{"enable_reservations"}, EnvVars: []string{"NTFY_ENABLE_RESERVATIONS"}, Value: false, Usage: "allows users to reserve topics (if their tier allows it)"}),
  59. altsrc.NewStringFlag(&cli.StringFlag{Name: "upstream-base-url", Aliases: []string{"upstream_base_url"}, EnvVars: []string{"NTFY_UPSTREAM_BASE_URL"}, Value: "", Usage: "forward poll request to an upstream server, this is needed for iOS push notifications for self-hosted servers"}),
  60. altsrc.NewStringFlag(&cli.StringFlag{Name: "upstream-access-token", Aliases: []string{"upstream_access_token"}, EnvVars: []string{"NTFY_UPSTREAM_ACCESS_TOKEN"}, Value: "", Usage: "access token to use for the upstream server; needed only if upstream rate limits are exceeded or upstream server requires auth"}),
  61. 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"}),
  62. 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)"}),
  63. 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)"}),
  64. 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)"}),
  65. 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"}),
  66. 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"}),
  67. 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-')"}),
  68. altsrc.NewStringFlag(&cli.StringFlag{Name: "twilio-account", Aliases: []string{"twilio_account"}, EnvVars: []string{"NTFY_TWILIO_ACCOUNT"}, Usage: "Twilio account SID, used for phone calls, e.g. AC123..."}),
  69. altsrc.NewStringFlag(&cli.StringFlag{Name: "twilio-auth-token", Aliases: []string{"twilio_auth_token"}, EnvVars: []string{"NTFY_TWILIO_AUTH_TOKEN"}, Usage: "Twilio auth token"}),
  70. altsrc.NewStringFlag(&cli.StringFlag{Name: "twilio-phone-number", Aliases: []string{"twilio_phone_number"}, EnvVars: []string{"NTFY_TWILIO_PHONE_NUMBER"}, Usage: "Twilio number to use for outgoing calls"}),
  71. altsrc.NewStringFlag(&cli.StringFlag{Name: "twilio-verify-service", Aliases: []string{"twilio_verify_service"}, EnvVars: []string{"NTFY_TWILIO_VERIFY_SERVICE"}, Usage: "Twilio Verify service ID, used for phone number verification"}),
  72. 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"}),
  73. 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"}),
  74. 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"}),
  75. 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"}),
  76. 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"}),
  77. 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)"}),
  78. 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"}),
  79. altsrc.NewIntFlag(&cli.IntFlag{Name: "visitor-message-daily-limit", Aliases: []string{"visitor_message_daily_limit"}, EnvVars: []string{"NTFY_VISITOR_MESSAGE_DAILY_LIMIT"}, Value: server.DefaultVisitorMessageDailyLimit, Usage: "max messages per visitor per day, derived from request limit if unset"}),
  80. 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"}),
  81. 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)"}),
  82. altsrc.NewBoolFlag(&cli.BoolFlag{Name: "visitor-subscriber-rate-limiting", Aliases: []string{"visitor_subscriber_rate_limiting"}, EnvVars: []string{"NTFY_VISITOR_SUBSCRIBER_RATE_LIMITING"}, Value: false, Usage: "enables subscriber-based rate limiting"}),
  83. 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)"}),
  84. altsrc.NewStringFlag(&cli.StringFlag{Name: "stripe-secret-key", Aliases: []string{"stripe_secret_key"}, EnvVars: []string{"NTFY_STRIPE_SECRET_KEY"}, Value: "", Usage: "key used for the Stripe API communication, this enables payments"}),
  85. altsrc.NewStringFlag(&cli.StringFlag{Name: "stripe-webhook-key", Aliases: []string{"stripe_webhook_key"}, EnvVars: []string{"NTFY_STRIPE_WEBHOOK_KEY"}, Value: "", Usage: "key required to validate the authenticity of incoming webhooks from Stripe"}),
  86. altsrc.NewStringFlag(&cli.StringFlag{Name: "billing-contact", Aliases: []string{"billing_contact"}, EnvVars: []string{"NTFY_BILLING_CONTACT"}, Value: "", Usage: "e-mail or website to display in upgrade dialog (only if payments are enabled)"}),
  87. altsrc.NewBoolFlag(&cli.BoolFlag{Name: "enable-metrics", Aliases: []string{"enable_metrics"}, EnvVars: []string{"NTFY_ENABLE_METRICS"}, Value: false, Usage: "if set, Prometheus metrics are exposed via the /metrics endpoint"}),
  88. altsrc.NewStringFlag(&cli.StringFlag{Name: "metrics-listen-http", Aliases: []string{"metrics_listen_http"}, EnvVars: []string{"NTFY_METRICS_LISTEN_HTTP"}, Usage: "ip:port used to expose the metrics endpoint (implicitly enables metrics)"}),
  89. altsrc.NewStringFlag(&cli.StringFlag{Name: "profile-listen-http", Aliases: []string{"profile_listen_http"}, EnvVars: []string{"NTFY_PROFILE_LISTEN_HTTP"}, Usage: "ip:port used to expose the profiling endpoints (implicitly enables profiling)"}),
  90. altsrc.NewStringFlag(&cli.StringFlag{Name: "web-push-public-key", Aliases: []string{"web_push_public_key"}, EnvVars: []string{"NTFY_WEB_PUSH_PUBLIC_KEY"}, Usage: "public key used for web push notifications"}),
  91. altsrc.NewStringFlag(&cli.StringFlag{Name: "web-push-private-key", Aliases: []string{"web_push_private_key"}, EnvVars: []string{"NTFY_WEB_PUSH_PRIVATE_KEY"}, Usage: "private key used for web push notifications"}),
  92. altsrc.NewStringFlag(&cli.StringFlag{Name: "web-push-file", Aliases: []string{"web_push_file"}, EnvVars: []string{"NTFY_WEB_PUSH_FILE"}, Usage: "file used to store web push subscriptions"}),
  93. altsrc.NewStringFlag(&cli.StringFlag{Name: "web-push-email-address", Aliases: []string{"web_push_email_address"}, EnvVars: []string{"NTFY_WEB_PUSH_EMAIL_ADDRESS"}, Usage: "e-mail address of sender, required to use browser push services"}),
  94. altsrc.NewStringFlag(&cli.StringFlag{Name: "web-push-startup-queries", Aliases: []string{"web_push_startup_queries"}, EnvVars: []string{"NTFY_WEB_PUSH_STARTUP_QUERIES"}, Usage: "queries run when the web push database is initialized"}),
  95. )
  96. var cmdServe = &cli.Command{
  97. Name: "serve",
  98. Usage: "Run the ntfy server",
  99. UsageText: "ntfy serve [OPTIONS..]",
  100. Action: execServe,
  101. Category: categoryServer,
  102. Flags: flagsServe,
  103. Before: initConfigFileInputSourceFunc("config", flagsServe, initLogFunc),
  104. Description: `Run the ntfy server and listen for incoming requests
  105. The command will load the configuration from /etc/ntfy/server.yml. Config options can
  106. be overridden using the command line options.
  107. Examples:
  108. ntfy serve # Starts server in the foreground (on port 80)
  109. ntfy serve --listen-http :8080 # Starts server with alternate port`,
  110. }
  111. func execServe(c *cli.Context) error {
  112. if c.NArg() > 0 {
  113. return errors.New("no arguments expected, see 'ntfy serve --help' for help")
  114. }
  115. // Read all the options
  116. config := c.String("config")
  117. baseURL := c.String("base-url")
  118. listenHTTP := c.String("listen-http")
  119. listenHTTPS := c.String("listen-https")
  120. listenUnix := c.String("listen-unix")
  121. listenUnixMode := c.Int("listen-unix-mode")
  122. keyFile := c.String("key-file")
  123. certFile := c.String("cert-file")
  124. firebaseKeyFile := c.String("firebase-key-file")
  125. webPushPrivateKey := c.String("web-push-private-key")
  126. webPushPublicKey := c.String("web-push-public-key")
  127. webPushFile := c.String("web-push-file")
  128. webPushEmailAddress := c.String("web-push-email-address")
  129. webPushStartupQueries := c.String("web-push-startup-queries")
  130. cacheFile := c.String("cache-file")
  131. cacheDuration := c.Duration("cache-duration")
  132. cacheStartupQueries := c.String("cache-startup-queries")
  133. cacheBatchSize := c.Int("cache-batch-size")
  134. cacheBatchTimeout := c.Duration("cache-batch-timeout")
  135. authFile := c.String("auth-file")
  136. authStartupQueries := c.String("auth-startup-queries")
  137. authDefaultAccess := c.String("auth-default-access")
  138. attachmentCacheDir := c.String("attachment-cache-dir")
  139. attachmentTotalSizeLimitStr := c.String("attachment-total-size-limit")
  140. attachmentFileSizeLimitStr := c.String("attachment-file-size-limit")
  141. attachmentExpiryDuration := c.Duration("attachment-expiry-duration")
  142. keepaliveInterval := c.Duration("keepalive-interval")
  143. managerInterval := c.Duration("manager-interval")
  144. disallowedTopics := c.StringSlice("disallowed-topics")
  145. webRoot := c.String("web-root")
  146. enableSignup := c.Bool("enable-signup")
  147. enableLogin := c.Bool("enable-login")
  148. enableReservations := c.Bool("enable-reservations")
  149. upstreamBaseURL := c.String("upstream-base-url")
  150. upstreamAccessToken := c.String("upstream-access-token")
  151. smtpSenderAddr := c.String("smtp-sender-addr")
  152. smtpSenderUser := c.String("smtp-sender-user")
  153. smtpSenderPass := c.String("smtp-sender-pass")
  154. smtpSenderFrom := c.String("smtp-sender-from")
  155. smtpServerListen := c.String("smtp-server-listen")
  156. smtpServerDomain := c.String("smtp-server-domain")
  157. smtpServerAddrPrefix := c.String("smtp-server-addr-prefix")
  158. twilioAccount := c.String("twilio-account")
  159. twilioAuthToken := c.String("twilio-auth-token")
  160. twilioPhoneNumber := c.String("twilio-phone-number")
  161. twilioVerifyService := c.String("twilio-verify-service")
  162. totalTopicLimit := c.Int("global-topic-limit")
  163. visitorSubscriptionLimit := c.Int("visitor-subscription-limit")
  164. visitorSubscriberRateLimiting := c.Bool("visitor-subscriber-rate-limiting")
  165. visitorAttachmentTotalSizeLimitStr := c.String("visitor-attachment-total-size-limit")
  166. visitorAttachmentDailyBandwidthLimitStr := c.String("visitor-attachment-daily-bandwidth-limit")
  167. visitorRequestLimitBurst := c.Int("visitor-request-limit-burst")
  168. visitorRequestLimitReplenish := c.Duration("visitor-request-limit-replenish")
  169. visitorRequestLimitExemptHosts := util.SplitNoEmpty(c.String("visitor-request-limit-exempt-hosts"), ",")
  170. visitorMessageDailyLimit := c.Int("visitor-message-daily-limit")
  171. visitorEmailLimitBurst := c.Int("visitor-email-limit-burst")
  172. visitorEmailLimitReplenish := c.Duration("visitor-email-limit-replenish")
  173. behindProxy := c.Bool("behind-proxy")
  174. stripeSecretKey := c.String("stripe-secret-key")
  175. stripeWebhookKey := c.String("stripe-webhook-key")
  176. billingContact := c.String("billing-contact")
  177. metricsListenHTTP := c.String("metrics-listen-http")
  178. enableMetrics := c.Bool("enable-metrics") || metricsListenHTTP != ""
  179. profileListenHTTP := c.String("profile-listen-http")
  180. // Check values
  181. if firebaseKeyFile != "" && !util.FileExists(firebaseKeyFile) {
  182. return errors.New("if set, FCM key file must exist")
  183. } else if webPushPublicKey != "" && (webPushPrivateKey == "" || webPushFile == "" || webPushEmailAddress == "" || baseURL == "") {
  184. return errors.New("if web push is enabled, web-push-private-key, web-push-public-key, web-push-file, web-push-email-address, and base-url should be set. run 'ntfy webpush keys' to generate keys")
  185. } else if keepaliveInterval < 5*time.Second {
  186. return errors.New("keepalive interval cannot be lower than five seconds")
  187. } else if managerInterval < 5*time.Second {
  188. return errors.New("manager interval cannot be lower than five seconds")
  189. } else if cacheDuration > 0 && cacheDuration < managerInterval {
  190. return errors.New("cache duration cannot be lower than manager interval")
  191. } else if keyFile != "" && !util.FileExists(keyFile) {
  192. return errors.New("if set, key file must exist")
  193. } else if certFile != "" && !util.FileExists(certFile) {
  194. return errors.New("if set, certificate file must exist")
  195. } else if listenHTTPS != "" && (keyFile == "" || certFile == "") {
  196. return errors.New("if listen-https is set, both key-file and cert-file must be set")
  197. } else if smtpSenderAddr != "" && (baseURL == "" || smtpSenderFrom == "") {
  198. return errors.New("if smtp-sender-addr is set, base-url, and smtp-sender-from must also be set")
  199. } else if smtpServerListen != "" && smtpServerDomain == "" {
  200. return errors.New("if smtp-server-listen is set, smtp-server-domain must also be set")
  201. } else if attachmentCacheDir != "" && baseURL == "" {
  202. return errors.New("if attachment-cache-dir is set, base-url must also be set")
  203. } else if baseURL != "" && !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") {
  204. return errors.New("if set, base-url must start with http:// or https://")
  205. } else if baseURL != "" && strings.HasSuffix(baseURL, "/") {
  206. return errors.New("if set, base-url must not end with a slash (/)")
  207. } else if upstreamBaseURL != "" && !strings.HasPrefix(upstreamBaseURL, "http://") && !strings.HasPrefix(upstreamBaseURL, "https://") {
  208. return errors.New("if set, upstream-base-url must start with http:// or https://")
  209. } else if upstreamBaseURL != "" && strings.HasSuffix(upstreamBaseURL, "/") {
  210. return errors.New("if set, upstream-base-url must not end with a slash (/)")
  211. } else if upstreamBaseURL != "" && baseURL == "" {
  212. return errors.New("if upstream-base-url is set, base-url must also be set")
  213. } else if upstreamBaseURL != "" && baseURL != "" && baseURL == upstreamBaseURL {
  214. return errors.New("base-url and upstream-base-url cannot be identical, you'll likely want to set upstream-base-url to https://ntfy.sh, see https://ntfy.sh/docs/config/#ios-instant-notifications")
  215. } else if authFile == "" && (enableSignup || enableLogin || enableReservations || stripeSecretKey != "") {
  216. return errors.New("cannot set enable-signup, enable-login, enable-reserve-topics, or stripe-secret-key if auth-file is not set")
  217. } else if enableSignup && !enableLogin {
  218. return errors.New("cannot set enable-signup without also setting enable-login")
  219. } else if stripeSecretKey != "" && (stripeWebhookKey == "" || baseURL == "") {
  220. return errors.New("if stripe-secret-key is set, stripe-webhook-key and base-url must also be set")
  221. } else if twilioAccount != "" && (twilioAuthToken == "" || twilioPhoneNumber == "" || twilioVerifyService == "" || baseURL == "" || authFile == "") {
  222. return errors.New("if twilio-account is set, twilio-auth-token, twilio-phone-number, twilio-verify-service, base-url, and auth-file must also be set")
  223. }
  224. // Backwards compatibility
  225. if webRoot == "app" {
  226. webRoot = "/"
  227. } else if webRoot == "home" {
  228. webRoot = "/app"
  229. } else if webRoot == "disable" {
  230. webRoot = ""
  231. } else if !strings.HasPrefix(webRoot, "/") {
  232. webRoot = "/" + webRoot
  233. }
  234. // Default auth permissions
  235. authDefault, err := user.ParsePermission(authDefaultAccess)
  236. if err != nil {
  237. return errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  238. }
  239. // Special case: Unset default
  240. if listenHTTP == "-" {
  241. listenHTTP = ""
  242. }
  243. // Convert sizes to bytes
  244. attachmentTotalSizeLimit, err := parseSize(attachmentTotalSizeLimitStr, server.DefaultAttachmentTotalSizeLimit)
  245. if err != nil {
  246. return err
  247. }
  248. attachmentFileSizeLimit, err := parseSize(attachmentFileSizeLimitStr, server.DefaultAttachmentFileSizeLimit)
  249. if err != nil {
  250. return err
  251. }
  252. visitorAttachmentTotalSizeLimit, err := parseSize(visitorAttachmentTotalSizeLimitStr, server.DefaultVisitorAttachmentTotalSizeLimit)
  253. if err != nil {
  254. return err
  255. }
  256. visitorAttachmentDailyBandwidthLimit, err := parseSize(visitorAttachmentDailyBandwidthLimitStr, server.DefaultVisitorAttachmentDailyBandwidthLimit)
  257. if err != nil {
  258. return err
  259. } else if visitorAttachmentDailyBandwidthLimit > math.MaxInt {
  260. return fmt.Errorf("config option visitor-attachment-daily-bandwidth-limit must be lower than %d", math.MaxInt)
  261. }
  262. // Resolve hosts
  263. visitorRequestLimitExemptIPs := make([]netip.Prefix, 0)
  264. for _, host := range visitorRequestLimitExemptHosts {
  265. ips, err := parseIPHostPrefix(host)
  266. if err != nil {
  267. log.Warn("cannot resolve host %s: %s, ignoring visitor request exemption", host, err.Error())
  268. continue
  269. }
  270. visitorRequestLimitExemptIPs = append(visitorRequestLimitExemptIPs, ips...)
  271. }
  272. // Stripe things
  273. if stripeSecretKey != "" {
  274. stripe.EnableTelemetry = false // Whoa!
  275. stripe.Key = stripeSecretKey
  276. }
  277. // Add default forbidden topics
  278. disallowedTopics = append(disallowedTopics, server.DefaultDisallowedTopics...)
  279. // Run server
  280. conf := server.NewConfig()
  281. conf.File = config
  282. conf.BaseURL = baseURL
  283. conf.ListenHTTP = listenHTTP
  284. conf.ListenHTTPS = listenHTTPS
  285. conf.ListenUnix = listenUnix
  286. conf.ListenUnixMode = fs.FileMode(listenUnixMode)
  287. conf.KeyFile = keyFile
  288. conf.CertFile = certFile
  289. conf.FirebaseKeyFile = firebaseKeyFile
  290. conf.CacheFile = cacheFile
  291. conf.CacheDuration = cacheDuration
  292. conf.CacheStartupQueries = cacheStartupQueries
  293. conf.CacheBatchSize = cacheBatchSize
  294. conf.CacheBatchTimeout = cacheBatchTimeout
  295. conf.AuthFile = authFile
  296. conf.AuthStartupQueries = authStartupQueries
  297. conf.AuthDefault = authDefault
  298. conf.AttachmentCacheDir = attachmentCacheDir
  299. conf.AttachmentTotalSizeLimit = attachmentTotalSizeLimit
  300. conf.AttachmentFileSizeLimit = attachmentFileSizeLimit
  301. conf.AttachmentExpiryDuration = attachmentExpiryDuration
  302. conf.KeepaliveInterval = keepaliveInterval
  303. conf.ManagerInterval = managerInterval
  304. conf.DisallowedTopics = disallowedTopics
  305. conf.WebRoot = webRoot
  306. conf.UpstreamBaseURL = upstreamBaseURL
  307. conf.UpstreamAccessToken = upstreamAccessToken
  308. conf.SMTPSenderAddr = smtpSenderAddr
  309. conf.SMTPSenderUser = smtpSenderUser
  310. conf.SMTPSenderPass = smtpSenderPass
  311. conf.SMTPSenderFrom = smtpSenderFrom
  312. conf.SMTPServerListen = smtpServerListen
  313. conf.SMTPServerDomain = smtpServerDomain
  314. conf.SMTPServerAddrPrefix = smtpServerAddrPrefix
  315. conf.TwilioAccount = twilioAccount
  316. conf.TwilioAuthToken = twilioAuthToken
  317. conf.TwilioPhoneNumber = twilioPhoneNumber
  318. conf.TwilioVerifyService = twilioVerifyService
  319. conf.TotalTopicLimit = totalTopicLimit
  320. conf.VisitorSubscriptionLimit = visitorSubscriptionLimit
  321. conf.VisitorAttachmentTotalSizeLimit = visitorAttachmentTotalSizeLimit
  322. conf.VisitorAttachmentDailyBandwidthLimit = visitorAttachmentDailyBandwidthLimit
  323. conf.VisitorRequestLimitBurst = visitorRequestLimitBurst
  324. conf.VisitorRequestLimitReplenish = visitorRequestLimitReplenish
  325. conf.VisitorRequestExemptIPAddrs = visitorRequestLimitExemptIPs
  326. conf.VisitorMessageDailyLimit = visitorMessageDailyLimit
  327. conf.VisitorEmailLimitBurst = visitorEmailLimitBurst
  328. conf.VisitorEmailLimitReplenish = visitorEmailLimitReplenish
  329. conf.VisitorSubscriberRateLimiting = visitorSubscriberRateLimiting
  330. conf.BehindProxy = behindProxy
  331. conf.StripeSecretKey = stripeSecretKey
  332. conf.StripeWebhookKey = stripeWebhookKey
  333. conf.BillingContact = billingContact
  334. conf.EnableSignup = enableSignup
  335. conf.EnableLogin = enableLogin
  336. conf.EnableReservations = enableReservations
  337. conf.EnableMetrics = enableMetrics
  338. conf.MetricsListenHTTP = metricsListenHTTP
  339. conf.ProfileListenHTTP = profileListenHTTP
  340. conf.Version = c.App.Version
  341. conf.WebPushPrivateKey = webPushPrivateKey
  342. conf.WebPushPublicKey = webPushPublicKey
  343. conf.WebPushFile = webPushFile
  344. conf.WebPushEmailAddress = webPushEmailAddress
  345. conf.WebPushStartupQueries = webPushStartupQueries
  346. // Set up hot-reloading of config
  347. go sigHandlerConfigReload(config)
  348. // Run server
  349. s, err := server.New(conf)
  350. if err != nil {
  351. log.Fatal(err.Error())
  352. } else if err := s.Run(); err != nil {
  353. log.Fatal(err.Error())
  354. }
  355. log.Info("Exiting.")
  356. return nil
  357. }
  358. func parseSize(s string, defaultValue int64) (v int64, err error) {
  359. if s == "" {
  360. return defaultValue, nil
  361. }
  362. v, err = util.ParseSize(s)
  363. if err != nil {
  364. return 0, err
  365. }
  366. return v, nil
  367. }
  368. func sigHandlerConfigReload(config string) {
  369. sigs := make(chan os.Signal, 1)
  370. signal.Notify(sigs, syscall.SIGHUP)
  371. for range sigs {
  372. log.Info("Partially hot reloading configuration ...")
  373. inputSource, err := newYamlSourceFromFile(config, flagsServe)
  374. if err != nil {
  375. log.Warn("Hot reload failed: %s", err.Error())
  376. continue
  377. }
  378. if err := reloadLogLevel(inputSource); err != nil {
  379. log.Warn("Reloading log level failed: %s", err.Error())
  380. }
  381. }
  382. }
  383. func parseIPHostPrefix(host string) (prefixes []netip.Prefix, err error) {
  384. // Try parsing as prefix, e.g. 10.0.1.0/24
  385. prefix, err := netip.ParsePrefix(host)
  386. if err == nil {
  387. prefixes = append(prefixes, prefix.Masked())
  388. return prefixes, nil
  389. }
  390. // Not a prefix, parse as host or IP (LookupHost passes through an IP as is)
  391. ips, err := net.LookupHost(host)
  392. if err != nil {
  393. return nil, err
  394. }
  395. for _, ipStr := range ips {
  396. ip, err := netip.ParseAddr(ipStr)
  397. if err == nil {
  398. prefix, err := ip.Prefix(ip.BitLen())
  399. if err != nil {
  400. return nil, fmt.Errorf("%s successfully parsed but unable to make prefix: %s", ip.String(), err.Error())
  401. }
  402. prefixes = append(prefixes, prefix.Masked())
  403. }
  404. }
  405. return
  406. }
  407. func reloadLogLevel(inputSource altsrc.InputSourceContext) error {
  408. newLevelStr, err := inputSource.String("log-level")
  409. if err != nil {
  410. return fmt.Errorf("cannot load log level: %s", err.Error())
  411. }
  412. overrides, err := inputSource.StringSlice("log-level-overrides")
  413. if err != nil {
  414. return fmt.Errorf("cannot load log level overrides (1): %s", err.Error())
  415. }
  416. log.ResetLevelOverrides()
  417. if err := applyLogLevelOverrides(overrides); err != nil {
  418. return fmt.Errorf("cannot load log level overrides (2): %s", err.Error())
  419. }
  420. log.SetLevel(log.ToLevel(newLevelStr))
  421. if len(overrides) > 0 {
  422. log.Info("Log level is %v, %d override(s) in place", strings.ToUpper(newLevelStr), len(overrides))
  423. } else {
  424. log.Info("Log level is %v", strings.ToUpper(newLevelStr))
  425. }
  426. return nil
  427. }