util.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package server
  2. import (
  3. "fmt"
  4. "github.com/emersion/go-smtp"
  5. "heckel.io/ntfy/util"
  6. "net/http"
  7. "strings"
  8. "unicode/utf8"
  9. )
  10. func readBoolParam(r *http.Request, defaultValue bool, names ...string) bool {
  11. value := strings.ToLower(readParam(r, names...))
  12. if value == "" {
  13. return defaultValue
  14. }
  15. return value == "1" || value == "yes" || value == "true"
  16. }
  17. func readParam(r *http.Request, names ...string) string {
  18. value := readHeaderParam(r, names...)
  19. if value != "" {
  20. return value
  21. }
  22. return readQueryParam(r, names...)
  23. }
  24. func readHeaderParam(r *http.Request, names ...string) string {
  25. for _, name := range names {
  26. value := r.Header.Get(name)
  27. if value != "" {
  28. return strings.TrimSpace(value)
  29. }
  30. }
  31. return ""
  32. }
  33. func readQueryParam(r *http.Request, names ...string) string {
  34. for _, name := range names {
  35. value := r.URL.Query().Get(strings.ToLower(name))
  36. if value != "" {
  37. return strings.TrimSpace(value)
  38. }
  39. }
  40. return ""
  41. }
  42. func logMessagePrefix(v *visitor, m *message) string {
  43. return fmt.Sprintf("%s/%s/%s", v.ip, m.Topic, m.ID)
  44. }
  45. func logHTTPPrefix(v *visitor, r *http.Request) string {
  46. requestURI := r.RequestURI
  47. if requestURI == "" {
  48. requestURI = r.URL.Path
  49. }
  50. return fmt.Sprintf("%s HTTP %s %s", v.ip, r.Method, requestURI)
  51. }
  52. func logSMTPPrefix(state *smtp.ConnectionState) string {
  53. return fmt.Sprintf("%s/%s SMTP", state.Hostname, state.RemoteAddr.String())
  54. }
  55. func renderHTTPRequest(r *http.Request) string {
  56. peekLimit := 4096
  57. lines := fmt.Sprintf("%s %s %s\n", r.Method, r.URL.RequestURI(), r.Proto)
  58. for key, values := range r.Header {
  59. for _, value := range values {
  60. lines += fmt.Sprintf("%s: %s\n", key, value)
  61. }
  62. }
  63. lines += "\n"
  64. body, err := util.Peek(r.Body, peekLimit)
  65. if err != nil {
  66. lines = fmt.Sprintf("(could not read body: %s)\n", err.Error())
  67. } else if utf8.Valid(body.PeekedBytes) {
  68. lines += string(body.PeekedBytes)
  69. if body.LimitReached {
  70. lines += fmt.Sprintf(" ... (peeked %d bytes)", peekLimit)
  71. }
  72. lines += "\n"
  73. } else {
  74. if body.LimitReached {
  75. lines += fmt.Sprintf("(peeked bytes not UTF-8, peek limit of %d bytes reached, hex: %x ...)\n", peekLimit, body.PeekedBytes)
  76. } else {
  77. lines += fmt.Sprintf("(peeked bytes not UTF-8, %d bytes, hex: %x)\n", len(body.PeekedBytes), body.PeekedBytes)
  78. }
  79. }
  80. r.Body = body // Important: Reset body, so it can be re-read
  81. return strings.TrimSpace(lines)
  82. }