-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhttp.go
More file actions
272 lines (237 loc) · 6.34 KB
/
http.go
File metadata and controls
272 lines (237 loc) · 6.34 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
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package proxy
import (
"context"
"crypto/tls"
"io"
"net"
"net/http"
"strings"
"time"
// "errors"
"fmt"
// "sync"
"bytes"
"github.com/urnetwork/connect"
)
// a simple http/https proxy focused on proper file descriptor management
type HttpProxy struct {
ProxyReadTimeout time.Duration
ProxyWriteTimeout time.Duration
ProxyIdleTimeout time.Duration
// only used for http proxy
ProxyTlsHandshakeTimeout time.Duration
MaxHttpBodyBytes int64
ConnectDialWithRequest func(r *http.Request, network string, addr string) (net.Conn, error)
GetTlsConfigForClient func(*tls.ClientHelloInfo) (*tls.Config, error)
}
func NewHttpProxy() *HttpProxy {
return &HttpProxy{
MaxHttpBodyBytes: 2 * 1024 * 1024,
}
}
func (self *HttpProxy) ListenAndServe(ctx context.Context, network string, addr string) error {
httpServer := &http.Server{
Addr: addr,
Handler: self,
ReadTimeout: self.ProxyReadTimeout,
WriteTimeout: self.ProxyWriteTimeout,
IdleTimeout: self.ProxyIdleTimeout,
}
listenConfig := net.ListenConfig{}
l, err := listenConfig.Listen(
ctx,
network,
addr,
)
if err != nil {
return err
}
defer l.Close()
return httpServer.Serve(l)
}
func (self *HttpProxy) ListenAndServeTls(ctx context.Context, network string, addr string) error {
tlsConfig := &tls.Config{
GetConfigForClient: self.GetTlsConfigForClient,
}
httpServer := &http.Server{
Addr: addr,
Handler: self,
TLSConfig: tlsConfig,
ReadTimeout: self.ProxyReadTimeout,
WriteTimeout: self.ProxyWriteTimeout,
IdleTimeout: self.ProxyIdleTimeout,
}
listenConfig := net.ListenConfig{}
l, err := listenConfig.Listen(
ctx,
network,
addr,
)
if err != nil {
return err
}
defer l.Close()
return httpServer.ServeTLS(l, "", "")
}
func (self *HttpProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
connect.HandleError(func() {
if r.Method == http.MethodConnect {
self.handleHttps(w, r)
} else {
self.handleHttp(w, r)
}
})
}
func (self *HttpProxy) handleHttps(w http.ResponseWriter, r *http.Request) {
hij := w.(http.Hijacker)
conn, _, err := hij.Hijack()
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
handleCtx, handleCancel := context.WithCancel(r.Context())
defer handleCancel()
go connect.HandleError(func() {
defer conn.Close()
select {
case <-handleCtx.Done():
}
})
// r.URL.Host contains both the host and port (if specified)
var proxyConn net.Conn
for {
select {
case <-handleCtx.Done():
httpError(conn, http.StatusBadGateway, err)
return
default:
}
proxyConn, err = self.ConnectDialWithRequest(r, "tcp", r.URL.Host)
if err == nil {
break
}
}
defer proxyConn.Close()
_, err = conn.Write([]byte("HTTP/1.0 200 Connection established\r\n\r\n"))
if err != nil {
return
}
copyConn(handleCtx, handleCancel, conn, proxyConn, self.ProxyReadTimeout, self.ProxyWriteTimeout)
}
func (self *HttpProxy) handleHttp(w http.ResponseWriter, r *http.Request) {
// r.Header.Del("Accept-Encoding")
// r.Header.Del("Proxy-Connection")
// r.Header.Del("Proxy-Authenticate")
// r.Header.Del("Proxy-Authorization")
b := bytes.NewBuffer(nil)
_, err := copyBufferWithTimeout(b, io.LimitReader(r.Body, self.MaxHttpBodyBytes), nil, self.ProxyReadTimeout, self.ProxyWriteTimeout)
r.Body.Close()
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
bodyBytes := b.Bytes()
handleCtx, handleCancel := context.WithCancel(r.Context())
defer handleCancel()
tr := &http.Transport{
Dial: func(network string, addr string) (net.Conn, error) {
return connect.HandleError2(func() (net.Conn, error) {
return self.ConnectDialWithRequest(r, network, addr)
}, func() (net.Conn, error) {
return nil, fmt.Errorf("Unexpected error")
})
},
DisableKeepAlives: true,
TLSHandshakeTimeout: self.ProxyTlsHandshakeTimeout,
ResponseHeaderTimeout: self.ProxyReadTimeout,
}
var response *http.Response
for {
select {
case <-handleCtx.Done():
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
return
default:
}
r2, err := http.NewRequestWithContext(
r.Context(),
r.Method,
r.URL.String(),
bytes.NewReader(bodyBytes),
)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response, err = tr.RoundTrip(r2)
if err == nil {
break
}
}
defer response.Body.Close()
h := w.Header()
for k := range w.Header() {
h.Del(k)
}
for k, vs := range response.Header {
h[k] = vs
}
w.WriteHeader(response.StatusCode)
if headerContains(response.Header, "connection", "upgrade") && headerContains(response.Header, "upgrade", "websocket") {
hij := w.(http.Hijacker)
conn, _, err := hij.Hijack()
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
go connect.HandleError(func() {
defer conn.Close()
select {
case <-handleCtx.Done():
}
})
proxyRw := response.Body.(io.ReadWriter)
copyConn(handleCtx, handleCancel, conn, proxyRw, self.ProxyReadTimeout, self.ProxyWriteTimeout)
} else {
var flush func()
chunked := false
if strings.HasPrefix(strings.ToLower(h.Get("content-type")), "text/event-stream") {
chunked = true
}
if strings.Contains(strings.ToLower(h.Get("transfer-encoding")), "chunked") {
chunked = true
}
if chunked {
f := w.(http.Flusher)
flush = f.Flush
}
_, err := copyBufferWithTimeoutAndFlush(w, response.Body, nil, self.ProxyReadTimeout, self.ProxyWriteTimeout, flush)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
}
}
}
func headerContains(h http.Header, name string, value string) bool {
value = strings.ToLower(value)
for _, v := range h.Values(name) {
for _, s := range strings.Split(strings.ToLower(v), ",") {
if value == s {
return true
}
}
}
return false
}
// for a hijacked connection
func httpError(w io.Writer, statusCode int, err error) error {
errorMessage := err.Error()
errStr := fmt.Sprintf(
"HTTP/1.1 %d %s\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s",
statusCode,
http.StatusText(statusCode),
len(errorMessage),
errorMessage,
)
_, writeErr := io.WriteString(w, errStr)
return writeErr
}