Debian Codegraph @

server/util.go

raw
1 package server
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "mime"
9 "net/http"
10 "net/netip"
11 "regexp"
12 "strings"
13
14 "heckel.io/ntfy/v2/util"
15 )
16
17 var (
18 mimeDecoder mime.WordDecoder
19
20 // priorityHeaderIgnoreRegex matches specific patterns of the "Priority" header (RFC 9218), so that it can be ignored
21 priorityHeaderIgnoreRegex = regexp.MustCompile(`^u=\d,\s*(i|\d)$|^u=\d$`)
22
23 // forwardedHeaderRegex parses IPv4 and IPv6 addresses from the "Forwarded" header (RFC 7239)
24 // IPv6 addresses in Forwarded header are enclosed in square brackets. The port is optional.
25 //
26 // Examples:
27 // for="1.2.3.4"
28 // for="[2001:db8::1]"; for=1.2.3.4:8080, by=phil
29 // for="1.2.3.4:8080"
30 forwardedHeaderRegex = regexp.MustCompile(`(?i)\bfor="?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[0-9a-f:]+])(?::\d+)?"?`)
31 )
32
33 func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
34 value := strings.ToLower(readParam(r, names...))
35 if value == "" {
36 return defaultValue
37 }
38 return toBool(value)
39 }
40
41 func isBoolValue(value string) bool {
42 return value == "1" || value == "yes" || value == "true" || value == "0" || value == "no" || value == "false"
43 }
44
45 func toBool(value string) bool {
46 return value == "1" || value == "yes" || value == "true"
47 }
48
49 func readCommaSeparatedParam(r *http.Request, names ...string) []string {
50 if paramStr := readParam(r, names...); paramStr != "" {
51 return util.Map(util.SplitNoEmpty(paramStr, ","), strings.TrimSpace)
52 }
53 return []string{}
54 }
55
56 func readParam(r *http.Request, names ...string) string {
57 value := readHeaderParam(r, names...)
58 if value != "" {
59 return value
60 }
61 return readQueryParam(r, names...)
62 }
63
64 func readHeaderParam(r *http.Request, names ...string) string {
65 for _, name := range names {
66 value := strings.TrimSpace(maybeDecodeHeader(name, r.Header.Get(name)))
67 if value != "" {
68 return value
69 }
70 }
71 return ""
72 }
73
74 func readQueryParam(r *http.Request, names ...string) string {
75 for _, name := range names {
76 value := r.URL.Query().Get(strings.ToLower(name))
77 if value != "" {
78 return strings.TrimSpace(value)
79 }
80 }
81 return ""
82 }
83
84 // extractIPAddress extracts the IP address of the visitor from the request,
85 // either from the TCP socket or from a proxy header.
86 func extractIPAddress(r *http.Request, behindProxy bool, proxyForwardedHeader string, proxyTrustedPrefixes []netip.Prefix) netip.Addr {
87 if behindProxy && proxyForwardedHeader != "" {
88 if addr, err := extractIPAddressFromHeader(r, proxyForwardedHeader, proxyTrustedPrefixes); err == nil {
89 return addr
90 }
91 // Fall back to the remote address if the header is not found or invalid
92 }
93 addrPort, err := netip.ParseAddrPort(r.RemoteAddr)
94 if err != nil {
95 logr(r).Err(err).Warn("unable to parse IP (%s), new visitor with unspecified IP (0.0.0.0) created", r.RemoteAddr)
96 return netip.IPv4Unspecified()
97 }
98 return addrPort.Addr()
99 }
100
101 // extractIPAddressFromHeader extracts the last IP address from the specified header.
102 //
103 // It supports multiple formats:
104 // - single IP address
105 // - comma-separated list
106 // - RFC 7239-style list (Forwarded header)
107 //
108 // If there are multiple addresses, we first remove the trusted IP addresses from the list, and
109 // then take the right-most address in the list (as this is the one added by our proxy server).
110 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For for details.
111 func extractIPAddressFromHeader(r *http.Request, forwardedHeader string, trustedPrefixes []netip.Prefix) (netip.Addr, error) {
112 value := strings.TrimSpace(strings.ToLower(r.Header.Get(forwardedHeader)))
113 if value == "" {
114 return netip.IPv4Unspecified(), fmt.Errorf("no %s header found", forwardedHeader)
115 }
116 // Extract valid addresses
117 addrsStrs := util.Map(util.SplitNoEmpty(value, ","), strings.TrimSpace)
118 var validAddrs []netip.Addr
119 for _, addrStr := range addrsStrs {
120 // Handle Forwarded header with for="[IPv6]" or for="IPv4"
121 if m := forwardedHeaderRegex.FindStringSubmatch(addrStr); len(m) == 2 {
122 addrRaw := m[1]
123 if strings.HasPrefix(addrRaw, "[") && strings.HasSuffix(addrRaw, "]") {
124 addrRaw = addrRaw[1 : len(addrRaw)-1]
125 }
126 if addr, err := netip.ParseAddr(addrRaw); err == nil {
127 validAddrs = append(validAddrs, addr)
128 }
129 } else if addr, err := netip.ParseAddr(addrStr); err == nil {
130 validAddrs = append(validAddrs, addr)
131 }
132 }
133 // Filter out proxy addresses
134 clientAddrs := util.Filter(validAddrs, func(addr netip.Addr) bool {
135 for _, prefix := range trustedPrefixes {
136 if prefix.Contains(addr) {
137 return false // Address is in the trusted range, ignore it
138 }
139 }
140 return true
141 })
142 if len(clientAddrs) == 0 {
143 return netip.IPv4Unspecified(), fmt.Errorf("no client IP address found in %s header: %s", forwardedHeader, value)
144 }
145 return clientAddrs[len(clientAddrs)-1], nil
146 }
147
148 func readJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error) {
149 obj, err := util.UnmarshalJSONWithLimit[T](r, limit, allowEmpty)
150 if errors.Is(err, util.ErrUnmarshalJSON) {
151 return nil, errHTTPBadRequestJSONInvalid
152 } else if errors.Is(err, util.ErrTooLargeJSON) {
153 return nil, errHTTPEntityTooLargeJSONBody
154 } else if err != nil {
155 return nil, err
156 }
157 return obj, nil
158 }
159
160 func withContext(r *http.Request, ctx map[contextKey]any) *http.Request {
161 c := r.Context()
162 for k, v := range ctx {
163 c = context.WithValue(c, k, v)
164 }
165 return r.WithContext(c)
166 }
167
168 func fromContext[T any](r *http.Request, key contextKey) (T, error) {
169 t, ok := r.Context().Value(key).(T)
170 if !ok {
171 return t, fmt.Errorf("cannot find key %v in request context", key)
172 }
173 return t, nil
174 }
175
176 // maybeDecodeHeader decodes the given header value if it is MIME encoded, e.g. "=?utf-8?q?Hello_World?=",
177 // or returns the original header value if it is not MIME encoded. It also calls maybeIgnoreSpecialHeader
178 // to ignore the new HTTP "Priority" header.
179 func maybeDecodeHeader(name, value string) string {
180 decoded, err := mimeDecoder.DecodeHeader(value)
181 if err != nil {
182 return maybeIgnoreSpecialHeader(name, value)
183 }
184 return maybeIgnoreSpecialHeader(name, decoded)
185 }
186
187 // maybeIgnoreSpecialHeader ignores the new HTTP "Priority" header (RFC 9218, see https://datatracker.ietf.org/doc/html/rfc9218)
188 //
189 // Cloudflare (and potentially other providers) add this to requests when forwarding to the backend (ntfy),
190 // so we just ignore it. If the "Priority" header is set to "u=*, i" or "u=*" (by Cloudflare), the header will be ignored.
191 // Returning an empty string will allow the rest of the logic to continue searching for another header (x-priority, prio, p),
192 // or in the Query parameters.
193 func maybeIgnoreSpecialHeader(name, value string) string {
194 if strings.ToLower(name) == "priority" && priorityHeaderIgnoreRegex.MatchString(strings.TrimSpace(value)) {
195 return ""
196 }
197 return value
198 }