Repository navigation
Expand file tree
/
Copy pathconn_http.go
More file actions
77 lines (66 loc) · 1.83 KB
/
Copy pathconn_http.go
File metadata and controls
77 lines (66 loc) · 1.83 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
package enproxy
import (
"fmt"
"io"
"net"
"net/http"
"strconv"
)
// Intercept intercepts a CONNECT request, hijacks the underlying client
// connetion and starts piping the data over a new enproxy.Conn configured using
// this Config.
func (c *Config) Intercept(resp http.ResponseWriter, req *http.Request) {
if req.Method != "CONNECT" {
panic("Intercept used for non-CONNECT request!")
}
// Hijack underlying connection
clientConn, _, err := resp.(http.Hijacker).Hijack()
if err != nil {
resp.WriteHeader(502)
fmt.Fprintf(resp, "Unable to hijack connection: %s", err)
}
defer clientConn.Close()
addr := hostIncludingPort(req, 443)
// Establish outbound connection
connOut := &Conn{
Addr: addr,
Config: c,
}
connOut.Connect()
defer connOut.Close()
// Pipe data
pipeData(clientConn, connOut, req)
}
// pipeData pipes data between the client and proxy connections. It's also
// responsible for responding to the initial CONNECT request with a 200 OK.
func pipeData(clientConn net.Conn, connOut *Conn, req *http.Request) {
// Start piping to proxy
go io.Copy(connOut, clientConn)
// Respond OK
err := respondOK(clientConn, req)
if err != nil {
log.Errorf("Unable to respond OK: %s", err)
return
}
// Then start coyping from out to writer
io.Copy(clientConn, connOut)
}
func respondOK(writer io.Writer, req *http.Request) error {
defer req.Body.Close()
resp := &http.Response{
StatusCode: 200,
ProtoMajor: 1,
ProtoMinor: 1,
}
return resp.Write(writer)
}
// hostIncludingPort extracts the host:port from a request. It fills in a
// a default port if none was found in the request.
func hostIncludingPort(req *http.Request, defaultPort int) string {
_, port, err := net.SplitHostPort(req.Host)
if port == "" || err != nil {
return req.Host + ":" + strconv.Itoa(defaultPort)
} else {
return req.Host
}
}