-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.go
197 lines (165 loc) · 4.85 KB
/
connection.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package main
import (
"bufio"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
const ProxyAuthenticationRequired = "HTTP/1.0 407 Proxy authentication required\r\n\r\n"
type connection struct {
id string
incoming net.Conn
outgoing net.Conn
proxy
localAddr net.Addr
}
func (c *connection) Dial(network, address string) (net.Conn, error) {
timeout := time.Second * time.Duration(config.DialTimeout)
if config.UseIncomingLocalAddr {
if c.localAddr == nil {
logger.Warn.Println(c.id, "Missing local net.Addr: a default local net.Addr will be used")
goto fallback
}
switch tcpAddr := c.localAddr.(type) {
case *net.TCPAddr:
// Ensure the TCPAddr has its Port set to 0, which is way of telling the dialer to
// use any random port. If you don't change this, you'll get a bind error.
tcpAddr.Port = 0
default:
logger.Warn.Println(c.id, "Ignoring local net.Addr", c.localAddr, "because net.TCPAddr was expected")
goto fallback
}
dialer := &net.Dialer{
LocalAddr: c.localAddr,
Timeout: timeout,
}
// Try to dial with the incoming LocalAddr to keep the incoming and outgoing IPs the same.
conn, err := dialer.Dial(network, address)
if err == nil {
return conn, nil
}
// If an error occurs, fallback to the default interface. This might happen if you connected
// via a loopback interace, like testing on the same machine. We should be more specifc about
// error handling, but falling back is fine for now.
logger.Warn.Println(c.id, "Ignoring local net.Addr for", c.localAddr, "dialing due to error:", err)
}
fallback:
return net.DialTimeout(network, address, timeout)
}
func (c *connection) Handle() {
logger.Info.Println(c.id, "Handling new connection.")
reader := bufio.NewReader(c.incoming)
request, err := http.ReadRequest(reader)
if err == io.EOF {
logger.Warn.Println(c.id, "Incoming connection disconnected.")
return
}
if err != nil {
logger.Warn.Println(c.id, "Could not parse or read request from incoming connection:", err)
return
}
defer request.Body.Close()
if !isAuthenticated(request) {
logger.Fatal.Println(c.id, "Invalid credentials.")
c.incoming.Write([]byte(ProxyAuthenticationRequired))
return
}
// Delete the auth and proxy headers.
if config.AuthenticationRequired() {
request.Header.Del("Proxy-Authorization")
}
// Delete any other proxy related thing if enabled.
if config.StripProxyHeaders {
request.Header.Del("Forwarded")
request.Header.Del("Proxy-Connection")
request.Header.Del("Via")
request.Header.Del("X-Forwarded-For")
request.Header.Del("X-Forwarded-Host")
request.Header.Del("X-Forwarded-Proto")
}
logger.Info.Println(c.id, "Processing connection to:", request.Method, request.Host)
if request.Method == "CONNECT" {
c.proxy = new(httpsProxy)
} else {
c.proxy = new(httpProxy)
}
err = c.proxy.SetupOutgoing(c, request)
if err != nil {
logger.Warn.Println(c.id, err)
return
}
// Spawn incoming->outgoing and outgoing->incoming streams.
signal := make(chan error, 1)
go streamBytes(c.incoming, c.outgoing, signal)
go streamBytes(c.outgoing, c.incoming, signal)
// Wait for either stream to complete and finish. The second will always be an error.
err = <-signal
if err != nil {
logger.Warn.Println(c.id, "Error reading or writing data", request.Host, err)
return
}
}
func (c *connection) Close() {
if c.incoming != nil {
c.incoming.Close()
}
if c.outgoing != nil {
c.outgoing.Close()
}
logger.Info.Println(c.id, "Connection closed.")
}
// COPIED FROM STD LIB TO USE WITH PROXY-AUTH HEADER
// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBasicAuth(auth string) (username, password string, ok bool) {
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
func isAuthenticated(request *http.Request) bool {
if !config.AuthenticationRequired() {
return true
}
proxyAuthHeader := request.Header.Get("Proxy-Authorization")
if proxyAuthHeader == "" {
return false
}
username, password, ok := parseBasicAuth(proxyAuthHeader)
if !ok {
return false
}
return config.IsAuthenticated(username, password)
}
func newConnectionId() string {
bytes := make([]byte, 3) // 6 characters long.
if _, err := rand.Read(bytes); err != nil {
return "[ERROR-MAKING-ID]"
}
return "[" + hex.EncodeToString(bytes) + "]"
}
func NewConnection(incoming net.Conn) *connection {
newId := fmt.Sprint(newConnectionId(), " [", incoming.RemoteAddr().String(), "]")
localAddr := incoming.LocalAddr()
return &connection{
id: newId,
incoming: incoming,
localAddr: localAddr,
}
}