forked from google/martian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
404 lines (346 loc) · 10.3 KB
/
handler.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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Copyright 2023 Sauce Labs Inc. All rights reserved.
//
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package martian
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"github.com/google/martian/v3/log"
"github.com/google/martian/v3/proxyutil"
)
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func addTrailerHeader(rw http.ResponseWriter, tr http.Header) int {
// The "Trailer" header isn't included in the Transport's response,
// at least for *http.Transport. Build it up from Trailer.
announcedTrailers := len(tr)
if announcedTrailers == 0 {
return 0
}
trailerKeys := make([]string, 0, announcedTrailers)
for k := range tr {
trailerKeys = append(trailerKeys, k)
}
rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
return announcedTrailers
}
func copyBody(w io.Writer, body io.ReadCloser) error {
bufp := copyBufPool.Get().(*[]byte)
buf := *bufp
defer copyBufPool.Put(bufp)
_, err := io.CopyBuffer(w, body, buf)
return err
}
// proxyHandler wraps Proxy and implements http.Handler.
//
// Known limitations:
// - MITM is not supported
// - HTTP status code 100 is not supported, see [issue 2184]
//
// [issue 2184]: https://github.com/golang/go/issues/2184
type proxyHandler struct {
*Proxy
}
// Handler returns proxy as http.Handler, see [proxyHandler] for details.
func (p *Proxy) Handler() http.Handler {
return proxyHandler{p}
}
func (p proxyHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
session := newSessionWithResponseWriter(rw)
if req.TLS != nil {
session.MarkSecure()
}
ctx := withSession(session)
outreq := req.Clone(ctx.addToContext(req.Context()))
if req.ContentLength == 0 {
outreq.Body = http.NoBody
}
if outreq.Body != nil {
defer outreq.Body.Close()
}
outreq.Close = false
p.handleRequest(ctx, rw, outreq)
}
func (p proxyHandler) handleConnectRequest(ctx *Context, rw http.ResponseWriter, req *http.Request) {
session := ctx.Session()
if err := p.reqmod.ModifyRequest(req); err != nil {
log.Errorf("martian: error modifying CONNECT request: %v", err)
p.warning(req.Header, err)
}
if session.Hijacked() {
log.Debugf("martian: connection hijacked by request modifier")
return
}
log.Debugf("martian: attempting to establish CONNECT tunnel: %s", req.URL.Host)
var (
res *http.Response
cr io.Reader
cw io.WriteCloser
cerr error
)
if p.ConnectPassthrough {
pr, pw := io.Pipe()
req.Body = pr
defer req.Body.Close()
// perform the HTTP roundtrip
res, cerr = p.roundTrip(ctx, req)
if res != nil {
cr = res.Body
cw = pw
if res.StatusCode/100 == 2 {
res = proxyutil.NewResponse(200, nil, req)
}
}
} else {
var cconn net.Conn
res, cconn, cerr = p.connect(req)
if cconn != nil {
defer cconn.Close()
cr = cconn
cw = cconn
}
}
if cerr != nil {
log.Errorf("martian: failed to CONNECT: %v", cerr)
res = p.errorResponse(req, cerr)
p.warning(res.Header, cerr)
}
defer res.Body.Close()
if err := p.resmod.ModifyResponse(res); err != nil {
log.Errorf("martian: error modifying CONNECT response: %v", err)
p.warning(res.Header, err)
}
if session.Hijacked() {
log.Debugf("martian: connection hijacked by response modifier")
return
}
if res.StatusCode != 200 {
if cerr == nil {
log.Errorf("martian: CONNECT rejected with status code: %d", res.StatusCode)
}
writeResponse(rw, res)
return
}
if req.ProtoMajor == 1 {
res.ContentLength = -1
}
if err := p.tunnel("CONNECT", rw, req, res, cw, cr); err != nil {
log.Errorf("martian: CONNECT tunnel: %v", err)
panic(http.ErrAbortHandler)
}
}
func (p proxyHandler) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
resUpType := upgradeType(res.Header)
uconn, ok := res.Body.(io.ReadWriteCloser)
if !ok {
log.Errorf("martian: %s tunnel: internal error: switching protocols response with non-ReadWriteCloser body", resUpType)
panic(http.ErrAbortHandler)
}
res.Body = nil
if err := p.tunnel(resUpType, rw, req, res, uconn, uconn); err != nil {
log.Errorf("martian: %s tunnel: %w", resUpType, err)
panic(http.ErrAbortHandler)
}
}
func (p proxyHandler) tunnel(name string, rw http.ResponseWriter, req *http.Request, res *http.Response, cw io.WriteCloser, cr io.Reader) error {
var (
rc = http.NewResponseController(rw)
donec = make(chan bool, 2)
)
switch req.ProtoMajor {
case 1:
conn, brw, err := rc.Hijack()
if err != nil {
return err
}
defer conn.Close()
if err := res.Write(brw); err != nil {
return fmt.Errorf("got error while writing response back to client: %w", err)
}
if err := brw.Flush(); err != nil {
return fmt.Errorf("got error while flushing response back to client: %w", err)
}
if err := drainBuffer(cw, brw.Reader); err != nil {
return fmt.Errorf("got error while draining buffer: %w", err)
}
go copySync("outbound "+name, cw, conn, donec)
go copySync("inbound "+name, conn, cr, donec)
case 2:
copyHeader(rw.Header(), res.Header)
rw.WriteHeader(res.StatusCode)
if err := rc.Flush(); err != nil {
return fmt.Errorf("got error while flushing response back to client: %w", err)
}
go copySync("outbound "+name, cw, req.Body, donec)
go copySync("inbound "+name, writeFlusher{rw, rc}, cr, donec)
default:
return fmt.Errorf("unsupported protocol version: %d", req.ProtoMajor)
}
log.Debugf("martian: established %s tunnel, proxying traffic", name)
<-donec
<-donec
log.Debugf("martian: closed %s tunnel", name)
return nil
}
// handleRequest handles a request and writes the response to the given http.ResponseWriter.
// It returns an error if the request
func (p proxyHandler) handleRequest(ctx *Context, rw http.ResponseWriter, req *http.Request) {
session := ctx.Session()
if req.Method == "CONNECT" {
p.handleConnectRequest(ctx, rw, req)
return
}
req.Proto = "HTTP/1.1"
req.ProtoMajor = 1
req.ProtoMinor = 1
req.RequestURI = ""
if req.URL.Scheme == "" {
req.URL.Scheme = "http"
if session.IsSecure() {
req.URL.Scheme = "https"
}
} else if req.URL.Scheme == "http" {
if session.IsSecure() && !p.AllowHTTP {
log.Infof("martian: forcing HTTPS inside secure session")
req.URL.Scheme = "https"
}
}
reqUpType := upgradeType(req.Header)
if reqUpType != "" {
log.Debugf("martian: upgrade request: %s", reqUpType)
}
if err := p.reqmod.ModifyRequest(req); err != nil {
log.Errorf("martian: error modifying request: %v", err)
p.warning(req.Header, err)
}
if session.Hijacked() {
log.Debugf("martian: connection hijacked by request modifier")
return
}
// After stripping all the hop-by-hop connection headers above, add back any
// necessary for protocol upgrades, such as for websockets.
if reqUpType != "" {
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", reqUpType)
}
// perform the HTTP roundtrip
res, err := p.roundTrip(ctx, req)
if err != nil {
log.Errorf("martian: failed to round trip: %v", err)
res = p.errorResponse(req, err)
p.warning(res.Header, err)
}
defer res.Body.Close()
// set request to original request manually, res.Request may be changed in transport.
// see https://github.com/google/martian/issues/298
res.Request = req
resUpType := upgradeType(res.Header)
if resUpType != "" {
log.Debugf("martian: upgrade response: %s", resUpType)
}
if err := p.resmod.ModifyResponse(res); err != nil {
log.Errorf("martian: error modifying response: %v", err)
p.warning(res.Header, err)
}
if session.Hijacked() {
log.Debugf("martian: connection hijacked by response modifier")
return
}
// after stripping all the hop-by-hop connection headers above, add back any
// necessary for protocol upgrades, such as for websockets.
if resUpType != "" {
res.Header.Set("Connection", "Upgrade")
res.Header.Set("Upgrade", resUpType)
}
if !req.ProtoAtLeast(1, 1) || req.Close || res.Close || p.Closing() {
log.Debugf("martian: received close request: %v", req.RemoteAddr)
res.Close = true
}
if p.CloseAfterReply {
res.Close = true
}
// deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
if res.StatusCode == 101 {
p.handleUpgradeResponse(rw, req, res)
} else {
writeResponse(rw, res)
}
}
func newWriteFlusher(rw http.ResponseWriter) writeFlusher {
return writeFlusher{
rw: rw,
rc: http.NewResponseController(rw),
}
}
type writeFlusher struct {
rw io.Writer
rc *http.ResponseController
}
func (w writeFlusher) Write(p []byte) (n int, err error) {
n, err = w.rw.Write(p)
if n > 0 {
if err := w.rc.Flush(); err != nil {
log.Errorf("martian: got error while flushing response back to client: %v", err)
}
}
return
}
func (w writeFlusher) CloseWrite() error {
// This is a nop implementation of closeWriter.
// It avoids printing the error log "cannot close write side of inbound CONNECT tunnel".
return nil
}
func writeResponse(rw http.ResponseWriter, res *http.Response) {
copyHeader(rw.Header(), res.Header)
if res.Close {
res.Header.Set("Connection", "close")
}
announcedTrailers := addTrailerHeader(rw, res.Trailer)
rw.WriteHeader(res.StatusCode)
// This flush is needed for http/1 server to flush the status code and headers.
// It prevents the server from buffering the response and trying to calculate the response size.
if f, ok := rw.(http.Flusher); ok {
f.Flush()
}
var err error
if shouldFlush(res) {
err = copyBody(newWriteFlusher(rw), res.Body)
} else {
err = copyBody(rw, res.Body)
}
if err != nil {
log.Errorf("martian: got error while writing response back to client: %v", err)
panic(http.ErrAbortHandler)
}
res.Body.Close() // close now, instead of defer, to populate res.Trailer
if len(res.Trailer) == announcedTrailers {
copyHeader(rw.Header(), res.Trailer)
} else {
h := rw.Header()
for k, vv := range res.Trailer {
for _, v := range vv {
h.Add(http.TrailerPrefix+k, v)
}
}
}
}