| 1 | package lfshttp |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/url" |
| 6 | "strings" |
| 7 | |
| 8 | "github.com/git-lfs/git-lfs/v3/config" |
| 9 | "golang.org/x/net/http/httpproxy" |
| 10 | ) |
| 11 | |
| 12 | // Logic is copied, with small changes, from "net/http".ProxyFromEnvironment in the go std lib. |
| 13 | func proxyFromClient(c *Client) func(req *http.Request) (*url.URL, error) { |
| 14 | return func(req *http.Request) (*url.URL, error) { |
| 15 | httpsProxy, httpProxy, noProxy := getProxyServers(req.URL, c.uc, c.osEnv) |
| 16 | |
| 17 | var proxy string |
| 18 | if req.URL.Scheme == "https" { |
| 19 | proxy = httpsProxy |
| 20 | } |
| 21 | |
| 22 | if len(proxy) == 0 { |
| 23 | proxy = httpProxy |
| 24 | } |
| 25 | |
| 26 | if len(proxy) == 0 { |
| 27 | return nil, nil |
| 28 | } |
| 29 | |
| 30 | if strings.HasPrefix(proxy, "socks5h://") { |
| 31 | proxy = strings.Replace(proxy, "socks5h://", "socks5://", 1) |
| 32 | } |
| 33 | |
| 34 | cfg := &httpproxy.Config{ |
| 35 | HTTPProxy: proxy, |
| 36 | HTTPSProxy: proxy, |
| 37 | NoProxy: noProxy, |
| 38 | CGI: false, |
| 39 | } |
| 40 | |
| 41 | // We want to use the standard logic except that we want to |
| 42 | // allow proxies for localhost, which the standard library does |
| 43 | // not. Since the proxy code looks only at the URL, we |
| 44 | // synthesize a fake URL except that we rewrite "localhost" to |
| 45 | // "127.0.0.1" for purposes of looking up the proxy. |
| 46 | u := *(req.URL) |
| 47 | if u.Host == "localhost" { |
| 48 | u.Host = "127.0.0.1" |
| 49 | } |
| 50 | return cfg.ProxyFunc()(&u) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | func getProxyServers(u *url.URL, urlCfg *config.URLConfig, osEnv config.Environment) (httpsProxy string, httpProxy string, noProxy string) { |
| 55 | if osEnv == nil { |
| 56 | return |
| 57 | } |
| 58 | |
| 59 | if len(httpsProxy) == 0 { |
| 60 | httpsProxy, _ = osEnv.Get("HTTPS_PROXY") |
| 61 | } |
| 62 | |
| 63 | if len(httpsProxy) == 0 { |
| 64 | httpsProxy, _ = osEnv.Get("https_proxy") |
| 65 | } |
| 66 | |
| 67 | if len(httpProxy) == 0 { |
| 68 | httpProxy, _ = osEnv.Get("HTTP_PROXY") |
| 69 | } |
| 70 | |
| 71 | if len(httpProxy) == 0 { |
| 72 | httpProxy, _ = osEnv.Get("http_proxy") |
| 73 | } |
| 74 | |
| 75 | if urlCfg != nil { |
| 76 | gitProxy, ok := urlCfg.Get("http", u.String(), "proxy") |
| 77 | if len(gitProxy) > 0 && ok { |
| 78 | if u.Scheme == "https" { |
| 79 | httpsProxy = gitProxy |
| 80 | } |
| 81 | httpProxy = gitProxy |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | noProxy, _ = osEnv.Get("NO_PROXY") |
| 86 | if len(noProxy) == 0 { |
| 87 | noProxy, _ = osEnv.Get("no_proxy") |
| 88 | } |
| 89 | |
| 90 | return |
| 91 | } |