serve.go 25 KB

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