1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-12-14 11:47:33 +00:00
binwiederhier-ntfy/server/server.go

682 lines
19 KiB
Go
Raw Normal View History

2021-10-23 01:26:01 +00:00
package server
import (
"bytes"
2021-10-29 03:50:38 +00:00
"context"
2021-12-07 16:45:15 +00:00
"embed" // required for go:embed
2021-10-23 01:26:01 +00:00
"encoding/json"
2021-10-29 03:50:38 +00:00
firebase "firebase.google.com/go"
"firebase.google.com/go/messaging"
2021-10-23 17:21:33 +00:00
"fmt"
2021-10-29 03:50:38 +00:00
"google.golang.org/api/option"
"heckel.io/ntfy/config"
2021-11-08 14:24:34 +00:00
"heckel.io/ntfy/util"
"html/template"
2021-10-23 01:26:01 +00:00
"io"
"log"
2021-10-24 02:49:50 +00:00
"net"
2021-10-23 01:26:01 +00:00
"net/http"
"regexp"
2021-10-29 17:58:14 +00:00
"strconv"
2021-10-23 01:26:01 +00:00
"strings"
"sync"
"time"
)
2021-10-29 17:58:14 +00:00
// TODO add "max messages in a topic" limit
2021-11-01 20:39:40 +00:00
// TODO implement "since=<ID>"
2021-10-29 17:58:14 +00:00
2021-12-07 16:45:15 +00:00
// Server is the main server, providing the UI and API for ntfy
2021-10-23 01:26:01 +00:00
type Server struct {
2021-10-24 02:49:50 +00:00
config *config.Config
topics map[string]*topic
visitors map[string]*visitor
2021-10-29 17:58:14 +00:00
firebase subscriber
messages int64
2021-11-03 01:09:49 +00:00
cache cache
2021-10-24 02:49:50 +00:00
mu sync.Mutex
2021-10-23 01:26:01 +00:00
}
2021-10-24 02:49:50 +00:00
// errHTTP is a generic HTTP error for any non-200 HTTP error
type errHTTP struct {
Code int
Status string
}
func (e errHTTP) Error() string {
return fmt.Sprintf("http: %s", e.Status)
2021-10-23 01:26:01 +00:00
}
2021-11-08 14:24:34 +00:00
type indexPage struct {
Topic string
2021-12-09 15:23:17 +00:00
CacheDuration time.Duration
2021-11-08 14:24:34 +00:00
}
type sinceTime time.Time
func (t sinceTime) IsAll() bool {
return t == sinceAllMessages
}
func (t sinceTime) IsNone() bool {
return t == sinceNoMessages
}
func (t sinceTime) Time() time.Time {
return time.Time(t)
}
var (
sinceAllMessages = sinceTime(time.Unix(0, 0))
sinceNoMessages = sinceTime(time.Unix(1, 0))
)
2021-10-23 01:26:01 +00:00
var (
2021-11-08 14:24:34 +00:00
topicRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}$`) // Regex must match JS & Android app!
2021-11-15 12:56:58 +00:00
jsonRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/json$`)
sseRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/sse$`)
rawRegex = regexp.MustCompile(`^/[-_A-Za-z0-9]{1,64}(,[-_A-Za-z0-9]{1,64})*/raw$`)
2021-10-29 17:58:14 +00:00
2021-12-09 03:13:59 +00:00
staticRegex = regexp.MustCompile(`^/static/.+`)
docsRegex = regexp.MustCompile(`^/docs(|/.*)$`)
disallowedTopics = []string{"docs", "static"}
2021-10-23 01:26:01 +00:00
2021-12-09 15:23:17 +00:00
templateFnMap = template.FuncMap{
"durationToHuman": util.DurationToHuman,
}
2021-11-08 14:24:34 +00:00
//go:embed "index.gohtml"
indexSource string
2021-12-09 15:23:17 +00:00
indexTemplate = template.Must(template.New("index").Funcs(templateFnMap).Parse(indexSource))
2021-11-18 14:22:33 +00:00
//go:embed "example.html"
2021-11-27 21:12:08 +00:00
exampleSource string
2021-11-18 14:22:33 +00:00
2021-10-24 18:22:53 +00:00
//go:embed static
webStaticFs embed.FS
webStaticFsCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: webStaticFs}
2021-10-24 18:22:53 +00:00
2021-12-02 22:27:31 +00:00
//go:embed docs
2021-12-07 15:38:58 +00:00
docsStaticFs embed.FS
2021-12-02 22:27:31 +00:00
docsStaticCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: docsStaticFs}
2021-10-29 17:58:14 +00:00
errHTTPBadRequest = &errHTTP{http.StatusBadRequest, http.StatusText(http.StatusBadRequest)}
2021-10-24 02:49:50 +00:00
errHTTPNotFound = &errHTTP{http.StatusNotFound, http.StatusText(http.StatusNotFound)}
errHTTPTooManyRequests = &errHTTP{http.StatusTooManyRequests, http.StatusText(http.StatusTooManyRequests)}
2021-10-23 01:26:01 +00:00
)
2021-12-14 03:30:28 +00:00
const (
firebaseControlTopic = "~control" // See Android if changed
)
2021-12-07 16:45:15 +00:00
// New instantiates a new Server. It creates the cache and adds a Firebase
// subscriber (if configured).
2021-10-29 03:50:38 +00:00
func New(conf *config.Config) (*Server, error) {
2021-10-29 17:58:14 +00:00
var firebaseSubscriber subscriber
2021-10-29 03:50:38 +00:00
if conf.FirebaseKeyFile != "" {
2021-10-29 17:58:14 +00:00
var err error
firebaseSubscriber, err = createFirebaseSubscriber(conf)
2021-10-29 03:50:38 +00:00
if err != nil {
return nil, err
}
}
2021-11-03 01:09:49 +00:00
cache, err := createCache(conf)
2021-11-02 18:08:21 +00:00
if err != nil {
return nil, err
}
2021-11-03 01:09:49 +00:00
topics, err := cache.Topics()
if err != nil {
return nil, err
2021-11-02 18:08:21 +00:00
}
2021-10-23 01:26:01 +00:00
return &Server{
2021-10-24 02:49:50 +00:00
config: conf,
2021-11-03 01:09:49 +00:00
cache: cache,
2021-10-29 17:58:14 +00:00
firebase: firebaseSubscriber,
2021-11-02 18:08:21 +00:00
topics: topics,
2021-10-24 02:49:50 +00:00
visitors: make(map[string]*visitor),
2021-10-29 03:50:38 +00:00
}, nil
2021-10-23 01:26:01 +00:00
}
2021-11-03 01:09:49 +00:00
func createCache(conf *config.Config) (cache, error) {
2021-12-09 15:23:17 +00:00
if conf.CacheDuration == 0 {
return newNopCache(), nil
} else if conf.CacheFile != "" {
2021-11-03 01:09:49 +00:00
return newSqliteCache(conf.CacheFile)
2021-11-02 18:08:21 +00:00
}
2021-11-03 01:09:49 +00:00
return newMemCache(), nil
2021-11-02 18:08:21 +00:00
}
2021-10-29 17:58:14 +00:00
func createFirebaseSubscriber(conf *config.Config) (subscriber, error) {
fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(conf.FirebaseKeyFile))
if err != nil {
return nil, err
}
msg, err := fb.Messaging(context.Background())
if err != nil {
return nil, err
}
return func(m *message) error {
2021-12-14 03:30:28 +00:00
var data map[string]string // Matches https://ntfy.sh/docs/subscribe/api/#json-message-format
switch m.Event {
case keepaliveEvent, openEvent:
data = map[string]string{
"id": m.ID,
"time": fmt.Sprintf("%d", m.Time),
"event": m.Event,
"topic": m.Topic,
}
case messageEvent:
data = map[string]string{
2021-11-27 21:12:08 +00:00
"id": m.ID,
"time": fmt.Sprintf("%d", m.Time),
"event": m.Event,
"topic": m.Topic,
"priority": fmt.Sprintf("%d", m.Priority),
"tags": strings.Join(m.Tags, ","),
"title": m.Title,
"message": m.Message,
2021-12-14 03:30:28 +00:00
}
}
_, err := msg.Send(context.Background(), &messaging.Message{
Topic: m.Topic,
Data: data,
2021-10-29 17:58:14 +00:00
})
return err
}, nil
}
2021-12-07 16:45:15 +00:00
// Run executes the main server. It listens on HTTP (+ HTTPS, if configured), and starts
// a manager go routine to print stats and prune messages.
2021-10-23 01:26:01 +00:00
func (s *Server) Run() error {
2021-12-15 14:13:16 +00:00
go s.runManager()
go s.runAtSender()
go s.runFirebaseKeepliver()
2021-12-02 13:52:48 +00:00
listenStr := fmt.Sprintf("%s/http", s.config.ListenHTTP)
if s.config.ListenHTTPS != "" {
listenStr += fmt.Sprintf(" %s/https", s.config.ListenHTTPS)
}
log.Printf("Listening on %s", listenStr)
2021-10-23 01:26:01 +00:00
http.HandleFunc("/", s.handle)
2021-12-02 13:52:48 +00:00
errChan := make(chan error)
go func() {
errChan <- http.ListenAndServe(s.config.ListenHTTP, nil)
}()
if s.config.ListenHTTPS != "" {
go func() {
errChan <- http.ListenAndServeTLS(s.config.ListenHTTPS, s.config.CertFile, s.config.KeyFile, nil)
}()
}
return <-errChan
2021-10-23 01:26:01 +00:00
}
func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
if err := s.handleInternal(w, r); err != nil {
2021-10-24 02:49:50 +00:00
if e, ok := err.(*errHTTP); ok {
s.fail(w, r, e.Code, e)
} else {
s.fail(w, r, http.StatusInternalServerError, err)
}
2021-10-23 01:26:01 +00:00
}
}
func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request) error {
2021-12-02 22:27:31 +00:00
if r.Method == http.MethodGet && r.URL.Path == "/" {
2021-10-23 01:26:01 +00:00
return s.handleHome(w, r)
2021-11-18 14:22:33 +00:00
} else if r.Method == http.MethodGet && r.URL.Path == "/example.html" {
return s.handleExample(w, r)
} else if r.Method == http.MethodHead && r.URL.Path == "/" {
return s.handleEmpty(w, r)
2021-10-24 18:22:53 +00:00
} else if r.Method == http.MethodGet && staticRegex.MatchString(r.URL.Path) {
return s.handleStatic(w, r)
2021-12-02 22:27:31 +00:00
} else if r.Method == http.MethodGet && docsRegex.MatchString(r.URL.Path) {
return s.handleDocs(w, r)
} else if r.Method == http.MethodOptions {
return s.handleOptions(w, r)
2021-12-02 22:27:31 +00:00
} else if r.Method == http.MethodGet && topicRegex.MatchString(r.URL.Path) {
return s.handleHome(w, r)
2021-10-29 17:58:14 +00:00
} else if (r.Method == http.MethodPut || r.Method == http.MethodPost) && topicRegex.MatchString(r.URL.Path) {
return s.withRateLimit(w, r, s.handlePublish)
2021-10-23 01:26:01 +00:00
} else if r.Method == http.MethodGet && jsonRegex.MatchString(r.URL.Path) {
return s.withRateLimit(w, r, s.handleSubscribeJSON)
2021-10-23 17:21:33 +00:00
} else if r.Method == http.MethodGet && sseRegex.MatchString(r.URL.Path) {
return s.withRateLimit(w, r, s.handleSubscribeSSE)
} else if r.Method == http.MethodGet && rawRegex.MatchString(r.URL.Path) {
return s.withRateLimit(w, r, s.handleSubscribeRaw)
2021-10-23 01:26:01 +00:00
}
2021-10-24 02:49:50 +00:00
return errHTTPNotFound
2021-10-23 01:26:01 +00:00
}
func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) error {
2021-11-08 14:24:34 +00:00
return indexTemplate.Execute(w, &indexPage{
Topic: r.URL.Path[1:],
2021-12-09 15:23:17 +00:00
CacheDuration: s.config.CacheDuration,
2021-11-08 14:24:34 +00:00
})
2021-10-23 01:26:01 +00:00
}
2021-12-07 16:45:15 +00:00
func (s *Server) handleEmpty(_ http.ResponseWriter, _ *http.Request) error {
return nil
}
2021-12-07 16:45:15 +00:00
func (s *Server) handleExample(w http.ResponseWriter, _ *http.Request) error {
2021-11-18 14:22:33 +00:00
_, err := io.WriteString(w, exampleSource)
return err
}
2021-10-29 17:58:14 +00:00
func (s *Server) handleStatic(w http.ResponseWriter, r *http.Request) error {
http.FileServer(http.FS(webStaticFsCached)).ServeHTTP(w, r)
2021-10-29 17:58:14 +00:00
return nil
}
2021-12-02 22:27:31 +00:00
func (s *Server) handleDocs(w http.ResponseWriter, r *http.Request) error {
http.FileServer(http.FS(docsStaticCached)).ServeHTTP(w, r)
return nil
}
2021-12-07 16:45:15 +00:00
func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, _ *visitor) error {
2021-11-15 12:56:58 +00:00
t, err := s.topicFromID(r.URL.Path[1:])
2021-11-01 20:39:40 +00:00
if err != nil {
return err
}
2021-12-11 03:57:01 +00:00
reader := io.LimitReader(r.Body, int64(s.config.MessageLimit))
2021-10-23 01:26:01 +00:00
b, err := io.ReadAll(reader)
if err != nil {
return err
}
2021-12-09 03:57:31 +00:00
m := newDefaultMessage(t.ID, string(b))
2021-11-18 19:21:00 +00:00
if m.Message == "" {
return errHTTPBadRequest
}
2021-12-11 03:57:01 +00:00
cache, firebase, err := s.parseHeaders(r.Header, m)
if err != nil {
2021-10-29 03:50:38 +00:00
return err
}
delayed := m.Time > time.Now().Unix()
if !delayed {
if err := t.Publish(m); err != nil {
return err
}
}
if s.firebase != nil && firebase && !delayed {
2021-12-09 17:15:17 +00:00
go func() {
if err := s.firebase(m); err != nil {
log.Printf("Unable to publish to Firebase: %v", err.Error())
}
}()
}
2021-12-09 15:23:17 +00:00
if cache {
if err := s.cache.AddMessage(m); err != nil {
return err
}
2021-11-02 18:08:21 +00:00
}
2021-10-24 17:34:15 +00:00
w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
2021-11-03 15:33:34 +00:00
if err := json.NewEncoder(w).Encode(m); err != nil {
return err
}
2021-10-29 17:58:14 +00:00
s.mu.Lock()
s.messages++
s.mu.Unlock()
2021-10-24 17:34:15 +00:00
return nil
2021-10-23 01:26:01 +00:00
}
2021-12-11 03:57:01 +00:00
func (s *Server) parseHeaders(header http.Header, m *message) (cache bool, firebase bool, err error) {
cache = readHeader(header, "x-cache", "cache") != "no"
firebase = readHeader(header, "x-firebase", "firebase") != "no"
m.Title = readHeader(header, "x-title", "title", "ti", "t")
2021-11-27 21:12:08 +00:00
priorityStr := readHeader(header, "x-priority", "priority", "prio", "p")
if priorityStr != "" {
switch strings.ToLower(priorityStr) {
case "1", "min":
m.Priority = 1
2021-11-27 21:12:08 +00:00
case "2", "low":
m.Priority = 2
2021-12-07 20:39:42 +00:00
case "3", "default":
m.Priority = 3
2021-11-27 21:12:08 +00:00
case "4", "high":
m.Priority = 4
2021-11-27 21:12:08 +00:00
case "5", "max", "urgent":
m.Priority = 5
2021-11-27 21:12:08 +00:00
default:
return false, false, errHTTPBadRequest
2021-11-27 21:12:08 +00:00
}
}
2021-12-07 20:39:42 +00:00
tagsStr := readHeader(header, "x-tags", "tag", "tags", "ta")
2021-11-27 21:12:08 +00:00
if tagsStr != "" {
m.Tags = make([]string, 0)
2021-12-07 20:39:42 +00:00
for _, s := range strings.Split(tagsStr, ",") {
m.Tags = append(m.Tags, strings.TrimSpace(s))
2021-12-07 20:39:42 +00:00
}
2021-11-27 21:12:08 +00:00
}
2021-12-11 05:06:25 +00:00
delayStr := readHeader(header, "x-delay", "delay", "x-at", "at", "x-in", "in")
if delayStr != "" {
if !cache {
return false, false, errHTTPBadRequest
}
2021-12-11 05:06:25 +00:00
delay, err := util.ParseFutureTime(delayStr, time.Now())
if err != nil {
return false, false, errHTTPBadRequest
2021-12-11 05:06:25 +00:00
} else if delay.Unix() < time.Now().Add(s.config.MinDelay).Unix() {
2021-12-11 03:57:01 +00:00
return false, false, errHTTPBadRequest
2021-12-11 05:06:25 +00:00
} else if delay.Unix() > time.Now().Add(s.config.MaxDelay).Unix() {
return false, false, errHTTPBadRequest
}
2021-12-11 05:06:25 +00:00
m.Time = delay.Unix()
}
return cache, firebase, nil
2021-11-27 21:12:08 +00:00
}
func readHeader(header http.Header, names ...string) string {
for _, name := range names {
value := header.Get(name)
if value != "" {
2021-12-07 20:39:42 +00:00
return strings.TrimSpace(value)
2021-11-27 21:12:08 +00:00
}
}
return ""
}
2021-11-01 19:21:38 +00:00
func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request, v *visitor) error {
encoder := func(msg *message) (string, error) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
return "", err
2021-10-23 01:26:01 +00:00
}
return buf.String(), nil
2021-10-23 01:26:01 +00:00
}
2021-11-07 18:08:03 +00:00
return s.handleSubscribe(w, r, v, "json", "application/x-ndjson", encoder)
2021-10-23 01:26:01 +00:00
}
2021-11-01 19:21:38 +00:00
func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request, v *visitor) error {
encoder := func(msg *message) (string, error) {
2021-10-23 17:21:33 +00:00
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
return "", err
2021-10-23 17:21:33 +00:00
}
2021-10-29 12:29:27 +00:00
if msg.Event != messageEvent {
return fmt.Sprintf("event: %s\ndata: %s\n", msg.Event, buf.String()), nil // Browser's .onmessage() does not fire on this!
2021-10-23 17:21:33 +00:00
}
return fmt.Sprintf("data: %s\n", buf.String()), nil
2021-10-23 19:22:17 +00:00
}
2021-11-01 19:21:38 +00:00
return s.handleSubscribe(w, r, v, "sse", "text/event-stream", encoder)
2021-10-23 17:21:33 +00:00
}
2021-11-01 19:21:38 +00:00
func (s *Server) handleSubscribeRaw(w http.ResponseWriter, r *http.Request, v *visitor) error {
encoder := func(msg *message) (string, error) {
2021-11-02 18:10:56 +00:00
if msg.Event == messageEvent { // only handle default events
return strings.ReplaceAll(msg.Message, "\n", " ") + "\n", nil
}
return "\n", nil // "keepalive" and "open" events just send an empty line
}
2021-11-01 19:21:38 +00:00
return s.handleSubscribe(w, r, v, "raw", "text/plain", encoder)
}
2021-11-01 19:21:38 +00:00
func (s *Server) handleSubscribe(w http.ResponseWriter, r *http.Request, v *visitor, format string, contentType string, encoder messageEncoder) error {
if err := v.AddSubscription(); err != nil {
2021-11-01 20:39:40 +00:00
return errHTTPTooManyRequests
2021-11-01 19:21:38 +00:00
}
defer v.RemoveSubscription()
2021-11-15 12:56:58 +00:00
topicsStr := strings.TrimSuffix(r.URL.Path[1:], "/"+format) // Hack
topicIDs := strings.Split(topicsStr, ",")
topics, err := s.topicsFromIDs(topicIDs...)
2021-11-01 20:39:40 +00:00
if err != nil {
return err
}
2021-10-29 17:58:14 +00:00
since, err := parseSince(r)
if err != nil {
return err
}
2021-12-07 21:03:01 +00:00
var wlock sync.Mutex
2021-10-29 17:58:14 +00:00
poll := r.URL.Query().Has("poll")
scheduled := r.URL.Query().Has("scheduled") || r.URL.Query().Has("sched")
sub := func(msg *message) error {
2021-12-07 21:03:01 +00:00
wlock.Lock()
defer wlock.Unlock()
m, err := encoder(msg)
if err != nil {
return err
}
if _, err := w.Write([]byte(m)); err != nil {
return err
}
if fl, ok := w.(http.Flusher); ok {
fl.Flush()
}
return nil
}
2021-11-07 18:08:03 +00:00
w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
w.Header().Set("Content-Type", contentType+"; charset=utf-8") // Android/Volley client needs charset!
2021-10-29 17:58:14 +00:00
if poll {
return s.sendOldMessages(topics, since, scheduled, sub)
2021-10-29 17:58:14 +00:00
}
2021-11-15 12:56:58 +00:00
subscriberIDs := make([]int, 0)
for _, t := range topics {
subscriberIDs = append(subscriberIDs, t.Subscribe(sub))
}
defer func() {
for i, subscriberID := range subscriberIDs {
topics[i].Unsubscribe(subscriberID) // Order!
}
}()
if err := sub(newOpenMessage(topicsStr)); err != nil { // Send out open message
2021-10-29 17:58:14 +00:00
return err
}
if err := s.sendOldMessages(topics, since, scheduled, sub); err != nil {
return err
}
for {
select {
case <-r.Context().Done():
return nil
case <-time.After(s.config.KeepaliveInterval):
2021-11-01 19:21:38 +00:00
v.Keepalive()
2021-11-15 12:56:58 +00:00
if err := sub(newKeepaliveMessage(topicsStr)); err != nil { // Send keepalive message
return err
}
}
}
}
func (s *Server) sendOldMessages(topics []*topic, since sinceTime, scheduled bool, sub subscriber) error {
if since.IsNone() {
2021-10-29 17:58:14 +00:00
return nil
}
2021-11-15 12:56:58 +00:00
for _, t := range topics {
messages, err := s.cache.Messages(t.ID, since, scheduled)
2021-11-15 12:56:58 +00:00
if err != nil {
2021-10-29 17:58:14 +00:00
return err
}
2021-11-15 12:56:58 +00:00
for _, m := range messages {
if err := sub(m); err != nil {
return err
}
}
2021-10-29 17:58:14 +00:00
}
2021-10-24 17:34:15 +00:00
return nil
}
// parseSince returns a timestamp identifying the time span from which cached messages should be received.
//
// Values in the "since=..." parameter can be either a unix timestamp or a duration (e.g. 12h), or
// "all" for all messages.
func parseSince(r *http.Request) (sinceTime, error) {
2021-10-29 17:58:14 +00:00
if !r.URL.Query().Has("since") {
if r.URL.Query().Has("poll") {
return sinceAllMessages, nil
}
return sinceNoMessages, nil
}
if r.URL.Query().Get("since") == "all" {
return sinceAllMessages, nil
2021-12-09 03:57:31 +00:00
} else if s, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64); err == nil {
return sinceTime(time.Unix(s, 0)), nil
2021-12-09 03:57:31 +00:00
} else if d, err := time.ParseDuration(r.URL.Query().Get("since")); err == nil {
return sinceTime(time.Now().Add(-1 * d)), nil
2021-10-29 17:58:14 +00:00
}
return sinceNoMessages, errHTTPBadRequest
2021-10-29 17:58:14 +00:00
}
2021-12-07 16:45:15 +00:00
func (s *Server) handleOptions(w http.ResponseWriter, _ *http.Request) error {
2021-10-29 17:58:14 +00:00
w.Header().Set("Access-Control-Allow-Origin", "*") // CORS, allow cross-origin requests
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST")
2021-10-24 18:22:53 +00:00
return nil
}
2021-11-15 12:56:58 +00:00
func (s *Server) topicFromID(id string) (*topic, error) {
topics, err := s.topicsFromIDs(id)
if err != nil {
return nil, err
}
return topics[0], nil
}
2021-11-27 21:12:08 +00:00
func (s *Server) topicsFromIDs(ids ...string) ([]*topic, error) {
2021-10-23 01:26:01 +00:00
s.mu.Lock()
defer s.mu.Unlock()
2021-11-15 12:56:58 +00:00
topics := make([]*topic, 0)
2021-11-27 21:12:08 +00:00
for _, id := range ids {
2021-12-09 03:13:59 +00:00
if util.InStringList(disallowedTopics, id) {
return nil, errHTTPBadRequest
}
2021-11-15 12:56:58 +00:00
if _, ok := s.topics[id]; !ok {
if len(s.topics) >= s.config.GlobalTopicLimit {
return nil, errHTTPTooManyRequests
}
2021-12-09 03:57:31 +00:00
s.topics[id] = newTopic(id)
2021-10-29 17:58:14 +00:00
}
2021-11-15 12:56:58 +00:00
topics = append(topics, s.topics[id])
2021-10-23 01:26:01 +00:00
}
2021-11-15 12:56:58 +00:00
return topics, nil
2021-10-23 01:26:01 +00:00
}
2021-12-11 03:57:01 +00:00
func (s *Server) updateStatsAndPrune() {
2021-10-23 01:26:01 +00:00
s.mu.Lock()
defer s.mu.Unlock()
2021-10-29 17:58:14 +00:00
// Expire visitors from rate visitors map
for ip, v := range s.visitors {
2021-11-01 19:21:38 +00:00
if v.Stale() {
2021-10-29 17:58:14 +00:00
delete(s.visitors, ip)
}
2021-10-23 01:26:01 +00:00
}
2021-12-11 03:57:01 +00:00
// Prune message cache
2021-12-09 03:57:31 +00:00
olderThan := time.Now().Add(-1 * s.config.CacheDuration)
if err := s.cache.Prune(olderThan); err != nil {
2021-11-03 01:09:49 +00:00
log.Printf("error pruning cache: %s", err.Error())
2021-11-02 18:08:21 +00:00
}
2021-12-11 03:57:01 +00:00
// Prune old topics, remove subscriptions without subscribers
2021-11-03 01:09:49 +00:00
var subscribers, messages int
2021-10-29 17:58:14 +00:00
for _, t := range s.topics {
2021-11-03 01:09:49 +00:00
subs := t.Subscribers()
2021-12-09 03:57:31 +00:00
msgs, err := s.cache.MessageCount(t.ID)
2021-11-03 01:09:49 +00:00
if err != nil {
2021-12-09 03:57:31 +00:00
log.Printf("cannot get stats for topic %s: %s", t.ID, err.Error())
2021-11-03 01:09:49 +00:00
continue
}
2021-12-09 17:15:17 +00:00
if msgs == 0 && subs == 0 {
2021-12-09 03:57:31 +00:00
delete(s.topics, t.ID)
2021-11-03 01:09:49 +00:00
continue
2021-10-29 17:58:14 +00:00
}
subscribers += subs
messages += msgs
}
2021-11-03 01:09:49 +00:00
// Print stats
2021-10-29 17:58:14 +00:00
log.Printf("Stats: %d message(s) published, %d topic(s) active, %d subscriber(s), %d message(s) buffered, %d visitor(s)",
s.messages, len(s.topics), subscribers, messages, len(s.visitors))
}
2021-10-24 02:49:50 +00:00
2021-12-15 14:13:16 +00:00
func (s *Server) runManager() {
func() {
ticker := time.NewTicker(s.config.ManagerInterval)
for {
<-ticker.C
s.updateStatsAndPrune()
}
}()
}
func (s *Server) runAtSender() {
ticker := time.NewTicker(s.config.AtSenderInterval)
for {
<-ticker.C
if err := s.sendDelayedMessages(); err != nil {
log.Printf("error sending scheduled messages: %s", err.Error())
}
}
}
func (s *Server) runFirebaseKeepliver() {
if s.firebase == nil {
return
}
ticker := time.NewTicker(s.config.FirebaseKeepaliveInterval)
for {
<-ticker.C
if err := s.firebase(newKeepaliveMessage(firebaseControlTopic)); err != nil {
log.Printf("error sending Firebase keepalive message: %s", err.Error())
}
}
}
func (s *Server) sendDelayedMessages() error {
s.mu.Lock()
defer s.mu.Unlock()
messages, err := s.cache.MessagesDue()
if err != nil {
return err
}
for _, m := range messages {
t, ok := s.topics[m.Topic] // If no subscribers, just mark message as published
if ok {
if err := t.Publish(m); err != nil {
log.Printf("unable to publish message %s to topic %s: %v", m.ID, m.Topic, err.Error())
}
if s.firebase != nil {
if err := s.firebase(m); err != nil {
log.Printf("unable to publish to Firebase: %v", err.Error())
}
}
}
if err := s.cache.MarkPublished(m); err != nil {
return err
}
}
return nil
}
func (s *Server) withRateLimit(w http.ResponseWriter, r *http.Request, handler func(w http.ResponseWriter, r *http.Request, v *visitor) error) error {
v := s.visitor(r)
if err := v.RequestAllowed(); err != nil {
return err
}
return handler(w, r, v)
}
2021-10-24 02:49:50 +00:00
// visitor creates or retrieves a rate.Limiter for the given visitor.
// This function was taken from https://www.alexedwards.net/blog/how-to-rate-limit-http-requests (MIT).
func (s *Server) visitor(r *http.Request) *visitor {
2021-10-24 02:49:50 +00:00
s.mu.Lock()
defer s.mu.Unlock()
remoteAddr := r.RemoteAddr
2021-10-24 02:49:50 +00:00
ip, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
ip = remoteAddr // This should not happen in real life; only in tests.
}
if s.config.BehindProxy && r.Header.Get("X-Forwarded-For") != "" {
ip = r.Header.Get("X-Forwarded-For")
}
2021-10-24 02:49:50 +00:00
v, exists := s.visitors[ip]
if !exists {
2021-11-01 19:21:38 +00:00
s.visitors[ip] = newVisitor(s.config)
return s.visitors[ip]
2021-10-24 02:49:50 +00:00
}
v.seen = time.Now()
return v
}
func (s *Server) fail(w http.ResponseWriter, r *http.Request, code int, err error) {
log.Printf("[%s] %s - %d - %s", r.RemoteAddr, r.Method, code, err.Error())
w.WriteHeader(code)
2021-12-07 16:45:15 +00:00
_, _ = io.WriteString(w, fmt.Sprintf("%s\n", http.StatusText(code)))
2021-10-24 02:49:50 +00:00
}