ntfy/cmd/serve.go

404 lines
25 KiB
Go
Raw Normal View History

//go:build !noserver
2021-12-17 01:33:01 +00:00
package cmd
import (
"errors"
2022-01-12 23:52:07 +00:00
"fmt"
2023-01-14 11:43:44 +00:00
"github.com/stripe/stripe-go/v74"
"heckel.io/ntfy/user"
2022-07-03 23:33:01 +00:00
"io/fs"
2022-01-12 23:52:07 +00:00
"math"
2022-02-14 21:09:59 +00:00
"net"
"net/netip"
2022-06-01 20:57:35 +00:00
"os"
"os/signal"
2022-01-20 18:20:04 +00:00
"strings"
2022-06-01 20:57:35 +00:00
"syscall"
2021-12-17 01:33:01 +00:00
"time"
"heckel.io/ntfy/log"
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
"heckel.io/ntfy/server"
"heckel.io/ntfy/util"
2021-12-17 01:33:01 +00:00
)
2022-05-09 15:03:40 +00:00
func init() {
commands = append(commands, cmdServe)
}
2022-06-01 20:57:35 +00:00
const (
defaultServerConfigFile = "/etc/ntfy/server.yml"
)
2022-05-30 02:14:14 +00:00
var flagsServe = append(
2023-02-06 04:34:27 +00:00
append([]cli.Flag{}, flagsDefault...),
2022-06-01 20:57:35 +00:00
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: defaultServerConfigFile, DefaultText: defaultServerConfigFile, Usage: "config file"},
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)"}),
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"}),
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"}),
altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-unix", Aliases: []string{"listen_unix", "U"}, EnvVars: []string{"NTFY_LISTEN_UNIX"}, Usage: "listen on unix socket path"}),
2022-07-03 23:33:01 +00:00
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"}),
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"}),
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"}),
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"}),
altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-file", Aliases: []string{"cache_file", "C"}, EnvVars: []string{"NTFY_CACHE_FILE"}, Usage: "cache file used for message caching"}),
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"}),
2022-11-16 15:28:20 +00:00
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)"}),
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)"}),
2022-06-23 15:02:45 +00:00
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"}),
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"}),
2023-01-05 20:20:44 +00:00
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"}),
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"}),
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"}),
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"}),
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)"}),
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)"}),
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"}),
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"}),
2023-02-09 13:32:51 +00:00
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"}),
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)"}),
2023-01-12 17:04:18 +00:00
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"}),
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"}),
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)"}),
2022-05-28 00:30:20 +00:00
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"}),
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"}),
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)"}),
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)"}),
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)"}),
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"}),
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"}),
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-')"}),
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"}),
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"}),
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"}),
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"}),
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"}),
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)"}),
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"}),
2023-01-27 03:57:18 +00:00
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"}),
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"}),
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)"}),
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)"}),
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"}),
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"}),
2023-02-28 19:38:31 +00:00
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)"}),
2022-05-30 02:14:14 +00:00
)
2021-12-17 01:33:01 +00:00
var cmdServe = &cli.Command{
Name: "serve",
Usage: "Run the ntfy server",
UsageText: "ntfy serve [OPTIONS..]",
Action: execServe,
2022-01-23 06:00:38 +00:00
Category: categoryServer,
2021-12-17 01:33:01 +00:00
Flags: flagsServe,
2022-06-01 20:57:35 +00:00
Before: initConfigFileInputSourceFunc("config", flagsServe, initLogFunc),
2021-12-17 01:33:01 +00:00
Description: `Run the ntfy server and listen for incoming requests
2021-12-19 03:02:36 +00:00
The command will load the configuration from /etc/ntfy/server.yml. Config options can
2021-12-17 01:33:01 +00:00
be overridden using the command line options.
Examples:
ntfy serve # Starts server in the foreground (on port 80)
ntfy serve --listen-http :8080 # Starts server with alternate port`,
}
func execServe(c *cli.Context) error {
if c.NArg() > 0 {
return errors.New("no arguments expected, see 'ntfy serve --help' for help")
}
2021-12-17 01:33:01 +00:00
// Read all the options
2022-06-01 20:57:35 +00:00
config := c.String("config")
2021-12-24 23:13:09 +00:00
baseURL := c.String("base-url")
2021-12-17 01:33:01 +00:00
listenHTTP := c.String("listen-http")
listenHTTPS := c.String("listen-https")
2022-01-10 21:28:13 +00:00
listenUnix := c.String("listen-unix")
2022-07-03 19:20:58 +00:00
listenUnixMode := c.Int("listen-unix-mode")
2021-12-17 01:33:01 +00:00
keyFile := c.String("key-file")
certFile := c.String("cert-file")
firebaseKeyFile := c.String("firebase-key-file")
cacheFile := c.String("cache-file")
cacheDuration := c.Duration("cache-duration")
2022-06-23 15:02:45 +00:00
cacheStartupQueries := c.String("cache-startup-queries")
2022-11-16 15:28:20 +00:00
cacheBatchSize := c.Int("cache-batch-size")
cacheBatchTimeout := c.Duration("cache-batch-timeout")
2022-01-23 04:01:20 +00:00
authFile := c.String("auth-file")
2023-01-05 20:20:44 +00:00
authStartupQueries := c.String("auth-startup-queries")
2022-01-23 06:00:38 +00:00
authDefaultAccess := c.String("auth-default-access")
2022-01-02 22:56:12 +00:00
attachmentCacheDir := c.String("attachment-cache-dir")
attachmentTotalSizeLimitStr := c.String("attachment-total-size-limit")
attachmentFileSizeLimitStr := c.String("attachment-file-size-limit")
2022-01-10 20:36:12 +00:00
attachmentExpiryDuration := c.Duration("attachment-expiry-duration")
2021-12-17 01:33:01 +00:00
keepaliveInterval := c.Duration("keepalive-interval")
managerInterval := c.Duration("manager-interval")
2023-02-09 13:32:51 +00:00
disallowedTopics := c.StringSlice("disallowed-topics")
2022-03-06 02:28:25 +00:00
webRoot := c.String("web-root")
2023-01-12 17:04:18 +00:00
enableSignup := c.Bool("enable-signup")
enableLogin := c.Bool("enable-login")
enableReservations := c.Bool("enable-reservations")
2022-05-28 00:30:20 +00:00
upstreamBaseURL := c.String("upstream-base-url")
2021-12-27 21:27:01 +00:00
smtpSenderAddr := c.String("smtp-sender-addr")
smtpSenderUser := c.String("smtp-sender-user")
smtpSenderPass := c.String("smtp-sender-pass")
smtpSenderFrom := c.String("smtp-sender-from")
2021-12-27 15:39:28 +00:00
smtpServerListen := c.String("smtp-server-listen")
smtpServerDomain := c.String("smtp-server-domain")
smtpServerAddrPrefix := c.String("smtp-server-addr-prefix")
totalTopicLimit := c.Int("global-topic-limit")
2021-12-17 01:33:01 +00:00
visitorSubscriptionLimit := c.Int("visitor-subscription-limit")
visitorAttachmentTotalSizeLimitStr := c.String("visitor-attachment-total-size-limit")
2022-01-13 02:24:48 +00:00
visitorAttachmentDailyBandwidthLimitStr := c.String("visitor-attachment-daily-bandwidth-limit")
2021-12-17 01:33:01 +00:00
visitorRequestLimitBurst := c.Int("visitor-request-limit-burst")
visitorRequestLimitReplenish := c.Duration("visitor-request-limit-replenish")
2022-02-14 21:09:59 +00:00
visitorRequestLimitExemptHosts := util.SplitNoEmpty(c.String("visitor-request-limit-exempt-hosts"), ",")
2023-01-27 03:57:18 +00:00
visitorMessageDailyLimit := c.Int("visitor-message-daily-limit")
2021-12-23 23:03:04 +00:00
visitorEmailLimitBurst := c.Int("visitor-email-limit-burst")
visitorEmailLimitReplenish := c.Duration("visitor-email-limit-replenish")
2021-12-17 01:33:01 +00:00
behindProxy := c.Bool("behind-proxy")
stripeSecretKey := c.String("stripe-secret-key")
2023-01-14 11:43:44 +00:00
stripeWebhookKey := c.String("stripe-webhook-key")
2023-02-28 19:38:31 +00:00
billingContact := c.String("billing-contact")
2021-12-17 01:33:01 +00:00
// Check values
if firebaseKeyFile != "" && !util.FileExists(firebaseKeyFile) {
return errors.New("if set, FCM key file must exist")
} else if keepaliveInterval < 5*time.Second {
return errors.New("keepalive interval cannot be lower than five seconds")
} else if managerInterval < 5*time.Second {
return errors.New("manager interval cannot be lower than five seconds")
} else if cacheDuration > 0 && cacheDuration < managerInterval {
return errors.New("cache duration cannot be lower than manager interval")
} else if keyFile != "" && !util.FileExists(keyFile) {
return errors.New("if set, key file must exist")
} else if certFile != "" && !util.FileExists(certFile) {
return errors.New("if set, certificate file must exist")
} else if listenHTTPS != "" && (keyFile == "" || certFile == "") {
return errors.New("if listen-https is set, both key-file and cert-file must be set")
2021-12-27 15:39:28 +00:00
} else if smtpSenderAddr != "" && (baseURL == "" || smtpSenderUser == "" || smtpSenderPass == "" || smtpSenderFrom == "") {
2021-12-28 16:36:12 +00:00
return errors.New("if smtp-sender-addr is set, base-url, smtp-sender-user, smtp-sender-pass and smtp-sender-from must also be set")
} else if smtpServerListen != "" && smtpServerDomain == "" {
return errors.New("if smtp-server-listen is set, smtp-server-domain must also be set")
2022-01-13 05:08:26 +00:00
} else if attachmentCacheDir != "" && baseURL == "" {
return errors.New("if attachment-cache-dir is set, base-url must also be set")
2022-10-01 19:23:14 +00:00
} else if baseURL != "" && !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") {
return errors.New("if set, base-url must start with http:// or https://")
} else if baseURL != "" && strings.HasSuffix(baseURL, "/") {
return errors.New("if set, base-url must not end with a slash (/)")
2022-10-01 19:50:48 +00:00
} else if !util.Contains([]string{"app", "home", "disable"}, webRoot) {
2022-03-06 02:28:25 +00:00
return errors.New("if set, web-root must be 'home' or 'app'")
2022-05-28 00:30:20 +00:00
} else if upstreamBaseURL != "" && !strings.HasPrefix(upstreamBaseURL, "http://") && !strings.HasPrefix(upstreamBaseURL, "https://") {
return errors.New("if set, upstream-base-url must start with http:// or https://")
2022-10-01 19:23:14 +00:00
} else if upstreamBaseURL != "" && strings.HasSuffix(upstreamBaseURL, "/") {
return errors.New("if set, upstream-base-url must not end with a slash (/)")
2022-05-29 00:20:46 +00:00
} else if upstreamBaseURL != "" && baseURL == "" {
return errors.New("if upstream-base-url is set, base-url must also be set")
} else if upstreamBaseURL != "" && baseURL != "" && baseURL == upstreamBaseURL {
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")
} else if authFile == "" && (enableSignup || enableLogin || enableReservations || stripeSecretKey != "") {
return errors.New("cannot set enable-signup, enable-login, enable-reserve-topics, or stripe-secret-key if auth-file is not set")
2023-01-12 17:04:18 +00:00
} else if enableSignup && !enableLogin {
return errors.New("cannot set enable-signup without also setting enable-login")
} else if stripeSecretKey != "" && (stripeWebhookKey == "" || baseURL == "") {
return errors.New("if stripe-secret-key is set, stripe-webhook-key and base-url must also be set")
2021-12-17 01:33:01 +00:00
}
2022-03-06 02:28:25 +00:00
webRootIsApp := webRoot == "app"
enableWeb := webRoot != "disable"
// Default auth permissions
authDefault, err := user.ParsePermission(authDefaultAccess)
if err != nil {
return errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
}
2022-01-23 04:01:20 +00:00
2022-01-15 01:16:12 +00:00
// Special case: Unset default
if listenHTTP == "-" {
listenHTTP = ""
}
// Convert sizes to bytes
attachmentTotalSizeLimit, err := parseSize(attachmentTotalSizeLimitStr, server.DefaultAttachmentTotalSizeLimit)
if err != nil {
return err
}
attachmentFileSizeLimit, err := parseSize(attachmentFileSizeLimitStr, server.DefaultAttachmentFileSizeLimit)
if err != nil {
return err
}
visitorAttachmentTotalSizeLimit, err := parseSize(visitorAttachmentTotalSizeLimitStr, server.DefaultVisitorAttachmentTotalSizeLimit)
if err != nil {
return err
2022-01-06 00:04:56 +00:00
}
2022-01-13 02:24:48 +00:00
visitorAttachmentDailyBandwidthLimit, err := parseSize(visitorAttachmentDailyBandwidthLimitStr, server.DefaultVisitorAttachmentDailyBandwidthLimit)
2022-01-12 23:52:07 +00:00
if err != nil {
return err
2022-01-13 02:24:48 +00:00
} else if visitorAttachmentDailyBandwidthLimit > math.MaxInt {
return fmt.Errorf("config option visitor-attachment-daily-bandwidth-limit must be lower than %d", math.MaxInt)
2021-12-17 01:33:01 +00:00
}
2022-02-14 21:09:59 +00:00
// Resolve hosts
visitorRequestLimitExemptIPs := make([]netip.Prefix, 0)
2022-02-14 21:09:59 +00:00
for _, host := range visitorRequestLimitExemptHosts {
ips, err := parseIPHostPrefix(host)
2022-02-14 21:09:59 +00:00
if err != nil {
2022-05-30 02:14:14 +00:00
log.Warn("cannot resolve host %s: %s, ignoring visitor request exemption", host, err.Error())
2022-02-14 21:09:59 +00:00
continue
}
2022-10-08 01:36:01 +00:00
visitorRequestLimitExemptIPs = append(visitorRequestLimitExemptIPs, ips...)
2022-02-14 21:09:59 +00:00
}
2023-01-14 11:43:44 +00:00
// Stripe things
if stripeSecretKey != "" {
2023-02-22 20:49:51 +00:00
stripe.EnableTelemetry = false // Whoa!
stripe.Key = stripeSecretKey
2023-01-14 11:43:44 +00:00
}
2023-02-09 13:32:51 +00:00
// Add default forbidden topics
disallowedTopics = append(disallowedTopics, server.DefaultDisallowedTopics...)
2021-12-17 01:33:01 +00:00
// Run server
2021-12-22 13:17:50 +00:00
conf := server.NewConfig()
2023-02-08 20:20:44 +00:00
conf.File = config
2021-12-24 23:13:09 +00:00
conf.BaseURL = baseURL
2021-12-22 13:17:50 +00:00
conf.ListenHTTP = listenHTTP
2021-12-17 01:33:01 +00:00
conf.ListenHTTPS = listenHTTPS
2022-01-10 21:28:13 +00:00
conf.ListenUnix = listenUnix
2022-07-03 19:20:58 +00:00
conf.ListenUnixMode = fs.FileMode(listenUnixMode)
2021-12-17 01:33:01 +00:00
conf.KeyFile = keyFile
conf.CertFile = certFile
conf.FirebaseKeyFile = firebaseKeyFile
conf.CacheFile = cacheFile
conf.CacheDuration = cacheDuration
2022-06-23 15:02:45 +00:00
conf.CacheStartupQueries = cacheStartupQueries
2022-11-16 15:28:20 +00:00
conf.CacheBatchSize = cacheBatchSize
conf.CacheBatchTimeout = cacheBatchTimeout
2022-01-23 04:01:20 +00:00
conf.AuthFile = authFile
2023-01-05 20:20:44 +00:00
conf.AuthStartupQueries = authStartupQueries
conf.AuthDefault = authDefault
2022-01-02 22:56:12 +00:00
conf.AttachmentCacheDir = attachmentCacheDir
conf.AttachmentTotalSizeLimit = attachmentTotalSizeLimit
conf.AttachmentFileSizeLimit = attachmentFileSizeLimit
2022-01-10 20:36:12 +00:00
conf.AttachmentExpiryDuration = attachmentExpiryDuration
2021-12-17 01:33:01 +00:00
conf.KeepaliveInterval = keepaliveInterval
conf.ManagerInterval = managerInterval
2023-02-09 13:32:51 +00:00
conf.DisallowedTopics = disallowedTopics
2022-03-06 02:28:25 +00:00
conf.WebRootIsApp = webRootIsApp
2022-05-28 00:30:20 +00:00
conf.UpstreamBaseURL = upstreamBaseURL
2021-12-27 15:39:28 +00:00
conf.SMTPSenderAddr = smtpSenderAddr
conf.SMTPSenderUser = smtpSenderUser
conf.SMTPSenderPass = smtpSenderPass
conf.SMTPSenderFrom = smtpSenderFrom
conf.SMTPServerListen = smtpServerListen
conf.SMTPServerDomain = smtpServerDomain
conf.SMTPServerAddrPrefix = smtpServerAddrPrefix
conf.TotalTopicLimit = totalTopicLimit
2021-12-17 01:33:01 +00:00
conf.VisitorSubscriptionLimit = visitorSubscriptionLimit
conf.VisitorAttachmentTotalSizeLimit = visitorAttachmentTotalSizeLimit
conf.VisitorAttachmentDailyBandwidthLimit = visitorAttachmentDailyBandwidthLimit
2021-12-17 01:33:01 +00:00
conf.VisitorRequestLimitBurst = visitorRequestLimitBurst
conf.VisitorRequestLimitReplenish = visitorRequestLimitReplenish
2022-02-14 21:09:59 +00:00
conf.VisitorRequestExemptIPAddrs = visitorRequestLimitExemptIPs
2023-01-27 03:57:18 +00:00
conf.VisitorMessageDailyLimit = visitorMessageDailyLimit
2021-12-23 23:03:04 +00:00
conf.VisitorEmailLimitBurst = visitorEmailLimitBurst
conf.VisitorEmailLimitReplenish = visitorEmailLimitReplenish
2021-12-17 01:33:01 +00:00
conf.BehindProxy = behindProxy
conf.StripeSecretKey = stripeSecretKey
2023-01-14 11:43:44 +00:00
conf.StripeWebhookKey = stripeWebhookKey
2023-02-28 19:38:31 +00:00
conf.BillingContact = billingContact
conf.EnableWeb = enableWeb
2022-12-15 04:11:22 +00:00
conf.EnableSignup = enableSignup
conf.EnableLogin = enableLogin
2023-01-10 01:37:13 +00:00
conf.EnableReservations = enableReservations
conf.Version = c.App.Version
2022-06-01 20:57:35 +00:00
// Set up hot-reloading of config
go sigHandlerConfigReload(config)
// Run server
2021-12-17 01:33:01 +00:00
s, err := server.New(conf)
if err != nil {
2023-02-04 03:21:50 +00:00
log.Fatal(err.Error())
2022-06-01 20:57:35 +00:00
} else if err := s.Run(); err != nil {
2023-02-04 03:21:50 +00:00
log.Fatal(err.Error())
2021-12-17 01:33:01 +00:00
}
2022-05-30 02:14:14 +00:00
log.Info("Exiting.")
2021-12-17 01:33:01 +00:00
return nil
}
func parseSize(s string, defaultValue int64) (v int64, err error) {
if s == "" {
return defaultValue, nil
}
v, err = util.ParseSize(s)
if err != nil {
return 0, err
}
return v, nil
}
2022-06-01 20:57:35 +00:00
func sigHandlerConfigReload(config string) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGHUP)
for range sigs {
log.Info("Partially hot reloading configuration ...")
inputSource, err := newYamlSourceFromFile(config, flagsServe)
if err != nil {
log.Warn("Hot reload failed: %s", err.Error())
continue
}
2023-02-04 03:21:50 +00:00
if err := reloadLogLevel(inputSource); err != nil {
log.Warn("Reloading log level failed: %s", err.Error())
}
2022-06-01 20:57:35 +00:00
}
}
func parseIPHostPrefix(host string) (prefixes []netip.Prefix, err error) {
2022-10-08 21:58:05 +00:00
// Try parsing as prefix, e.g. 10.0.1.0/24
2022-10-07 21:16:20 +00:00
prefix, err := netip.ParsePrefix(host)
if err == nil {
2022-10-08 21:58:05 +00:00
prefixes = append(prefixes, prefix.Masked())
return prefixes, nil
2022-10-07 21:16:20 +00:00
}
2022-10-08 21:58:05 +00:00
// Not a prefix, parse as host or IP (LookupHost passes through an IP as is)
2022-10-07 21:16:20 +00:00
ips, err := net.LookupHost(host)
2022-10-07 21:24:11 +00:00
if err != nil {
return nil, err
}
2022-10-08 21:58:05 +00:00
for _, ipStr := range ips {
ip, err := netip.ParseAddr(ipStr)
2022-10-07 21:24:11 +00:00
if err == nil {
prefix, err := ip.Prefix(ip.BitLen())
if err != nil {
return nil, fmt.Errorf("%s successfully parsed but unable to make prefix: %s", ip.String(), err.Error())
2022-10-07 21:16:20 +00:00
}
2022-10-08 21:58:05 +00:00
prefixes = append(prefixes, prefix.Masked())
2022-10-07 21:16:20 +00:00
}
}
return
}
2023-02-04 03:21:50 +00:00
func reloadLogLevel(inputSource altsrc.InputSourceContext) error {
2022-06-01 20:57:35 +00:00
newLevelStr, err := inputSource.String("log-level")
if err != nil {
2023-02-04 03:21:50 +00:00
return fmt.Errorf("cannot load log level: %s", err.Error())
}
overrides, err := inputSource.StringSlice("log-level-overrides")
if err != nil {
return fmt.Errorf("cannot load log level overrides (1): %s", err.Error())
2022-06-01 20:57:35 +00:00
}
2023-02-06 04:34:27 +00:00
log.ResetLevelOverrides()
2023-02-04 03:21:50 +00:00
if err := applyLogLevelOverrides(overrides); err != nil {
return fmt.Errorf("cannot load log level overrides (2): %s", err.Error())
}
log.SetLevel(log.ToLevel(newLevelStr))
if len(overrides) > 0 {
log.Info("Log level is %v, %d override(s) in place", strings.ToUpper(newLevelStr), len(overrides))
} else {
log.Info("Log level is %v", strings.ToUpper(newLevelStr))
}
return nil
2022-06-01 20:57:35 +00:00
}