util.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. package server
  2. import (
  3. "fmt"
  4. "github.com/emersion/go-smtp"
  5. "heckel.io/ntfy/log"
  6. "heckel.io/ntfy/util"
  7. "io"
  8. "net/http"
  9. "net/netip"
  10. "strings"
  11. "unicode/utf8"
  12. )
  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 value == "1" || value == "yes" || value == "true"
  19. }
  20. func readParam(r *http.Request, names ...string) string {
  21. value := readHeaderParam(r, names...)
  22. if value != "" {
  23. return value
  24. }
  25. return readQueryParam(r, names...)
  26. }
  27. func readHeaderParam(r *http.Request, names ...string) string {
  28. for _, name := range names {
  29. value := r.Header.Get(name)
  30. if value != "" {
  31. return strings.TrimSpace(value)
  32. }
  33. }
  34. return ""
  35. }
  36. func readQueryParam(r *http.Request, names ...string) string {
  37. for _, name := range names {
  38. value := r.URL.Query().Get(strings.ToLower(name))
  39. if value != "" {
  40. return strings.TrimSpace(value)
  41. }
  42. }
  43. return ""
  44. }
  45. func logMessagePrefix(v *visitor, m *message) string {
  46. return fmt.Sprintf("%s/%s/%s", v.String(), m.Topic, m.ID)
  47. }
  48. func logHTTPPrefix(v *visitor, r *http.Request) string {
  49. requestURI := r.RequestURI
  50. if requestURI == "" {
  51. requestURI = r.URL.Path
  52. }
  53. return fmt.Sprintf("HTTP %s %s %s", v.String(), r.Method, requestURI)
  54. }
  55. func logStripePrefix(customerID, subscriptionID string) string {
  56. if subscriptionID != "" {
  57. return fmt.Sprintf("STRIPE %s/%s", customerID, subscriptionID)
  58. }
  59. return fmt.Sprintf("STRIPE %s", customerID)
  60. }
  61. func logSMTPPrefix(state *smtp.ConnectionState) string {
  62. return fmt.Sprintf("SMTP %s/%s", state.Hostname, state.RemoteAddr.String())
  63. }
  64. func renderHTTPRequest(r *http.Request) string {
  65. peekLimit := 4096
  66. lines := fmt.Sprintf("%s %s %s\n", r.Method, r.URL.RequestURI(), r.Proto)
  67. for key, values := range r.Header {
  68. for _, value := range values {
  69. lines += fmt.Sprintf("%s: %s\n", key, value)
  70. }
  71. }
  72. lines += "\n"
  73. body, err := util.Peek(r.Body, peekLimit)
  74. if err != nil {
  75. lines = fmt.Sprintf("(could not read body: %s)\n", err.Error())
  76. } else if utf8.Valid(body.PeekedBytes) {
  77. lines += string(body.PeekedBytes)
  78. if body.LimitReached {
  79. lines += fmt.Sprintf(" ... (peeked %d bytes)", peekLimit)
  80. }
  81. lines += "\n"
  82. } else {
  83. if body.LimitReached {
  84. lines += fmt.Sprintf("(peeked bytes not UTF-8, peek limit of %d bytes reached, hex: %x ...)\n", peekLimit, body.PeekedBytes)
  85. } else {
  86. lines += fmt.Sprintf("(peeked bytes not UTF-8, %d bytes, hex: %x)\n", len(body.PeekedBytes), body.PeekedBytes)
  87. }
  88. }
  89. r.Body = body // Important: Reset body, so it can be re-read
  90. return strings.TrimSpace(lines)
  91. }
  92. func extractIPAddress(r *http.Request, behindProxy bool) netip.Addr {
  93. remoteAddr := r.RemoteAddr
  94. addrPort, err := netip.ParseAddrPort(remoteAddr)
  95. ip := addrPort.Addr()
  96. if err != nil {
  97. // This should not happen in real life; only in tests. So, using falling back to 0.0.0.0 if address unspecified
  98. ip, err = netip.ParseAddr(remoteAddr)
  99. if err != nil {
  100. ip = netip.IPv4Unspecified()
  101. if remoteAddr != "@" || !behindProxy { // RemoteAddr is @ when unix socket is used
  102. log.Warn("unable to parse IP (%s), new visitor with unspecified IP (0.0.0.0) created %s", remoteAddr, err)
  103. }
  104. }
  105. }
  106. if behindProxy && strings.TrimSpace(r.Header.Get("X-Forwarded-For")) != "" {
  107. // X-Forwarded-For can contain multiple addresses (see #328). If we are behind a proxy,
  108. // only the right-most address can be trusted (as this is the one added by our proxy server).
  109. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For for details.
  110. ips := util.SplitNoEmpty(r.Header.Get("X-Forwarded-For"), ",")
  111. realIP, err := netip.ParseAddr(strings.TrimSpace(util.LastString(ips, remoteAddr)))
  112. if err != nil {
  113. log.Error("invalid IP address %s received in X-Forwarded-For header: %s", ip, err.Error())
  114. // Fall back to regular remote address if X-Forwarded-For is damaged
  115. } else {
  116. ip = realIP
  117. }
  118. }
  119. return ip
  120. }
  121. func readJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error) {
  122. obj, err := util.UnmarshalJSONWithLimit[T](r, limit, allowEmpty)
  123. if err == util.ErrUnmarshalJSON {
  124. return nil, errHTTPBadRequestJSONInvalid
  125. } else if err == util.ErrTooLargeJSON {
  126. return nil, errHTTPEntityTooLargeJSONBody
  127. } else if err != nil {
  128. return nil, err
  129. }
  130. return obj, nil
  131. }