-
Notifications
You must be signed in to change notification settings - Fork 256
/
httpProxy.go
843 lines (720 loc) · 26.1 KB
/
httpProxy.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
/*
* Copyright (c) 2016, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package psiphon
import (
"bytes"
"compress/gzip"
"crypto/tls"
std_errors "errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
"github.com/grafov/m3u8"
)
// HttpProxy is a HTTP server that relays HTTP requests through the Psiphon tunnel.
// It includes support for HTTP CONNECT.
//
// This proxy also offers a "URL proxy" mode that relays requests for HTTP or HTTPS
// or URLs specified in the proxy request path. This mode relays either through the
// Psiphon tunnel, or directly.
//
// An example use case for tunneled URL proxy relays is to craft proxied URLs to pass to
// components that don't support HTTP or SOCKS proxy settings. For example, the
// Android Media Player (http://developer.android.com/reference/android/media/MediaPlayer.html).
// To make the Media Player use the Psiphon tunnel, construct a URL such as:
// "http://127.0.0.1:<proxy-port>/tunneled/<origin media URL>"; and pass this to the player.
// The <origin media URL> must be escaped in such a way that it can be used inside a URL query.
//
// An example use case for direct, untunneled, relaying is to make use of Go's TLS
// stack for HTTPS requests in cases where the native TLS stack is lacking (e.g.,
// WinHTTP on Windows XP). The URL for direct relaying is:
// "http://127.0.0.1:<proxy-port>/direct/<origin URL>".
// Again, the <origin URL> must be escaped in such a way that it can be used inside a URL query.
//
// An example use case for tunneled relaying with rewriting (/tunneled-rewrite/) is when the
// content of retrieved files contains URLs that also need to be modified to be tunneled.
// For example, in iOS 10 the UIWebView media player does not put requests through the
// NSURLProtocol, so they are not tunneled. Instead, we rewrite those URLs to use the URL
// proxy, and rewrite retrieved playlist files so they also contain proxied URLs.
//
// The URL proxy offers /tunneled-icy/ which is compatible with both HTTP and ICY protocol
// resources.
//
// Origin URLs must include the scheme prefix ("http://" or "https://") and must be
// URL encoded.
//
type HttpProxy struct {
config *Config
tunneler Tunneler
listener net.Listener
serveWaitGroup *sync.WaitGroup
httpProxyTunneledRelay *http.Transport
urlProxyTunneledRelay *http.Transport
urlProxyTunneledClient *http.Client
urlProxyDirectRelay *http.Transport
urlProxyDirectClient *http.Client
responseHeaderTimeout time.Duration
openConns *common.Conns
stopListeningBroadcast chan struct{}
listenIP string
listenPort int
}
var _HTTP_PROXY_TYPE = "HTTP"
// NewHttpProxy initializes and runs a new HTTP proxy server.
func NewHttpProxy(
config *Config,
tunneler Tunneler,
listenIP string) (proxy *HttpProxy, err error) {
listener, portInUse, err := makeLocalProxyListener(
listenIP, config.LocalHttpProxyPort)
if err != nil {
if portInUse {
NoticeHttpProxyPortInUse(config.LocalHttpProxyPort)
}
return nil, errors.Trace(err)
}
tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
// downstreamConn is not set in this case, as there is not a fixed
// association between a downstream client connection and a particular
// tunnel.
return tunneler.Dial(addr, nil)
}
directDialer := func(_, addr string) (conn net.Conn, err error) {
return tunneler.DirectDial(addr)
}
p := config.GetParameters().Get()
responseHeaderTimeout := p.Duration(parameters.HTTPProxyOriginServerTimeout)
maxIdleConnsPerHost := p.Int(parameters.HTTPProxyMaxIdleConnectionsPerHost)
// TODO: could HTTP proxy share a tunneled transport with URL proxy?
// For now, keeping them distinct just to be conservative.
httpProxyTunneledRelay := &http.Transport{
Dial: tunneledDialer,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
ResponseHeaderTimeout: responseHeaderTimeout,
}
// Note: URL proxy relays use http.Client for upstream requests, so
// redirects will be followed. HTTP proxy should not follow redirects
// and simply uses http.Transport directly.
urlProxyTunneledRelay := &http.Transport{
Dial: tunneledDialer,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
ResponseHeaderTimeout: responseHeaderTimeout,
}
urlProxyTunneledClient := &http.Client{
Transport: urlProxyTunneledRelay,
Jar: nil, // TODO: cookie support for URL proxy?
// Leaving original value in the note below:
// Note: don't use this timeout -- it interrupts downloads of large response bodies
//Timeout: HTTP_PROXY_ORIGIN_SERVER_TIMEOUT,
}
urlProxyDirectRelay := &http.Transport{
Dial: directDialer,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
ResponseHeaderTimeout: responseHeaderTimeout,
}
urlProxyDirectClient := &http.Client{
Transport: urlProxyDirectRelay,
Jar: nil,
}
proxyIP, proxyPortString, _ := net.SplitHostPort(listener.Addr().String())
proxyPort, _ := strconv.Atoi(proxyPortString)
proxy = &HttpProxy{
config: config,
tunneler: tunneler,
listener: listener,
serveWaitGroup: new(sync.WaitGroup),
httpProxyTunneledRelay: httpProxyTunneledRelay,
urlProxyTunneledRelay: urlProxyTunneledRelay,
urlProxyTunneledClient: urlProxyTunneledClient,
urlProxyDirectRelay: urlProxyDirectRelay,
urlProxyDirectClient: urlProxyDirectClient,
responseHeaderTimeout: responseHeaderTimeout,
openConns: common.NewConns(),
stopListeningBroadcast: make(chan struct{}),
listenIP: proxyIP,
listenPort: proxyPort,
}
proxy.serveWaitGroup.Add(1)
go proxy.serve()
// TODO: NoticeListeningHttpProxyPort is emitted after net.Listen
// but before go proxy.server() and httpServer.Serve(), and this
// appears to cause client connections to the HTTP proxy to fail
// (in controller_test.go, only when a tunnel is established very quickly
// and NoticeTunnels is emitted and the client makes a request -- all
// before the proxy.server() goroutine runs).
// This condition doesn't arise in Go 1.4, just in Go tip (pre-1.5).
// Note that httpServer.Serve() blocks so the fix can't be to emit
// NoticeListeningHttpProxyPort after that call.
// Also, check the listen backlog queue length -- shouldn't it be possible
// to enqueue pending connections between net.Listen() and httpServer.Serve()?
NoticeListeningHttpProxyPort(proxy.listenPort)
return proxy, nil
}
// Close terminates the HTTP server.
func (proxy *HttpProxy) Close() {
close(proxy.stopListeningBroadcast)
proxy.listener.Close()
proxy.serveWaitGroup.Wait()
// Close local->proxy persistent connections
proxy.openConns.CloseAll()
// Close idle proxy->origin persistent connections
// TODO: also close active connections
proxy.httpProxyTunneledRelay.CloseIdleConnections()
proxy.urlProxyTunneledRelay.CloseIdleConnections()
proxy.urlProxyDirectRelay.CloseIdleConnections()
}
// ServeHTTP receives HTTP requests and proxies them. CONNECT requests
// are hijacked and all data is relayed. Other HTTP requests are proxied
// with explicit round trips. In both cases, the tunnel is used for proxied
// traffic.
//
// Implementation is based on:
//
// https://github.com/justmao945/mallory
// Copyright (c) 2014 JianjunMao
// The MIT License (MIT)
//
// https://golang.org/src/pkg/net/http/httputil/reverseproxy.go
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
if request.Method == "CONNECT" {
conn := hijack(responseWriter)
if conn == nil {
// hijack emits an alert notice
http.Error(responseWriter, "", http.StatusInternalServerError)
return
}
go func() {
err := proxy.httpConnectHandler(conn, request.URL.Host)
if err != nil {
NoticeWarning("%s", errors.Trace(err))
}
}()
} else if request.URL.IsAbs() {
proxy.httpProxyHandler(responseWriter, request)
} else {
proxy.urlProxyHandler(responseWriter, request)
}
}
func (proxy *HttpProxy) httpConnectHandler(localConn net.Conn, target string) (err error) {
defer localConn.Close()
defer proxy.openConns.Remove(localConn)
proxy.openConns.Add(localConn)
// Setting downstreamConn so localConn.Close() will be called when remoteConn.Close() is called.
// This ensures that the downstream client (e.g., web browser) doesn't keep waiting on the
// open connection for data which will never arrive.
remoteConn, err := proxy.tunneler.Dial(target, localConn)
if err != nil {
return errors.Trace(err)
}
defer remoteConn.Close()
_, err = localConn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
if err != nil {
return errors.Trace(err)
}
LocalProxyRelay(proxy.config, _HTTP_PROXY_TYPE, localConn, remoteConn)
return nil
}
func (proxy *HttpProxy) httpProxyHandler(responseWriter http.ResponseWriter, request *http.Request) {
proxy.relayHTTPRequest(nil, proxy.httpProxyTunneledRelay, request, responseWriter, nil, nil)
}
const (
URL_PROXY_TUNNELED_REQUEST_PATH = "/tunneled/"
URL_PROXY_TUNNELED_REWRITE_REQUEST_PATH = "/tunneled-rewrite/"
URL_PROXY_TUNNELED_ICY_REQUEST_PATH = "/tunneled-icy/"
URL_PROXY_DIRECT_REQUEST_PATH = "/direct/"
)
func (proxy *HttpProxy) urlProxyHandler(responseWriter http.ResponseWriter, request *http.Request) {
var client *http.Client
var rewriteICYStatus *rewriteICYStatus
var originURLString string
var err error
var rewrites url.Values
// Request URL should be "/tunneled/<origin URL>" or "/direct/<origin URL>" and the
// origin URL must be URL encoded.
switch {
case strings.HasPrefix(request.URL.RawPath, URL_PROXY_TUNNELED_REQUEST_PATH):
originURLString, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_TUNNELED_REQUEST_PATH):])
client = proxy.urlProxyTunneledClient
case strings.HasPrefix(request.URL.RawPath, URL_PROXY_TUNNELED_REWRITE_REQUEST_PATH):
originURLString, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_TUNNELED_REWRITE_REQUEST_PATH):])
client = proxy.urlProxyTunneledClient
rewrites = request.URL.Query()
case strings.HasPrefix(request.URL.RawPath, URL_PROXY_TUNNELED_ICY_REQUEST_PATH):
originURLString, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_TUNNELED_ICY_REQUEST_PATH):])
client, rewriteICYStatus = proxy.makeRewriteICYClient()
rewrites = request.URL.Query()
case strings.HasPrefix(request.URL.RawPath, URL_PROXY_DIRECT_REQUEST_PATH):
originURLString, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_DIRECT_REQUEST_PATH):])
client = proxy.urlProxyDirectClient
default:
err = std_errors.New("missing origin URL")
}
if err != nil {
NoticeWarning("%s", errors.Trace(common.RedactURLError(err)))
forceClose(responseWriter)
return
}
// Origin URL must be well-formed, absolute, and have a scheme of "http" or "https"
originURL, err := common.SafeParseRequestURI(originURLString)
if err != nil {
NoticeWarning("%s", errors.Trace(common.RedactURLError(err)))
forceClose(responseWriter)
return
}
if !originURL.IsAbs() || (originURL.Scheme != "http" && originURL.Scheme != "https") {
NoticeWarning("invalid origin URL")
forceClose(responseWriter)
return
}
// Transform received request to directly reference the origin URL
request.Host = originURL.Host
request.URL = originURL
proxy.relayHTTPRequest(client, nil, request, responseWriter, rewrites, rewriteICYStatus)
}
// rewriteICYConn rewrites an ICY procotol responses to that it may be
// consumed by Go's http package. rewriteICYConn expects the ICY response to
// be equivalent to HTTP/1.1 with the exception of the protocol name in the
// status line, which is the one part that is rewritten. Responses that are
// already HTTP are passed through unmodified.
type rewriteICYConn struct {
net.Conn
doneRewriting int32
isICY *int32
}
func (conn *rewriteICYConn) Read(b []byte) (int, error) {
if !atomic.CompareAndSwapInt32(&conn.doneRewriting, 0, 1) {
return conn.Conn.Read(b)
}
if len(b) < 3 {
// Don't attempt to rewrite the protocol when insufficient
// buffer space. This is not expected to happen in practise
// when Go's http reads the response, so for now we just
// skip the rewrite instead of tracking state accross Reads.
return conn.Conn.Read(b)
}
// Expect to read either "ICY" or "HTT".
n, err := conn.Conn.Read(b[:3])
if err != nil {
return n, err
}
if bytes.Equal(b[:3], []byte("ICY")) {
atomic.StoreInt32(conn.isICY, 1)
protocol := "HTTP/1.0"
copy(b, []byte(protocol))
return len(protocol), nil
}
return n, nil
}
type rewriteICYStatus struct {
isFirstConnICY int32
}
func (status *rewriteICYStatus) isICY() bool {
return atomic.LoadInt32(&status.isFirstConnICY) == 1
}
// makeRewriteICYClient creates an http.Client with a Transport configured to
// use rewriteICYConn. Both HTTP and HTTPS are handled. The http.Client is
// intended to be used for one single request. The client disables keep alives
// as rewriteICYConn can only rewrite the first response in a connection. The
// returned rewriteICYStatus indicates whether the first response for the first
// request was ICY, allowing the downstream relayed response to replicate the
// ICY protocol.
func (proxy *HttpProxy) makeRewriteICYClient() (*http.Client, *rewriteICYStatus) {
rewriteICYStatus := &rewriteICYStatus{}
tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
// See comment in NewHttpProxy regarding downstreamConn
return proxy.tunneler.Dial(addr, nil)
}
dial := func(network, address string) (net.Conn, error) {
conn, err := tunneledDialer(network, address)
if err != nil {
return nil, errors.Trace(err)
}
return &rewriteICYConn{
Conn: conn,
isICY: &rewriteICYStatus.isFirstConnICY,
}, nil
}
dialTLS := func(network, address string) (net.Conn, error) {
conn, err := tunneledDialer(network, address)
if err != nil {
return nil, errors.Trace(err)
}
serverName, _, err := net.SplitHostPort(address)
if err != nil {
conn.Close()
return nil, errors.Trace(err)
}
tlsConn := tls.Client(conn, &tls.Config{ServerName: serverName})
resultChannel := make(chan error, 1)
timeout := proxy.responseHeaderTimeout
afterFunc := time.AfterFunc(timeout, func() {
resultChannel <- errors.TraceNew("TLS handshake timeout")
})
defer afterFunc.Stop()
go func() {
resultChannel <- tlsConn.Handshake()
}()
err = <-resultChannel
if err != nil {
conn.Close()
return nil, errors.Trace(err)
}
err = tlsConn.VerifyHostname(serverName)
if err != nil {
conn.Close()
return nil, errors.Trace(err)
}
return &rewriteICYConn{
Conn: tlsConn,
isICY: &rewriteICYStatus.isFirstConnICY,
}, nil
}
return &http.Client{
Transport: &http.Transport{
Dial: dial,
DialTLS: dialTLS,
DisableKeepAlives: true,
ResponseHeaderTimeout: proxy.responseHeaderTimeout,
},
}, rewriteICYStatus
}
func (proxy *HttpProxy) relayHTTPRequest(
client *http.Client,
transport *http.Transport,
request *http.Request,
responseWriter http.ResponseWriter,
rewrites url.Values,
rewriteICYStatus *rewriteICYStatus) {
// Transform received request struct before using as input to relayed request
request.Close = false
request.RequestURI = ""
for _, key := range hopHeaders {
request.Header.Del(key)
}
// Relay the HTTP request and get the response. Use a client when supplied,
// otherwise a transport. A client handles cookies and redirects, and a
// transport does not.
var response *http.Response
var err error
if client != nil {
response, err = client.Do(request)
} else {
response, err = transport.RoundTrip(request)
}
if err != nil {
NoticeWarning("%s", errors.Trace(common.RedactURLError(err)))
forceClose(responseWriter)
return
}
defer response.Body.Close()
// Note: Rewrite functions are responsible for leaving response.Body in
// a valid, readable state if there's no error.
for key := range rewrites {
var err error
switch key {
case "m3u8":
err = rewriteM3U8(proxy.listenIP, proxy.listenPort, response)
}
if err != nil {
NoticeWarning("URL proxy rewrite failed for %s: %s", key, errors.Trace(err))
forceClose(responseWriter)
response.Body.Close()
return
}
}
// Relay the remote response headers
for _, key := range hopHeaders {
response.Header.Del(key)
}
for key := range responseWriter.Header() {
responseWriter.Header().Del(key)
}
for key, values := range response.Header {
for _, value := range values {
responseWriter.Header().Add(key, value)
}
}
// Send the response downstream
if rewriteICYStatus != nil && rewriteICYStatus.isICY() {
// Custom ICY response, using "ICY" as the protocol name
// but otherwise equivalent to the HTTP response.
// As the ICY http.Transport has disabled keep-alives,
// hijacking here does not disrupt an otherwise persistent
// connection.
conn := hijack(responseWriter)
if conn == nil {
// hijack emits an alert notice
return
}
_, err := fmt.Fprintf(
conn,
"ICY %d %s\r\n",
response.StatusCode,
http.StatusText(response.StatusCode))
if err != nil {
NoticeWarning("write status line failed: %s", errors.Trace(err))
conn.Close()
return
}
err = responseWriter.Header().Write(conn)
if err != nil {
NoticeWarning("write headers failed: %s", errors.Trace(err))
conn.Close()
return
}
_, err = RelayCopyBuffer(proxy.config, conn, response.Body)
if err != nil {
NoticeWarning("write body failed: %s", errors.Trace(err))
conn.Close()
return
}
} else {
// Standard HTTP response.
responseWriter.WriteHeader(response.StatusCode)
_, err = RelayCopyBuffer(proxy.config, responseWriter, response.Body)
if err != nil {
NoticeWarning("%s", errors.Trace(err))
forceClose(responseWriter)
return
}
}
}
// forceClose hijacks and closes persistent connections. This is used
// to ensure local persistent connections into the HTTP proxy are closed
// when ServeHTTP encounters an error.
func forceClose(responseWriter http.ResponseWriter) {
conn := hijack(responseWriter)
if conn != nil {
conn.Close()
}
}
func hijack(responseWriter http.ResponseWriter) net.Conn {
hijacker, ok := responseWriter.(http.Hijacker)
if !ok {
NoticeWarning("%s", errors.TraceNew("responseWriter is not an http.Hijacker"))
return nil
}
conn, _, err := hijacker.Hijack()
if err != nil {
NoticeWarning("%s", errors.Tracef("responseWriter hijack failed: %s", err))
return nil
}
return conn
}
// From https://golang.org/src/pkg/net/http/httputil/reverseproxy.go:
// Hop-by-hop headers. These are removed when sent to the backend.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Proxy-Connection", // see: http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/web-proxy-connection-header.html
"Te", // canonicalized version of "TE"
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
// httpConnStateCallback is called by http.Server when the state of a local->proxy
// connection changes. Open connections are tracked so that all local->proxy persistent
// connections can be closed by HttpProxy.Close()
// TODO: if the HttpProxy is decoupled from a single Tunnel instance and
// instead uses the "current" Tunnel, it may not be necessary to close
// local persistent connections when the tunnel reconnects.
func (proxy *HttpProxy) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
switch connState {
case http.StateNew:
proxy.openConns.Add(conn)
case http.StateActive, http.StateIdle:
// No action
case http.StateHijacked, http.StateClosed:
proxy.openConns.Remove(conn)
}
}
func (proxy *HttpProxy) serve() {
defer proxy.listener.Close()
defer proxy.serveWaitGroup.Done()
httpServer := &http.Server{
Handler: proxy,
ConnState: proxy.httpConnStateCallback,
}
// Note: will be interrupted by listener.Close() call made by proxy.Close()
err := httpServer.Serve(proxy.listener)
// Can't check for the exact error that Close() will cause in Accept(),
// (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
// explicit stop signal to stop gracefully.
select {
case <-proxy.stopListeningBroadcast:
default:
if err != nil {
proxy.tunneler.SignalComponentFailure()
NoticeLocalProxyError(_HTTP_PROXY_TYPE, errors.Trace(err))
}
}
NoticeInfo("HTTP proxy stopped")
}
//
// Rewrite functions
//
// toAbsoluteURL takes a base URL and a relative URL and constructs an appropriate absolute URL.
func toAbsoluteURL(baseURL *url.URL, relativeURLString string) string {
relativeURL, err := common.SafeParseURL(relativeURLString)
if err != nil {
return ""
}
if relativeURL.IsAbs() {
return relativeURL.String()
}
return baseURL.ResolveReference(relativeURL).String()
}
// proxifyURL takes an absolute URL and rewrites it to go through the local URL proxy.
// urlProxy port is the local HTTP proxy port.
//
// If rewriteParams is nil, then no rewriting will be done. Otherwise, it should contain
// supported rewriting flags (like "m3u8").
func proxifyURL(localHTTPProxyIP string, localHTTPProxyPort int, urlString string, rewriteParams []string) string {
// Note that we need to use the "opaque" form of URL so that it doesn't double-escape the path. See: https://github.com/golang/go/issues/10887
// TODO: IPv6 support
if localHTTPProxyIP == "0.0.0.0" {
localHTTPProxyIP = "127.0.0.1"
}
proxyPath := URL_PROXY_TUNNELED_REQUEST_PATH
if rewriteParams != nil {
proxyPath = URL_PROXY_TUNNELED_REWRITE_REQUEST_PATH
}
opaqueFormat := fmt.Sprintf("//%%s:%%d%s%%s", proxyPath)
var proxifiedURL url.URL
proxifiedURL.Scheme = "http"
proxifiedURL.Opaque = fmt.Sprintf(opaqueFormat, localHTTPProxyIP, localHTTPProxyPort, url.QueryEscape(urlString))
qp := proxifiedURL.Query()
for _, rewrite := range rewriteParams {
qp.Set(rewrite, "")
}
proxifiedURL.RawQuery = qp.Encode()
return proxifiedURL.String()
}
// Rewrite the contents of the M3U8 file in body to be compatible with URL proxying.
// If error is returned, response body may not be valid for reading.
func rewriteM3U8(localHTTPProxyIP string, localHTTPProxyPort int, response *http.Response) error {
// Check URL path extension
extension := filepath.Ext(response.Request.URL.Path)
var shouldHandle = (extension == ".m3u8")
// If not .m3u8 then check content type
if !shouldHandle {
contentType := strings.ToLower(response.Header.Get("Content-Type"))
shouldHandle = (contentType == "application/x-mpegurl" || contentType == "vnd.apple.mpegurl")
}
if !shouldHandle {
return nil
}
var reader io.ReadCloser
switch response.Header.Get("Content-Encoding") {
case "gzip":
var err error
reader, err = gzip.NewReader(response.Body)
if err != nil {
return errors.Trace(err)
}
// Unset Content-Encoding.
// There's is no point in deflating the decoded/rewritten content
response.Header.Del("Content-Encoding")
defer reader.Close()
default:
reader = response.Body
}
contentBodyBytes, err := ioutil.ReadAll(reader)
response.Body.Close()
if err != nil {
return errors.Trace(err)
}
p, listType, err := m3u8.Decode(*bytes.NewBuffer(contentBodyBytes), true)
if err != nil {
// Don't pass this error up. Just don't change anything.
response.Body = ioutil.NopCloser(bytes.NewReader(contentBodyBytes))
response.Header.Set("Content-Length", strconv.FormatInt(int64(len(contentBodyBytes)), 10))
return nil
}
var rewrittenBodyBytes []byte
switch listType {
case m3u8.MEDIA:
mediapl := p.(*m3u8.MediaPlaylist)
for _, segment := range mediapl.Segments {
if segment == nil {
break
}
if segment.URI != "" {
segment.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, segment.URI), nil)
}
if segment.Key != nil && segment.Key.URI != "" {
segment.Key.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, segment.Key.URI), nil)
}
if segment.Map != nil && segment.Map.URI != "" {
segment.Map.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, segment.Map.URI), nil)
}
}
rewrittenBodyBytes = []byte(mediapl.String())
case m3u8.MASTER:
masterpl := p.(*m3u8.MasterPlaylist)
for _, variant := range masterpl.Variants {
if variant == nil {
break
}
if variant.URI != "" {
variant.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, variant.URI), []string{"m3u8"})
}
for _, alternative := range variant.Alternatives {
if alternative == nil {
break
}
if alternative.URI != "" {
alternative.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, alternative.URI), []string{"m3u8"})
}
}
}
rewrittenBodyBytes = []byte(masterpl.String())
}
var responseBodyBytes []byte
if len(rewrittenBodyBytes) == 0 {
responseBodyBytes = contentBodyBytes[:]
} else {
responseBodyBytes = rewrittenBodyBytes[:]
// When rewriting the original URL so that it was URL-proxied, we lost the
// file extension of it. That means we'd better make sure the Content-Type is set.
response.Header.Set("Content-Type", "application/x-mpegurl")
}
response.Header.Set("Content-Length", strconv.FormatInt(int64(len(responseBodyBytes)), 10))
response.Body = ioutil.NopCloser(bytes.NewReader(responseBodyBytes))
return nil
}