forked from cloudfoundry/credhub-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socksify.go
107 lines (85 loc) · 2.02 KB
/
socksify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package credhub
import (
"io/ioutil"
"net"
"net/url"
"os"
"strings"
"sync"
"github.com/cloudfoundry/socks5-proxy"
goproxy "golang.org/x/net/proxy"
)
type DialFunc func(network, address string) (net.Conn, error)
type ProxyDialer interface {
Dialer(string, string, string) (proxy.DialFunc, error)
}
func (f DialFunc) Dial(network, address string) (net.Conn, error) { return f(network, address) }
func SOCKS5DialFuncFromEnvironment(origDialer DialFunc, socks5Proxy ProxyDialer) DialFunc {
allProxy := os.Getenv("CREDHUB_PROXY")
if len(allProxy) == 0 {
return origDialer
}
if strings.HasPrefix(allProxy, "ssh+") {
allProxy = strings.TrimPrefix(allProxy, "ssh+")
proxyURL, err := url.Parse(allProxy)
if err != nil {
return origDialer
}
queryMap, err := url.ParseQuery(proxyURL.RawQuery)
if err != nil {
return origDialer
}
proxySSHKeyPath, ok := queryMap["private-key"]
if !ok {
return origDialer
}
username := ""
if proxyURL.User != nil {
username = proxyURL.User.Username()
}
if len(proxySSHKeyPath) == 0 {
return origDialer
}
proxySSHKey, err := ioutil.ReadFile(proxySSHKeyPath[0])
if err != nil {
return origDialer
}
var (
dialer proxy.DialFunc
mut sync.RWMutex
)
return func(network, address string) (net.Conn, error) {
mut.RLock()
haveDialer := dialer != nil
mut.RUnlock()
if haveDialer {
return dialer(network, address)
}
mut.Lock()
defer mut.Unlock()
if dialer == nil {
proxyDialer, err := socks5Proxy.Dialer(username,string(proxySSHKey), proxyURL.Host)
if err != nil {
return nil, err
}
dialer = proxyDialer
}
return dialer(network, address)
}
}
proxyURL, err := url.Parse(allProxy)
if err != nil {
return origDialer
}
proxy, err := goproxy.FromURL(proxyURL, origDialer)
if err != nil {
return origDialer
}
noProxy := os.Getenv("no_proxy")
if len(noProxy) == 0 {
return proxy.Dial
}
perHost := goproxy.NewPerHost(proxy, origDialer)
perHost.AddFromString(noProxy)
return perHost.Dial
}