headers.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package http
  2. import (
  3. "net/http"
  4. "strconv"
  5. "strings"
  6. "github.com/v2fly/v2ray-core/v5/common/net"
  7. )
  8. // ParseXForwardedFor parses X-Forwarded-For header in http headers, and return the IP list in it.
  9. func ParseXForwardedFor(header http.Header) []net.Address {
  10. xff := header.Get("X-Forwarded-For")
  11. if xff == "" {
  12. return nil
  13. }
  14. list := strings.Split(xff, ",")
  15. addrs := make([]net.Address, 0, len(list))
  16. for _, proxy := range list {
  17. addrs = append(addrs, net.ParseAddress(proxy))
  18. }
  19. return addrs
  20. }
  21. // RemoveHopByHopHeaders remove hop by hop headers in http header list.
  22. func RemoveHopByHopHeaders(header http.Header) {
  23. // Strip hop-by-hop header based on RFC:
  24. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
  25. // https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
  26. header.Del("Proxy-Connection")
  27. header.Del("Proxy-Authenticate")
  28. header.Del("Proxy-Authorization")
  29. header.Del("TE")
  30. header.Del("Trailers")
  31. header.Del("Transfer-Encoding")
  32. header.Del("Upgrade")
  33. header.Del("Keep-Alive")
  34. connections := header.Get("Connection")
  35. header.Del("Connection")
  36. if connections == "" {
  37. return
  38. }
  39. for _, h := range strings.Split(connections, ",") {
  40. header.Del(strings.TrimSpace(h))
  41. }
  42. }
  43. // ParseHost splits host and port from a raw string. Default port is used when raw string doesn't contain port.
  44. func ParseHost(rawHost string, defaultPort net.Port) (net.Destination, error) {
  45. port := defaultPort
  46. host, rawPort, err := net.SplitHostPort(rawHost)
  47. if err != nil {
  48. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  49. host = rawHost
  50. } else {
  51. return net.Destination{}, err
  52. }
  53. } else if len(rawPort) > 0 {
  54. intPort, err := strconv.ParseUint(rawPort, 0, 16)
  55. if err != nil {
  56. return net.Destination{}, err
  57. }
  58. port = net.Port(intPort)
  59. }
  60. return net.TCPDestination(net.ParseAddress(host), port), nil
  61. }