util.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "heckel.io/ntfy/util"
  6. "io"
  7. "mime"
  8. "net/http"
  9. "net/netip"
  10. "strings"
  11. )
  12. var mimeDecoder mime.WordDecoder
  13. func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
  14. value := strings.ToLower(readParam(r, names...))
  15. if value == "" {
  16. return defaultValue
  17. }
  18. return toBool(value)
  19. }
  20. func isBoolValue(value string) bool {
  21. return value == "1" || value == "yes" || value == "true" || value == "0" || value == "no" || value == "false"
  22. }
  23. func toBool(value string) bool {
  24. return value == "1" || value == "yes" || value == "true"
  25. }
  26. func readCommaSeparatedParam(r *http.Request, names ...string) (params []string) {
  27. paramStr := readParam(r, names...)
  28. if paramStr != "" {
  29. params = make([]string, 0)
  30. for _, s := range util.SplitNoEmpty(paramStr, ",") {
  31. params = append(params, strings.TrimSpace(s))
  32. }
  33. }
  34. return params
  35. }
  36. func readParam(r *http.Request, names ...string) string {
  37. value := readHeaderParam(r, names...)
  38. if value != "" {
  39. return value
  40. }
  41. return readQueryParam(r, names...)
  42. }
  43. func readHeaderParam(r *http.Request, names ...string) string {
  44. for _, name := range names {
  45. value := maybeDecodeHeader(r.Header.Get(name))
  46. if value != "" {
  47. return strings.TrimSpace(value)
  48. }
  49. }
  50. return ""
  51. }
  52. func readQueryParam(r *http.Request, names ...string) string {
  53. for _, name := range names {
  54. value := r.URL.Query().Get(strings.ToLower(name))
  55. if value != "" {
  56. return strings.TrimSpace(value)
  57. }
  58. }
  59. return ""
  60. }
  61. func extractIPAddress(r *http.Request, behindProxy bool) netip.Addr {
  62. remoteAddr := r.RemoteAddr
  63. addrPort, err := netip.ParseAddrPort(remoteAddr)
  64. ip := addrPort.Addr()
  65. if err != nil {
  66. // This should not happen in real life; only in tests. So, using falling back to 0.0.0.0 if address unspecified
  67. ip, err = netip.ParseAddr(remoteAddr)
  68. if err != nil {
  69. ip = netip.IPv4Unspecified()
  70. if remoteAddr != "@" || !behindProxy { // RemoteAddr is @ when unix socket is used
  71. logr(r).Err(err).Warn("unable to parse IP (%s), new visitor with unspecified IP (0.0.0.0) created", remoteAddr)
  72. }
  73. }
  74. }
  75. if behindProxy && strings.TrimSpace(r.Header.Get("X-Forwarded-For")) != "" {
  76. // X-Forwarded-For can contain multiple addresses (see #328). If we are behind a proxy,
  77. // only the right-most address can be trusted (as this is the one added by our proxy server).
  78. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For for details.
  79. ips := util.SplitNoEmpty(r.Header.Get("X-Forwarded-For"), ",")
  80. realIP, err := netip.ParseAddr(strings.TrimSpace(util.LastString(ips, remoteAddr)))
  81. if err != nil {
  82. logr(r).Err(err).Error("invalid IP address %s received in X-Forwarded-For header", ip)
  83. // Fall back to regular remote address if X-Forwarded-For is damaged
  84. } else {
  85. ip = realIP
  86. }
  87. }
  88. return ip
  89. }
  90. func readJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error) {
  91. obj, err := util.UnmarshalJSONWithLimit[T](r, limit, allowEmpty)
  92. if err == util.ErrUnmarshalJSON {
  93. return nil, errHTTPBadRequestJSONInvalid
  94. } else if err == util.ErrTooLargeJSON {
  95. return nil, errHTTPEntityTooLargeJSONBody
  96. } else if err != nil {
  97. return nil, err
  98. }
  99. return obj, nil
  100. }
  101. func withContext(r *http.Request, ctx map[contextKey]any) *http.Request {
  102. c := r.Context()
  103. for k, v := range ctx {
  104. c = context.WithValue(c, k, v)
  105. }
  106. return r.WithContext(c)
  107. }
  108. func fromContext[T any](r *http.Request, key contextKey) (T, error) {
  109. t, ok := r.Context().Value(key).(T)
  110. if !ok {
  111. return t, fmt.Errorf("cannot find key %v in request context", key)
  112. }
  113. return t, nil
  114. }
  115. func maybeDecodeHeader(header string) string {
  116. decoded, err := mimeDecoder.DecodeHeader(header)
  117. if err != nil {
  118. return header
  119. }
  120. return decoded
  121. }