-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
96 lines (83 loc) · 1.99 KB
/
http.go
File metadata and controls
96 lines (83 loc) · 1.99 KB
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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"os"
"strings"
"golang.org/x/crypto/ssh"
)
func proxyconn(r io.ReadCloser, w io.Writer) {
io.Copy(w, r)
r.Close()
}
func connectHandler(sshc *ssh.Client, dh http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "CONNECT" {
dh.ServeHTTP(w, r)
return
}
host := r.URL.Host
if strings.Index(host, ":") < 0 {
host += ":80"
}
sconn, err := sshc.Dial("tcp", host)
if err != nil {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusBadGateway)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
cconn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
cconn.Close()
sconn.Close()
log.Print("CONNECT hijack error: ", err)
return
}
go proxyconn(cconn, sconn)
go proxyconn(sconn, cconn)
}
}
func jsonHandler(v interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.Encode(v)
}
}
func httpProxy(sshc *ssh.Client, l net.Listener) error {
proxy := httputil.ReverseProxy{
Director: func(r *http.Request) {},
Transport: &http.Transport{Dial: sshc.Dial},
}
mux := http.NewServeMux()
mux.Handle("/", &proxy)
mux.Handle("/config", jsonHandler(&proxyConfig{
ProxyAddr: l.Addr().String(),
ProxyPid: os.Getpid(),
}))
// connectHandler must be spliced in here because the CONNECT
// method URI has no "/" which means mux will not see it.
return http.Serve(l, connectHandler(sshc, mux))
}
func queryConfig(port int) (pc proxyConfig, err error) {
var resp *http.Response
cli := &http.Client{}
resp, err = cli.Get(fmt.Sprintf("http://localhost:%d/config", port))
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("http: %s", resp.Status)
return
}
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&pc)
return
}