util.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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.ip, 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("%s HTTP %s %s", v.ip, r.Method, requestURI)
  54. }
  55. func logSMTPPrefix(state *smtp.ConnectionState) string {
  56. return fmt.Sprintf("%s/%s SMTP", state.Hostname, state.RemoteAddr.String())
  57. }
  58. func renderHTTPRequest(r *http.Request) string {
  59. peekLimit := 4096
  60. lines := fmt.Sprintf("%s %s %s\n", r.Method, r.URL.RequestURI(), r.Proto)
  61. for key, values := range r.Header {
  62. for _, value := range values {
  63. lines += fmt.Sprintf("%s: %s\n", key, value)
  64. }
  65. }
  66. lines += "\n"
  67. body, err := util.Peek(r.Body, peekLimit)
  68. if err != nil {
  69. lines = fmt.Sprintf("(could not read body: %s)\n", err.Error())
  70. } else if utf8.Valid(body.PeekedBytes) {
  71. lines += string(body.PeekedBytes)
  72. if body.LimitReached {
  73. lines += fmt.Sprintf(" ... (peeked %d bytes)", peekLimit)
  74. }
  75. lines += "\n"
  76. } else {
  77. if body.LimitReached {
  78. lines += fmt.Sprintf("(peeked bytes not UTF-8, peek limit of %d bytes reached, hex: %x ...)\n", peekLimit, body.PeekedBytes)
  79. } else {
  80. lines += fmt.Sprintf("(peeked bytes not UTF-8, %d bytes, hex: %x)\n", len(body.PeekedBytes), body.PeekedBytes)
  81. }
  82. }
  83. r.Body = body // Important: Reset body, so it can be re-read
  84. return strings.TrimSpace(lines)
  85. }
  86. func extractIPAddress(r *http.Request, behindProxy bool) netip.Addr {
  87. remoteAddr := r.RemoteAddr
  88. addrPort, err := netip.ParseAddrPort(remoteAddr)
  89. ip := addrPort.Addr()
  90. if err != nil {
  91. // This should not happen in real life; only in tests. So, using falling back to 0.0.0.0 if address unspecified
  92. ip, err = netip.ParseAddr(remoteAddr)
  93. if err != nil {
  94. ip = netip.IPv4Unspecified()
  95. if remoteAddr != "@" || !behindProxy { // RemoteAddr is @ when unix socket is used
  96. log.Warn("unable to parse IP (%s), new visitor with unspecified IP (0.0.0.0) created %s", remoteAddr, err)
  97. }
  98. }
  99. }
  100. if behindProxy && strings.TrimSpace(r.Header.Get("X-Forwarded-For")) != "" {
  101. // X-Forwarded-For can contain multiple addresses (see #328). If we are behind a proxy,
  102. // only the right-most address can be trusted (as this is the one added by our proxy server).
  103. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For for details.
  104. ips := util.SplitNoEmpty(r.Header.Get("X-Forwarded-For"), ",")
  105. realIP, err := netip.ParseAddr(strings.TrimSpace(util.LastString(ips, remoteAddr)))
  106. if err != nil {
  107. log.Error("invalid IP address %s received in X-Forwarded-For header: %s", ip, err.Error())
  108. // Fall back to regular remote address if X-Forwarded-For is damaged
  109. } else {
  110. ip = realIP
  111. }
  112. }
  113. return ip
  114. }
  115. func readJSONWithLimit[T any](r io.ReadCloser, limit int) (*T, error) {
  116. obj, err := util.UnmarshalJSONWithLimit[T](r, limit)
  117. if err == util.ErrUnmarshalJSON {
  118. return nil, errHTTPBadRequestJSONInvalid
  119. } else if err == util.ErrTooLargeJSON {
  120. return nil, errHTTPEntityTooLargeJSONBody
  121. } else if err != nil {
  122. return nil, err
  123. }
  124. return obj, nil
  125. }