serve.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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: "auth-user-header", Aliases: []string{"auth_user_header"}, EnvVars: []string{"NTFY_AUTH_USER_HEADER"}, Usage: "HTTP header that may be used to pass an authenticated user from a proxy, e.g. X-Forwarded-User"}),
  49. 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"}),
  50. 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"}),
  51. 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)"}),
  52. 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)"}),
  53. 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"}),
  54. 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"}),
  55. 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"}),
  56. 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)"}),
  57. 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"}),
  58. 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"}),
  59. 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)"}),
  60. 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"}),
  61. 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"}),
  62. 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"}),
  63. 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)"}),
  64. 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)"}),
  65. 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)"}),
  66. 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"}),
  67. 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"}),
  68. 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-')"}),
  69. 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..."}),
  70. altsrc.NewStringFlag(&cli.StringFlag{Name: "twilio-auth-token", Aliases: []string{"twilio_auth_token"}, EnvVars: []string{"NTFY_TWILIO_AUTH_TOKEN"}, Usage: "Twilio auth token"}),
  71. 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"}),
  72. 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"}),
  73. 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"}),
  74. 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"}),
  75. 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"}),
  76. 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"}),
  77. 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"}),
  78. 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)"}),
  79. 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"}),
  80. 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"}),
  81. 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"}),
  82. 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)"}),
  83. 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"}),
  84. 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)"}),
  85. 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"}),
  86. 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"}),
  87. 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)"}),
  88. 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"}),
  89. 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)"}),
  90. 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)"}),
  91. 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"}),
  92. 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"}),
  93. 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"}),
  94. 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"}),
  95. 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"}),
  96. )
  97. var cmdServe = &cli.Command{
  98. Name: "serve",
  99. Usage: "Run the ntfy server",
  100. UsageText: "ntfy serve [OPTIONS..]",
  101. Action: execServe,
  102. Category: categoryServer,
  103. Flags: flagsServe,
  104. Before: initConfigFileInputSourceFunc("config", flagsServe, initLogFunc),
  105. Description: `Run the ntfy server and listen for incoming requests
  106. The command will load the configuration from /etc/ntfy/server.yml. Config options can
  107. be overridden using the command line options.
  108. Examples:
  109. ntfy serve # Starts server in the foreground (on port 80)
  110. ntfy serve --listen-http :8080 # Starts server with alternate port`,
  111. }
  112. func execServe(c *cli.Context) error {
  113. if c.NArg() > 0 {
  114. return errors.New("no arguments expected, see 'ntfy serve --help' for help")
  115. }
  116. // Read all the options
  117. config := c.String("config")
  118. baseURL := c.String("base-url")
  119. listenHTTP := c.String("listen-http")
  120. listenHTTPS := c.String("listen-https")
  121. listenUnix := c.String("listen-unix")
  122. listenUnixMode := c.Int("listen-unix-mode")
  123. keyFile := c.String("key-file")
  124. certFile := c.String("cert-file")
  125. firebaseKeyFile := c.String("firebase-key-file")
  126. webPushPrivateKey := c.String("web-push-private-key")
  127. webPushPublicKey := c.String("web-push-public-key")
  128. webPushFile := c.String("web-push-file")
  129. webPushEmailAddress := c.String("web-push-email-address")
  130. webPushStartupQueries := c.String("web-push-startup-queries")
  131. cacheFile := c.String("cache-file")
  132. cacheDuration := c.Duration("cache-duration")
  133. cacheStartupQueries := c.String("cache-startup-queries")
  134. cacheBatchSize := c.Int("cache-batch-size")
  135. cacheBatchTimeout := c.Duration("cache-batch-timeout")
  136. authFile := c.String("auth-file")
  137. authStartupQueries := c.String("auth-startup-queries")
  138. authDefaultAccess := c.String("auth-default-access")
  139. authUserHeader := c.String("auth-user-header")
  140. attachmentCacheDir := c.String("attachment-cache-dir")
  141. attachmentTotalSizeLimitStr := c.String("attachment-total-size-limit")
  142. attachmentFileSizeLimitStr := c.String("attachment-file-size-limit")
  143. attachmentExpiryDuration := c.Duration("attachment-expiry-duration")
  144. keepaliveInterval := c.Duration("keepalive-interval")
  145. managerInterval := c.Duration("manager-interval")
  146. disallowedTopics := c.StringSlice("disallowed-topics")
  147. webRoot := c.String("web-root")
  148. enableSignup := c.Bool("enable-signup")
  149. enableLogin := c.Bool("enable-login")
  150. enableReservations := c.Bool("enable-reservations")
  151. upstreamBaseURL := c.String("upstream-base-url")
  152. upstreamAccessToken := c.String("upstream-access-token")
  153. smtpSenderAddr := c.String("smtp-sender-addr")
  154. smtpSenderUser := c.String("smtp-sender-user")
  155. smtpSenderPass := c.String("smtp-sender-pass")
  156. smtpSenderFrom := c.String("smtp-sender-from")
  157. smtpServerListen := c.String("smtp-server-listen")
  158. smtpServerDomain := c.String("smtp-server-domain")
  159. smtpServerAddrPrefix := c.String("smtp-server-addr-prefix")
  160. twilioAccount := c.String("twilio-account")
  161. twilioAuthToken := c.String("twilio-auth-token")
  162. twilioPhoneNumber := c.String("twilio-phone-number")
  163. twilioVerifyService := c.String("twilio-verify-service")
  164. totalTopicLimit := c.Int("global-topic-limit")
  165. visitorSubscriptionLimit := c.Int("visitor-subscription-limit")
  166. visitorSubscriberRateLimiting := c.Bool("visitor-subscriber-rate-limiting")
  167. visitorAttachmentTotalSizeLimitStr := c.String("visitor-attachment-total-size-limit")
  168. visitorAttachmentDailyBandwidthLimitStr := c.String("visitor-attachment-daily-bandwidth-limit")
  169. visitorRequestLimitBurst := c.Int("visitor-request-limit-burst")
  170. visitorRequestLimitReplenish := c.Duration("visitor-request-limit-replenish")
  171. visitorRequestLimitExemptHosts := util.SplitNoEmpty(c.String("visitor-request-limit-exempt-hosts"), ",")
  172. visitorMessageDailyLimit := c.Int("visitor-message-daily-limit")
  173. visitorEmailLimitBurst := c.Int("visitor-email-limit-burst")
  174. visitorEmailLimitReplenish := c.Duration("visitor-email-limit-replenish")
  175. behindProxy := c.Bool("behind-proxy")
  176. stripeSecretKey := c.String("stripe-secret-key")
  177. stripeWebhookKey := c.String("stripe-webhook-key")
  178. billingContact := c.String("billing-contact")
  179. metricsListenHTTP := c.String("metrics-listen-http")
  180. enableMetrics := c.Bool("enable-metrics") || metricsListenHTTP != ""
  181. profileListenHTTP := c.String("profile-listen-http")
  182. // Check values
  183. if firebaseKeyFile != "" && !util.FileExists(firebaseKeyFile) {
  184. return errors.New("if set, FCM key file must exist")
  185. } else if webPushPublicKey != "" && (webPushPrivateKey == "" || webPushFile == "" || webPushEmailAddress == "" || baseURL == "") {
  186. 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")
  187. } else if keepaliveInterval < 5*time.Second {
  188. return errors.New("keepalive interval cannot be lower than five seconds")
  189. } else if managerInterval < 5*time.Second {
  190. return errors.New("manager interval cannot be lower than five seconds")
  191. } else if cacheDuration > 0 && cacheDuration < managerInterval {
  192. return errors.New("cache duration cannot be lower than manager interval")
  193. } else if keyFile != "" && !util.FileExists(keyFile) {
  194. return errors.New("if set, key file must exist")
  195. } else if certFile != "" && !util.FileExists(certFile) {
  196. return errors.New("if set, certificate file must exist")
  197. } else if listenHTTPS != "" && (keyFile == "" || certFile == "") {
  198. return errors.New("if listen-https is set, both key-file and cert-file must be set")
  199. } else if smtpSenderAddr != "" && (baseURL == "" || smtpSenderFrom == "") {
  200. return errors.New("if smtp-sender-addr is set, base-url, and smtp-sender-from must also be set")
  201. } else if smtpServerListen != "" && smtpServerDomain == "" {
  202. return errors.New("if smtp-server-listen is set, smtp-server-domain must also be set")
  203. } else if attachmentCacheDir != "" && baseURL == "" {
  204. return errors.New("if attachment-cache-dir is set, base-url must also be set")
  205. } else if baseURL != "" && !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") {
  206. return errors.New("if set, base-url must start with http:// or https://")
  207. } else if baseURL != "" && strings.HasSuffix(baseURL, "/") {
  208. return errors.New("if set, base-url must not end with a slash (/)")
  209. } else if upstreamBaseURL != "" && !strings.HasPrefix(upstreamBaseURL, "http://") && !strings.HasPrefix(upstreamBaseURL, "https://") {
  210. return errors.New("if set, upstream-base-url must start with http:// or https://")
  211. } else if upstreamBaseURL != "" && strings.HasSuffix(upstreamBaseURL, "/") {
  212. return errors.New("if set, upstream-base-url must not end with a slash (/)")
  213. } else if upstreamBaseURL != "" && baseURL == "" {
  214. return errors.New("if upstream-base-url is set, base-url must also be set")
  215. } else if upstreamBaseURL != "" && baseURL != "" && baseURL == upstreamBaseURL {
  216. 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")
  217. } else if authFile == "" && (enableSignup || enableLogin || enableReservations || stripeSecretKey != "") {
  218. return errors.New("cannot set enable-signup, enable-login, enable-reserve-topics, or stripe-secret-key if auth-file is not set")
  219. } else if authUserHeader != "" && !behindProxy {
  220. return errors.New("if auth-user-header is set, behind-proxy must also be set; this is a security measure")
  221. } else if enableSignup && !enableLogin {
  222. return errors.New("cannot set enable-signup without also setting enable-login")
  223. } else if stripeSecretKey != "" && (stripeWebhookKey == "" || baseURL == "") {
  224. return errors.New("if stripe-secret-key is set, stripe-webhook-key and base-url must also be set")
  225. } else if twilioAccount != "" && (twilioAuthToken == "" || twilioPhoneNumber == "" || twilioVerifyService == "" || baseURL == "" || authFile == "") {
  226. 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")
  227. }
  228. // Backwards compatibility
  229. if webRoot == "app" {
  230. webRoot = "/"
  231. } else if webRoot == "home" {
  232. webRoot = "/app"
  233. } else if webRoot == "disable" {
  234. webRoot = ""
  235. } else if !strings.HasPrefix(webRoot, "/") {
  236. webRoot = "/" + webRoot
  237. }
  238. // Default auth permissions
  239. authDefault, err := user.ParsePermission(authDefaultAccess)
  240. if err != nil {
  241. return errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  242. }
  243. // Special case: Unset default
  244. if listenHTTP == "-" {
  245. listenHTTP = ""
  246. }
  247. // Convert sizes to bytes
  248. attachmentTotalSizeLimit, err := parseSize(attachmentTotalSizeLimitStr, server.DefaultAttachmentTotalSizeLimit)
  249. if err != nil {
  250. return err
  251. }
  252. attachmentFileSizeLimit, err := parseSize(attachmentFileSizeLimitStr, server.DefaultAttachmentFileSizeLimit)
  253. if err != nil {
  254. return err
  255. }
  256. visitorAttachmentTotalSizeLimit, err := parseSize(visitorAttachmentTotalSizeLimitStr, server.DefaultVisitorAttachmentTotalSizeLimit)
  257. if err != nil {
  258. return err
  259. }
  260. visitorAttachmentDailyBandwidthLimit, err := parseSize(visitorAttachmentDailyBandwidthLimitStr, server.DefaultVisitorAttachmentDailyBandwidthLimit)
  261. if err != nil {
  262. return err
  263. } else if visitorAttachmentDailyBandwidthLimit > math.MaxInt {
  264. return fmt.Errorf("config option visitor-attachment-daily-bandwidth-limit must be lower than %d", math.MaxInt)
  265. }
  266. // Resolve hosts
  267. visitorRequestLimitExemptIPs := make([]netip.Prefix, 0)
  268. for _, host := range visitorRequestLimitExemptHosts {
  269. ips, err := parseIPHostPrefix(host)
  270. if err != nil {
  271. log.Warn("cannot resolve host %s: %s, ignoring visitor request exemption", host, err.Error())
  272. continue
  273. }
  274. visitorRequestLimitExemptIPs = append(visitorRequestLimitExemptIPs, ips...)
  275. }
  276. // Stripe things
  277. if stripeSecretKey != "" {
  278. stripe.EnableTelemetry = false // Whoa!
  279. stripe.Key = stripeSecretKey
  280. }
  281. // Add default forbidden topics
  282. disallowedTopics = append(disallowedTopics, server.DefaultDisallowedTopics...)
  283. // Run server
  284. conf := server.NewConfig()
  285. conf.File = config
  286. conf.BaseURL = baseURL
  287. conf.ListenHTTP = listenHTTP
  288. conf.ListenHTTPS = listenHTTPS
  289. conf.ListenUnix = listenUnix
  290. conf.ListenUnixMode = fs.FileMode(listenUnixMode)
  291. conf.KeyFile = keyFile
  292. conf.CertFile = certFile
  293. conf.FirebaseKeyFile = firebaseKeyFile
  294. conf.CacheFile = cacheFile
  295. conf.CacheDuration = cacheDuration
  296. conf.CacheStartupQueries = cacheStartupQueries
  297. conf.CacheBatchSize = cacheBatchSize
  298. conf.CacheBatchTimeout = cacheBatchTimeout
  299. conf.AuthFile = authFile
  300. conf.AuthStartupQueries = authStartupQueries
  301. conf.AuthDefault = authDefault
  302. conf.AuthUserHeader = authUserHeader
  303. conf.AttachmentCacheDir = attachmentCacheDir
  304. conf.AttachmentTotalSizeLimit = attachmentTotalSizeLimit
  305. conf.AttachmentFileSizeLimit = attachmentFileSizeLimit
  306. conf.AttachmentExpiryDuration = attachmentExpiryDuration
  307. conf.KeepaliveInterval = keepaliveInterval
  308. conf.ManagerInterval = managerInterval
  309. conf.DisallowedTopics = disallowedTopics
  310. conf.WebRoot = webRoot
  311. conf.UpstreamBaseURL = upstreamBaseURL
  312. conf.UpstreamAccessToken = upstreamAccessToken
  313. conf.SMTPSenderAddr = smtpSenderAddr
  314. conf.SMTPSenderUser = smtpSenderUser
  315. conf.SMTPSenderPass = smtpSenderPass
  316. conf.SMTPSenderFrom = smtpSenderFrom
  317. conf.SMTPServerListen = smtpServerListen
  318. conf.SMTPServerDomain = smtpServerDomain
  319. conf.SMTPServerAddrPrefix = smtpServerAddrPrefix
  320. conf.TwilioAccount = twilioAccount
  321. conf.TwilioAuthToken = twilioAuthToken
  322. conf.TwilioPhoneNumber = twilioPhoneNumber
  323. conf.TwilioVerifyService = twilioVerifyService
  324. conf.TotalTopicLimit = totalTopicLimit
  325. conf.VisitorSubscriptionLimit = visitorSubscriptionLimit
  326. conf.VisitorAttachmentTotalSizeLimit = visitorAttachmentTotalSizeLimit
  327. conf.VisitorAttachmentDailyBandwidthLimit = visitorAttachmentDailyBandwidthLimit
  328. conf.VisitorRequestLimitBurst = visitorRequestLimitBurst
  329. conf.VisitorRequestLimitReplenish = visitorRequestLimitReplenish
  330. conf.VisitorRequestExemptIPAddrs = visitorRequestLimitExemptIPs
  331. conf.VisitorMessageDailyLimit = visitorMessageDailyLimit
  332. conf.VisitorEmailLimitBurst = visitorEmailLimitBurst
  333. conf.VisitorEmailLimitReplenish = visitorEmailLimitReplenish
  334. conf.VisitorSubscriberRateLimiting = visitorSubscriberRateLimiting
  335. conf.BehindProxy = behindProxy
  336. conf.StripeSecretKey = stripeSecretKey
  337. conf.StripeWebhookKey = stripeWebhookKey
  338. conf.BillingContact = billingContact
  339. conf.EnableSignup = enableSignup
  340. conf.EnableLogin = enableLogin
  341. conf.EnableReservations = enableReservations
  342. conf.EnableMetrics = enableMetrics
  343. conf.MetricsListenHTTP = metricsListenHTTP
  344. conf.ProfileListenHTTP = profileListenHTTP
  345. conf.Version = c.App.Version
  346. conf.WebPushPrivateKey = webPushPrivateKey
  347. conf.WebPushPublicKey = webPushPublicKey
  348. conf.WebPushFile = webPushFile
  349. conf.WebPushEmailAddress = webPushEmailAddress
  350. conf.WebPushStartupQueries = webPushStartupQueries
  351. // Set up hot-reloading of config
  352. go sigHandlerConfigReload(config)
  353. // Run server
  354. s, err := server.New(conf)
  355. if err != nil {
  356. log.Fatal(err.Error())
  357. } else if err := s.Run(); err != nil {
  358. log.Fatal(err.Error())
  359. }
  360. log.Info("Exiting.")
  361. return nil
  362. }
  363. func parseSize(s string, defaultValue int64) (v int64, err error) {
  364. if s == "" {
  365. return defaultValue, nil
  366. }
  367. v, err = util.ParseSize(s)
  368. if err != nil {
  369. return 0, err
  370. }
  371. return v, nil
  372. }
  373. func sigHandlerConfigReload(config string) {
  374. sigs := make(chan os.Signal, 1)
  375. signal.Notify(sigs, syscall.SIGHUP)
  376. for range sigs {
  377. log.Info("Partially hot reloading configuration ...")
  378. inputSource, err := newYamlSourceFromFile(config, flagsServe)
  379. if err != nil {
  380. log.Warn("Hot reload failed: %s", err.Error())
  381. continue
  382. }
  383. if err := reloadLogLevel(inputSource); err != nil {
  384. log.Warn("Reloading log level failed: %s", err.Error())
  385. }
  386. }
  387. }
  388. func parseIPHostPrefix(host string) (prefixes []netip.Prefix, err error) {
  389. // Try parsing as prefix, e.g. 10.0.1.0/24
  390. prefix, err := netip.ParsePrefix(host)
  391. if err == nil {
  392. prefixes = append(prefixes, prefix.Masked())
  393. return prefixes, nil
  394. }
  395. // Not a prefix, parse as host or IP (LookupHost passes through an IP as is)
  396. ips, err := net.LookupHost(host)
  397. if err != nil {
  398. return nil, err
  399. }
  400. for _, ipStr := range ips {
  401. ip, err := netip.ParseAddr(ipStr)
  402. if err == nil {
  403. prefix, err := ip.Prefix(ip.BitLen())
  404. if err != nil {
  405. return nil, fmt.Errorf("%s successfully parsed but unable to make prefix: %s", ip.String(), err.Error())
  406. }
  407. prefixes = append(prefixes, prefix.Masked())
  408. }
  409. }
  410. return
  411. }
  412. func reloadLogLevel(inputSource altsrc.InputSourceContext) error {
  413. newLevelStr, err := inputSource.String("log-level")
  414. if err != nil {
  415. return fmt.Errorf("cannot load log level: %s", err.Error())
  416. }
  417. overrides, err := inputSource.StringSlice("log-level-overrides")
  418. if err != nil {
  419. return fmt.Errorf("cannot load log level overrides (1): %s", err.Error())
  420. }
  421. log.ResetLevelOverrides()
  422. if err := applyLogLevelOverrides(overrides); err != nil {
  423. return fmt.Errorf("cannot load log level overrides (2): %s", err.Error())
  424. }
  425. log.SetLevel(log.ToLevel(newLevelStr))
  426. if len(overrides) > 0 {
  427. log.Info("Log level is %v, %d override(s) in place", strings.ToUpper(newLevelStr), len(overrides))
  428. } else {
  429. log.Info("Log level is %v", strings.ToUpper(newLevelStr))
  430. }
  431. return nil
  432. }