serve.go 28 KB

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