headers.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package http
  2. import (
  3. "net/http"
  4. "strconv"
  5. "strings"
  6. "github.com/xtls/xray-core/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 removes 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. connections := header.Get("Connection")
  34. header.Del("Connection")
  35. if connections == "" {
  36. return
  37. }
  38. for _, h := range strings.Split(connections, ",") {
  39. header.Del(strings.TrimSpace(h))
  40. }
  41. }
  42. // ParseHost splits host and port from a raw string. Default port is used when raw string doesn't contain port.
  43. func ParseHost(rawHost string, defaultPort net.Port) (net.Destination, error) {
  44. port := defaultPort
  45. host, rawPort, err := net.SplitHostPort(rawHost)
  46. if err != nil {
  47. if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
  48. host = rawHost
  49. } else {
  50. return net.Destination{}, err
  51. }
  52. } else if len(rawPort) > 0 {
  53. intPort, err := strconv.Atoi(rawPort)
  54. if err != nil {
  55. return net.Destination{}, err
  56. }
  57. port = net.Port(intPort)
  58. }
  59. return net.TCPDestination(net.ParseAddress(host), port), nil
  60. }