Skip to content

Commit 4650671

Browse files
authored
Merge pull request #5 from mattn/http-proxy
ssh over $http_proxy
2 parents d0f62b7 + 826fad8 commit 4650671

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

tunnel.go

+42-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ import (
66
"io"
77
"log"
88
"net"
9+
"net/http"
10+
"net/url"
11+
"os"
912

1013
"golang.org/x/crypto/ssh"
1114
)
@@ -40,9 +43,46 @@ func (t *Tunnel) Create() {
4043
return nil
4144
},
4245
}
46+
hostport := "labstack.me:22"
47+
var client *ssh.Client
4348

4449
// Connect
45-
client, err := ssh.Dial("tcp", "labstack.me:22", config)
50+
proxy := os.Getenv("http_proxy")
51+
if proxy != "" {
52+
proxyUrl, err := url.Parse(proxy)
53+
if err != nil {
54+
log.Fatalf("cannot open new session: %v\n", err)
55+
}
56+
tcp, err := net.Dial("tcp", proxyUrl.Host)
57+
if err != nil {
58+
log.Fatalf("cannot open new session: %v\n", err)
59+
}
60+
connReq := &http.Request{
61+
Method: "CONNECT",
62+
URL: &url.URL{Path: hostport},
63+
Host: hostport,
64+
Header: make(http.Header),
65+
}
66+
if proxyUrl.User != nil {
67+
if p, ok := proxyUrl.User.Password(); ok {
68+
connReq.SetBasicAuth(proxyUrl.User.Username(), p)
69+
}
70+
}
71+
connReq.Write(tcp)
72+
resp, err := http.ReadResponse(bufio.NewReader(tcp), connReq)
73+
if err != nil {
74+
log.Fatalf("cannot open new session: %v\n", err)
75+
}
76+
defer resp.Body.Close()
77+
78+
c, chans, reqs, err := ssh.NewClientConn(tcp, hostport, config)
79+
if err != nil {
80+
log.Fatalf("cannot open new session: %v\n", err)
81+
}
82+
client = ssh.NewClient(c, chans, reqs)
83+
} else {
84+
client, err = ssh.Dial("tcp", hostport, config)
85+
}
4686
if err != nil {
4787
log.Fatalf("Failed to connect %v\n", err)
4888
}
@@ -88,6 +128,7 @@ func (t *Tunnel) Create() {
88128
out, err := net.Dial("tcp", fmt.Sprintf("%s:%d", t.TargetHost, t.TargetPort))
89129
if err != nil {
90130
log.Printf("%v\n", err)
131+
return
91132
}
92133
defer out.Close()
93134

0 commit comments

Comments
 (0)