headers.go 1.7 KB

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