| 1 |
package server |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"crypto/sha256" |
| 7 |
"embed" |
| 8 |
"encoding/base64" |
| 9 |
"encoding/json" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"net" |
| 14 |
"net/http" |
| 15 |
"net/http/pprof" |
| 16 |
"net/netip" |
| 17 |
"net/url" |
| 18 |
"os" |
| 19 |
"path" |
| 20 |
"regexp" |
| 21 |
"sort" |
| 22 |
"strconv" |
| 23 |
"strings" |
| 24 |
"sync" |
| 25 |
"time" |
| 26 |
"unicode/utf8" |
| 27 |
|
| 28 |
"github.com/emersion/go-smtp" |
| 29 |
"github.com/gorilla/websocket" |
| 30 |
"github.com/prometheus/client_golang/prometheus/promhttp" |
| 31 |
"golang.org/x/sync/errgroup" |
| 32 |
"heckel.io/ntfy/v2/action" |
| 33 |
"heckel.io/ntfy/v2/attachment" |
| 34 |
"heckel.io/ntfy/v2/ban" |
| 35 |
"heckel.io/ntfy/v2/db" |
| 36 |
"heckel.io/ntfy/v2/db/pg" |
| 37 |
"heckel.io/ntfy/v2/log" |
| 38 |
"heckel.io/ntfy/v2/mail" |
| 39 |
"heckel.io/ntfy/v2/message" |
| 40 |
"heckel.io/ntfy/v2/metrics" |
| 41 |
"heckel.io/ntfy/v2/model" |
| 42 |
"heckel.io/ntfy/v2/payments" |
| 43 |
"heckel.io/ntfy/v2/twilio" |
| 44 |
"heckel.io/ntfy/v2/user" |
| 45 |
"heckel.io/ntfy/v2/util" |
| 46 |
"heckel.io/ntfy/v2/webpush" |
| 47 |
) |
| 48 |
|
| 49 |
// Server is the main server, providing the UI and API for ntfy |
| 50 |
type Server struct { |
| 51 |
config *Config |
| 52 |
db *db.DB // Shared PostgreSQL connection pool (with optional replicas), nil when using SQLite |
| 53 |
httpServer *http.Server |
| 54 |
httpsServer *http.Server |
| 55 |
httpMetricsServer *http.Server |
| 56 |
httpProfileServer *http.Server |
| 57 |
unixListener net.Listener |
| 58 |
smtpServer *smtp.Server |
| 59 |
smtpServerBackend *smtpBackend |
| 60 |
mailer mail.Sender |
| 61 |
topics map[string]*topic |
| 62 |
visitors map[string]*visitor // ip:<ip> or user:<user> |
| 63 |
ban *ban.Service // Abuse ban-feed; nil when the feature is disabled (no ban file) |
| 64 |
firebaseClient *firebaseClient |
| 65 |
twilio *twilio.Client |
| 66 |
messages int64 // Total number of messages (persisted if messageCache enabled) |
| 67 |
messagesHistory []int64 // Last n values of the messages counter, used to determine rate |
| 68 |
userManager *user.Manager // Might be nil! |
| 69 |
messageCache *message.Cache // Database that stores the messages |
| 70 |
webPush *webpush.Store // Database that stores web push subscriptions |
| 71 |
attachment *attachment.Store // Attachment store (file system or S3) |
| 72 |
stripe stripeAPI // Stripe API, can be replaced with a mock |
| 73 |
priceCache *util.LookupCache[map[string]int64] // Stripe price ID -> price as cents (USD implied!) |
| 74 |
metricsHandler http.Handler // Handles /metrics if enable-metrics set, and listen-metrics-http not set |
| 75 |
closeChan chan bool |
| 76 |
mu sync.RWMutex |
| 77 |
} |
| 78 |
|
| 79 |
// handleFunc extends the normal http.HandlerFunc to be able to easily return errors |
| 80 |
type handleFunc func(http.ResponseWriter, *http.Request, *visitor) error |
| 81 |
|
| 82 |
var ( |
| 83 |
// If changed, don't forget to update Android App and auth_sqlite.go |
| 84 |
topicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No /! |
| 85 |
topicPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}$`) // Regex must match JS & Android app! |
| 86 |
externalTopicPathRegex = regexp.MustCompile(`^/[^/]+\.[^/]+/[-_A-Za-z0-9]{1,64}$`) // Extended topic path, for web-app, e.g. /example.com/mytopic |
| 87 |
jsonPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/json$`) |
| 88 |
ssePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/sse$`) |
| 89 |
rawPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/raw$`) |
| 90 |
wsPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/ws$`) |
| 91 |
authPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/auth$`) |
| 92 |
publishPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/(publish|send|trigger)$`) |
| 93 |
updatePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/[-_A-Za-z0-9]{1,64}$`) |
| 94 |
clearPathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/[-_A-Za-z0-9]{1,64}/(read|clear)$`) |
| 95 |
deletePathRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}/[-_A-Za-z0-9]{1,64}/delete$`) |
| 96 |
sequenceIDRegex = topicRegex |
| 97 |
|
| 98 |
webAppConfigPath = "/config.js" |
| 99 |
webAppManifestPath = "/manifest.webmanifest" |
| 100 |
webAppEmailVerifyPathPrefix = "/account/email/verify/" // Browser landing route; raw token appended |
| 101 |
webAppEmailVerifyRegex = regexp.MustCompile(`^/account/email/verify/[-_A-Za-z0-9]+$`) // Magic-link landing (served by the web app) |
| 102 |
webAppPasswordResetPathPrefix = "/account/password/reset/" // Browser landing route; raw token appended |
| 103 |
webAppPasswordResetRegex = regexp.MustCompile(`^/account/password/reset/[-_A-Za-z0-9]+$`) // Password-reset landing (served by the web app) |
| 104 |
|
| 105 |
accountPath = "/account" |
| 106 |
matrixPushPath = "/_matrix/push/v1/notify" |
| 107 |
metricsPath = "/metrics" |
| 108 |
apiHealthPath = "/v1/health" |
| 109 |
apiVersionPath = "/v1/version" |
| 110 |
apiConfigPath = "/v1/config" |
| 111 |
apiStatsPath = "/v1/stats" |
| 112 |
apiWebPushPath = "/v1/webpush" |
| 113 |
apiTiersPath = "/v1/tiers" |
| 114 |
apiUsersPath = "/v1/users" |
| 115 |
apiUsersAccessPath = "/v1/users/access" |
| 116 |
apiAccountPath = "/v1/account" |
| 117 |
apiAccountLoginPath = "/v1/account/login" |
| 118 |
apiAccountTokenPath = "/v1/account/token" |
| 119 |
apiAccountPasswordPath = "/v1/account/password" |
| 120 |
apiAccountSettingsPath = "/v1/account/settings" |
| 121 |
apiAccountSubscriptionPath = "/v1/account/subscription" |
| 122 |
apiAccountReservationPath = "/v1/account/reservation" |
| 123 |
apiAccountPhonePath = "/v1/account/phone" |
| 124 |
apiAccountPhoneVerifyPath = "/v1/account/phone/verify" |
| 125 |
apiAccountEmailPath = "/v1/account/email" |
| 126 |
apiAccountEmailVerifyPath = "/v1/account/email/verify" |
| 127 |
apiAccountEmailPrimaryPath = "/v1/account/email/primary" |
| 128 |
apiAccountEmailResendPath = "/v1/account/email/resend" |
| 129 |
apiAccountPasswordResetRequestPath = "/v1/account/password/reset/request" |
| 130 |
apiAccountPasswordResetPath = "/v1/account/password/reset" |
| 131 |
apiAccountBillingPortalPath = "/v1/account/billing/portal" |
| 132 |
apiAccountBillingWebhookPath = "/v1/account/billing/webhook" |
| 133 |
apiAccountBillingSubscriptionPath = "/v1/account/billing/subscription" |
| 134 |
apiAccountBillingSubscriptionCheckoutSuccessTemplate = "/v1/account/billing/subscription/success/{CHECKOUT_SESSION_ID}" |
| 135 |
apiAccountBillingSubscriptionCheckoutSuccessRegex = regexp.MustCompile(`/v1/account/billing/subscription/success/(.+)$`) |
| 136 |
apiAccountReservationSingleRegex = regexp.MustCompile(`/v1/account/reservation/([-_A-Za-z0-9]{1,64})$`) |
| 137 |
staticRegex = regexp.MustCompile(`^/(static/.+|app.html|sw.js|sw.js.map)$`) |
| 138 |
docsRegex = regexp.MustCompile(`^/docs(|/.*)$`) |
| 139 |
fileRegex = regexp.MustCompile(`^/file/([-_A-Za-z0-9]{1,64})(?:\.[A-Za-z0-9]{1,16})?$`) |
| 140 |
urlRegex = regexp.MustCompile(`^https?://`) |
| 141 |
phoneNumberRegex = regexp.MustCompile(`^\+\d{1,100}$`) |
| 142 |
emailAddressRegex = regexp.MustCompile(`^[^\s,;]+@[^\s,;]+$`) |
| 143 |
|
| 144 |
//go:embed site |
| 145 |
webFs embed.FS |
| 146 |
webFsCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: webFs} |
| 147 |
webSiteDir = "/site" |
| 148 |
webAppIndex = "/app.html" // React app |
| 149 |
|
| 150 |
//go:embed docs |
| 151 |
docsStaticFs embed.FS |
| 152 |
docsStaticCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: docsStaticFs} |
| 153 |
) |
| 154 |
|
| 155 |
const ( |
| 156 |
firebaseControlTopic = "~control" // See Android if changed |
| 157 |
firebasePollTopic = "~poll" // See iOS if changed (DISABLED for now) |
| 158 |
emptyMessageBody = "triggered" // Used when a message body is empty |
| 159 |
newMessageBody = "New message" // Used in poll requests as generic message |
| 160 |
defaultAttachmentMessage = "You received a file: %s" // Used if message body is empty, and there is an attachment |
| 161 |
encodingBase64 = "base64" // Used mainly for binary UnifiedPush messages |
| 162 |
jsonBodyBytesLimit = 131072 // Max number of bytes for a request bodys (unless MessageLimit is higher) |
| 163 |
unifiedPushTopicPrefix = "up" // Temporarily, we rate limit all "up*" topics based on the subscriber |
| 164 |
unifiedPushTopicLength = 14 // Length of UnifiedPush topics, including the "up" part |
| 165 |
messagesHistoryMax = 10 // Number of message count values to keep in memory |
| 166 |
) |
| 167 |
|
| 168 |
// WebSocket constants |
| 169 |
const ( |
| 170 |
wsWriteWait = 2 * time.Second |
| 171 |
wsBufferSize = 1024 |
| 172 |
wsReadLimit = 64 // We only ever receive PINGs |
| 173 |
wsPongWait = 15 * time.Second |
| 174 |
) |
| 175 |
|
| 176 |
// New instantiates a new Server. It creates the cache and adds a Firebase |
| 177 |
// subscriber (if configured). |
| 178 |
func New(conf *Config) (*Server, error) { |
| 179 |
var sender mail.Sender |
| 180 |
if conf.SMTPSenderAddr != "" { |
| 181 |
sender = mail.NewSender(&mail.Config{ |
| 182 |
BaseURL: conf.BaseURL, |
| 183 |
SMTPAddr: conf.SMTPSenderAddr, |
| 184 |
SMTPUser: conf.SMTPSenderUser, |
| 185 |
SMTPPass: conf.SMTPSenderPass, |
| 186 |
From: conf.SMTPSenderFrom, |
| 187 |
}) |
| 188 |
} |
| 189 |
var stripe stripeAPI |
| 190 |
if payments.Available && conf.StripeSecretKey != "" { |
| 191 |
stripe = newStripeAPI() |
| 192 |
} |
| 193 |
// Open shared PostgreSQL connection pool if configured |
| 194 |
var pool *db.DB |
| 195 |
if conf.DatabaseURL != "" { |
| 196 |
primary, err := pg.Open(conf.DatabaseURL) |
| 197 |
if err != nil { |
| 198 |
return nil, err |
| 199 |
} |
| 200 |
var replicas []*db.Host |
| 201 |
for _, replicaURL := range conf.DatabaseReplicaURLs { |
| 202 |
r, err := pg.OpenReplica(replicaURL) |
| 203 |
if err != nil { |
| 204 |
// Close already-opened replicas before returning |
| 205 |
for _, opened := range replicas { |
| 206 |
opened.DB.Close() |
| 207 |
} |
| 208 |
primary.DB.Close() |
| 209 |
return nil, fmt.Errorf("failed to open database replica: %w", err) |
| 210 |
} |
| 211 |
replicas = append(replicas, r) |
| 212 |
} |
| 213 |
pool = db.New(primary, replicas) |
| 214 |
} |
| 215 |
messageCache, err := createMessageCache(conf, pool) |
| 216 |
if err != nil { |
| 217 |
return nil, err |
| 218 |
} |
| 219 |
var wp *webpush.Store |
| 220 |
if conf.WebPushPublicKey != "" { |
| 221 |
if pool != nil { |
| 222 |
wp, err = webpush.NewPostgresStore(pool) |
| 223 |
} else { |
| 224 |
wp, err = webpush.NewSQLiteStore(conf.WebPushFile, conf.WebPushStartupQueries) |
| 225 |
} |
| 226 |
if err != nil { |
| 227 |
return nil, err |
| 228 |
} |
| 229 |
} |
| 230 |
topicIDs, err := messageCache.Topics() |
| 231 |
if err != nil { |
| 232 |
return nil, err |
| 233 |
} |
| 234 |
topics := make(map[string]*topic, len(topicIDs)) |
| 235 |
for _, id := range topicIDs { |
| 236 |
topics[id] = newTopic(id) |
| 237 |
} |
| 238 |
messages, err := messageCache.Stats() |
| 239 |
if err != nil { |
| 240 |
return nil, err |
| 241 |
} |
| 242 |
attachmentStore, err := createAttachmentStore(conf, messageCache) |
| 243 |
if err != nil { |
| 244 |
return nil, err |
| 245 |
} |
| 246 |
twilioClient := twilio.NewClient(&twilio.Config{ |
| 247 |
Account: conf.TwilioAccount, |
| 248 |
AuthToken: conf.TwilioAuthToken, |
| 249 |
PhoneNumber: conf.TwilioPhoneNumber, |
| 250 |
CallsBaseURL: conf.TwilioCallsBaseURL, |
| 251 |
VerifyBaseURL: conf.TwilioVerifyBaseURL, |
| 252 |
VerifyService: conf.TwilioVerifyService, |
| 253 |
CallFormat: conf.TwilioCallFormat, |
| 254 |
BuildVersion: conf.BuildVersion, |
| 255 |
}) |
| 256 |
var userManager *user.Manager |
| 257 |
if conf.AuthFile != "" || pool != nil { |
| 258 |
authConfig := &user.Config{ |
| 259 |
Filename: conf.AuthFile, |
| 260 |
DatabaseURL: conf.DatabaseURL, |
| 261 |
StartupQueries: conf.AuthStartupQueries, |
| 262 |
DefaultAccess: conf.AuthDefault, |
| 263 |
ProvisionEnabled: true, // Enable provisioning of users and access |
| 264 |
Users: conf.AuthUsers, |
| 265 |
Access: conf.AuthAccess, |
| 266 |
Tokens: conf.AuthTokens, |
| 267 |
BcryptCost: conf.AuthBcryptCost, |
| 268 |
QueueWriterInterval: conf.AuthStatsQueueWriterInterval, |
| 269 |
AccessCacheEnabled: conf.AuthAccessCacheEnabled, |
| 270 |
AccessCacheReloadInterval: conf.AuthAccessCacheReloadInterval, |
| 271 |
} |
| 272 |
if pool != nil { |
| 273 |
userManager, err = user.NewPostgresManager(pool, authConfig) |
| 274 |
} else { |
| 275 |
userManager, err = user.NewSQLiteManager(conf.AuthFile, conf.AuthStartupQueries, authConfig) |
| 276 |
} |
| 277 |
if err != nil { |
| 278 |
return nil, err |
| 279 |
} |
| 280 |
} |
| 281 |
var firebaseClient *firebaseClient |
| 282 |
if conf.FirebaseKeyFile != "" { |
| 283 |
sender, err := newFirebaseSender(conf.FirebaseKeyFile) |
| 284 |
if err != nil { |
| 285 |
return nil, err |
| 286 |
} |
| 287 |
// This awkward logic is required because Go is weird about nil types and interfaces. |
| 288 |
// See issue #641, and https://go.dev/play/p/uur1flrv1t3 for an example |
| 289 |
var auther user.Auther |
| 290 |
if userManager != nil { |
| 291 |
auther = userManager |
| 292 |
} |
| 293 |
firebaseClient = newFirebaseClient(sender, auther) |
| 294 |
} |
| 295 |
var banner *ban.Service |
| 296 |
if conf.BanFile != "" { |
| 297 |
banner = ban.NewService(&ban.Config{ |
| 298 |
File: conf.BanFile, |
| 299 |
Window: conf.BanWindow, |
| 300 |
Threshold: conf.BanThreshold, |
| 301 |
Weights: conf.BanWeights, |
| 302 |
PrefixBitsIPv4: conf.VisitorPrefixBitsIPv4, |
| 303 |
PrefixBitsIPv6: conf.VisitorPrefixBitsIPv6, |
| 304 |
}) |
| 305 |
} |
| 306 |
s := &Server{ |
| 307 |
config: conf, |
| 308 |
db: pool, |
| 309 |
messageCache: messageCache, |
| 310 |
webPush: wp, |
| 311 |
attachment: attachmentStore, |
| 312 |
firebaseClient: firebaseClient, |
| 313 |
twilio: twilioClient, |
| 314 |
mailer: sender, |
| 315 |
ban: banner, |
| 316 |
topics: topics, |
| 317 |
userManager: userManager, |
| 318 |
messages: messages, |
| 319 |
messagesHistory: []int64{messages}, |
| 320 |
visitors: make(map[string]*visitor), |
| 321 |
stripe: stripe, |
| 322 |
} |
| 323 |
s.priceCache = util.NewLookupCache(s.fetchStripePrices, conf.StripePriceCacheDuration) |
| 324 |
return s, nil |
| 325 |
} |
| 326 |
|
| 327 |
func createMessageCache(conf *Config, pool *db.DB) (*message.Cache, error) { |
| 328 |
if conf.CacheDuration == 0 { |
| 329 |
return message.NewNopStore() |
| 330 |
} else if pool != nil { |
| 331 |
return message.NewPostgresStore(pool, conf.CacheBatchSize, conf.CacheBatchTimeout) |
| 332 |
} else if conf.CacheFile != "" { |
| 333 |
return message.NewSQLiteStore(conf.CacheFile, conf.CacheStartupQueries, conf.CacheDuration, conf.CacheBatchSize, conf.CacheBatchTimeout, false) |
| 334 |
} |
| 335 |
return message.NewMemStore() |
| 336 |
} |
| 337 |
|
| 338 |
func createAttachmentStore(conf *Config, messageCache *message.Cache) (*attachment.Store, error) { |
| 339 |
if strings.HasPrefix(conf.AttachmentCacheDir, "s3://") { |
| 340 |
return attachment.NewS3Store(conf.AttachmentCacheDir, conf.AttachmentTotalSizeLimit, conf.AttachmentOrphanGracePeriod, messageCache.AttachmentsWithSizes) |
| 341 |
} else if conf.AttachmentCacheDir != "" { |
| 342 |
return attachment.NewFileStore(conf.AttachmentCacheDir, conf.AttachmentTotalSizeLimit, conf.AttachmentOrphanGracePeriod, messageCache.AttachmentsWithSizes) |
| 343 |
} |
| 344 |
return nil, nil |
| 345 |
} |
| 346 |
|
| 347 |
// Run executes the main server. It listens on HTTP (+ HTTPS, if configured), and starts |
| 348 |
// a manager go routine to print stats and prune messages. |
| 349 |
func (s *Server) Run() error { |
| 350 |
var listenStr string |
| 351 |
if s.config.ListenHTTP != "" { |
| 352 |
listenStr += fmt.Sprintf(" %s[http]", s.config.ListenHTTP) |
| 353 |
} |
| 354 |
if s.config.ListenHTTPS != "" { |
| 355 |
listenStr += fmt.Sprintf(" %s[https]", s.config.ListenHTTPS) |
| 356 |
} |
| 357 |
if s.config.ListenUnix != "" { |
| 358 |
listenStr += fmt.Sprintf(" %s[unix]", s.config.ListenUnix) |
| 359 |
} |
| 360 |
if s.config.SMTPServerListen != "" { |
| 361 |
listenStr += fmt.Sprintf(" %s[smtp]", s.config.SMTPServerListen) |
| 362 |
} |
| 363 |
if s.config.MetricsListenHTTP != "" { |
| 364 |
listenStr += fmt.Sprintf(" %s[http/metrics]", s.config.MetricsListenHTTP) |
| 365 |
} |
| 366 |
if s.config.ProfileListenHTTP != "" { |
| 367 |
listenStr += fmt.Sprintf(" %s[http/profile]", s.config.ProfileListenHTTP) |
| 368 |
} |
| 369 |
log.Tag(tagStartup).Info("Listening on%s, ntfy %s, log level is %s", listenStr, s.config.BuildVersion, log.CurrentLevel().String()) |
| 370 |
if log.IsFile() { |
| 371 |
fmt.Fprintf(os.Stderr, "Listening on%s, ntfy %s\n", listenStr, s.config.BuildVersion) |
| 372 |
fmt.Fprintf(os.Stderr, "Logs are written to %s\n", log.File()) |
| 373 |
} |
| 374 |
mux := http.NewServeMux() |
| 375 |
mux.HandleFunc("/", s.handle) |
| 376 |
errChan := make(chan error) |
| 377 |
s.mu.Lock() |
| 378 |
s.closeChan = make(chan bool) |
| 379 |
if s.config.ListenHTTP != "" { |
| 380 |
s.httpServer = &http.Server{Addr: s.config.ListenHTTP, Handler: mux} |
| 381 |
go func() { |
| 382 |
errChan <- s.httpServer.ListenAndServe() |
| 383 |
}() |
| 384 |
} |
| 385 |
if s.config.ListenHTTPS != "" { |
| 386 |
s.httpsServer = &http.Server{Addr: s.config.ListenHTTPS, Handler: mux} |
| 387 |
go func() { |
| 388 |
errChan <- s.httpsServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile) |
| 389 |
}() |
| 390 |
} |
| 391 |
if s.config.ListenUnix != "" { |
| 392 |
go func() { |
| 393 |
var err error |
| 394 |
s.mu.Lock() |
| 395 |
os.Remove(s.config.ListenUnix) |
| 396 |
s.unixListener, err = net.Listen("unix", s.config.ListenUnix) |
| 397 |
if err != nil { |
| 398 |
s.mu.Unlock() |
| 399 |
errChan <- err |
| 400 |
return |
| 401 |
} |
| 402 |
defer s.unixListener.Close() |
| 403 |
if s.config.ListenUnixMode > 0 { |
| 404 |
if err := os.Chmod(s.config.ListenUnix, s.config.ListenUnixMode); err != nil { |
| 405 |
s.mu.Unlock() |
| 406 |
errChan <- err |
| 407 |
return |
| 408 |
} |
| 409 |
} |
| 410 |
s.mu.Unlock() |
| 411 |
httpServer := &http.Server{Handler: mux} |
| 412 |
errChan <- httpServer.Serve(s.unixListener) |
| 413 |
}() |
| 414 |
} |
| 415 |
if s.config.MetricsListenHTTP != "" { |
| 416 |
s.httpMetricsServer = &http.Server{Addr: s.config.MetricsListenHTTP, Handler: promhttp.Handler()} |
| 417 |
go func() { |
| 418 |
errChan <- s.httpMetricsServer.ListenAndServe() |
| 419 |
}() |
| 420 |
} else if s.config.EnableMetrics { |
| 421 |
s.metricsHandler = promhttp.Handler() |
| 422 |
} |
| 423 |
if s.config.ProfileListenHTTP != "" { |
| 424 |
profileMux := http.NewServeMux() |
| 425 |
profileMux.HandleFunc("/debug/pprof/", pprof.Index) |
| 426 |
profileMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) |
| 427 |
profileMux.HandleFunc("/debug/pprof/profile", pprof.Profile) |
| 428 |
profileMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) |
| 429 |
profileMux.HandleFunc("/debug/pprof/trace", pprof.Trace) |
| 430 |
s.httpProfileServer = &http.Server{Addr: s.config.ProfileListenHTTP, Handler: profileMux} |
| 431 |
go func() { |
| 432 |
errChan <- s.httpProfileServer.ListenAndServe() |
| 433 |
}() |
| 434 |
} |
| 435 |
if s.config.SMTPServerListen != "" { |
| 436 |
go func() { |
| 437 |
errChan <- s.runSMTPServer() |
| 438 |
}() |
| 439 |
} |
| 440 |
s.mu.Unlock() |
| 441 |
go s.runManager() |
| 442 |
go s.runStatsResetter() |
| 443 |
go s.runDelayedSender() |
| 444 |
go s.runFirebaseKeepaliver() |
| 445 |
|
| 446 |
return <-errChan |
| 447 |
} |
| 448 |
|
| 449 |
// Stop stops HTTP (+HTTPS) server and all managers |
| 450 |
func (s *Server) Stop() { |
| 451 |
s.mu.Lock() |
| 452 |
defer s.mu.Unlock() |
| 453 |
if s.httpServer != nil { |
| 454 |
s.httpServer.Close() |
| 455 |
} |
| 456 |
if s.httpsServer != nil { |
| 457 |
s.httpsServer.Close() |
| 458 |
} |
| 459 |
if s.unixListener != nil { |
| 460 |
s.unixListener.Close() |
| 461 |
} |
| 462 |
if s.smtpServer != nil { |
| 463 |
s.smtpServer.Close() |
| 464 |
} |
| 465 |
if s.attachment != nil { |
| 466 |
s.attachment.Close() |
| 467 |
} |
| 468 |
s.closeDatabases() |
| 469 |
if s.ban != nil { |
| 470 |
s.ban.Close() |
| 471 |
} |
| 472 |
if s.closeChan != nil { |
| 473 |
close(s.closeChan) |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
func (s *Server) closeDatabases() { |
| 478 |
if s.userManager != nil { |
| 479 |
s.userManager.Close() |
| 480 |
} |
| 481 |
if s.messageCache != nil { |
| 482 |
s.messageCache.Close() |
| 483 |
} |
| 484 |
if s.webPush != nil { |
| 485 |
s.webPush.Close() |
| 486 |
} |
| 487 |
if s.db != nil { |
| 488 |
s.db.Close() |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
// handle is the main entry point for all HTTP requests |
| 493 |
func (s *Server) handle(w http.ResponseWriter, r *http.Request) { |
| 494 |
r, v, err := s.maybeAuthenticate(r) // Note: Always returns v (and r, with the client IP in its context), even on error |
| 495 |
if err != nil { |
| 496 |
s.handleError(w, r, v, err) |
| 497 |
return |
| 498 |
} |
| 499 |
ev := logvr(v, r) |
| 500 |
if ev.IsTrace() { |
| 501 |
ev.Field("http_request", renderHTTPRequest(r)).Trace("HTTP request started") |
| 502 |
} else if logvr(v, r).IsDebug() { |
| 503 |
ev.Debug("HTTP request started") |
| 504 |
} |
| 505 |
logvr(v, r). |
| 506 |
Timing(func() { |
| 507 |
if err := s.handleInternal(w, r, v); err != nil { |
| 508 |
s.handleError(w, r, v, err) |
| 509 |
return |
| 510 |
} |
| 511 |
metrics.HTTPRequests.WithLabelValues("200", "20000", r.Method).Inc() |
| 512 |
}). |
| 513 |
Debug("HTTP request finished") |
| 514 |
} |
| 515 |
|
| 516 |
func (s *Server) handleError(w http.ResponseWriter, r *http.Request, v *visitor, err error) { |
| 517 |
httpErr, ok := err.(*errHTTP) |
| 518 |
if !ok { |
| 519 |
httpErr = errHTTPInternalError |
| 520 |
} |
| 521 |
metrics.HTTPRequests.WithLabelValues(strconv.Itoa(httpErr.HTTPCode), strconv.Itoa(httpErr.Code), r.Method).Inc() |
| 522 |
isRateLimiting := util.Contains(rateLimitingErrorCodes, httpErr.HTTPCode) |
| 523 |
isNormalError := strings.Contains(err.Error(), "i/o timeout") || util.Contains(normalErrorCodes, httpErr.HTTPCode) |
| 524 |
ev := logvr(v, r).Err(err) |
| 525 |
if websocket.IsWebSocketUpgrade(r) { |
| 526 |
ev.Tag(tagWebsocket).Fields(websocketErrorContext(err)) |
| 527 |
if isNormalError { |
| 528 |
ev.Debug("WebSocket error (this error is okay, it happens a lot): %s", err.Error()) |
| 529 |
} else { |
| 530 |
ev.Info("WebSocket error: %s", err.Error()) |
| 531 |
} |
| 532 |
// Write error response only if the connection was not hijacked yet. Bytes written to hijacked |
| 533 |
// connections are WebSocket frames, not HTTP, and will cause "http: response.WriteHeader on hijacked |
| 534 |
// connection" log spam. |
| 535 |
var postUpgradeErr *errWebSocketPostUpgrade |
| 536 |
if !errors.As(err, &postUpgradeErr) { |
| 537 |
w.WriteHeader(httpErr.HTTPCode) |
| 538 |
} |
| 539 |
return |
| 540 |
} |
| 541 |
if isNormalError { |
| 542 |
ev.Debug("Connection closed with HTTP %d (ntfy error %d)", httpErr.HTTPCode, httpErr.Code) |
| 543 |
} else { |
| 544 |
ev.Info("Connection closed with HTTP %d (ntfy error %d)", httpErr.HTTPCode, httpErr.Code) |
| 545 |
} |
| 546 |
if isRateLimiting && s.config.StripeSecretKey != "" { |
| 547 |
u := v.User() |
| 548 |
if u == nil || u.Tier == nil { |
| 549 |
httpErr = httpErr.Wrap("increase your limits with a paid plan, see %s", s.config.BaseURL) |
| 550 |
} |
| 551 |
} |
| 552 |
w.Header().Set("Content-Type", "application/json") |
| 553 |
w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests |
| 554 |
w.WriteHeader(httpErr.HTTPCode) |
| 555 |
io.WriteString(w, httpErr.JSON()+"\n") |
| 556 |
if s.ban != nil { |
| 557 |
if ip, err := fromContext[netip.Addr](r, contextVisitorIP); err == nil { |
| 558 |
s.ban.Record(ip, httpErr.HTTPCode, httpErr.Code) |
| 559 |
} |
| 560 |
} |
| 561 |
} |
| 562 |
|
| 563 |
func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 564 |
if r.Method == http.MethodGet && r.URL.Path == "/" && s.config.WebRoot == "/" { |
| 565 |
return s.ensureWebEnabled(s.handleWebApp)(w, r, v) |
| 566 |
} else if r.Method == http.MethodHead && r.URL.Path == "/" { |
| 567 |
return s.ensureWebEnabled(s.handleEmpty)(w, r, v) |
| 568 |
} else if r.Method == http.MethodGet && r.URL.Path == apiHealthPath { |
| 569 |
return s.handleHealth(w, r, v) |
| 570 |
} else if r.Method == http.MethodGet && r.URL.Path == apiVersionPath { |
| 571 |
return s.ensureAdmin(s.handleVersion)(w, r, v) |
| 572 |
} else if r.Method == http.MethodGet && r.URL.Path == apiConfigPath { |
| 573 |
return s.handleConfig(w, r, v) |
| 574 |
} else if r.Method == http.MethodGet && r.URL.Path == webAppConfigPath { |
| 575 |
return s.ensureWebEnabled(s.handleWebConfig)(w, r, v) |
| 576 |
} else if r.Method == http.MethodGet && r.URL.Path == webAppManifestPath { |
| 577 |
return s.ensureWebPushEnabled(s.handleWebManifest)(w, r, v) |
| 578 |
} else if r.Method == http.MethodGet && r.URL.Path == apiUsersPath { |
| 579 |
return s.ensureAdmin(s.handleUsersGet)(w, r, v) |
| 580 |
} else if r.Method == http.MethodPost && r.URL.Path == apiUsersPath { |
| 581 |
return s.ensureAdmin(s.handleUsersAdd)(w, r, v) |
| 582 |
} else if r.Method == http.MethodPut && r.URL.Path == apiUsersPath { |
| 583 |
return s.ensureAdmin(s.handleUsersUpdate)(w, r, v) |
| 584 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiUsersPath { |
| 585 |
return s.ensureAdmin(s.handleUsersDelete)(w, r, v) |
| 586 |
} else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && r.URL.Path == apiUsersAccessPath { |
| 587 |
return s.ensureAdmin(s.handleAccessAllow)(w, r, v) |
| 588 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiUsersAccessPath { |
| 589 |
return s.ensureAdmin(s.handleAccessReset)(w, r, v) |
| 590 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountPath { |
| 591 |
return s.ensureUserManager(s.handleAccountCreate)(w, r, v) |
| 592 |
} else if r.Method == http.MethodGet && r.URL.Path == apiAccountPath { |
| 593 |
return s.handleAccountGet(w, r, v) // Allowed by anonymous |
| 594 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiAccountPath { |
| 595 |
return s.ensureUser(s.withAccountSync(s.handleAccountDelete))(w, r, v) |
| 596 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountPasswordPath { |
| 597 |
return s.ensureUser(s.handleAccountPasswordChange)(w, r, v) |
| 598 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountLoginPath { |
| 599 |
return s.ensureUser(s.withAccountSync(s.handleAccountLogin))(w, r, v) |
| 600 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountTokenPath { |
| 601 |
return s.ensureUser(s.withAccountSync(s.handleAccountTokenCreate))(w, r, v) |
| 602 |
} else if r.Method == http.MethodPatch && r.URL.Path == apiAccountTokenPath { |
| 603 |
return s.ensureUser(s.withAccountSync(s.handleAccountTokenUpdate))(w, r, v) |
| 604 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiAccountTokenPath { |
| 605 |
return s.ensureUser(s.withAccountSync(s.handleAccountTokenDelete))(w, r, v) |
| 606 |
} else if r.Method == http.MethodPatch && r.URL.Path == apiAccountSettingsPath { |
| 607 |
return s.ensureUser(s.withAccountSync(s.handleAccountSettingsChange))(w, r, v) |
| 608 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountSubscriptionPath { |
| 609 |
return s.ensureUser(s.withAccountSync(s.handleAccountSubscriptionAdd))(w, r, v) |
| 610 |
} else if r.Method == http.MethodPatch && r.URL.Path == apiAccountSubscriptionPath { |
| 611 |
return s.ensureUser(s.withAccountSync(s.handleAccountSubscriptionChange))(w, r, v) |
| 612 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiAccountSubscriptionPath { |
| 613 |
return s.ensureUser(s.withAccountSync(s.handleAccountSubscriptionDelete))(w, r, v) |
| 614 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountReservationPath { |
| 615 |
return s.ensureUser(s.withAccountSync(s.handleAccountReservationAdd))(w, r, v) |
| 616 |
} else if r.Method == http.MethodDelete && apiAccountReservationSingleRegex.MatchString(r.URL.Path) { |
| 617 |
return s.ensureUser(s.withAccountSync(s.handleAccountReservationDelete))(w, r, v) |
| 618 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountBillingSubscriptionPath { |
| 619 |
return s.ensurePaymentsEnabled(s.ensureUser(s.handleAccountBillingSubscriptionCreate))(w, r, v) // Account sync via incoming Stripe webhook |
| 620 |
} else if r.Method == http.MethodGet && apiAccountBillingSubscriptionCheckoutSuccessRegex.MatchString(r.URL.Path) { |
| 621 |
return s.ensurePaymentsEnabled(s.ensureUserManager(s.handleAccountBillingSubscriptionCreateSuccess))(w, r, v) // No user context! |
| 622 |
} else if r.Method == http.MethodPut && r.URL.Path == apiAccountBillingSubscriptionPath { |
| 623 |
return s.ensurePaymentsEnabled(s.ensureStripeCustomer(s.handleAccountBillingSubscriptionUpdate))(w, r, v) // Account sync via incoming Stripe webhook |
| 624 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiAccountBillingSubscriptionPath { |
| 625 |
return s.ensurePaymentsEnabled(s.ensureStripeCustomer(s.handleAccountBillingSubscriptionDelete))(w, r, v) // Account sync via incoming Stripe webhook |
| 626 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountBillingPortalPath { |
| 627 |
return s.ensurePaymentsEnabled(s.ensureStripeCustomer(s.handleAccountBillingPortalSessionCreate))(w, r, v) |
| 628 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountBillingWebhookPath { |
| 629 |
return s.ensurePaymentsEnabled(s.ensureUserManager(s.handleAccountBillingWebhook))(w, r, v) // This request comes from Stripe! |
| 630 |
} else if r.Method == http.MethodPut && r.URL.Path == apiAccountPhoneVerifyPath { |
| 631 |
return s.ensureUser(s.ensureCallsEnabled(s.withAccountSync(s.handleAccountPhoneNumberVerify)))(w, r, v) |
| 632 |
} else if r.Method == http.MethodPut && r.URL.Path == apiAccountPhonePath { |
| 633 |
return s.ensureUser(s.ensureCallsEnabled(s.withAccountSync(s.handleAccountPhoneNumberAdd)))(w, r, v) |
| 634 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiAccountPhonePath { |
| 635 |
return s.ensureUser(s.ensureCallsEnabled(s.withAccountSync(s.handleAccountPhoneNumberDelete)))(w, r, v) |
| 636 |
} else if r.Method == http.MethodPut && r.URL.Path == apiAccountEmailPath { |
| 637 |
return s.ensureUser(s.ensureEmailsEnabled(s.withAccountSync(s.handleAccountEmailAdd)))(w, r, v) |
| 638 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountEmailVerifyPath { |
| 639 |
return s.ensureEmailsEnabled(s.limitRequests(s.handleAccountEmailVerify))(w, r, v) // No ensureUser: clicked from a mail client, possibly logged out |
| 640 |
} else if r.Method == http.MethodDelete && r.URL.Path == apiAccountEmailPath { |
| 641 |
return s.ensureUser(s.ensureEmailsEnabled(s.withAccountSync(s.handleAccountEmailDelete)))(w, r, v) |
| 642 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountEmailPrimaryPath { |
| 643 |
return s.ensureUser(s.withAccountSync(s.handleAccountEmailSetPrimary))(w, r, v) |
| 644 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountEmailResendPath { |
| 645 |
return s.ensureUser(s.ensureEmailsEnabled(s.handleAccountEmailResend))(w, r, v) |
| 646 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountPasswordResetRequestPath { |
| 647 |
return s.ensureEmailsEnabled(s.limitRequests(s.handleAccountPasswordResetRequest))(w, r, v) // Unauthenticated |
| 648 |
} else if r.Method == http.MethodPost && r.URL.Path == apiAccountPasswordResetPath { |
| 649 |
return s.ensureEmailsEnabled(s.limitRequests(s.handleAccountPasswordReset))(w, r, v) // Unauthenticated |
| 650 |
} else if r.Method == http.MethodPost && apiWebPushPath == r.URL.Path { |
| 651 |
return s.ensureWebPushEnabled(s.limitRequests(s.handleWebPushUpdate))(w, r, v) |
| 652 |
} else if r.Method == http.MethodDelete && apiWebPushPath == r.URL.Path { |
| 653 |
return s.ensureWebPushEnabled(s.limitRequests(s.handleWebPushDelete))(w, r, v) |
| 654 |
} else if r.Method == http.MethodGet && r.URL.Path == apiStatsPath { |
| 655 |
return s.handleStats(w, r, v) |
| 656 |
} else if r.Method == http.MethodGet && r.URL.Path == apiTiersPath { |
| 657 |
return s.ensurePaymentsEnabled(s.handleBillingTiersGet)(w, r, v) |
| 658 |
} else if r.Method == http.MethodGet && r.URL.Path == matrixPushPath { |
| 659 |
return s.handleMatrixDiscovery(w) |
| 660 |
} else if r.Method == http.MethodGet && r.URL.Path == metricsPath && s.metricsHandler != nil { |
| 661 |
return s.handleMetrics(w, r, v) |
| 662 |
} else if r.Method == http.MethodGet && staticRegex.MatchString(r.URL.Path) { |
| 663 |
return s.ensureWebEnabled(s.handleStatic)(w, r, v) |
| 664 |
} else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) { |
| 665 |
return s.ensureWebEnabled(s.handleDocs)(w, r, v) |
| 666 |
} else if (r.Method == http.MethodGet || r.Method == http.MethodHead) && fileRegex.MatchString(r.URL.Path) && s.attachment != nil { |
| 667 |
return s.limitRequests(s.handleFile)(w, r, v) |
| 668 |
} else if r.Method == http.MethodOptions { |
| 669 |
return s.limitRequests(s.handleOptions)(w, r, v) // Should work even if the web app is not enabled, see #598 |
| 670 |
} else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && r.URL.Path == "/" { |
| 671 |
return s.transformBodyJSON(s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublish)))(w, r, v) |
| 672 |
} else if r.Method == http.MethodPost && r.URL.Path == matrixPushPath { |
| 673 |
return s.transformMatrixJSON(s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublishMatrix)))(w, r, v) |
| 674 |
} else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && (topicPathRegex.MatchString(r.URL.Path) || updatePathRegex.MatchString(r.URL.Path)) { |
| 675 |
return s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublish))(w, r, v) |
| 676 |
} else if (r.Method == http.MethodDelete && updatePathRegex.MatchString(r.URL.Path)) || (r.Method == http.MethodGet && deletePathRegex.MatchString(r.URL.Path)) { |
| 677 |
return s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handleDelete))(w, r, v) |
| 678 |
} else if (r.Method == http.MethodGet || r.Method == http.MethodPut) && clearPathRegex.MatchString(r.URL.Path) { |
| 679 |
return s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handleClear))(w, r, v) |
| 680 |
} else if r.Method == http.MethodGet && publishPathRegex.MatchString(r.URL.Path) { |
| 681 |
return s.limitRequestsWithTopic(s.authorizeTopicWrite(s.handlePublish))(w, r, v) |
| 682 |
} else if r.Method == http.MethodGet && jsonPathRegex.MatchString(r.URL.Path) { |
| 683 |
return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeJSON))(w, r, v) |
| 684 |
} else if r.Method == http.MethodGet && ssePathRegex.MatchString(r.URL.Path) { |
| 685 |
return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeSSE))(w, r, v) |
| 686 |
} else if r.Method == http.MethodGet && rawPathRegex.MatchString(r.URL.Path) { |
| 687 |
return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeRaw))(w, r, v) |
| 688 |
} else if r.Method == http.MethodGet && wsPathRegex.MatchString(r.URL.Path) { |
| 689 |
return s.limitRequests(s.authorizeTopicRead(s.handleSubscribeWS))(w, r, v) |
| 690 |
} else if r.Method == http.MethodGet && authPathRegex.MatchString(r.URL.Path) { |
| 691 |
return s.limitRequests(s.authorizeTopicRead(s.handleTopicAuth))(w, r, v) |
| 692 |
} else if r.Method == http.MethodGet && (webAppEmailVerifyRegex.MatchString(r.URL.Path) || webAppPasswordResetRegex.MatchString(r.URL.Path)) { |
| 693 |
return s.ensureWebEnabled(s.handleWebAppNoIndex)(w, r, v) // Magic-link landing pages (client-side routes) |
| 694 |
} else if r.Method == http.MethodGet && (topicPathRegex.MatchString(r.URL.Path) || externalTopicPathRegex.MatchString(r.URL.Path)) { |
| 695 |
return s.ensureWebEnabled(s.handleTopic)(w, r, v) |
| 696 |
} |
| 697 |
return errHTTPNotFound |
| 698 |
} |
| 699 |
|
| 700 |
func (s *Server) handleTopic(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 701 |
unifiedpush := readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see PUT/POST too! |
| 702 |
if unifiedpush { |
| 703 |
w.Header().Set("Content-Type", "application/json") |
| 704 |
w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests |
| 705 |
_, err := io.WriteString(w, `{"unifiedpush":{"version":1}}`+"\n") |
| 706 |
return err |
| 707 |
} |
| 708 |
return s.handleWebApp(w, r, v) |
| 709 |
} |
| 710 |
|
| 711 |
func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request, _ *visitor) error { |
| 712 |
return nil |
| 713 |
} |
| 714 |
|
| 715 |
func (s *Server) handleTopicAuth(w http.ResponseWriter, _ *http.Request, _ *visitor) error { |
| 716 |
return s.writeJSON(w, newSuccessResponse()) |
| 717 |
} |
| 718 |
|
| 719 |
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request, _ *visitor) error { |
| 720 |
response := &apiHealthResponse{ |
| 721 |
Healthy: true, |
| 722 |
} |
| 723 |
return s.writeJSON(w, response) |
| 724 |
} |
| 725 |
|
| 726 |
// handleMetrics returns Prometheus metrics. This endpoint is only called if enable-metrics is set, |
| 727 |
// and listen-metrics-http is not set. |
| 728 |
func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request, _ *visitor) error { |
| 729 |
s.metricsHandler.ServeHTTP(w, r) |
| 730 |
return nil |
| 731 |
} |
| 732 |
|
| 733 |
// handleStats returns the publicly available server stats |
| 734 |
func (s *Server) handleStats(w http.ResponseWriter, _ *http.Request, _ *visitor) error { |
| 735 |
s.mu.RLock() |
| 736 |
messages, n, rate := s.messages, len(s.messagesHistory), float64(0) |
| 737 |
if n > 1 { |
| 738 |
rate = float64(s.messagesHistory[n-1]-s.messagesHistory[0]) / (float64(n-1) * s.config.ManagerInterval.Seconds()) |
| 739 |
} |
| 740 |
s.mu.RUnlock() |
| 741 |
response := &apiStatsResponse{ |
| 742 |
Messages: messages, |
| 743 |
MessagesRate: rate, |
| 744 |
} |
| 745 |
return s.writeJSON(w, response) |
| 746 |
} |
| 747 |
|
| 748 |
// handleFile processes the download of attachment files. The method handles GET and HEAD requests against a file. |
| 749 |
// Before streaming the file to a client, it locates uploader (m.Sender or m.User) in the message cache, so it |
| 750 |
// can associate the download bandwidth with the uploader. |
| 751 |
func (s *Server) handleFile(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 752 |
if s.attachment == nil { |
| 753 |
return errHTTPInternalError |
| 754 |
} |
| 755 |
matches := fileRegex.FindStringSubmatch(r.URL.Path) |
| 756 |
if len(matches) != 2 { |
| 757 |
return errHTTPInternalErrorInvalidPath |
| 758 |
} |
| 759 |
messageID := matches[1] |
| 760 |
reader, size, err := s.attachment.Read(messageID) |
| 761 |
if err != nil { |
| 762 |
return errHTTPNotFound.Fields(log.Context{ |
| 763 |
"message_id": messageID, |
| 764 |
"error_context": "attachment_store", |
| 765 |
}) |
| 766 |
} |
| 767 |
defer reader.Close() |
| 768 |
w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests |
| 769 |
w.Header().Set("Content-Length", fmt.Sprintf("%d", size)) |
| 770 |
if r.Method == http.MethodHead { |
| 771 |
return nil |
| 772 |
} |
| 773 |
// Find message in database, and associate bandwidth to the uploader user |
| 774 |
// This is an easy way to |
| 775 |
// - avoid abuse (e.g. 1 uploader, 1k downloaders) |
| 776 |
// - and also uses the higher bandwidth limits of a paying user |
| 777 |
m, err := s.messageCache.Message(messageID) |
| 778 |
if errors.Is(err, model.ErrMessageNotFound) { |
| 779 |
if s.config.CacheBatchTimeout > 0 { |
| 780 |
// Strange edge case: If we immediately after upload request the file (the web app does this for images), |
| 781 |
// and messages are persisted asynchronously, retry fetching from the database |
| 782 |
m, err = util.Retry(func() (*model.Message, error) { |
| 783 |
return s.messageCache.Message(messageID) |
| 784 |
}, s.config.CacheBatchTimeout, 100*time.Millisecond, 300*time.Millisecond, 600*time.Millisecond) |
| 785 |
} |
| 786 |
if err != nil { |
| 787 |
return errHTTPNotFound.Fields(log.Context{ |
| 788 |
"message_id": messageID, |
| 789 |
"error_context": "message_cache", |
| 790 |
}) |
| 791 |
} |
| 792 |
} else if err != nil { |
| 793 |
return err |
| 794 |
} |
| 795 |
bandwidthVisitor := v |
| 796 |
if s.userManager != nil && m.User != "" { |
| 797 |
u, err := s.userManager.UserByID(m.User) |
| 798 |
if err != nil { |
| 799 |
return err |
| 800 |
} |
| 801 |
bandwidthVisitor = s.visitor(v.IP(), u) |
| 802 |
} else if m.Sender.IsValid() { |
| 803 |
bandwidthVisitor = s.visitor(m.Sender, nil) |
| 804 |
} |
| 805 |
if !bandwidthVisitor.BandwidthAllowed(size) { |
| 806 |
return errHTTPTooManyRequestsLimitAttachmentBandwidth.With(m) |
| 807 |
} |
| 808 |
// Actually send file |
| 809 |
if m.Attachment.Name != "" { |
| 810 |
w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(m.Attachment.Name)) |
| 811 |
} |
| 812 |
_, err = io.Copy(util.NewContentTypeWriter(w, r.URL.Path), reader) |
| 813 |
return err |
| 814 |
} |
| 815 |
|
| 816 |
func (s *Server) handleMatrixDiscovery(w http.ResponseWriter) error { |
| 817 |
if s.config.BaseURL == "" { |
| 818 |
return errHTTPInternalErrorMissingBaseURL |
| 819 |
} |
| 820 |
return writeMatrixDiscoveryResponse(w) |
| 821 |
} |
| 822 |
|
| 823 |
// dispatch delivers m to local subscribers and fires the requested side-effect targets. It is |
| 824 |
// the single choke point through which every published message must pass; t may be nil when |
| 825 |
// the topic has no local subscribers (delayed sender). |
| 826 |
func (s *Server) dispatch(v *visitor, t *topic, m *model.Message, opts dispatchOpts) error { |
| 827 |
// Deliver to local subscribers |
| 828 |
if t != nil { |
| 829 |
if opts.async { |
| 830 |
go func() { |
| 831 |
if err := t.Publish(v, m); err != nil { |
| 832 |
logvm(v, m).Err(err).Warn("Unable to publish message") |
| 833 |
} |
| 834 |
}() |
| 835 |
} else if err := t.Publish(v, m); err != nil { |
| 836 |
return err |
| 837 |
} |
| 838 |
} |
| 839 |
// Fire the requested side-effect targets |
| 840 |
if s.firebaseClient != nil && opts.firebase { |
| 841 |
go s.sendToFirebase(v, m) |
| 842 |
} |
| 843 |
if s.mailer != nil && opts.email != "" { |
| 844 |
go s.sendEmail(v, m, opts.email) |
| 845 |
} |
| 846 |
if s.config.TwilioAccount != "" && opts.call != "" { |
| 847 |
go s.callPhone(v, m, opts.call) |
| 848 |
} |
| 849 |
if s.config.UpstreamBaseURL != "" && opts.upstream { |
| 850 |
go s.forwardPollRequest(v, m) |
| 851 |
} |
| 852 |
if s.config.WebPushPublicKey != "" && opts.webPush { |
| 853 |
go s.publishToWebPushEndpoints(v, m) |
| 854 |
} |
| 855 |
return nil |
| 856 |
} |
| 857 |
|
| 858 |
func (s *Server) handlePublishInternal(r *http.Request, v *visitor) (*model.Message, error) { |
| 859 |
start := time.Now() |
| 860 |
t, err := fromContext[*topic](r, contextTopic) |
| 861 |
if err != nil { |
| 862 |
return nil, err |
| 863 |
} |
| 864 |
vrate, err := fromContext[*visitor](r, contextRateVisitor) |
| 865 |
if err != nil { |
| 866 |
return nil, err |
| 867 |
} |
| 868 |
body, err := util.Peek(r.Body, s.config.MessageSizeLimit) |
| 869 |
if err != nil { |
| 870 |
return nil, err |
| 871 |
} |
| 872 |
m := model.NewDefaultMessage(t.ID, "") |
| 873 |
cache, firebase, email, call, template, unifiedpush, priorityStr, e := s.parsePublishParams(r, m) |
| 874 |
if e != nil { |
| 875 |
return nil, e.With(t) |
| 876 |
} |
| 877 |
if unifiedpush && s.config.VisitorSubscriberRateLimiting && t.RateVisitor() == nil { |
| 878 |
// UnifiedPush clients must subscribe before publishing to allow proper subscriber-based rate limiting. |
| 879 |
// The 5xx response is because some app servers (in particular Mastodon) will remove |
| 880 |
// the subscription as invalid if any 400-499 code (except 429/408) is returned. |
| 881 |
// See https://github.com/mastodon/mastodon/blob/730bb3e211a84a2f30e3e2bbeae3f77149824a68/app/workers/web/push_notification_worker.rb#L35-L46 |
| 882 |
return nil, errHTTPInsufficientStorageUnifiedPush.With(t) |
| 883 |
} else if !util.ContainsIP(s.config.VisitorRequestExemptPrefixes, v.ip) && !vrate.MessageAllowed() { |
| 884 |
return nil, errHTTPTooManyRequestsLimitMessages.With(t) |
| 885 |
} |
| 886 |
if email != "" { |
| 887 |
var httpErr *errHTTP |
| 888 |
email, httpErr = s.convertEmailAddress(v.User(), email) |
| 889 |
if httpErr != nil { |
| 890 |
return nil, httpErr.With(t) |
| 891 |
} else if !vrate.EmailAllowed() { |
| 892 |
return nil, errHTTPTooManyRequestsLimitEmails.With(t) |
| 893 |
} |
| 894 |
} |
| 895 |
if call != "" { |
| 896 |
var httpErr *errHTTP |
| 897 |
call, httpErr = s.convertPhoneNumber(v.User(), call) |
| 898 |
if httpErr != nil { |
| 899 |
return nil, httpErr.With(t) |
| 900 |
} else if !vrate.CallAllowed() { |
| 901 |
return nil, errHTTPTooManyRequestsLimitCalls.With(t) |
| 902 |
} |
| 903 |
} |
| 904 |
if m.PollID != "" { |
| 905 |
m = model.NewPollRequestMessage(t.ID, m.PollID) |
| 906 |
} |
| 907 |
m.Sender = v.IP() |
| 908 |
m.User = v.MaybeUserID() |
| 909 |
if cache { |
| 910 |
m.Expires = time.Unix(m.Time, 0).Add(v.Limits().MessageExpiryDuration).Unix() |
| 911 |
} |
| 912 |
if err := s.handlePublishBody(r, v, m, body, template, unifiedpush, priorityStr); err != nil { |
| 913 |
return nil, err |
| 914 |
} |
| 915 |
if m.Message == "" { |
| 916 |
m.Message = emptyMessageBody |
| 917 |
} |
| 918 |
m.SanitizeUTF8() |
| 919 |
delayed := m.Time > time.Now().Unix() |
| 920 |
ev := logvrm(v, r, m). |
| 921 |
Tag(tagPublish). |
| 922 |
With(t). |
| 923 |
Fields(log.Context{ |
| 924 |
"message_delayed": delayed, |
| 925 |
"message_firebase": firebase, |
| 926 |
"message_unifiedpush": unifiedpush, |
| 927 |
"message_email": email, |
| 928 |
"message_call": call, |
| 929 |
}) |
| 930 |
if ev.IsTrace() { |
| 931 |
ev.Field("message_body", util.MaybeMarshalJSON(m)).Trace("Received message") |
| 932 |
} else if ev.IsDebug() { |
| 933 |
ev.Debug("Received message") |
| 934 |
} |
| 935 |
if !delayed { |
| 936 |
err := s.dispatch(v, t, m, dispatchOpts{ |
| 937 |
firebase: firebase, |
| 938 |
email: email, |
| 939 |
call: call, |
| 940 |
upstream: !unifiedpush, // UP messages are not sent to upstream |
| 941 |
webPush: true, |
| 942 |
}) |
| 943 |
if err != nil { |
| 944 |
return nil, err |
| 945 |
} |
| 946 |
} else { |
| 947 |
logvrm(v, r, m).Tag(tagPublish).Debug("Message delayed, will process later") |
| 948 |
} |
| 949 |
if cache { |
| 950 |
// Delete any existing scheduled message with the same sequence ID |
| 951 |
deletedIDs, err := s.messageCache.DeleteScheduledBySequenceID(t.ID, m.SequenceID) |
| 952 |
if err != nil { |
| 953 |
return nil, err |
| 954 |
} |
| 955 |
// Delete attachment files for deleted scheduled messages |
| 956 |
if s.attachment != nil && len(deletedIDs) > 0 { |
| 957 |
if err := s.attachment.Remove(deletedIDs...); err != nil { |
| 958 |
logvrm(v, r, m).Tag(tagPublish).Err(err).Warn("Error removing attachments for deleted scheduled messages") |
| 959 |
} |
| 960 |
} |
| 961 |
logvrm(v, r, m).Tag(tagPublish).Debug("Adding message to cache") |
| 962 |
if err := s.messageCache.AddMessage(m); err != nil { |
| 963 |
return nil, err |
| 964 |
} |
| 965 |
} |
| 966 |
u := v.User() |
| 967 |
if s.userManager != nil && u != nil && u.Tier != nil { |
| 968 |
go s.userManager.EnqueueUserStats(u.ID, v.Stats()) |
| 969 |
} |
| 970 |
s.mu.Lock() |
| 971 |
s.messages++ |
| 972 |
s.mu.Unlock() |
| 973 |
if unifiedpush { |
| 974 |
metrics.UnifiedPushPublishedSuccess.Inc() |
| 975 |
} |
| 976 |
metrics.MessagePublishDurationMillis.Set(float64(time.Since(start).Milliseconds())) |
| 977 |
return m, nil |
| 978 |
} |
| 979 |
|
| 980 |
func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 981 |
m, err := s.handlePublishInternal(r, v) |
| 982 |
if err != nil { |
| 983 |
metrics.MessagesPublishedFailure.Inc() |
| 984 |
return err |
| 985 |
} |
| 986 |
metrics.MessagesPublishedSuccess.Inc() |
| 987 |
return s.writeJSON(w, m.ForJSON()) |
| 988 |
} |
| 989 |
|
| 990 |
func (s *Server) handlePublishMatrix(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 991 |
_, err := s.handlePublishInternal(r, v) |
| 992 |
if err != nil { |
| 993 |
metrics.MessagesPublishedFailure.Inc() |
| 994 |
metrics.MatrixPublishedFailure.Inc() |
| 995 |
if e, ok := err.(*errHTTP); ok && e.HTTPCode == errHTTPInsufficientStorageUnifiedPush.HTTPCode { |
| 996 |
topic, err := fromContext[*topic](r, contextTopic) |
| 997 |
if err != nil { |
| 998 |
return err |
| 999 |
} |
| 1000 |
pushKey, err := fromContext[string](r, contextMatrixPushKey) |
| 1001 |
if err != nil { |
| 1002 |
return err |
| 1003 |
} |
| 1004 |
if time.Since(topic.LastAccess()) > matrixRejectPushKeyForUnifiedPushTopicWithoutRateVisitorAfter { |
| 1005 |
return writeMatrixResponse(w, pushKey) |
| 1006 |
} |
| 1007 |
} |
| 1008 |
return err |
| 1009 |
} |
| 1010 |
metrics.MessagesPublishedSuccess.Inc() |
| 1011 |
metrics.MatrixPublishedSuccess.Inc() |
| 1012 |
return writeMatrixSuccess(w) |
| 1013 |
} |
| 1014 |
|
| 1015 |
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 1016 |
return s.handleActionMessage(w, r, v, model.MessageDeleteEvent) |
| 1017 |
} |
| 1018 |
|
| 1019 |
func (s *Server) handleClear(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 1020 |
return s.handleActionMessage(w, r, v, model.MessageClearEvent) |
| 1021 |
} |
| 1022 |
|
| 1023 |
func (s *Server) handleActionMessage(w http.ResponseWriter, r *http.Request, v *visitor, event string) error { |
| 1024 |
t, err := fromContext[*topic](r, contextTopic) |
| 1025 |
if err != nil { |
| 1026 |
return err |
| 1027 |
} |
| 1028 |
vrate, err := fromContext[*visitor](r, contextRateVisitor) |
| 1029 |
if err != nil { |
| 1030 |
return err |
| 1031 |
} |
| 1032 |
if !util.ContainsIP(s.config.VisitorRequestExemptPrefixes, v.ip) && !vrate.MessageAllowed() { |
| 1033 |
return errHTTPTooManyRequestsLimitMessages.With(t) |
| 1034 |
} |
| 1035 |
sequenceID, e := s.sequenceIDFromPath(r.URL.Path) |
| 1036 |
if e != nil { |
| 1037 |
return e.With(t) |
| 1038 |
} |
| 1039 |
// Create an action message with the given event type |
| 1040 |
m := model.NewActionMessage(event, t.ID, sequenceID) |
| 1041 |
m.Sender = v.IP() |
| 1042 |
m.User = v.MaybeUserID() |
| 1043 |
m.Expires = time.Unix(m.Time, 0).Add(v.Limits().MessageExpiryDuration).Unix() |
| 1044 |
// Publish to subscribers, Firebase (for Android clients), and web push endpoints |
| 1045 |
if err := s.dispatch(v, t, m, dispatchOpts{firebase: true, webPush: true}); err != nil { |
| 1046 |
return err |
| 1047 |
} |
| 1048 |
if event == model.MessageDeleteEvent { |
| 1049 |
// Delete any existing scheduled message with the same sequence ID |
| 1050 |
deletedIDs, err := s.messageCache.DeleteScheduledBySequenceID(t.ID, sequenceID) |
| 1051 |
if err != nil { |
| 1052 |
return err |
| 1053 |
} |
| 1054 |
// Delete attachment files for deleted scheduled messages |
| 1055 |
if s.attachment != nil && len(deletedIDs) > 0 { |
| 1056 |
if err := s.attachment.Remove(deletedIDs...); err != nil { |
| 1057 |
logvrm(v, r, m).Tag(tagPublish).Err(err).Warn("Error removing attachments for deleted scheduled messages") |
| 1058 |
} |
| 1059 |
} |
| 1060 |
} |
| 1061 |
// Add to message cache |
| 1062 |
if err := s.messageCache.AddMessage(m); err != nil { |
| 1063 |
return err |
| 1064 |
} |
| 1065 |
logvrm(v, r, m).Tag(tagPublish).Debug("Published %s for sequence ID %s", event, sequenceID) |
| 1066 |
s.mu.Lock() |
| 1067 |
s.messages++ |
| 1068 |
s.mu.Unlock() |
| 1069 |
return s.writeJSON(w, m.ForJSON()) |
| 1070 |
} |
| 1071 |
|
| 1072 |
func (s *Server) sendToFirebase(v *visitor, m *model.Message) { |
| 1073 |
logvm(v, m).Tag(tagFirebase).Debug("Publishing to Firebase") |
| 1074 |
if err := s.firebaseClient.Send(v, m); err != nil { |
| 1075 |
metrics.FirebasePublishedFailure.Inc() |
| 1076 |
if errors.Is(err, errFirebaseTemporarilyBanned) { |
| 1077 |
logvm(v, m).Tag(tagFirebase).Err(err).Debug("Unable to publish to Firebase: %v", err.Error()) |
| 1078 |
} else { |
| 1079 |
logvm(v, m).Tag(tagFirebase).Err(err).Warn("Unable to publish to Firebase: %v", err.Error()) |
| 1080 |
} |
| 1081 |
return |
| 1082 |
} |
| 1083 |
metrics.FirebasePublishedSuccess.Inc() |
| 1084 |
} |
| 1085 |
|
| 1086 |
func (s *Server) sendEmail(v *visitor, m *model.Message, email string) { |
| 1087 |
logvm(v, m).Tag(tagEmail).Field("email", email).Info("Sending email to %s", email) |
| 1088 |
if err := s.mailer.SendNotification(email, m, v.ip.String()); err != nil { |
| 1089 |
logvm(v, m).Tag(tagEmail).Field("email", email).Err(err).Warn("Unable to send email to %s: %v", email, err.Error()) |
| 1090 |
metrics.EmailsPublishedFailure.Inc() |
| 1091 |
return |
| 1092 |
} |
| 1093 |
metrics.EmailsPublishedSuccess.Inc() |
| 1094 |
} |
| 1095 |
|
| 1096 |
func (s *Server) forwardPollRequest(v *visitor, m *model.Message) { |
| 1097 |
topicURL := fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic) |
| 1098 |
topicHash := fmt.Sprintf("%x", sha256.Sum256([]byte(topicURL))) |
| 1099 |
forwardURL := fmt.Sprintf("%s/%s", s.config.UpstreamBaseURL, topicHash) |
| 1100 |
logvm(v, m).Debug("Publishing poll request to %s", forwardURL) |
| 1101 |
req, err := http.NewRequest("POST", forwardURL, strings.NewReader("")) |
| 1102 |
if err != nil { |
| 1103 |
logvm(v, m).Err(err).Warn("Unable to publish poll request") |
| 1104 |
return |
| 1105 |
} |
| 1106 |
req.Header.Set("User-Agent", "ntfy/"+s.config.BuildVersion) |
| 1107 |
req.Header.Set("X-Poll-ID", m.ID) |
| 1108 |
if s.config.UpstreamAccessToken != "" { |
| 1109 |
req.Header.Set("Authorization", util.BearerAuth(s.config.UpstreamAccessToken)) |
| 1110 |
} |
| 1111 |
var httpClient = &http.Client{ |
| 1112 |
Timeout: time.Second * 10, |
| 1113 |
} |
| 1114 |
response, err := httpClient.Do(req) |
| 1115 |
if err != nil { |
| 1116 |
logvm(v, m).Err(err).Warn("Unable to publish poll request") |
| 1117 |
return |
| 1118 |
} else if response.StatusCode != http.StatusOK { |
| 1119 |
if response.StatusCode == http.StatusTooManyRequests { |
| 1120 |
logvm(v, m).Err(err).Warn("Unable to publish poll request, the upstream server %s responded with HTTP %s; you may solve this by sending fewer daily messages, or by configuring upstream-access-token (assuming you have an account with higher rate limits) ", s.config.UpstreamBaseURL, response.Status) |
| 1121 |
} else { |
| 1122 |
logvm(v, m).Err(err).Warn("Unable to publish poll request, the upstream server %s responded with HTTP %s", s.config.UpstreamBaseURL, response.Status) |
| 1123 |
} |
| 1124 |
return |
| 1125 |
} |
| 1126 |
} |
| 1127 |
|
| 1128 |
func (s *Server) parsePublishParams(r *http.Request, m *model.Message) (cache bool, firebase bool, email, call string, template templateMode, unifiedpush bool, priorityStr string, err *errHTTP) { |
| 1129 |
if r.Method != http.MethodGet && updatePathRegex.MatchString(r.URL.Path) { |
| 1130 |
pathSequenceID, err := s.sequenceIDFromPath(r.URL.Path) |
| 1131 |
if err != nil { |
| 1132 |
return false, false, "", "", "", false, "", err |
| 1133 |
} |
| 1134 |
m.SequenceID = pathSequenceID |
| 1135 |
} else { |
| 1136 |
sequenceID := readParam(r, "x-sequence-id", "sequence-id", "sid") |
| 1137 |
if sequenceID != "" { |
| 1138 |
if sequenceIDRegex.MatchString(sequenceID) { |
| 1139 |
m.SequenceID = sequenceID |
| 1140 |
} else { |
| 1141 |
return false, false, "", "", "", false, "", errHTTPBadRequestSequenceIDInvalid |
| 1142 |
} |
| 1143 |
} else { |
| 1144 |
m.SequenceID = m.ID |
| 1145 |
} |
| 1146 |
} |
| 1147 |
cache = readBoolParam(r, true, "x-cache", "cache") |
| 1148 |
firebase = readBoolParam(r, true, "x-firebase", "firebase") |
| 1149 |
m.Title = readParam(r, "x-title", "title", "t") |
| 1150 |
m.Click = readParam(r, "x-click", "click") |
| 1151 |
icon := readParam(r, "x-icon", "icon") |
| 1152 |
filename := readParam(r, "x-filename", "filename", "file", "f") |
| 1153 |
attach := readParam(r, "x-attach", "attach", "a") |
| 1154 |
if attach != "" || filename != "" { |
| 1155 |
m.Attachment = &model.Attachment{} |
| 1156 |
} |
| 1157 |
if filename != "" { |
| 1158 |
m.Attachment.Name = filename |
| 1159 |
} |
| 1160 |
if attach != "" { |
| 1161 |
if !urlRegex.MatchString(attach) { |
| 1162 |
return false, false, "", "", "", false, "", errHTTPBadRequestAttachmentURLInvalid |
| 1163 |
} |
| 1164 |
m.Attachment.URL = attach |
| 1165 |
if m.Attachment.Name == "" { |
| 1166 |
u, err := url.Parse(m.Attachment.URL) |
| 1167 |
if err == nil { |
| 1168 |
m.Attachment.Name = path.Base(u.Path) |
| 1169 |
if m.Attachment.Name == "." || m.Attachment.Name == "/" { |
| 1170 |
m.Attachment.Name = "" |
| 1171 |
} |
| 1172 |
} |
| 1173 |
} |
| 1174 |
if m.Attachment.Name == "" { |
| 1175 |
m.Attachment.Name = "attachment" |
| 1176 |
} |
| 1177 |
} |
| 1178 |
if icon != "" { |
| 1179 |
if !urlRegex.MatchString(icon) { |
| 1180 |
return false, false, "", "", "", false, "", errHTTPBadRequestIconURLInvalid |
| 1181 |
} |
| 1182 |
m.Icon = icon |
| 1183 |
} |
| 1184 |
email = readParam(r, "x-email", "x-e-mail", "email", "e-mail", "mail", "e") |
| 1185 |
if email != "" && !emailAddressRegex.MatchString(email) && !toBool(email) { |
| 1186 |
return false, false, "", "", "", false, "", errHTTPBadRequestEmailAddressInvalid |
| 1187 |
} |
| 1188 |
if s.mailer == nil && email != "" { |
| 1189 |
return false, false, "", "", "", false, "", errHTTPBadRequestEmailDisabled |
| 1190 |
} |
| 1191 |
call = readParam(r, "x-call", "call") |
| 1192 |
if call != "" && (s.config.TwilioAccount == "" || s.userManager == nil) { |
| 1193 |
return false, false, "", "", "", false, "", errHTTPBadRequestPhoneCallsDisabled |
| 1194 |
} else if call != "" && !isBoolValue(call) && !phoneNumberRegex.MatchString(call) { |
| 1195 |
return false, false, "", "", "", false, "", errHTTPBadRequestPhoneNumberInvalid |
| 1196 |
} |
| 1197 |
template = templateMode(readParam(r, "x-template", "template", "tpl")) |
| 1198 |
messageStr := readParam(r, "x-message", "message", "m") |
| 1199 |
if !template.InlineMode() { |
| 1200 |
// Convert "\n" to literal newline everything but inline mode |
| 1201 |
messageStr = strings.ReplaceAll(messageStr, "\\n", "\n") |
| 1202 |
} |
| 1203 |
if messageStr != "" { |
| 1204 |
m.Message = messageStr |
| 1205 |
} |
| 1206 |
var e error |
| 1207 |
priorityStr = readParam(r, "x-priority", "priority", "prio", "p") |
| 1208 |
if !template.Enabled() { |
| 1209 |
m.Priority, e = util.ParsePriority(priorityStr) |
| 1210 |
if e != nil { |
| 1211 |
return false, false, "", "", "", false, "", errHTTPBadRequestPriorityInvalid |
| 1212 |
} |
| 1213 |
priorityStr = "" // Clear since it's already parsed |
| 1214 |
} |
| 1215 |
m.Tags = readCommaSeparatedParam(r, "x-tags", "tags", "tag", "ta") |
| 1216 |
delayStr := readParam(r, "x-delay", "delay", "x-at", "at", "x-in", "in") |
| 1217 |
if delayStr != "" { |
| 1218 |
if !cache { |
| 1219 |
return false, false, "", "", "", false, "", errHTTPBadRequestDelayNoCache |
| 1220 |
} |
| 1221 |
if email != "" { |
| 1222 |
return false, false, "", "", "", false, "", errHTTPBadRequestDelayNoEmail // we cannot store the email address (yet) |
| 1223 |
} |
| 1224 |
if call != "" { |
| 1225 |
return false, false, "", "", "", false, "", errHTTPBadRequestDelayNoCall // we cannot store the phone number (yet) |
| 1226 |
} |
| 1227 |
delay, err := util.ParseFutureTime(delayStr, time.Now()) |
| 1228 |
if err != nil { |
| 1229 |
return false, false, "", "", "", false, "", errHTTPBadRequestDelayCannotParse |
| 1230 |
} else if delay.Unix() < time.Now().Add(s.config.MessageDelayMin).Unix() { |
| 1231 |
return false, false, "", "", "", false, "", errHTTPBadRequestDelayTooSmall |
| 1232 |
} else if delay.Unix() > time.Now().Add(s.config.MessageDelayMax).Unix() { |
| 1233 |
return false, false, "", "", "", false, "", errHTTPBadRequestDelayTooLarge |
| 1234 |
} |
| 1235 |
m.Time = delay.Unix() |
| 1236 |
} |
| 1237 |
actionsStr := readParam(r, "x-actions", "actions", "action") |
| 1238 |
if actionsStr != "" { |
| 1239 |
m.Actions, e = action.Parse(actionsStr) |
| 1240 |
if e != nil { |
| 1241 |
return false, false, "", "", "", false, "", errHTTPBadRequestActionsInvalid.Wrap("%s", e.Error()) |
| 1242 |
} |
| 1243 |
} |
| 1244 |
contentType, markdown := readParam(r, "content-type", "content_type"), readBoolParam(r, false, "x-markdown", "markdown", "md") |
| 1245 |
if markdown || strings.ToLower(contentType) == "text/markdown" { |
| 1246 |
m.ContentType = "text/markdown" |
| 1247 |
} |
| 1248 |
unifiedpush = readBoolParam(r, false, "x-unifiedpush", "unifiedpush", "up") // see GET too! |
| 1249 |
contentEncoding := readParam(r, "content-encoding") |
| 1250 |
if unifiedpush || contentEncoding == "aes128gcm" { |
| 1251 |
firebase = false |
| 1252 |
unifiedpush = true |
| 1253 |
} |
| 1254 |
m.PollID = readParam(r, "x-poll-id", "poll-id") |
| 1255 |
if m.PollID != "" { |
| 1256 |
unifiedpush = false |
| 1257 |
cache = false |
| 1258 |
email = "" |
| 1259 |
} |
| 1260 |
return cache, firebase, email, call, template, unifiedpush, priorityStr, nil |
| 1261 |
} |
| 1262 |
|
| 1263 |
// handlePublishBody consumes the PUT/POST body and decides whether the body is an attachment or the message. |
| 1264 |
// |
| 1265 |
// 1. curl -X POST -H "Poll: 1234" ntfy.sh/... |
| 1266 |
// If a message is flagged as poll request, the body does not matter and is discarded |
| 1267 |
// 2. curl -T somebinarydata.bin "ntfy.sh/mytopic?up=1" |
| 1268 |
// If UnifiedPush is enabled, encode as base64 if body is binary, and do not trim |
| 1269 |
// 3. curl -H "Attach: http://example.com/file.jpg" ntfy.sh/mytopic |
| 1270 |
// Body must be a message, because we attached an external URL |
| 1271 |
// 4. curl -T short.txt -H "Filename: short.txt" ntfy.sh/mytopic |
| 1272 |
// Body must be attachment, because we passed a filename |
| 1273 |
// 5. curl -H "Template: yes" -T file.txt ntfy.sh/mytopic |
| 1274 |
// If templating is enabled, read up to 32k and treat message body as JSON |
| 1275 |
// 6. curl -T file.txt ntfy.sh/mytopic |
| 1276 |
// If file.txt is <= 4096 (message limit) and valid UTF-8, treat it as a message |
| 1277 |
// 7. curl -T file.txt ntfy.sh/mytopic |
| 1278 |
// In all other cases, mostly if file.txt is > message limit, treat it as an attachment |
| 1279 |
func (s *Server) handlePublishBody(r *http.Request, v *visitor, m *model.Message, body *util.PeekedReadCloser, template templateMode, unifiedpush bool, priorityStr string) error { |
| 1280 |
if m.Event == model.PollRequestEvent { // Case 1 |
| 1281 |
return s.handleBodyDiscard(body) |
| 1282 |
} else if unifiedpush { |
| 1283 |
return s.handleBodyAsMessageAutoDetect(m, body) // Case 2 |
| 1284 |
} else if m.Attachment != nil && m.Attachment.URL != "" { |
| 1285 |
return s.handleBodyAsTextMessage(m, body) // Case 3 |
| 1286 |
} else if m.Attachment != nil && m.Attachment.Name != "" { |
| 1287 |
return s.handleBodyAsAttachment(r, v, m, body) // Case 4 |
| 1288 |
} else if template.Enabled() { |
| 1289 |
return s.handleBodyAsTemplatedTextMessage(r.Context(), m, template, body, priorityStr) // Case 5 |
| 1290 |
} else if !body.LimitReached && utf8.Valid(body.PeekedBytes) { |
| 1291 |
return s.handleBodyAsTextMessage(m, body) // Case 6 |
| 1292 |
} |
| 1293 |
return s.handleBodyAsAttachment(r, v, m, body) // Case 7 |
| 1294 |
} |
| 1295 |
|
| 1296 |
func (s *Server) handleBodyDiscard(body *util.PeekedReadCloser) error { |
| 1297 |
_, err := io.Copy(io.Discard, body) |
| 1298 |
_ = body.Close() |
| 1299 |
return err |
| 1300 |
} |
| 1301 |
|
| 1302 |
func (s *Server) handleBodyAsMessageAutoDetect(m *model.Message, body *util.PeekedReadCloser) error { |
| 1303 |
if utf8.Valid(body.PeekedBytes) { |
| 1304 |
m.Message = string(body.PeekedBytes) // Do not trim |
| 1305 |
} else { |
| 1306 |
m.Message = base64.StdEncoding.EncodeToString(body.PeekedBytes) |
| 1307 |
m.Encoding = encodingBase64 |
| 1308 |
} |
| 1309 |
return nil |
| 1310 |
} |
| 1311 |
|
| 1312 |
func (s *Server) handleBodyAsTextMessage(m *model.Message, body *util.PeekedReadCloser) error { |
| 1313 |
if !utf8.Valid(body.PeekedBytes) { |
| 1314 |
return errHTTPBadRequestMessageNotUTF8.With(m) |
| 1315 |
} |
| 1316 |
if len(body.PeekedBytes) > 0 { // Empty body should not override message (publish via GET!) |
| 1317 |
m.Message = strings.TrimSpace(string(body.PeekedBytes)) // Truncates the message to the peek limit if required |
| 1318 |
} |
| 1319 |
if m.Attachment != nil && m.Attachment.Name != "" && m.Message == "" { |
| 1320 |
m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name) |
| 1321 |
} |
| 1322 |
return nil |
| 1323 |
} |
| 1324 |
|
| 1325 |
func (s *Server) handleBodyAsAttachment(r *http.Request, v *visitor, m *model.Message, body *util.PeekedReadCloser) error { |
| 1326 |
if s.attachment == nil || s.config.BaseURL == "" { |
| 1327 |
return errHTTPBadRequestAttachmentsDisallowed.With(m) |
| 1328 |
} |
| 1329 |
vinfo, err := v.Info() |
| 1330 |
if err != nil { |
| 1331 |
return err |
| 1332 |
} |
| 1333 |
attachmentExpiry := time.Now().Add(vinfo.Limits.AttachmentExpiryDuration).Unix() |
| 1334 |
if m.Expires > 0 && attachmentExpiry > m.Expires { |
| 1335 |
attachmentExpiry = m.Expires // Attachment must never outlive the message |
| 1336 |
} |
| 1337 |
if m.Time > attachmentExpiry { |
| 1338 |
return errHTTPBadRequestAttachmentsExpiryBeforeDelivery.With(m) |
| 1339 |
} |
| 1340 |
// Early "do-not-trust" check, hard limit see below |
| 1341 |
if r.ContentLength > 0 && (r.ContentLength > vinfo.Stats.AttachmentTotalSizeRemaining || r.ContentLength > vinfo.Limits.AttachmentFileSizeLimit) { |
| 1342 |
return errHTTPEntityTooLargeAttachment.With(m).Fields(log.Context{ |
| 1343 |
"message_content_length": r.ContentLength, |
| 1344 |
"attachment_total_size_remaining": vinfo.Stats.AttachmentTotalSizeRemaining, |
| 1345 |
"attachment_file_size_limit": vinfo.Limits.AttachmentFileSizeLimit, |
| 1346 |
}) |
| 1347 |
} |
| 1348 |
if m.Attachment == nil { |
| 1349 |
m.Attachment = &model.Attachment{} |
| 1350 |
} |
| 1351 |
var ext string |
| 1352 |
m.Attachment.Expires = attachmentExpiry |
| 1353 |
m.Attachment.Type, ext = util.DetectContentType(body.PeekedBytes, m.Attachment.Name) |
| 1354 |
m.Attachment.URL = fmt.Sprintf("%s/file/%s%s", s.config.BaseURL, m.ID, ext) |
| 1355 |
if m.Attachment.Name == "" { |
| 1356 |
m.Attachment.Name = fmt.Sprintf("attachment%s", ext) |
| 1357 |
} |
| 1358 |
if m.Message == "" { |
| 1359 |
m.Message = fmt.Sprintf(defaultAttachmentMessage, m.Attachment.Name) |
| 1360 |
} |
| 1361 |
limiters := []util.Limiter{ |
| 1362 |
v.BandwidthLimiter(), |
| 1363 |
util.NewFixedLimiter(vinfo.Limits.AttachmentFileSizeLimit), |
| 1364 |
util.NewFixedLimiter(vinfo.Stats.AttachmentTotalSizeRemaining), |
| 1365 |
} |
| 1366 |
m.Attachment.Size, err = s.attachment.Write(m.ID, body, r.ContentLength, limiters...) |
| 1367 |
if errors.Is(err, util.ErrLimitReached) { |
| 1368 |
return errHTTPEntityTooLargeAttachment.With(m) |
| 1369 |
} else if err != nil { |
| 1370 |
return err |
| 1371 |
} |
| 1372 |
return nil |
| 1373 |
} |
| 1374 |
|
| 1375 |
func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 1376 |
encoder := func(msg *model.Message) (string, error) { |
| 1377 |
var buf bytes.Buffer |
| 1378 |
if err := util.EncodeJSON(&buf, msg.ForJSON()); err != nil { |
| 1379 |
return "", err |
| 1380 |
} |
| 1381 |
return buf.String(), nil |
| 1382 |
} |
| 1383 |
return s.handleSubscribeHTTP(w, r, v, "application/x-ndjson", encoder) |
| 1384 |
} |
| 1385 |
|
| 1386 |
func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 1387 |
encoder := func(msg *model.Message) (string, error) { |
| 1388 |
var buf bytes.Buffer |
| 1389 |
if err := util.EncodeJSON(&buf, msg.ForJSON()); err != nil { |
| 1390 |
return "", err |
| 1391 |
} |
| 1392 |
if msg.Event != model.MessageEvent && msg.Event != model.MessageDeleteEvent && msg.Event != model.MessageClearEvent { |
| 1393 |
return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this! |
| 1394 |
} |
| 1395 |
return fmt.Sprintf("data: %s\n", buf.String()), nil |
| 1396 |
} |
| 1397 |
return s.handleSubscribeHTTP(w, r, v, "text/event-stream", encoder) |
| 1398 |
} |
| 1399 |
|
| 1400 |
func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 1401 |
encoder := func(msg *model.Message) (string, error) { |
| 1402 |
if msg.Event == model.MessageEvent { // only handle default events |
| 1403 |
return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil |
| 1404 |
} |
| 1405 |
return "\n", nil // "keepalive" and "open" events just send an empty line |
| 1406 |
} |
| 1407 |
return s.handleSubscribeHTTP(w, r, v, "text/plain", encoder) |
| 1408 |
} |
| 1409 |
|
| 1410 |
func (s *Server) handleSubscribeHTTP(w http.ResponseWriter, r *http.Request, v *visitor, contentType string, encoder messageEncoder) error { |
| 1411 |
logvr(v, r).Tag(tagSubscribe).Debug("HTTP stream connection opened") |
| 1412 |
defer logvr(v, r).Tag(tagSubscribe).Debug("HTTP stream connection closed") |
| 1413 |
if !v.SubscriptionAllowed() { |
| 1414 |
return errHTTPTooManyRequestsLimitSubscriptions |
| 1415 |
} |
| 1416 |
defer v.RemoveSubscription() |
| 1417 |
topics, topicsStr, err := s.topicsFromPath(v, r.URL.Path) |
| 1418 |
if err != nil { |
| 1419 |
return err |
| 1420 |
} |
| 1421 |
poll, since, scheduled, filters, err := parseSubscribeParams(r) |
| 1422 |
if err != nil { |
| 1423 |
return err |
| 1424 |
} |
| 1425 |
var wlock sync.Mutex |
| 1426 |
var closed bool |
| 1427 |
defer func() { |
| 1428 |
// This blocks until any in-flight sub() call finishes writing/flushing the response writer, |
| 1429 |
// then marks the connection as closed so future sub() calls are no-ops. This prevents a panic |
| 1430 |
// from writing to a response writer that has been cleaned up after the handler returns. |
| 1431 |
// See https://github.com/binwiederhier/ntfy/issues/338#issuecomment-1163425889 |
| 1432 |
// and https://github.com/binwiederhier/ntfy/pull/1598. |
| 1433 |
wlock.Lock() |
| 1434 |
closed = true |
| 1435 |
wlock.Unlock() |
| 1436 |
}() |
| 1437 |
sub := func(v *visitor, msg *model.Message) error { |
| 1438 |
if !filters.Pass(msg) { |
| 1439 |
return nil |
| 1440 |
} |
| 1441 |
m, err := encoder(msg) |
| 1442 |
if err != nil { |
| 1443 |
return err |
| 1444 |
} |
| 1445 |
wlock.Lock() |
| 1446 |
defer wlock.Unlock() |
| 1447 |
if closed { |
| 1448 |
return nil |
| 1449 |
} |
| 1450 |
if _, err := w.Write([]byte(m)); err != nil { |
| 1451 |
return err |
| 1452 |
} |
| 1453 |
if fl, ok := w.(http.Flusher); ok { |
| 1454 |
fl.Flush() |
| 1455 |
} |
| 1456 |
return nil |
| 1457 |
} |
| 1458 |
if err := s.maybeSetRateVisitors(r, v, topics); err != nil { |
| 1459 |
return err |
| 1460 |
} |
| 1461 |
w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests |
| 1462 |
w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset! |
| 1463 |
if poll { |
| 1464 |
for _, t := range topics { |
| 1465 |
t.Keepalive() |
| 1466 |
} |
| 1467 |
return s.sendOldMessages(topics, since, scheduled, v, sub) |
| 1468 |
} |
| 1469 |
ctx, cancel := context.WithCancel(context.Background()) |
| 1470 |
defer cancel() |
| 1471 |
subscriberIDs := make([]int, 0) |
| 1472 |
for _, t := range topics { |
| 1473 |
subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v.MaybeUserID(), cancel)) |
| 1474 |
} |
| 1475 |
defer func() { |
| 1476 |
for i, subscriberID := range subscriberIDs { |
| 1477 |
topics[i].Unsubscribe(subscriberID) // Order! |
| 1478 |
} |
| 1479 |
}() |
| 1480 |
if err := sub(v, model.NewOpenMessage(topicsStr)); err != nil { // Send out open message |
| 1481 |
return err |
| 1482 |
} |
| 1483 |
if err := s.sendOldMessages(topics, since, scheduled, v, sub); err != nil { |
| 1484 |
return err |
| 1485 |
} |
| 1486 |
for { |
| 1487 |
select { |
| 1488 |
case <-ctx.Done(): |
| 1489 |
return nil |
| 1490 |
case <-r.Context().Done(): |
| 1491 |
return nil |
| 1492 |
case <-time.After(s.config.KeepaliveInterval): |
| 1493 |
ev := logvr(v, r).Tag(tagSubscribe) |
| 1494 |
if len(topics) == 1 { |
| 1495 |
ev.With(topics[0]).Trace("Sending keepalive message to %s", topics[0].ID) |
| 1496 |
} else { |
| 1497 |
ev.Trace("Sending keepalive message to %d topics", len(topics)) |
| 1498 |
} |
| 1499 |
v.Keepalive() |
| 1500 |
for _, t := range topics { |
| 1501 |
t.Keepalive() |
| 1502 |
} |
| 1503 |
if err := sub(v, model.NewKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message |
| 1504 |
return err |
| 1505 |
} |
| 1506 |
} |
| 1507 |
} |
| 1508 |
} |
| 1509 |
|
| 1510 |
func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 1511 |
if strings.ToLower(r.Header.Get("Upgrade")) != "websocket" { |
| 1512 |
return errHTTPBadRequestWebSocketsUpgradeHeaderMissing |
| 1513 |
} |
| 1514 |
if !v.SubscriptionAllowed() { |
| 1515 |
return errHTTPTooManyRequestsLimitSubscriptions |
| 1516 |
} |
| 1517 |
defer v.RemoveSubscription() |
| 1518 |
logvr(v, r).Tag(tagWebsocket).Debug("WebSocket connection opened") |
| 1519 |
defer logvr(v, r).Tag(tagWebsocket).Debug("WebSocket connection closed") |
| 1520 |
topics, topicsStr, err := s.topicsFromPath(v, r.URL.Path) |
| 1521 |
if err != nil { |
| 1522 |
return err |
| 1523 |
} |
| 1524 |
poll, since, scheduled, filters, err := parseSubscribeParams(r) |
| 1525 |
if err != nil { |
| 1526 |
return err |
| 1527 |
} |
| 1528 |
upgrader := &websocket.Upgrader{ |
| 1529 |
ReadBufferSize: wsBufferSize, |
| 1530 |
WriteBufferSize: wsBufferSize, |
| 1531 |
CheckOrigin: func(r *http.Request) bool { |
| 1532 |
return true // We're open for business! |
| 1533 |
}, |
| 1534 |
} |
| 1535 |
conn, err := upgrader.Upgrade(w, r, nil) |
| 1536 |
if err != nil { |
| 1537 |
return err |
| 1538 |
} |
| 1539 |
defer conn.Close() |
| 1540 |
|
| 1541 |
// Subscription connections can be canceled externally, see topic.CancelSubscribersExceptUser |
| 1542 |
cancelCtx, cancel := context.WithCancel(context.Background()) |
| 1543 |
defer cancel() |
| 1544 |
|
| 1545 |
// Use errgroup to run WebSocket reader and writer in Go routines |
| 1546 |
var wlock sync.Mutex |
| 1547 |
g, gctx := errgroup.WithContext(cancelCtx) |
| 1548 |
g.Go(func() error { |
| 1549 |
pongWait := s.config.KeepaliveInterval + wsPongWait |
| 1550 |
conn.SetReadLimit(wsReadLimit) |
| 1551 |
if err := conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil { |
| 1552 |
return err |
| 1553 |
} |
| 1554 |
conn.SetPongHandler(func(appData string) error { |
| 1555 |
logvr(v, r).Tag(tagWebsocket).Trace("Received WebSocket pong") |
| 1556 |
return conn.SetReadDeadline(time.Now().Add(pongWait)) |
| 1557 |
}) |
| 1558 |
for { |
| 1559 |
_, _, err := conn.NextReader() |
| 1560 |
if err != nil { |
| 1561 |
return err |
| 1562 |
} |
| 1563 |
select { |
| 1564 |
case <-gctx.Done(): |
| 1565 |
return nil |
| 1566 |
default: |
| 1567 |
} |
| 1568 |
} |
| 1569 |
}) |
| 1570 |
g.Go(func() error { |
| 1571 |
ping := func() error { |
| 1572 |
wlock.Lock() |
| 1573 |
defer wlock.Unlock() |
| 1574 |
if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil { |
| 1575 |
return err |
| 1576 |
} |
| 1577 |
logvr(v, r).Tag(tagWebsocket).Trace("Sending WebSocket ping") |
| 1578 |
return conn.WriteMessage(websocket.PingMessage, nil) |
| 1579 |
} |
| 1580 |
for { |
| 1581 |
select { |
| 1582 |
case <-gctx.Done(): |
| 1583 |
return nil |
| 1584 |
case <-cancelCtx.Done(): |
| 1585 |
logvr(v, r).Tag(tagWebsocket).Trace("Cancel received, closing subscriber connection") |
| 1586 |
conn.Close() |
| 1587 |
return &websocket.CloseError{Code: websocket.CloseNormalClosure, Text: "subscription was canceled"} |
| 1588 |
case <-time.After(s.config.KeepaliveInterval): |
| 1589 |
v.Keepalive() |
| 1590 |
for _, t := range topics { |
| 1591 |
t.Keepalive() |
| 1592 |
} |
| 1593 |
if err := ping(); err != nil { |
| 1594 |
return err |
| 1595 |
} |
| 1596 |
} |
| 1597 |
} |
| 1598 |
}) |
| 1599 |
sub := func(v *visitor, msg *model.Message) error { |
| 1600 |
if !filters.Pass(msg) { |
| 1601 |
return nil |
| 1602 |
} |
| 1603 |
wlock.Lock() |
| 1604 |
defer wlock.Unlock() |
| 1605 |
if err := conn.SetWriteDeadline(time.Now().Add(wsWriteWait)); err != nil { |
| 1606 |
return err |
| 1607 |
} |
| 1608 |
return conn.WriteJSON(msg) |
| 1609 |
} |
| 1610 |
if err := s.maybeSetRateVisitors(r, v, topics); err != nil { |
| 1611 |
return err |
| 1612 |
} |
| 1613 |
w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests |
| 1614 |
if poll { |
| 1615 |
for _, t := range topics { |
| 1616 |
t.Keepalive() |
| 1617 |
} |
| 1618 |
return s.sendOldMessages(topics, since, scheduled, v, sub) |
| 1619 |
} |
| 1620 |
subscriberIDs := make([]int, 0) |
| 1621 |
for _, t := range topics { |
| 1622 |
subscriberIDs = append(subscriberIDs, t.Subscribe(sub, v.MaybeUserID(), cancel)) |
| 1623 |
} |
| 1624 |
defer func() { |
| 1625 |
for i, subscriberID := range subscriberIDs { |
| 1626 |
topics[i].Unsubscribe(subscriberID) // Order! |
| 1627 |
} |
| 1628 |
}() |
| 1629 |
if err := sub(v, model.NewOpenMessage(topicsStr)); err != nil { // Send out open message |
| 1630 |
return err |
| 1631 |
} |
| 1632 |
if err := s.sendOldMessages(topics, since, scheduled, v, sub); err != nil { |
| 1633 |
return err |
| 1634 |
} |
| 1635 |
err = g.Wait() |
| 1636 |
if err != nil && websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseAbnormalClosure, websocket.CloseNoStatusReceived) { |
| 1637 |
logvr(v, r).Tag(tagWebsocket).Err(err).Fields(websocketErrorContext(err)).Trace("WebSocket connection closed") |
| 1638 |
return nil // Normal closures are not errors; note: "1006 (abnormal closure)" is treated as normal, because people disconnect a lot |
| 1639 |
} |
| 1640 |
if err != nil { |
| 1641 |
return &errWebSocketPostUpgrade{err} |
| 1642 |
} |
| 1643 |
return nil |
| 1644 |
} |
| 1645 |
|
| 1646 |
func parseSubscribeParams(r *http.Request) (poll bool, since model.SinceMarker, scheduled bool, filters *queryFilter, err error) { |
| 1647 |
poll = readBoolParam(r, false, "x-poll", "poll", "po") |
| 1648 |
scheduled = readBoolParam(r, false, "x-scheduled", "scheduled", "sched") |
| 1649 |
since, err = parseSince(r, poll) |
| 1650 |
if err != nil { |
| 1651 |
return |
| 1652 |
} |
| 1653 |
filters, err = parseQueryFilters(r) |
| 1654 |
if err != nil { |
| 1655 |
return |
| 1656 |
} |
| 1657 |
return |
| 1658 |
} |
| 1659 |
|
| 1660 |
// maybeSetRateVisitors sets the rate visitor on a topic (v.SetRateVisitor), indicating that all messages published |
| 1661 |
// to that topic will be rate limited against the rate visitor instead of the publishing visitor. |
| 1662 |
// |
| 1663 |
// Setting the rate visitor is ony allowed if the `visitor-subscriber-rate-limiting` setting is enabled, AND |
| 1664 |
// - auth-file is not set (everything is open by default) |
| 1665 |
// - or the topic is reserved, and v.user is the owner |
| 1666 |
// - or the topic is not reserved, and v.user has write access |
| 1667 |
// |
| 1668 |
// This only applies to UnifiedPush topics ("up..."). |
| 1669 |
func (s *Server) maybeSetRateVisitors(r *http.Request, v *visitor, topics []*topic) error { |
| 1670 |
// Bail out if not enabled |
| 1671 |
if !s.config.VisitorSubscriberRateLimiting { |
| 1672 |
return nil |
| 1673 |
} |
| 1674 |
|
| 1675 |
// Make a list of topics that we'll actually set the RateVisitor on |
| 1676 |
eligibleRateTopics := make([]*topic, 0) |
| 1677 |
for _, t := range topics { |
| 1678 |
if strings.HasPrefix(t.ID, unifiedPushTopicPrefix) && len(t.ID) == unifiedPushTopicLength { |
| 1679 |
eligibleRateTopics = append(eligibleRateTopics, t) |
| 1680 |
} |
| 1681 |
} |
| 1682 |
if len(eligibleRateTopics) == 0 { |
| 1683 |
return nil |
| 1684 |
} |
| 1685 |
|
| 1686 |
// If access controls are turned off, v has access to everything, and we can set the rate visitor |
| 1687 |
if s.userManager == nil { |
| 1688 |
return s.setRateVisitors(r, v, eligibleRateTopics) |
| 1689 |
} |
| 1690 |
|
| 1691 |
// If access controls are enabled, only set rate visitor if |
| 1692 |
// - topic is reserved, and v.user is the owner |
| 1693 |
// - topic is not reserved, and v.user has write access |
| 1694 |
writableRateTopics := make([]*topic, 0) |
| 1695 |
for _, t := range topics { |
| 1696 |
if !util.Contains(eligibleRateTopics, t) { |
| 1697 |
continue |
| 1698 |
} |
| 1699 |
ownerUserID, err := s.userManager.ReservationOwner(t.ID) |
| 1700 |
if err != nil { |
| 1701 |
return err |
| 1702 |
} |
| 1703 |
if ownerUserID == "" { |
| 1704 |
if err := s.userManager.Authorize(v.User(), t.ID, user.PermissionWrite); err == nil { |
| 1705 |
writableRateTopics = append(writableRateTopics, t) |
| 1706 |
} |
| 1707 |
} else if ownerUserID == v.MaybeUserID() { |
| 1708 |
writableRateTopics = append(writableRateTopics, t) |
| 1709 |
} |
| 1710 |
} |
| 1711 |
return s.setRateVisitors(r, v, writableRateTopics) |
| 1712 |
} |
| 1713 |
|
| 1714 |
func (s *Server) setRateVisitors(r *http.Request, v *visitor, rateTopics []*topic) error { |
| 1715 |
for _, t := range rateTopics { |
| 1716 |
logvr(v, r). |
| 1717 |
Tag(tagSubscribe). |
| 1718 |
With(t). |
| 1719 |
Debug("Setting visitor as rate visitor for topic %s", t.ID) |
| 1720 |
t.SetRateVisitor(v) |
| 1721 |
} |
| 1722 |
return nil |
| 1723 |
} |
| 1724 |
|
| 1725 |
// sendOldMessages selects old messages from the messageCache and calls sub for each of them. It uses since as the |
| 1726 |
// marker, returning only messages that are newer than the marker. |
| 1727 |
func (s *Server) sendOldMessages(topics []*topic, since model.SinceMarker, scheduled bool, v *visitor, sub subscriber) error { |
| 1728 |
if since.IsNone() { |
| 1729 |
return nil |
| 1730 |
} |
| 1731 |
messages := make([]*model.Message, 0) |
| 1732 |
for _, t := range topics { |
| 1733 |
topicMessages, err := s.messageCache.Messages(t.ID, since, scheduled) |
| 1734 |
if err != nil { |
| 1735 |
return err |
| 1736 |
} |
| 1737 |
messages = append(messages, topicMessages...) |
| 1738 |
} |
| 1739 |
sort.Slice(messages, func(i, j int) bool { |
| 1740 |
return messages[i].Time < messages[j].Time |
| 1741 |
}) |
| 1742 |
for _, m := range messages { |
| 1743 |
if err := sub(v, m); err != nil { |
| 1744 |
return err |
| 1745 |
} |
| 1746 |
} |
| 1747 |
return nil |
| 1748 |
} |
| 1749 |
|
| 1750 |
// parseSince returns a timestamp identifying the time span from which cached messages should be received. |
| 1751 |
// |
| 1752 |
// Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), |
| 1753 |
// "all" for all messages, or "latest" for the most recent message for a topic |
| 1754 |
func parseSince(r *http.Request, poll bool) (model.SinceMarker, error) { |
| 1755 |
since := readParam(r, "x-since", "since", "si") |
| 1756 |
|
| 1757 |
// Easy cases (empty, all, none) |
| 1758 |
if since == "" { |
| 1759 |
if poll { |
| 1760 |
return model.SinceAllMessages, nil |
| 1761 |
} |
| 1762 |
return model.SinceNoMessages, nil |
| 1763 |
} else if since == "all" { |
| 1764 |
return model.SinceAllMessages, nil |
| 1765 |
} else if since == "latest" { |
| 1766 |
return model.SinceLatestMessage, nil |
| 1767 |
} else if since == "none" { |
| 1768 |
return model.SinceNoMessages, nil |
| 1769 |
} |
| 1770 |
|
| 1771 |
// ID, timestamp, duration |
| 1772 |
if model.ValidMessageID(since) { |
| 1773 |
return model.NewSinceID(since), nil |
| 1774 |
} else if s, err := strconv.ParseInt(since, 10, 64); err == nil { |
| 1775 |
return model.NewSinceTime(s), nil |
| 1776 |
} else if d, err := time.ParseDuration(since); err == nil { |
| 1777 |
return model.NewSinceTime(time.Now().Add(-1 * d).Unix()), nil |
| 1778 |
} |
| 1779 |
return model.SinceNoMessages, errHTTPBadRequestSinceInvalid |
| 1780 |
} |
| 1781 |
|
| 1782 |
func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request, _ *visitor) error { |
| 1783 |
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, PATCH, DELETE") |
| 1784 |
w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests |
| 1785 |
w.Header().Set("Access-Control-Allow-Headers", "*") // CORS, allow auth via JS // FIXME is this terrible? |
| 1786 |
return nil |
| 1787 |
} |
| 1788 |
|
| 1789 |
// topicFromPath returns the topic from a root path (e.g. /mytopic), creating it if it doesn't exist. |
| 1790 |
// The visitor is consulted for the per-visitor topic-creation rate limit; pass nil to bypass (internal use). |
| 1791 |
func (s *Server) topicFromPath(v *visitor, path string) (*topic, error) { |
| 1792 |
parts := strings.Split(path, "/") |
| 1793 |
if len(parts) < 2 { |
| 1794 |
return nil, errHTTPBadRequestTopicInvalid |
| 1795 |
} |
| 1796 |
return s.topicFromID(v, parts[1]) |
| 1797 |
} |
| 1798 |
|
| 1799 |
// topicsFromPath returns the topic from a root path (e.g. /mytopic,mytopic2), creating it if it doesn't exist. |
| 1800 |
// The visitor is consulted for the per-visitor topic-creation rate limit; pass nil to bypass (internal use). |
| 1801 |
func (s *Server) topicsFromPath(v *visitor, path string) ([]*topic, string, error) { |
| 1802 |
parts := strings.Split(path, "/") |
| 1803 |
if len(parts) < 2 { |
| 1804 |
return nil, "", errHTTPBadRequestTopicInvalid |
| 1805 |
} |
| 1806 |
topicIDs := util.SplitNoEmpty(parts[1], ",") |
| 1807 |
topics, err := s.topicsFromIDs(v, topicIDs...) |
| 1808 |
if err != nil { |
| 1809 |
return nil, "", err |
| 1810 |
} |
| 1811 |
return topics, parts[1], nil |
| 1812 |
} |
| 1813 |
|
| 1814 |
// sequenceIDFromPath returns the sequence ID from a path like /mytopic/sequenceIdHere |
| 1815 |
func (s *Server) sequenceIDFromPath(path string) (string, *errHTTP) { |
| 1816 |
parts := strings.Split(path, "/") |
| 1817 |
if len(parts) < 3 { |
| 1818 |
return "", errHTTPBadRequestSequenceIDInvalid |
| 1819 |
} |
| 1820 |
return parts[2], nil |
| 1821 |
} |
| 1822 |
|
| 1823 |
// topicsFromIDs returns the topics with the given IDs, creating them if they don't exist. |
| 1824 |
// If v is non-nil, its per-visitor topic-creation rate limiter is consulted before each new |
| 1825 |
// insertion into the in-memory topic map. Pass nil to bypass the limit (internal use only). |
| 1826 |
func (s *Server) topicsFromIDs(v *visitor, ids ...string) ([]*topic, error) { |
| 1827 |
s.mu.Lock() |
| 1828 |
defer s.mu.Unlock() |
| 1829 |
topics := make([]*topic, 0) |
| 1830 |
for _, id := range ids { |
| 1831 |
if util.Contains(s.config.DisallowedTopics, id) { |
| 1832 |
return nil, errHTTPBadRequestTopicDisallowed |
| 1833 |
} |
| 1834 |
if _, ok := s.topics[id]; !ok { |
| 1835 |
if len(s.topics) >= s.config.TotalTopicLimit { |
| 1836 |
return nil, errHTTPTooManyRequestsLimitTotalTopics |
| 1837 |
} |
| 1838 |
if v != nil && !v.TopicCreationAllowed() { |
| 1839 |
return nil, errHTTPTooManyRequestsLimitTopicCreation |
| 1840 |
} |
| 1841 |
s.topics[id] = newTopic(id) |
| 1842 |
} |
| 1843 |
topics = append(topics, s.topics[id]) |
| 1844 |
} |
| 1845 |
return topics, nil |
| 1846 |
} |
| 1847 |
|
| 1848 |
// topicFromID returns the topic with the given ID, creating it if it doesn't exist. |
| 1849 |
// The visitor is consulted for the per-visitor topic-creation rate limit; pass nil to bypass (internal use). |
| 1850 |
func (s *Server) topicFromID(v *visitor, id string) (*topic, error) { |
| 1851 |
topics, err := s.topicsFromIDs(v, id) |
| 1852 |
if err != nil { |
| 1853 |
return nil, err |
| 1854 |
} |
| 1855 |
return topics[0], nil |
| 1856 |
} |
| 1857 |
|
| 1858 |
// topicsFromPattern returns a list of topics matching the given pattern, but it does not create them. |
| 1859 |
func (s *Server) topicsFromPattern(pattern string) ([]*topic, error) { |
| 1860 |
s.mu.RLock() |
| 1861 |
defer s.mu.RUnlock() |
| 1862 |
patternRegexp, err := regexp.Compile("^" + strings.ReplaceAll(pattern, "*", ".*") + "$") |
| 1863 |
if err != nil { |
| 1864 |
return nil, err |
| 1865 |
} |
| 1866 |
topics := make([]*topic, 0) |
| 1867 |
for _, t := range s.topics { |
| 1868 |
if patternRegexp.MatchString(t.ID) { |
| 1869 |
topics = append(topics, t) |
| 1870 |
} |
| 1871 |
} |
| 1872 |
return topics, nil |
| 1873 |
} |
| 1874 |
|
| 1875 |
func (s *Server) runSMTPServer() error { |
| 1876 |
s.smtpServerBackend = newMailBackend(s.config, s.handle) |
| 1877 |
s.smtpServer = smtp.NewServer(s.smtpServerBackend) |
| 1878 |
s.smtpServer.Addr = s.config.SMTPServerListen |
| 1879 |
s.smtpServer.Domain = s.config.SMTPServerDomain |
| 1880 |
s.smtpServer.ReadTimeout = 10 * time.Second |
| 1881 |
s.smtpServer.WriteTimeout = 10 * time.Second |
| 1882 |
s.smtpServer.MaxMessageBytes = 1024 * 1024 // Must be much larger than message size (headers, multipart, etc.) |
| 1883 |
s.smtpServer.MaxRecipients = 1 |
| 1884 |
s.smtpServer.AllowInsecureAuth = true |
| 1885 |
return s.smtpServer.ListenAndServe() |
| 1886 |
} |
| 1887 |
|
| 1888 |
func (s *Server) runManager() { |
| 1889 |
for { |
| 1890 |
select { |
| 1891 |
case <-time.After(s.config.ManagerInterval): |
| 1892 |
log. |
| 1893 |
Tag(tagManager). |
| 1894 |
Timing(s.execManager). |
| 1895 |
Debug("Manager finished") |
| 1896 |
case <-s.closeChan: |
| 1897 |
return |
| 1898 |
} |
| 1899 |
} |
| 1900 |
} |
| 1901 |
|
| 1902 |
// runStatsResetter runs once a day (usually midnight UTC) to reset all the visitor's message and |
| 1903 |
// email counters. The stats are used to display the counters in the web app, as well as for rate limiting. |
| 1904 |
func (s *Server) runStatsResetter() { |
| 1905 |
for { |
| 1906 |
runAt := util.NextOccurrenceUTC(s.config.VisitorStatsResetTime, time.Now()) |
| 1907 |
timer := time.NewTimer(time.Until(runAt)) |
| 1908 |
log.Tag(tagResetter).Debug("Waiting until %v to reset visitor stats", runAt) |
| 1909 |
select { |
| 1910 |
case <-timer.C: |
| 1911 |
log.Tag(tagResetter).Debug("Running stats resetter") |
| 1912 |
s.resetStats() |
| 1913 |
case <-s.closeChan: |
| 1914 |
log.Tag(tagResetter).Debug("Stopping stats resetter") |
| 1915 |
timer.Stop() |
| 1916 |
return |
| 1917 |
} |
| 1918 |
} |
| 1919 |
} |
| 1920 |
|
| 1921 |
func (s *Server) resetStats() { |
| 1922 |
log.Info("Resetting all visitor stats (daily task)") |
| 1923 |
s.mu.Lock() |
| 1924 |
defer s.mu.Unlock() // Includes the database query to avoid races with other processes |
| 1925 |
for _, v := range s.visitors { |
| 1926 |
v.ResetStats() |
| 1927 |
} |
| 1928 |
if s.userManager != nil { |
| 1929 |
if err := s.userManager.ResetStats(); err != nil { |
| 1930 |
log.Tag(tagResetter).Warn("Failed to write to database: %s", err.Error()) |
| 1931 |
} |
| 1932 |
} |
| 1933 |
} |
| 1934 |
|
| 1935 |
func (s *Server) runFirebaseKeepaliver() { |
| 1936 |
if s.firebaseClient == nil { |
| 1937 |
return |
| 1938 |
} |
| 1939 |
v := newVisitor(s.config, s.messageCache, s.userManager, netip.IPv4Unspecified(), nil) // Background process, not a real visitor, uses IP 0.0.0.0 |
| 1940 |
for { |
| 1941 |
select { |
| 1942 |
case <-time.After(s.config.FirebaseKeepaliveInterval): |
| 1943 |
s.sendToFirebase(v, model.NewKeepaliveMessage(firebaseControlTopic)) |
| 1944 |
/* |
| 1945 |
FIXME: Disable iOS polling entirely for now due to thundering herd problem (see #677) |
| 1946 |
To solve this, we'd have to shard the iOS poll topics to spread out the polling evenly. |
| 1947 |
Given that it's not really necessary to poll, turning it off for now should not have any impact. |
| 1948 |
|
| 1949 |
case <-time.After(s.config.FirebasePollInterval): |
| 1950 |
s.sendToFirebase(v, model.NewKeepaliveMessage(firebasePollTopic)) |
| 1951 |
*/ |
| 1952 |
case <-s.closeChan: |
| 1953 |
return |
| 1954 |
} |
| 1955 |
} |
| 1956 |
} |
| 1957 |
|
| 1958 |
func (s *Server) runDelayedSender() { |
| 1959 |
for { |
| 1960 |
select { |
| 1961 |
case <-time.After(s.config.DelayedSenderInterval): |
| 1962 |
if err := s.sendDelayedMessages(); err != nil { |
| 1963 |
log.Tag(tagPublish).Err(err).Warn("Error sending delayed messages") |
| 1964 |
} |
| 1965 |
case <-s.closeChan: |
| 1966 |
return |
| 1967 |
} |
| 1968 |
} |
| 1969 |
} |
| 1970 |
|
| 1971 |
func (s *Server) sendDelayedMessages() error { |
| 1972 |
messages, err := s.messageCache.MessagesDue() |
| 1973 |
if err != nil { |
| 1974 |
return err |
| 1975 |
} |
| 1976 |
for _, m := range messages { |
| 1977 |
var u *user.User |
| 1978 |
if s.userManager != nil && m.User != "" { |
| 1979 |
u, err = s.userManager.UserByID(m.User) |
| 1980 |
if err != nil { |
| 1981 |
log.With(m).Err(err).Warn("Error sending delayed message") |
| 1982 |
continue |
| 1983 |
} |
| 1984 |
} |
| 1985 |
v := s.visitor(m.Sender, u) |
| 1986 |
if err := s.sendDelayedMessage(v, m); err != nil { |
| 1987 |
logvm(v, m).Err(err).Warn("Error sending delayed message") |
| 1988 |
} |
| 1989 |
} |
| 1990 |
return nil |
| 1991 |
} |
| 1992 |
|
| 1993 |
func (s *Server) sendDelayedMessage(v *visitor, m *model.Message) error { |
| 1994 |
logvm(v, m).Debug("Sending delayed message") |
| 1995 |
s.mu.RLock() |
| 1996 |
t := s.topics[m.Topic] // May be nil if there are no local subscribers; dispatch handles that |
| 1997 |
s.mu.RUnlock() |
| 1998 |
// We do not rate-limit messages here, since we've rate limited them in the PUT/POST handler. |
| 1999 |
// Firebase subscribers may not show up in the topics map, so side effects fire regardless. |
| 2000 |
err := s.dispatch(v, t, m, dispatchOpts{ |
| 2001 |
firebase: true, |
| 2002 |
upstream: true, |
| 2003 |
webPush: true, |
| 2004 |
async: true, |
| 2005 |
}) |
| 2006 |
if err != nil { |
| 2007 |
return err |
| 2008 |
} |
| 2009 |
if err := s.messageCache.MarkPublished(m); err != nil { |
| 2010 |
return err |
| 2011 |
} |
| 2012 |
return nil |
| 2013 |
} |
| 2014 |
|
| 2015 |
// transformBodyJSON peeks the request body, reads the JSON, and converts it to headers |
| 2016 |
// before passing it on to the next handler. This is meant to be used in combination with handlePublish. |
| 2017 |
func (s *Server) transformBodyJSON(next handleFunc) handleFunc { |
| 2018 |
return func(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 2019 |
m, err := readJSONWithLimit[publishMessage](r.Body, s.config.MessageSizeLimit*2, false) // 2x to account for JSON format overhead |
| 2020 |
if err != nil { |
| 2021 |
return err |
| 2022 |
} |
| 2023 |
if !topicRegex.MatchString(m.Topic) { |
| 2024 |
return errHTTPBadRequestTopicInvalid |
| 2025 |
} |
| 2026 |
if m.Message == "" { |
| 2027 |
m.Message = emptyMessageBody |
| 2028 |
} |
| 2029 |
r.URL.Path = "/" + m.Topic |
| 2030 |
r.Body = io.NopCloser(strings.NewReader(m.Message)) |
| 2031 |
if m.Title != "" { |
| 2032 |
r.Header.Set("X-Title", m.Title) |
| 2033 |
} |
| 2034 |
if m.Priority != 0 { |
| 2035 |
r.Header.Set("X-Priority", fmt.Sprintf("%d", m.Priority)) |
| 2036 |
} |
| 2037 |
if len(m.Tags) > 0 { |
| 2038 |
r.Header.Set("X-Tags", strings.Join(m.Tags, ",")) |
| 2039 |
} |
| 2040 |
if m.Attach != "" { |
| 2041 |
r.Header.Set("X-Attach", m.Attach) |
| 2042 |
} |
| 2043 |
if m.Filename != "" { |
| 2044 |
r.Header.Set("X-Filename", m.Filename) |
| 2045 |
} |
| 2046 |
if m.Click != "" { |
| 2047 |
r.Header.Set("X-Click", m.Click) |
| 2048 |
} |
| 2049 |
if m.Icon != "" { |
| 2050 |
r.Header.Set("X-Icon", m.Icon) |
| 2051 |
} |
| 2052 |
if m.Markdown { |
| 2053 |
r.Header.Set("X-Markdown", "yes") |
| 2054 |
} |
| 2055 |
if len(m.Actions) > 0 { |
| 2056 |
actionsStr, err := json.Marshal(m.Actions) |
| 2057 |
if err != nil { |
| 2058 |
return errHTTPBadRequestMessageJSONInvalid |
| 2059 |
} |
| 2060 |
r.Header.Set("X-Actions", string(actionsStr)) |
| 2061 |
} |
| 2062 |
if m.Email != "" { |
| 2063 |
r.Header.Set("X-Email", m.Email) |
| 2064 |
} |
| 2065 |
if m.Delay != "" { |
| 2066 |
r.Header.Set("X-Delay", m.Delay) |
| 2067 |
} |
| 2068 |
if m.Call != "" { |
| 2069 |
r.Header.Set("X-Call", m.Call) |
| 2070 |
} |
| 2071 |
if m.Cache != "" { |
| 2072 |
r.Header.Set("X-Cache", m.Cache) |
| 2073 |
} |
| 2074 |
if m.Firebase != "" { |
| 2075 |
r.Header.Set("X-Firebase", m.Firebase) |
| 2076 |
} |
| 2077 |
if m.SequenceID != "" { |
| 2078 |
r.Header.Set("X-Sequence-ID", m.SequenceID) |
| 2079 |
} |
| 2080 |
return next(w, r, v) |
| 2081 |
} |
| 2082 |
} |
| 2083 |
|
| 2084 |
func (s *Server) transformMatrixJSON(next handleFunc) handleFunc { |
| 2085 |
return func(w http.ResponseWriter, r *http.Request, v *visitor) error { |
| 2086 |
newRequest, err := newRequestFromMatrixJSON(r, s.config.BaseURL, s.config.MessageSizeLimit) |
| 2087 |
if err != nil { |
| 2088 |
logvr(v, r).Tag(tagMatrix).Err(err).Debug("Invalid Matrix request") |
| 2089 |
if e, ok := err.(*errMatrixPushkeyRejected); ok { |
| 2090 |
return writeMatrixResponse(w, e.rejectedPushKey) |
| 2091 |
} |
| 2092 |
return err |
| 2093 |
} |
| 2094 |
if err := next(w, newRequest, v); err != nil { |
| 2095 |
logvr(v, r).Tag(tagMatrix).Err(err).Debug("Error handling Matrix request") |
| 2096 |
return err |
| 2097 |
} |
| 2098 |
return nil |
| 2099 |
} |
| 2100 |
} |
| 2101 |
|
| 2102 |
func (s *Server) visitor(ip netip.Addr, user *user.User) *visitor { |
| 2103 |
s.mu.Lock() |
| 2104 |
defer s.mu.Unlock() |
| 2105 |
id := visitorID(ip, user, s.config) |
| 2106 |
v, exists := s.visitors[id] |
| 2107 |
if !exists { |
| 2108 |
s.visitors[id] = newVisitor(s.config, s.messageCache, s.userManager, ip, user) |
| 2109 |
return s.visitors[id] |
| 2110 |
} |
| 2111 |
v.Keepalive() |
| 2112 |
v.SetUser(user) // Always update with the latest user, may be nil! |
| 2113 |
return v |
| 2114 |
} |
| 2115 |
|
| 2116 |
func (s *Server) writeJSON(w http.ResponseWriter, v any) error { |
| 2117 |
return s.writeJSONWithContentType(w, v, "application/json") |
| 2118 |
} |
| 2119 |
|
| 2120 |
func (s *Server) writeJSONWithContentType(w http.ResponseWriter, v any, contentType string) error { |
| 2121 |
w.Header().Set("Content-Type", contentType) |
| 2122 |
w.Header().Set("Access-Control-Allow-Origin", s.config.AccessControlAllowOrigin) // CORS, allow cross-origin requests |
| 2123 |
return util.EncodeJSON(w, v) |
| 2124 |
} |
| 2125 |
|
| 2126 |
func (s *Server) updateAndWriteStats(messagesCount int64) { |
| 2127 |
s.mu.Lock() |
| 2128 |
s.messagesHistory = append(s.messagesHistory, messagesCount) |
| 2129 |
if len(s.messagesHistory) > messagesHistoryMax { |
| 2130 |
s.messagesHistory = s.messagesHistory[1:] |
| 2131 |
} |
| 2132 |
s.mu.Unlock() |
| 2133 |
if err := s.messageCache.UpdateStats(messagesCount); err != nil { |
| 2134 |
log.Tag(tagManager).Err(err).Warn("Cannot write messages stats") |
| 2135 |
} |
| 2136 |
} |