github.com/chwjbn/xclash@v0.2.0/listener/http/utils.go (about)

     1  package http
     2  
     3  import (
     4  	"encoding/base64"
     5  	"errors"
     6  	"net"
     7  	"net/http"
     8  	"strings"
     9  )
    10  
    11  // removeHopByHopHeaders remove hop-by-hop header
    12  func removeHopByHopHeaders(header http.Header) {
    13  	// Strip hop-by-hop header based on RFC:
    14  	// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
    15  	// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
    16  
    17  	header.Del("Proxy-Connection")
    18  	header.Del("Proxy-Authenticate")
    19  	header.Del("Proxy-Authorization")
    20  	header.Del("TE")
    21  	header.Del("Trailers")
    22  	header.Del("Transfer-Encoding")
    23  	header.Del("Upgrade")
    24  
    25  	connections := header.Get("Connection")
    26  	header.Del("Connection")
    27  	if len(connections) == 0 {
    28  		return
    29  	}
    30  	for _, h := range strings.Split(connections, ",") {
    31  		header.Del(strings.TrimSpace(h))
    32  	}
    33  }
    34  
    35  // removeExtraHTTPHostPort remove extra host port (example.com:80 --> example.com)
    36  // It resolves the behavior of some HTTP servers that do not handle host:80 (e.g. baidu.com)
    37  func removeExtraHTTPHostPort(req *http.Request) {
    38  	host := req.Host
    39  	if host == "" {
    40  		host = req.URL.Host
    41  	}
    42  
    43  	if pHost, port, err := net.SplitHostPort(host); err == nil && port == "80" {
    44  		host = pHost
    45  	}
    46  
    47  	req.Host = host
    48  	req.URL.Host = host
    49  }
    50  
    51  // parseBasicProxyAuthorization parse header Proxy-Authorization and return base64-encoded credential
    52  func parseBasicProxyAuthorization(request *http.Request) string {
    53  	value := request.Header.Get("Proxy-Authorization")
    54  	if !strings.HasPrefix(value, "Basic ") {
    55  		return ""
    56  	}
    57  
    58  	return value[6:] // value[len("Basic "):]
    59  }
    60  
    61  // decodeBasicProxyAuthorization decode base64-encoded credential
    62  func decodeBasicProxyAuthorization(credential string) (string, string, error) {
    63  	plain, err := base64.StdEncoding.DecodeString(credential)
    64  	if err != nil {
    65  		return "", "", err
    66  	}
    67  
    68  	login := strings.Split(string(plain), ":")
    69  	if len(login) != 2 {
    70  		return "", "", errors.New("invalid login")
    71  	}
    72  
    73  	return login[0], login[1], nil
    74  }