ntfy/server/util.go

157 lines
4.8 KiB
Go
Raw Normal View History

2022-01-16 07:17:46 +03:00
package server
import (
2023-02-23 06:26:43 +03:00
"context"
2024-03-21 04:33:54 +03:00
"errors"
2023-02-24 04:46:53 +03:00
"fmt"
2023-11-17 04:54:58 +03:00
"heckel.io/ntfy/v2/util"
2022-12-29 17:57:42 +03:00
"io"
2023-04-22 01:45:27 +03:00
"mime"
2022-01-16 07:17:46 +03:00
"net/http"
2022-12-22 05:55:39 +03:00
"net/netip"
"regexp"
2023-09-25 00:59:23 +03:00
"strings"
2022-01-16 07:17:46 +03:00
)
2023-09-25 00:59:23 +03:00
var (
mimeDecoder mime.WordDecoder
priorityHeaderIgnoreRegex = regexp.MustCompile(`^u=\d,\s*(i|\d)$|^u=\d$`)
)
2023-04-22 01:45:27 +03:00
2022-01-16 07:17:46 +03:00
func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
value := strings.ToLower(readParam(r, names...))
if value == "" {
return defaultValue
}
2023-05-13 19:26:14 +03:00
return toBool(value)
}
func isBoolValue(value string) bool {
return value == "1" || value == "yes" || value == "true" || value == "0" || value == "no" || value == "false"
}
func toBool(value string) bool {
2022-01-16 07:17:46 +03:00
return value == "1" || value == "yes" || value == "true"
}
2023-02-23 05:33:18 +03:00
func readCommaSeparatedParam(r *http.Request, names ...string) (params []string) {
2023-02-22 05:04:56 +03:00
paramStr := readParam(r, names...)
if paramStr != "" {
params = make([]string, 0)
for _, s := range util.SplitNoEmpty(paramStr, ",") {
params = append(params, strings.TrimSpace(s))
}
}
return params
}
2022-01-16 07:17:46 +03:00
func readParam(r *http.Request, names ...string) string {
value := readHeaderParam(r, names...)
if value != "" {
return value
}
return readQueryParam(r, names...)
}
func readHeaderParam(r *http.Request, names ...string) string {
2022-01-16 07:17:46 +03:00
for _, name := range names {
2023-09-25 00:59:23 +03:00
value := strings.TrimSpace(maybeDecodeHeader(name, r.Header.Get(name)))
2022-01-16 07:17:46 +03:00
if value != "" {
2023-09-25 00:59:23 +03:00
return value
2022-01-16 07:17:46 +03:00
}
}
return ""
}
func readQueryParam(r *http.Request, names ...string) string {
2022-01-16 07:17:46 +03:00
for _, name := range names {
value := r.URL.Query().Get(strings.ToLower(name))
if value != "" {
return strings.TrimSpace(value)
}
}
return ""
}
2022-06-02 06:24:44 +03:00
2022-12-22 05:55:39 +03:00
func extractIPAddress(r *http.Request, behindProxy bool) netip.Addr {
remoteAddr := r.RemoteAddr
addrPort, err := netip.ParseAddrPort(remoteAddr)
ip := addrPort.Addr()
if err != nil {
// This should not happen in real life; only in tests. So, using falling back to 0.0.0.0 if address unspecified
ip, err = netip.ParseAddr(remoteAddr)
if err != nil {
ip = netip.IPv4Unspecified()
2022-12-23 17:37:47 +03:00
if remoteAddr != "@" || !behindProxy { // RemoteAddr is @ when unix socket is used
2023-02-15 18:55:01 +03:00
logr(r).Err(err).Warn("unable to parse IP (%s), new visitor with unspecified IP (0.0.0.0) created", remoteAddr)
2022-12-23 17:37:47 +03:00
}
2022-12-22 05:55:39 +03:00
}
}
if behindProxy && strings.TrimSpace(r.Header.Get("X-Forwarded-For")) != "" {
// X-Forwarded-For can contain multiple addresses (see #328). If we are behind a proxy,
// only the right-most address can be trusted (as this is the one added by our proxy server).
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For for details.
ips := util.SplitNoEmpty(r.Header.Get("X-Forwarded-For"), ",")
realIP, err := netip.ParseAddr(strings.TrimSpace(util.LastString(ips, remoteAddr)))
if err != nil {
2023-02-15 18:55:01 +03:00
logr(r).Err(err).Error("invalid IP address %s received in X-Forwarded-For header", ip)
2022-12-22 05:55:39 +03:00
// Fall back to regular remote address if X-Forwarded-For is damaged
} else {
ip = realIP
}
}
return ip
}
2022-12-29 17:57:42 +03:00
2023-01-28 07:10:59 +03:00
func readJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error) {
obj, err := util.UnmarshalJSONWithLimit[T](r, limit, allowEmpty)
2024-03-21 04:33:54 +03:00
if errors.Is(err, util.ErrUnmarshalJSON) {
2022-12-29 17:57:42 +03:00
return nil, errHTTPBadRequestJSONInvalid
2024-03-21 04:33:54 +03:00
} else if errors.Is(err, util.ErrTooLargeJSON) {
2022-12-29 17:57:42 +03:00
return nil, errHTTPEntityTooLargeJSONBody
} else if err != nil {
return nil, err
}
return obj, nil
}
2023-02-23 06:26:43 +03:00
func withContext(r *http.Request, ctx map[contextKey]any) *http.Request {
c := r.Context()
for k, v := range ctx {
c = context.WithValue(c, k, v)
}
return r.WithContext(c)
}
2023-02-24 04:46:53 +03:00
2023-03-14 17:19:15 +03:00
func fromContext[T any](r *http.Request, key contextKey) (T, error) {
2023-03-04 06:22:07 +03:00
t, ok := r.Context().Value(key).(T)
2023-02-24 04:46:53 +03:00
if !ok {
2023-03-14 17:19:15 +03:00
return t, fmt.Errorf("cannot find key %v in request context", key)
2023-02-24 04:46:53 +03:00
}
2023-03-14 17:19:15 +03:00
return t, nil
2023-02-24 04:46:53 +03:00
}
2023-04-22 04:07:07 +03:00
2023-09-25 00:59:23 +03:00
// maybeDecodeHeader decodes the given header value if it is MIME encoded, e.g. "=?utf-8?q?Hello_World?=",
// or returns the original header value if it is not MIME encoded. It also calls maybeIgnoreSpecialHeader
// to ignore new HTTP "Priority" header.
func maybeDecodeHeader(name, value string) string {
decoded, err := mimeDecoder.DecodeHeader(value)
2023-04-22 04:07:07 +03:00
if err != nil {
2023-09-25 00:59:23 +03:00
return maybeIgnoreSpecialHeader(name, value)
2023-04-22 04:07:07 +03:00
}
2023-09-25 00:59:23 +03:00
return maybeIgnoreSpecialHeader(name, decoded)
}
2023-09-25 00:59:23 +03:00
// maybeIgnoreSpecialHeader ignores new HTTP "Priority" header (see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-priority)
//
// Cloudflare (and potentially other providers) add this to requests when forwarding to the backend (ntfy),
// so we just ignore it. If the "Priority" header is set to "u=*, i" or "u=*" (by Cloudflare), the header will be ignored.
// Returning an empty string will allow the rest of the logic to continue searching for another header (x-priority, prio, p),
// or in the Query parameters.
func maybeIgnoreSpecialHeader(name, value string) string {
if strings.ToLower(name) == "priority" && priorityHeaderIgnoreRegex.MatchString(strings.TrimSpace(value)) {
return ""
}
return value
2023-04-22 04:07:07 +03:00
}