serve.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. //go:build !noserver
  2. package cmd
  3. import (
  4. "errors"
  5. "fmt"
  6. "github.com/stripe/stripe-go/v74"
  7. "github.com/urfave/cli/v2"
  8. "github.com/urfave/cli/v2/altsrc"
  9. "heckel.io/ntfy/v2/log"
  10. "heckel.io/ntfy/v2/server"
  11. "heckel.io/ntfy/v2/user"
  12. "heckel.io/ntfy/v2/util"
  13. "io/fs"
  14. "math"
  15. "net"
  16. "net/netip"
  17. "net/url"
  18. "os"
  19. "os/signal"
  20. "strings"
  21. "syscall"
  22. "time"
  23. )
  24. func init() {
  25. commands = append(commands, cmdServe)
  26. }
  27. const (
  28. defaultServerConfigFile = "/etc/ntfy/server.yml"
  29. )
  30. var flagsServe = append(
  31. append([]cli.Flag{}, flagsDefault...),
  32. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: defaultServerConfigFile, Usage: "config file"},
  33. 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)"}),
  34. 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"}),
  35. 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"}),
  36. altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-unix", Aliases: []string{"listen_unix", "U"}, EnvVars: []string{"NTFY_LISTEN_UNIX"}, Usage: "listen on unix socket path"}),
  37. 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"}),
  38. 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"}),
  39. 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"}),
  40. 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"}),
  41. altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-file", Aliases: []string{"cache_file", "C"}, EnvVars: []string{"NTFY_CACHE_FILE"}, Usage: "cache file used for message caching"}),
  42. altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-duration", Aliases: []string{"cache_duration", "b"}, EnvVars: []string{"NTFY_CACHE_DURATION"}, Value: util.FormatDuration(server.DefaultCacheDuration), Usage: "buffer messages for this time to allow `since` requests"}),
  43. 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)"}),
  44. altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-batch-timeout", Aliases: []string{"cache_batch_timeout"}, EnvVars: []string{"NTFY_CACHE_BATCH_TIMEOUT"}, Value: util.FormatDuration(server.DefaultCacheBatchTimeout), Usage: "timeout for batched async writes to the message cache (if zero, writes are synchronous)"}),
  45. 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"}),
  46. 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"}),
  47. 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"}),
  48. 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"}),
  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"}, Value: util.FormatSize(server.DefaultAttachmentTotalSizeLimit), 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"}, Value: util.FormatSize(server.DefaultAttachmentFileSizeLimit), Usage: "per-file attachment size limit (e.g. 300k, 2M, 100M)"}),
  52. altsrc.NewStringFlag(&cli.StringFlag{Name: "attachment-expiry-duration", Aliases: []string{"attachment_expiry_duration", "X"}, EnvVars: []string{"NTFY_ATTACHMENT_EXPIRY_DURATION"}, Value: util.FormatDuration(server.DefaultAttachmentExpiryDuration), Usage: "duration after which uploaded attachments will be deleted (e.g. 3h, 20h)"}),
  53. altsrc.NewStringFlag(&cli.StringFlag{Name: "keepalive-interval", Aliases: []string{"keepalive_interval", "k"}, EnvVars: []string{"NTFY_KEEPALIVE_INTERVAL"}, Value: util.FormatDuration(server.DefaultKeepaliveInterval), Usage: "interval of keepalive messages"}),
  54. altsrc.NewStringFlag(&cli.StringFlag{Name: "manager-interval", Aliases: []string{"manager_interval", "m"}, EnvVars: []string{"NTFY_MANAGER_INTERVAL"}, Value: util.FormatDuration(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.NewStringFlag(&cli.StringFlag{Name: "message-size-limit", Aliases: []string{"message_size_limit"}, EnvVars: []string{"NTFY_MESSAGE_SIZE_LIMIT"}, Value: util.FormatSize(server.DefaultMessageSizeLimit), Usage: "size limit for the message (see docs for limitations)"}),
  74. altsrc.NewStringFlag(&cli.StringFlag{Name: "message-delay-limit", Aliases: []string{"message_delay_limit"}, EnvVars: []string{"NTFY_MESSAGE_DELAY_LIMIT"}, Value: util.FormatDuration(server.DefaultMessageDelayMax), Usage: "max duration a message can be scheduled into the future"}),
  75. 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"}),
  76. 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"}),
  77. 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: util.FormatSize(server.DefaultVisitorAttachmentTotalSizeLimit), Usage: "total storage limit used for attachments per visitor"}),
  78. 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"}),
  79. 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"}),
  80. altsrc.NewStringFlag(&cli.StringFlag{Name: "visitor-request-limit-replenish", Aliases: []string{"visitor_request_limit_replenish"}, EnvVars: []string{"NTFY_VISITOR_REQUEST_LIMIT_REPLENISH"}, Value: util.FormatDuration(server.DefaultVisitorRequestLimitReplenish), Usage: "interval at which burst limit is replenished (one per x)"}),
  81. 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"}),
  82. 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"}),
  83. 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"}),
  84. altsrc.NewStringFlag(&cli.StringFlag{Name: "visitor-email-limit-replenish", Aliases: []string{"visitor_email_limit_replenish"}, EnvVars: []string{"NTFY_VISITOR_EMAIL_LIMIT_REPLENISH"}, Value: util.FormatDuration(server.DefaultVisitorEmailLimitReplenish), Usage: "interval at which burst limit is replenished (one per x)"}),
  85. 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"}),
  86. 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)"}),
  87. 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"}),
  88. 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"}),
  89. 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)"}),
  90. 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"}),
  91. 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)"}),
  92. 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)"}),
  93. 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"}),
  94. 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"}),
  95. 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"}),
  96. 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"}),
  97. 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"}),
  98. )
  99. var cmdServe = &cli.Command{
  100. Name: "serve",
  101. Usage: "Run the ntfy server",
  102. UsageText: "ntfy serve [OPTIONS..]",
  103. Action: execServe,
  104. Category: categoryServer,
  105. Flags: flagsServe,
  106. Before: initConfigFileInputSourceFunc("config", flagsServe, initLogFunc),
  107. Description: `Run the ntfy server and listen for incoming requests
  108. The command will load the configuration from /etc/ntfy/server.yml. Config options can
  109. be overridden using the command line options.
  110. Examples:
  111. ntfy serve # Starts server in the foreground (on port 80)
  112. ntfy serve --listen-http :8080 # Starts server with alternate port`,
  113. }
  114. func execServe(c *cli.Context) error {
  115. if c.NArg() > 0 {
  116. return errors.New("no arguments expected, see 'ntfy serve --help' for help")
  117. }
  118. // Read all the options
  119. config := c.String("config")
  120. baseURL := strings.TrimSuffix(c.String("base-url"), "/")
  121. listenHTTP := c.String("listen-http")
  122. listenHTTPS := c.String("listen-https")
  123. listenUnix := c.String("listen-unix")
  124. listenUnixMode := c.Int("listen-unix-mode")
  125. keyFile := c.String("key-file")
  126. certFile := c.String("cert-file")
  127. firebaseKeyFile := c.String("firebase-key-file")
  128. webPushPrivateKey := c.String("web-push-private-key")
  129. webPushPublicKey := c.String("web-push-public-key")
  130. webPushFile := c.String("web-push-file")
  131. webPushEmailAddress := c.String("web-push-email-address")
  132. webPushStartupQueries := c.String("web-push-startup-queries")
  133. cacheFile := c.String("cache-file")
  134. cacheDurationStr := c.String("cache-duration")
  135. cacheStartupQueries := c.String("cache-startup-queries")
  136. cacheBatchSize := c.Int("cache-batch-size")
  137. cacheBatchTimeoutStr := c.String("cache-batch-timeout")
  138. authFile := c.String("auth-file")
  139. authStartupQueries := c.String("auth-startup-queries")
  140. authDefaultAccess := c.String("auth-default-access")
  141. attachmentCacheDir := c.String("attachment-cache-dir")
  142. attachmentTotalSizeLimitStr := c.String("attachment-total-size-limit")
  143. attachmentFileSizeLimitStr := c.String("attachment-file-size-limit")
  144. attachmentExpiryDurationStr := c.String("attachment-expiry-duration")
  145. keepaliveIntervalStr := c.String("keepalive-interval")
  146. managerIntervalStr := c.String("manager-interval")
  147. disallowedTopics := c.StringSlice("disallowed-topics")
  148. webRoot := c.String("web-root")
  149. enableSignup := c.Bool("enable-signup")
  150. enableLogin := c.Bool("enable-login")
  151. enableReservations := c.Bool("enable-reservations")
  152. upstreamBaseURL := c.String("upstream-base-url")
  153. upstreamAccessToken := c.String("upstream-access-token")
  154. smtpSenderAddr := c.String("smtp-sender-addr")
  155. smtpSenderUser := c.String("smtp-sender-user")
  156. smtpSenderPass := c.String("smtp-sender-pass")
  157. smtpSenderFrom := c.String("smtp-sender-from")
  158. smtpServerListen := c.String("smtp-server-listen")
  159. smtpServerDomain := c.String("smtp-server-domain")
  160. smtpServerAddrPrefix := c.String("smtp-server-addr-prefix")
  161. twilioAccount := c.String("twilio-account")
  162. twilioAuthToken := c.String("twilio-auth-token")
  163. twilioPhoneNumber := c.String("twilio-phone-number")
  164. twilioVerifyService := c.String("twilio-verify-service")
  165. messageSizeLimitStr := c.String("message-size-limit")
  166. messageDelayLimitStr := c.String("message-delay-limit")
  167. totalTopicLimit := c.Int("global-topic-limit")
  168. visitorSubscriptionLimit := c.Int("visitor-subscription-limit")
  169. visitorSubscriberRateLimiting := c.Bool("visitor-subscriber-rate-limiting")
  170. visitorAttachmentTotalSizeLimitStr := c.String("visitor-attachment-total-size-limit")
  171. visitorAttachmentDailyBandwidthLimitStr := c.String("visitor-attachment-daily-bandwidth-limit")
  172. visitorRequestLimitBurst := c.Int("visitor-request-limit-burst")
  173. visitorRequestLimitReplenishStr := c.String("visitor-request-limit-replenish")
  174. visitorRequestLimitExemptHosts := util.SplitNoEmpty(c.String("visitor-request-limit-exempt-hosts"), ",")
  175. visitorMessageDailyLimit := c.Int("visitor-message-daily-limit")
  176. visitorEmailLimitBurst := c.Int("visitor-email-limit-burst")
  177. visitorEmailLimitReplenishStr := c.String("visitor-email-limit-replenish")
  178. behindProxy := c.Bool("behind-proxy")
  179. stripeSecretKey := c.String("stripe-secret-key")
  180. stripeWebhookKey := c.String("stripe-webhook-key")
  181. billingContact := c.String("billing-contact")
  182. metricsListenHTTP := c.String("metrics-listen-http")
  183. enableMetrics := c.Bool("enable-metrics") || metricsListenHTTP != ""
  184. profileListenHTTP := c.String("profile-listen-http")
  185. // Convert durations
  186. cacheDuration, err := util.ParseDuration(cacheDurationStr)
  187. if err != nil {
  188. return fmt.Errorf("invalid cache duration: %s", cacheDurationStr)
  189. }
  190. cacheBatchTimeout, err := util.ParseDuration(cacheBatchTimeoutStr)
  191. if err != nil {
  192. return fmt.Errorf("invalid cache batch timeout: %s", cacheBatchTimeoutStr)
  193. }
  194. attachmentExpiryDuration, err := util.ParseDuration(attachmentExpiryDurationStr)
  195. if err != nil {
  196. return fmt.Errorf("invalid attachment expiry duration: %s", attachmentExpiryDurationStr)
  197. }
  198. keepaliveInterval, err := util.ParseDuration(keepaliveIntervalStr)
  199. if err != nil {
  200. return fmt.Errorf("invalid keepalive interval: %s", keepaliveIntervalStr)
  201. }
  202. managerInterval, err := util.ParseDuration(managerIntervalStr)
  203. if err != nil {
  204. return fmt.Errorf("invalid manager interval: %s", managerIntervalStr)
  205. }
  206. messageDelayLimit, err := util.ParseDuration(messageDelayLimitStr)
  207. if err != nil {
  208. return fmt.Errorf("invalid message delay limit: %s", messageDelayLimitStr)
  209. }
  210. visitorRequestLimitReplenish, err := util.ParseDuration(visitorRequestLimitReplenishStr)
  211. if err != nil {
  212. return fmt.Errorf("invalid visitor request limit replenish: %s", visitorRequestLimitReplenishStr)
  213. }
  214. visitorEmailLimitReplenish, err := util.ParseDuration(visitorEmailLimitReplenishStr)
  215. if err != nil {
  216. return fmt.Errorf("invalid visitor email limit replenish: %s", visitorEmailLimitReplenishStr)
  217. }
  218. // Convert sizes to bytes
  219. messageSizeLimit, err := util.ParseSize(messageSizeLimitStr)
  220. if err != nil {
  221. return fmt.Errorf("invalid message size limit: %s", messageSizeLimitStr)
  222. }
  223. attachmentTotalSizeLimit, err := util.ParseSize(attachmentTotalSizeLimitStr)
  224. if err != nil {
  225. return fmt.Errorf("invalid attachment total size limit: %s", attachmentTotalSizeLimitStr)
  226. }
  227. attachmentFileSizeLimit, err := util.ParseSize(attachmentFileSizeLimitStr)
  228. if err != nil {
  229. return fmt.Errorf("invalid attachment file size limit: %s", attachmentFileSizeLimitStr)
  230. }
  231. visitorAttachmentTotalSizeLimit, err := util.ParseSize(visitorAttachmentTotalSizeLimitStr)
  232. if err != nil {
  233. return fmt.Errorf("invalid visitor attachment total size limit: %s", visitorAttachmentTotalSizeLimitStr)
  234. }
  235. visitorAttachmentDailyBandwidthLimit, err := util.ParseSize(visitorAttachmentDailyBandwidthLimitStr)
  236. if err != nil {
  237. return fmt.Errorf("invalid visitor attachment daily bandwidth limit: %s", visitorAttachmentDailyBandwidthLimitStr)
  238. } else if visitorAttachmentDailyBandwidthLimit > math.MaxInt {
  239. return fmt.Errorf("config option visitor-attachment-daily-bandwidth-limit must be lower than %d", math.MaxInt)
  240. }
  241. // Check values
  242. if firebaseKeyFile != "" && !util.FileExists(firebaseKeyFile) {
  243. return errors.New("if set, FCM key file must exist")
  244. } else if webPushPublicKey != "" && (webPushPrivateKey == "" || webPushFile == "" || webPushEmailAddress == "" || baseURL == "") {
  245. 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")
  246. } else if keepaliveInterval < 5*time.Second {
  247. return errors.New("keepalive interval cannot be lower than five seconds")
  248. } else if managerInterval < 5*time.Second {
  249. return errors.New("manager interval cannot be lower than five seconds")
  250. } else if cacheDuration > 0 && cacheDuration < managerInterval {
  251. return errors.New("cache duration cannot be lower than manager interval")
  252. } else if keyFile != "" && !util.FileExists(keyFile) {
  253. return errors.New("if set, key file must exist")
  254. } else if certFile != "" && !util.FileExists(certFile) {
  255. return errors.New("if set, certificate file must exist")
  256. } else if listenHTTPS != "" && (keyFile == "" || certFile == "") {
  257. return errors.New("if listen-https is set, both key-file and cert-file must be set")
  258. } else if smtpSenderAddr != "" && (baseURL == "" || smtpSenderFrom == "") {
  259. return errors.New("if smtp-sender-addr is set, base-url, and smtp-sender-from must also be set")
  260. } else if smtpServerListen != "" && smtpServerDomain == "" {
  261. return errors.New("if smtp-server-listen is set, smtp-server-domain must also be set")
  262. } else if attachmentCacheDir != "" && baseURL == "" {
  263. return errors.New("if attachment-cache-dir is set, base-url must also be set")
  264. } else if baseURL != "" {
  265. u, err := url.Parse(baseURL)
  266. if err != nil {
  267. return fmt.Errorf("if set, base-url must be a valid URL, e.g. https://ntfy.mydomain.com: %v", err)
  268. } else if u.Scheme != "http" && u.Scheme != "https" {
  269. return errors.New("if set, base-url must be a valid URL starting with http:// or https://, e.g. https://ntfy.mydomain.com")
  270. } else if u.Path != "" {
  271. return fmt.Errorf("if set, base-url must not have a path (%s), as hosting ntfy on a sub-path is not supported, e.g. https://ntfy.mydomain.com", u.Path)
  272. }
  273. } else if upstreamBaseURL != "" && !strings.HasPrefix(upstreamBaseURL, "http://") && !strings.HasPrefix(upstreamBaseURL, "https://") {
  274. return errors.New("if set, upstream-base-url must start with http:// or https://")
  275. } else if upstreamBaseURL != "" && strings.HasSuffix(upstreamBaseURL, "/") {
  276. return errors.New("if set, upstream-base-url must not end with a slash (/)")
  277. } else if upstreamBaseURL != "" && baseURL == "" {
  278. return errors.New("if upstream-base-url is set, base-url must also be set")
  279. } else if upstreamBaseURL != "" && baseURL != "" && baseURL == upstreamBaseURL {
  280. 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")
  281. } else if authFile == "" && (enableSignup || enableLogin || enableReservations || stripeSecretKey != "") {
  282. return errors.New("cannot set enable-signup, enable-login, enable-reserve-topics, or stripe-secret-key if auth-file is not set")
  283. } else if enableSignup && !enableLogin {
  284. return errors.New("cannot set enable-signup without also setting enable-login")
  285. } else if stripeSecretKey != "" && (stripeWebhookKey == "" || baseURL == "") {
  286. return errors.New("if stripe-secret-key is set, stripe-webhook-key and base-url must also be set")
  287. } else if twilioAccount != "" && (twilioAuthToken == "" || twilioPhoneNumber == "" || twilioVerifyService == "" || baseURL == "" || authFile == "") {
  288. 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")
  289. } else if messageSizeLimit > server.DefaultMessageSizeLimit {
  290. log.Warn("message-size-limit is greater than 4K, this is not recommended and largely untested, and may lead to issues with some clients")
  291. if messageSizeLimit > 5*1024*1024 {
  292. return errors.New("message-size-limit cannot be higher than 5M")
  293. }
  294. }
  295. // Backwards compatibility
  296. if webRoot == "app" {
  297. webRoot = "/"
  298. } else if webRoot == "home" {
  299. webRoot = "/app"
  300. } else if webRoot == "disable" {
  301. webRoot = ""
  302. } else if !strings.HasPrefix(webRoot, "/") {
  303. webRoot = "/" + webRoot
  304. }
  305. // Default auth permissions
  306. authDefault, err := user.ParsePermission(authDefaultAccess)
  307. if err != nil {
  308. return errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  309. }
  310. // Special case: Unset default
  311. if listenHTTP == "-" {
  312. listenHTTP = ""
  313. }
  314. // Resolve hosts
  315. visitorRequestLimitExemptIPs := make([]netip.Prefix, 0)
  316. for _, host := range visitorRequestLimitExemptHosts {
  317. ips, err := parseIPHostPrefix(host)
  318. if err != nil {
  319. log.Warn("cannot resolve host %s: %s, ignoring visitor request exemption", host, err.Error())
  320. continue
  321. }
  322. visitorRequestLimitExemptIPs = append(visitorRequestLimitExemptIPs, ips...)
  323. }
  324. // Stripe things
  325. if stripeSecretKey != "" {
  326. stripe.EnableTelemetry = false // Whoa!
  327. stripe.Key = stripeSecretKey
  328. }
  329. // Add default forbidden topics
  330. disallowedTopics = append(disallowedTopics, server.DefaultDisallowedTopics...)
  331. // Run server
  332. conf := server.NewConfig()
  333. conf.File = config
  334. conf.BaseURL = baseURL
  335. conf.ListenHTTP = listenHTTP
  336. conf.ListenHTTPS = listenHTTPS
  337. conf.ListenUnix = listenUnix
  338. conf.ListenUnixMode = fs.FileMode(listenUnixMode)
  339. conf.KeyFile = keyFile
  340. conf.CertFile = certFile
  341. conf.FirebaseKeyFile = firebaseKeyFile
  342. conf.CacheFile = cacheFile
  343. conf.CacheDuration = cacheDuration
  344. conf.CacheStartupQueries = cacheStartupQueries
  345. conf.CacheBatchSize = cacheBatchSize
  346. conf.CacheBatchTimeout = cacheBatchTimeout
  347. conf.AuthFile = authFile
  348. conf.AuthStartupQueries = authStartupQueries
  349. conf.AuthDefault = authDefault
  350. conf.AttachmentCacheDir = attachmentCacheDir
  351. conf.AttachmentTotalSizeLimit = attachmentTotalSizeLimit
  352. conf.AttachmentFileSizeLimit = attachmentFileSizeLimit
  353. conf.AttachmentExpiryDuration = attachmentExpiryDuration
  354. conf.KeepaliveInterval = keepaliveInterval
  355. conf.ManagerInterval = managerInterval
  356. conf.DisallowedTopics = disallowedTopics
  357. conf.WebRoot = webRoot
  358. conf.UpstreamBaseURL = upstreamBaseURL
  359. conf.UpstreamAccessToken = upstreamAccessToken
  360. conf.SMTPSenderAddr = smtpSenderAddr
  361. conf.SMTPSenderUser = smtpSenderUser
  362. conf.SMTPSenderPass = smtpSenderPass
  363. conf.SMTPSenderFrom = smtpSenderFrom
  364. conf.SMTPServerListen = smtpServerListen
  365. conf.SMTPServerDomain = smtpServerDomain
  366. conf.SMTPServerAddrPrefix = smtpServerAddrPrefix
  367. conf.TwilioAccount = twilioAccount
  368. conf.TwilioAuthToken = twilioAuthToken
  369. conf.TwilioPhoneNumber = twilioPhoneNumber
  370. conf.TwilioVerifyService = twilioVerifyService
  371. conf.MessageSizeLimit = int(messageSizeLimit)
  372. conf.MessageDelayMax = messageDelayLimit
  373. conf.TotalTopicLimit = totalTopicLimit
  374. conf.VisitorSubscriptionLimit = visitorSubscriptionLimit
  375. conf.VisitorAttachmentTotalSizeLimit = visitorAttachmentTotalSizeLimit
  376. conf.VisitorAttachmentDailyBandwidthLimit = visitorAttachmentDailyBandwidthLimit
  377. conf.VisitorRequestLimitBurst = visitorRequestLimitBurst
  378. conf.VisitorRequestLimitReplenish = visitorRequestLimitReplenish
  379. conf.VisitorRequestExemptIPAddrs = visitorRequestLimitExemptIPs
  380. conf.VisitorMessageDailyLimit = visitorMessageDailyLimit
  381. conf.VisitorEmailLimitBurst = visitorEmailLimitBurst
  382. conf.VisitorEmailLimitReplenish = visitorEmailLimitReplenish
  383. conf.VisitorSubscriberRateLimiting = visitorSubscriberRateLimiting
  384. conf.BehindProxy = behindProxy
  385. conf.StripeSecretKey = stripeSecretKey
  386. conf.StripeWebhookKey = stripeWebhookKey
  387. conf.BillingContact = billingContact
  388. conf.EnableSignup = enableSignup
  389. conf.EnableLogin = enableLogin
  390. conf.EnableReservations = enableReservations
  391. conf.EnableMetrics = enableMetrics
  392. conf.MetricsListenHTTP = metricsListenHTTP
  393. conf.ProfileListenHTTP = profileListenHTTP
  394. conf.Version = c.App.Version
  395. conf.WebPushPrivateKey = webPushPrivateKey
  396. conf.WebPushPublicKey = webPushPublicKey
  397. conf.WebPushFile = webPushFile
  398. conf.WebPushEmailAddress = webPushEmailAddress
  399. conf.WebPushStartupQueries = webPushStartupQueries
  400. // Set up hot-reloading of config
  401. go sigHandlerConfigReload(config)
  402. // Run server
  403. s, err := server.New(conf)
  404. if err != nil {
  405. log.Fatal(err.Error())
  406. } else if err := s.Run(); err != nil {
  407. log.Fatal(err.Error())
  408. }
  409. log.Info("Exiting.")
  410. return nil
  411. }
  412. func sigHandlerConfigReload(config string) {
  413. sigs := make(chan os.Signal, 1)
  414. signal.Notify(sigs, syscall.SIGHUP)
  415. for range sigs {
  416. log.Info("Partially hot reloading configuration ...")
  417. inputSource, err := newYamlSourceFromFile(config, flagsServe)
  418. if err != nil {
  419. log.Warn("Hot reload failed: %s", err.Error())
  420. continue
  421. }
  422. if err := reloadLogLevel(inputSource); err != nil {
  423. log.Warn("Reloading log level failed: %s", err.Error())
  424. }
  425. }
  426. }
  427. func parseIPHostPrefix(host string) (prefixes []netip.Prefix, err error) {
  428. // Try parsing as prefix, e.g. 10.0.1.0/24
  429. prefix, err := netip.ParsePrefix(host)
  430. if err == nil {
  431. prefixes = append(prefixes, prefix.Masked())
  432. return prefixes, nil
  433. }
  434. // Not a prefix, parse as host or IP (LookupHost passes through an IP as is)
  435. ips, err := net.LookupHost(host)
  436. if err != nil {
  437. return nil, err
  438. }
  439. for _, ipStr := range ips {
  440. ip, err := netip.ParseAddr(ipStr)
  441. if err == nil {
  442. prefix, err := ip.Prefix(ip.BitLen())
  443. if err != nil {
  444. return nil, fmt.Errorf("%s successfully parsed but unable to make prefix: %s", ip.String(), err.Error())
  445. }
  446. prefixes = append(prefixes, prefix.Masked())
  447. }
  448. }
  449. return
  450. }
  451. func reloadLogLevel(inputSource altsrc.InputSourceContext) error {
  452. newLevelStr, err := inputSource.String("log-level")
  453. if err != nil {
  454. return fmt.Errorf("cannot load log level: %s", err.Error())
  455. }
  456. overrides, err := inputSource.StringSlice("log-level-overrides")
  457. if err != nil {
  458. return fmt.Errorf("cannot load log level overrides (1): %s", err.Error())
  459. }
  460. log.ResetLevelOverrides()
  461. if err := applyLogLevelOverrides(overrides); err != nil {
  462. return fmt.Errorf("cannot load log level overrides (2): %s", err.Error())
  463. }
  464. log.SetLevel(log.ToLevel(newLevelStr))
  465. if len(overrides) > 0 {
  466. log.Info("Log level is %v, %d override(s) in place", strings.ToUpper(newLevelStr), len(overrides))
  467. } else {
  468. log.Info("Log level is %v", strings.ToUpper(newLevelStr))
  469. }
  470. return nil
  471. }