ntfy/server/util.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

199 lines
6.6 KiB
Go
Raw Permalink Normal View History

2022-01-15 23:17:46 -05:00
package server
import (
2023-02-22 22:26:43 -05:00
"context"
2024-03-20 21:33:54 -04:00
"errors"
2023-02-23 20:46:53 -05:00
"fmt"
2022-12-29 09:57:42 -05:00
"io"
2023-04-21 18:45:27 -04:00
"mime"
2022-01-15 23:17:46 -05:00
"net/http"
2022-12-21 21:55:39 -05:00
"net/netip"
"regexp"
2023-09-24 17:59:23 -04:00
"strings"
2025-07-04 07:38:58 +02:00
"heckel.io/ntfy/v2/util"
2022-01-15 23:17:46 -05:00
)
2023-09-24 17:59:23 -04:00
var (
2025-06-01 09:57:39 -04:00
mimeDecoder mime.WordDecoder
// priorityHeaderIgnoreRegex matches specific patterns of the "Priority" header (RFC 9218), so that it can be ignored
2023-09-24 17:59:23 -04:00
priorityHeaderIgnoreRegex = regexp.MustCompile(`^u=\d,\s*(i|\d)$|^u=\d$`)
2025-06-01 09:57:39 -04:00
2025-07-04 07:38:58 +02:00
// forwardedHeaderRegex parses IPv4 and IPv6 addresses from the "Forwarded" header (RFC 7239)
2025-07-04 10:16:49 +02:00
// IPv6 addresses in Forwarded header are enclosed in square brackets. The port is optional.
//
// Examples:
// for="1.2.3.4"
// for="[2001:db8::1]"; for=1.2.3.4:8080, by=phil
// for="1.2.3.4:8080"
forwardedHeaderRegex = regexp.MustCompile(`(?i)\bfor="?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[0-9a-f:]+])(?::\d+)?"?`)
2023-09-24 17:59:23 -04:00
)
2023-04-21 18:45:27 -04:00
2022-01-15 23:17:46 -05:00
func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
value := strings.ToLower(readParam(r, names...))
if value == "" {
return defaultValue
}
2023-05-13 12:26:14 -04: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-15 23:17:46 -05:00
return value == "1" || value == "yes" || value == "true"
}
2025-06-01 09:57:39 -04:00
func readCommaSeparatedParam(r *http.Request, names ...string) []string {
if paramStr := readParam(r, names...); paramStr != "" {
return util.Map(util.SplitNoEmpty(paramStr, ","), strings.TrimSpace)
2023-02-21 20:04:56 -06:00
}
2025-06-01 09:57:39 -04:00
return []string{}
2023-02-21 20:04:56 -06:00
}
2022-01-15 23:17:46 -05: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-15 23:17:46 -05:00
for _, name := range names {
2023-09-24 17:59:23 -04:00
value := strings.TrimSpace(maybeDecodeHeader(name, r.Header.Get(name)))
2022-01-15 23:17:46 -05:00
if value != "" {
2023-09-24 17:59:23 -04:00
return value
2022-01-15 23:17:46 -05:00
}
}
return ""
}
func readQueryParam(r *http.Request, names ...string) string {
2022-01-15 23:17:46 -05:00
for _, name := range names {
value := r.URL.Query().Get(strings.ToLower(name))
if value != "" {
return strings.TrimSpace(value)
}
}
return ""
}
2022-06-01 23:24:44 -04:00
2025-06-01 10:12:06 -04:00
// extractIPAddress extracts the IP address of the visitor from the request,
// either from the TCP socket or from a proxy header.
func extractIPAddress(r *http.Request, behindProxy bool, proxyForwardedHeader string, proxyTrustedPrefixes []netip.Prefix) netip.Addr {
if behindProxy && proxyForwardedHeader != "" {
if addr, err := extractIPAddressFromHeader(r, proxyForwardedHeader, proxyTrustedPrefixes); err == nil {
return addr
2022-12-21 21:55:39 -05:00
}
// Fall back to the remote address if the header is not found or invalid
2025-05-31 15:33:21 -04:00
}
addrPort, err := netip.ParseAddrPort(r.RemoteAddr)
if err != nil {
logr(r).Err(err).Warn("unable to parse IP (%s), new visitor with unspecified IP (0.0.0.0) created", r.RemoteAddr)
return netip.IPv4Unspecified()
}
return addrPort.Addr()
}
// extractIPAddressFromHeader extracts the last IP address from the specified header.
//
2025-06-01 10:12:06 -04:00
// It supports multiple formats:
// - single IP address
// - comma-separated list
// - RFC 7239-style list (Forwarded header)
//
// If there are multiple addresses, we first remove the trusted IP addresses from the list, and
// then take the right-most address in the list (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.
func extractIPAddressFromHeader(r *http.Request, forwardedHeader string, trustedPrefixes []netip.Prefix) (netip.Addr, error) {
2025-07-04 10:16:49 +02:00
value := strings.TrimSpace(strings.ToLower(r.Header.Get(forwardedHeader)))
if value == "" {
return netip.IPv4Unspecified(), fmt.Errorf("no %s header found", forwardedHeader)
}
2025-06-01 09:57:39 -04:00
// Extract valid addresses
addrsStrs := util.Map(util.SplitNoEmpty(value, ","), strings.TrimSpace)
var validAddrs []netip.Addr
for _, addrStr := range addrsStrs {
2025-07-04 07:38:58 +02:00
// Handle Forwarded header with for="[IPv6]" or for="IPv4"
if m := forwardedHeaderRegex.FindStringSubmatch(addrStr); len(m) == 2 {
addrRaw := m[1]
if strings.HasPrefix(addrRaw, "[") && strings.HasSuffix(addrRaw, "]") {
addrRaw = addrRaw[1 : len(addrRaw)-1]
}
if addr, err := netip.ParseAddr(addrRaw); err == nil {
2025-06-01 09:57:39 -04:00
validAddrs = append(validAddrs, addr)
}
2025-07-04 07:38:58 +02:00
} else if addr, err := netip.ParseAddr(addrStr); err == nil {
validAddrs = append(validAddrs, addr)
2025-06-01 09:57:39 -04:00
}
}
// Filter out proxy addresses
clientAddrs := util.Filter(validAddrs, func(addr netip.Addr) bool {
for _, prefix := range trustedPrefixes {
if prefix.Contains(addr) {
return false // Address is in the trusted range, ignore it
}
}
return true
})
if len(clientAddrs) == 0 {
return netip.IPv4Unspecified(), fmt.Errorf("no client IP address found in %s header: %s", forwardedHeader, value)
}
2025-06-01 09:57:39 -04:00
return clientAddrs[len(clientAddrs)-1], nil
2022-12-21 21:55:39 -05:00
}
2022-12-29 09:57:42 -05:00
2023-01-27 23:10:59 -05:00
func readJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error) {
obj, err := util.UnmarshalJSONWithLimit[T](r, limit, allowEmpty)
2024-03-20 21:33:54 -04:00
if errors.Is(err, util.ErrUnmarshalJSON) {
2022-12-29 09:57:42 -05:00
return nil, errHTTPBadRequestJSONInvalid
2024-03-20 21:33:54 -04:00
} else if errors.Is(err, util.ErrTooLargeJSON) {
2022-12-29 09:57:42 -05:00
return nil, errHTTPEntityTooLargeJSONBody
} else if err != nil {
return nil, err
}
return obj, nil
}
2023-02-22 22:26:43 -05: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-23 20:46:53 -05:00
2023-03-14 10:19:15 -04:00
func fromContext[T any](r *http.Request, key contextKey) (T, error) {
2023-03-03 22:22:07 -05:00
t, ok := r.Context().Value(key).(T)
2023-02-23 20:46:53 -05:00
if !ok {
2023-03-14 10:19:15 -04:00
return t, fmt.Errorf("cannot find key %v in request context", key)
2023-02-23 20:46:53 -05:00
}
2023-03-14 10:19:15 -04:00
return t, nil
2023-02-23 20:46:53 -05:00
}
2023-04-21 21:07:07 -04:00
2023-09-24 17:59:23 -04: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
2025-06-01 09:57:39 -04:00
// to ignore the new HTTP "Priority" header.
2023-09-24 17:59:23 -04:00
func maybeDecodeHeader(name, value string) string {
decoded, err := mimeDecoder.DecodeHeader(value)
2023-04-21 21:07:07 -04:00
if err != nil {
2023-09-24 17:59:23 -04:00
return maybeIgnoreSpecialHeader(name, value)
2023-04-21 21:07:07 -04:00
}
2023-09-24 17:59:23 -04:00
return maybeIgnoreSpecialHeader(name, decoded)
}
2025-06-01 09:57:39 -04:00
// maybeIgnoreSpecialHeader ignores the new HTTP "Priority" header (RFC 9218, see https://datatracker.ietf.org/doc/html/rfc9218)
2023-09-24 17:59:23 -04:00
//
// 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-21 21:07:07 -04:00
}