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