httpProxy.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "bytes"
  22. "compress/gzip"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "path/filepath"
  31. "strconv"
  32. "strings"
  33. "sync"
  34. "time"
  35. "github.com/Psiphon-Inc/m3u8"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  37. )
  38. // HttpProxy is a HTTP server that relays HTTP requests through the Psiphon tunnel.
  39. // It includes support for HTTP CONNECT.
  40. //
  41. // This proxy also offers a "URL proxy" mode that relays requests for HTTP or HTTPS
  42. // or URLs specified in the proxy request path. This mode relays either through the
  43. // Psiphon tunnel, or directly.
  44. //
  45. // An example use case for tunneled URL proxy relays is to craft proxied URLs to pass to
  46. // components that don't support HTTP or SOCKS proxy settings. For example, the
  47. // Android Media Player (http://developer.android.com/reference/android/media/MediaPlayer.html).
  48. // To make the Media Player use the Psiphon tunnel, construct a URL such as:
  49. // "http://127.0.0.1:<proxy-port>/tunneled/<origin media URL>"; and pass this to the player.
  50. // The <origin media URL> must be escaped in such a way that it can be used inside a URL query.
  51. // TODO: add ICY protocol to support certain streaming media (e.g., https://gist.github.com/tulskiy/1008126)
  52. //
  53. // An example use case for direct, untunneled, relaying is to make use of Go's TLS
  54. // stack for HTTPS requests in cases where the native TLS stack is lacking (e.g.,
  55. // WinHTTP on Windows XP). The URL for direct relaying is:
  56. // "http://127.0.0.1:<proxy-port>/direct/<origin URL>".
  57. // Again, the <origin URL> must be escaped in such a way that it can be used inside a URL query.
  58. //
  59. // An example use case for tunneled relaying with rewriting (/tunneled-rewrite/) is when the
  60. // content of retrieved files contains URLs that also need to be modified to be tunneled.
  61. // For example, in iOS 10 the UIWebView media player does not put requests through the
  62. // NSURLProtocol, so they are not tunneled. Instead, we rewrite those URLs to use the URL
  63. // proxy, and rewrite retrieved playlist files so they also contain proxied URLs.
  64. //
  65. // Origin URLs must include the scheme prefix ("http://" or "https://") and must be
  66. // URL encoded.
  67. //
  68. type HttpProxy struct {
  69. tunneler Tunneler
  70. listener net.Listener
  71. serveWaitGroup *sync.WaitGroup
  72. httpProxyTunneledRelay *http.Transport
  73. urlProxyTunneledRelay *http.Transport
  74. urlProxyTunneledClient *http.Client
  75. urlProxyDirectRelay *http.Transport
  76. urlProxyDirectClient *http.Client
  77. openConns *common.Conns
  78. stopListeningBroadcast chan struct{}
  79. listenIP string
  80. listenPort int
  81. }
  82. var _HTTP_PROXY_TYPE = "HTTP"
  83. // NewHttpProxy initializes and runs a new HTTP proxy server.
  84. func NewHttpProxy(
  85. config *Config,
  86. untunneledDialConfig *DialConfig,
  87. tunneler Tunneler,
  88. listenIP string) (proxy *HttpProxy, err error) {
  89. listener, err := net.Listen(
  90. "tcp", fmt.Sprintf("%s:%d", listenIP, config.LocalHttpProxyPort))
  91. if err != nil {
  92. if IsAddressInUseError(err) {
  93. NoticeHttpProxyPortInUse(config.LocalHttpProxyPort)
  94. }
  95. return nil, common.ContextError(err)
  96. }
  97. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  98. // downstreamConn is not set in this case, as there is not a fixed
  99. // association between a downstream client connection and a particular
  100. // tunnel.
  101. // TODO: connect timeout?
  102. return tunneler.Dial(addr, false, nil)
  103. }
  104. directDialer := func(_, addr string) (conn net.Conn, err error) {
  105. return DialTCP(addr, untunneledDialConfig)
  106. }
  107. responseHeaderTimeout := time.Duration(*config.HttpProxyOriginServerTimeoutSeconds) * time.Second
  108. // TODO: could HTTP proxy share a tunneled transport with URL proxy?
  109. // For now, keeping them distinct just to be conservative.
  110. httpProxyTunneledRelay := &http.Transport{
  111. Dial: tunneledDialer,
  112. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  113. ResponseHeaderTimeout: responseHeaderTimeout,
  114. }
  115. // Note: URL proxy relays use http.Client for upstream requests, so
  116. // redirects will be followed. HTTP proxy should not follow redirects
  117. // and simply uses http.Transport directly.
  118. urlProxyTunneledRelay := &http.Transport{
  119. Dial: tunneledDialer,
  120. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  121. ResponseHeaderTimeout: responseHeaderTimeout,
  122. }
  123. urlProxyTunneledClient := &http.Client{
  124. Transport: urlProxyTunneledRelay,
  125. Jar: nil, // TODO: cookie support for URL proxy?
  126. // Leaving original value in the note below:
  127. // Note: don't use this timeout -- it interrupts downloads of large response bodies
  128. //Timeout: HTTP_PROXY_ORIGIN_SERVER_TIMEOUT,
  129. }
  130. urlProxyDirectRelay := &http.Transport{
  131. Dial: directDialer,
  132. MaxIdleConnsPerHost: HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST,
  133. ResponseHeaderTimeout: responseHeaderTimeout,
  134. }
  135. urlProxyDirectClient := &http.Client{
  136. Transport: urlProxyDirectRelay,
  137. Jar: nil,
  138. }
  139. proxyIP, proxyPortString, _ := net.SplitHostPort(listener.Addr().String())
  140. proxyPort, _ := strconv.Atoi(proxyPortString)
  141. proxy = &HttpProxy{
  142. tunneler: tunneler,
  143. listener: listener,
  144. serveWaitGroup: new(sync.WaitGroup),
  145. httpProxyTunneledRelay: httpProxyTunneledRelay,
  146. urlProxyTunneledRelay: urlProxyTunneledRelay,
  147. urlProxyTunneledClient: urlProxyTunneledClient,
  148. urlProxyDirectRelay: urlProxyDirectRelay,
  149. urlProxyDirectClient: urlProxyDirectClient,
  150. openConns: new(common.Conns),
  151. stopListeningBroadcast: make(chan struct{}),
  152. listenIP: proxyIP,
  153. listenPort: proxyPort,
  154. }
  155. proxy.serveWaitGroup.Add(1)
  156. go proxy.serve()
  157. // TODO: NoticeListeningHttpProxyPort is emitted after net.Listen
  158. // but before go proxy.server() and httpServer.Serve(), and this
  159. // appears to cause client connections to the HTTP proxy to fail
  160. // (in controller_test.go, only when a tunnel is established very quickly
  161. // and NoticeTunnels is emitted and the client makes a request -- all
  162. // before the proxy.server() goroutine runs).
  163. // This condition doesn't arise in Go 1.4, just in Go tip (pre-1.5).
  164. // Note that httpServer.Serve() blocks so the fix can't be to emit
  165. // NoticeListeningHttpProxyPort after that call.
  166. // Also, check the listen backlog queue length -- shouldn't it be possible
  167. // to enqueue pending connections between net.Listen() and httpServer.Serve()?
  168. NoticeListeningHttpProxyPort(proxy.listenPort)
  169. return proxy, nil
  170. }
  171. // Close terminates the HTTP server.
  172. func (proxy *HttpProxy) Close() {
  173. close(proxy.stopListeningBroadcast)
  174. proxy.listener.Close()
  175. proxy.serveWaitGroup.Wait()
  176. // Close local->proxy persistent connections
  177. proxy.openConns.CloseAll()
  178. // Close idle proxy->origin persistent connections
  179. // TODO: also close active connections
  180. proxy.httpProxyTunneledRelay.CloseIdleConnections()
  181. proxy.urlProxyTunneledRelay.CloseIdleConnections()
  182. proxy.urlProxyDirectRelay.CloseIdleConnections()
  183. }
  184. // ServeHTTP receives HTTP requests and proxies them. CONNECT requests
  185. // are hijacked and all data is relayed. Other HTTP requests are proxied
  186. // with explicit round trips. In both cases, the tunnel is used for proxied
  187. // traffic.
  188. //
  189. // Implementation is based on:
  190. //
  191. // https://github.com/justmao945/mallory
  192. // Copyright (c) 2014 JianjunMao
  193. // The MIT License (MIT)
  194. //
  195. // https://golang.org/src/pkg/net/http/httputil/reverseproxy.go
  196. // Copyright 2011 The Go Authors. All rights reserved.
  197. // Use of this source code is governed by a BSD-style
  198. // license that can be found in the LICENSE file.
  199. //
  200. func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  201. if request.Method == "CONNECT" {
  202. hijacker, _ := responseWriter.(http.Hijacker)
  203. conn, _, err := hijacker.Hijack()
  204. if err != nil {
  205. NoticeAlert("%s", common.ContextError(err))
  206. http.Error(responseWriter, "", http.StatusInternalServerError)
  207. return
  208. }
  209. go func() {
  210. err := proxy.httpConnectHandler(conn, request.URL.Host)
  211. if err != nil {
  212. NoticeAlert("%s", common.ContextError(err))
  213. }
  214. }()
  215. } else if request.URL.IsAbs() {
  216. proxy.httpProxyHandler(responseWriter, request)
  217. } else {
  218. proxy.urlProxyHandler(responseWriter, request)
  219. }
  220. }
  221. func (proxy *HttpProxy) httpConnectHandler(localConn net.Conn, target string) (err error) {
  222. defer localConn.Close()
  223. defer proxy.openConns.Remove(localConn)
  224. proxy.openConns.Add(localConn)
  225. // Setting downstreamConn so localConn.Close() will be called when remoteConn.Close() is called.
  226. // This ensures that the downstream client (e.g., web browser) doesn't keep waiting on the
  227. // open connection for data which will never arrive.
  228. remoteConn, err := proxy.tunneler.Dial(target, false, localConn)
  229. if err != nil {
  230. return common.ContextError(err)
  231. }
  232. defer remoteConn.Close()
  233. _, err = localConn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
  234. if err != nil {
  235. return common.ContextError(err)
  236. }
  237. LocalProxyRelay(_HTTP_PROXY_TYPE, localConn, remoteConn)
  238. return nil
  239. }
  240. func (proxy *HttpProxy) httpProxyHandler(responseWriter http.ResponseWriter, request *http.Request) {
  241. proxy.relayHTTPRequest(nil, proxy.httpProxyTunneledRelay, request, responseWriter, nil)
  242. }
  243. const (
  244. URL_PROXY_TUNNELED_REQUEST_PATH = "/tunneled/"
  245. URL_PROXY_REWRITE_REQUEST_PATH = "/tunneled-rewrite/"
  246. URL_PROXY_DIRECT_REQUEST_PATH = "/direct/"
  247. )
  248. func (proxy *HttpProxy) urlProxyHandler(responseWriter http.ResponseWriter, request *http.Request) {
  249. var client *http.Client
  250. var originURLString string
  251. var err error
  252. var rewrites url.Values
  253. // Request URL should be "/tunneled/<origin URL>" or "/direct/<origin URL>" and the
  254. // origin URL must be URL encoded.
  255. switch {
  256. case strings.HasPrefix(request.URL.RawPath, URL_PROXY_TUNNELED_REQUEST_PATH):
  257. originURLString, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_TUNNELED_REQUEST_PATH):])
  258. client = proxy.urlProxyTunneledClient
  259. case strings.HasPrefix(request.URL.RawPath, URL_PROXY_REWRITE_REQUEST_PATH):
  260. originURLString, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_REWRITE_REQUEST_PATH):])
  261. client = proxy.urlProxyTunneledClient
  262. rewrites = request.URL.Query()
  263. case strings.HasPrefix(request.URL.RawPath, URL_PROXY_DIRECT_REQUEST_PATH):
  264. originURLString, err = url.QueryUnescape(request.URL.RawPath[len(URL_PROXY_DIRECT_REQUEST_PATH):])
  265. client = proxy.urlProxyDirectClient
  266. default:
  267. err = errors.New("missing origin URL")
  268. }
  269. if err != nil {
  270. NoticeAlert("%s", common.ContextError(FilterUrlError(err)))
  271. forceClose(responseWriter)
  272. return
  273. }
  274. // Origin URL must be well-formed, absolute, and have a scheme of "http" or "https"
  275. originURL, err := url.ParseRequestURI(originURLString)
  276. if err != nil {
  277. NoticeAlert("%s", common.ContextError(FilterUrlError(err)))
  278. forceClose(responseWriter)
  279. return
  280. }
  281. if !originURL.IsAbs() || (originURL.Scheme != "http" && originURL.Scheme != "https") {
  282. NoticeAlert("invalid origin URL")
  283. forceClose(responseWriter)
  284. return
  285. }
  286. // Transform received request to directly reference the origin URL
  287. request.Host = originURL.Host
  288. request.URL = originURL
  289. proxy.relayHTTPRequest(client, nil, request, responseWriter, rewrites)
  290. }
  291. func (proxy *HttpProxy) relayHTTPRequest(
  292. client *http.Client,
  293. transport *http.Transport,
  294. request *http.Request,
  295. responseWriter http.ResponseWriter,
  296. rewrites url.Values) {
  297. // Transform received request struct before using as input to relayed request
  298. request.Close = false
  299. request.RequestURI = ""
  300. for _, key := range hopHeaders {
  301. request.Header.Del(key)
  302. }
  303. // Relay the HTTP request and get the response. Use a client when supplied,
  304. // otherwise a transport. A client handles cookies and redirects, and a
  305. // transport does not.
  306. var response *http.Response
  307. var err error
  308. if client != nil {
  309. response, err = client.Do(request)
  310. } else {
  311. response, err = transport.RoundTrip(request)
  312. }
  313. if err != nil {
  314. NoticeAlert("%s", common.ContextError(FilterUrlError(err)))
  315. forceClose(responseWriter)
  316. return
  317. }
  318. defer response.Body.Close()
  319. if rewrites != nil {
  320. // NOTE: Rewrite functions are responsible for leaving response.Body in
  321. // a valid, readable state if there's no error.
  322. for key := range rewrites {
  323. var err error
  324. switch key {
  325. case "m3u8":
  326. err = rewriteM3U8(proxy.listenIP, proxy.listenPort, response)
  327. }
  328. if err != nil {
  329. NoticeAlert("URL proxy rewrite failed for %s: %s", key, common.ContextError(err))
  330. forceClose(responseWriter)
  331. response.Body.Close()
  332. return
  333. }
  334. }
  335. }
  336. // Relay the remote response headers
  337. for _, key := range hopHeaders {
  338. response.Header.Del(key)
  339. }
  340. for key := range responseWriter.Header() {
  341. responseWriter.Header().Del(key)
  342. }
  343. for key, values := range response.Header {
  344. for _, value := range values {
  345. responseWriter.Header().Add(key, value)
  346. }
  347. }
  348. // Relay the response code and body
  349. responseWriter.WriteHeader(response.StatusCode)
  350. _, err = io.Copy(responseWriter, response.Body)
  351. if err != nil {
  352. NoticeAlert("%s", common.ContextError(err))
  353. forceClose(responseWriter)
  354. return
  355. }
  356. }
  357. // forceClose hijacks and closes persistent connections. This is used
  358. // to ensure local persistent connections into the HTTP proxy are closed
  359. // when ServeHTTP encounters an error.
  360. func forceClose(responseWriter http.ResponseWriter) {
  361. hijacker, _ := responseWriter.(http.Hijacker)
  362. conn, _, err := hijacker.Hijack()
  363. if err == nil {
  364. conn.Close()
  365. }
  366. }
  367. // From https://golang.org/src/pkg/net/http/httputil/reverseproxy.go:
  368. // Hop-by-hop headers. These are removed when sent to the backend.
  369. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  370. var hopHeaders = []string{
  371. "Connection",
  372. "Keep-Alive",
  373. "Proxy-Authenticate",
  374. "Proxy-Authorization",
  375. "Proxy-Connection", // see: http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/web-proxy-connection-header.html
  376. "Te", // canonicalized version of "TE"
  377. "Trailers",
  378. "Transfer-Encoding",
  379. "Upgrade",
  380. }
  381. // httpConnStateCallback is called by http.Server when the state of a local->proxy
  382. // connection changes. Open connections are tracked so that all local->proxy persistent
  383. // connections can be closed by HttpProxy.Close()
  384. // TODO: if the HttpProxy is decoupled from a single Tunnel instance and
  385. // instead uses the "current" Tunnel, it may not be necessary to close
  386. // local persistent connections when the tunnel reconnects.
  387. func (proxy *HttpProxy) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  388. switch connState {
  389. case http.StateNew:
  390. proxy.openConns.Add(conn)
  391. case http.StateActive, http.StateIdle:
  392. // No action
  393. case http.StateHijacked, http.StateClosed:
  394. proxy.openConns.Remove(conn)
  395. }
  396. }
  397. func (proxy *HttpProxy) serve() {
  398. defer proxy.listener.Close()
  399. defer proxy.serveWaitGroup.Done()
  400. httpServer := &http.Server{
  401. Handler: proxy,
  402. ConnState: proxy.httpConnStateCallback,
  403. }
  404. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  405. err := httpServer.Serve(proxy.listener)
  406. // Can't check for the exact error that Close() will cause in Accept(),
  407. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  408. // explicit stop signal to stop gracefully.
  409. select {
  410. case <-proxy.stopListeningBroadcast:
  411. default:
  412. if err != nil {
  413. proxy.tunneler.SignalComponentFailure()
  414. NoticeLocalProxyError(_HTTP_PROXY_TYPE, common.ContextError(err))
  415. }
  416. }
  417. NoticeInfo("HTTP proxy stopped")
  418. }
  419. //
  420. // Rewrite functions
  421. //
  422. // toAbsoluteURL takes a base URL and a relative URL and constructs an appropriate absolute URL.
  423. func toAbsoluteURL(baseURL *url.URL, relativeURLString string) string {
  424. relativeURL, err := url.Parse(relativeURLString)
  425. if err != nil {
  426. return ""
  427. }
  428. if relativeURL.IsAbs() {
  429. return relativeURL.String()
  430. }
  431. return baseURL.ResolveReference(relativeURL).String()
  432. }
  433. // proxifyURL takes an absolute URL and rewrites it to go through the local URL proxy.
  434. // urlProxy port is the local HTTP proxy port.
  435. // If rewriteParams is nil, then no rewriting will be done. Otherwise, it should contain
  436. // supported rewriting flags (like "m3u8").
  437. func proxifyURL(localHTTPProxyIP string, localHTTPProxyPort int, urlString string, rewriteParams []string) string {
  438. // 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
  439. // TODO: IPv6 support
  440. if localHTTPProxyIP == "0.0.0.0" {
  441. localHTTPProxyIP = "127.0.0.1"
  442. }
  443. opaqueFormat := "//%s:%d/tunneled/%s"
  444. if rewriteParams != nil {
  445. opaqueFormat = "//%s:%d/tunneled-rewrite/%s"
  446. }
  447. var proxifiedURL url.URL
  448. proxifiedURL.Scheme = "http"
  449. proxifiedURL.Opaque = fmt.Sprintf(opaqueFormat, localHTTPProxyIP, localHTTPProxyPort, url.QueryEscape(urlString))
  450. qp := proxifiedURL.Query()
  451. for _, rewrite := range rewriteParams {
  452. qp.Set(rewrite, "")
  453. }
  454. proxifiedURL.RawQuery = qp.Encode()
  455. return proxifiedURL.String()
  456. }
  457. // Rewrite the contents of the M3U8 file in body to be compatible with URL proxying.
  458. // If error is returned, response body may not be valid for reading.
  459. func rewriteM3U8(localHTTPProxyIP string, localHTTPProxyPort int, response *http.Response) error {
  460. // Check URL path extension
  461. extension := filepath.Ext(response.Request.URL.Path)
  462. var shouldHandle = (extension == ".m3u8")
  463. // If not .m3u8 then check content type
  464. if !shouldHandle {
  465. contentType := strings.ToLower(response.Header.Get("Content-Type"))
  466. shouldHandle = (contentType == "application/x-mpegurl" || contentType == "vnd.apple.mpegurl")
  467. }
  468. if !shouldHandle {
  469. return nil
  470. }
  471. var reader io.ReadCloser
  472. switch response.Header.Get("Content-Encoding") {
  473. case "gzip":
  474. var err error
  475. reader, err = gzip.NewReader(response.Body)
  476. if err != nil {
  477. return common.ContextError(err)
  478. }
  479. // Unset Content-Encoding.
  480. // There's is no point in deflating the decoded/rewritten content
  481. response.Header.Del("Content-Encoding")
  482. defer reader.Close()
  483. default:
  484. reader = response.Body
  485. }
  486. contentBodyBytes, err := ioutil.ReadAll(reader)
  487. response.Body.Close()
  488. if err != nil {
  489. return common.ContextError(err)
  490. }
  491. p, listType, err := m3u8.Decode(*bytes.NewBuffer(contentBodyBytes), true)
  492. if err != nil {
  493. // Don't pass this error up. Just don't change anything.
  494. response.Body = ioutil.NopCloser(bytes.NewReader(contentBodyBytes))
  495. response.Header.Set("Content-Length", strconv.FormatInt(int64(len(contentBodyBytes)), 10))
  496. return nil
  497. }
  498. var rewrittenBodyBytes []byte
  499. switch listType {
  500. case m3u8.MEDIA:
  501. mediapl := p.(*m3u8.MediaPlaylist)
  502. for _, segment := range mediapl.Segments {
  503. if segment == nil {
  504. break
  505. }
  506. if segment.URI != "" {
  507. segment.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, segment.URI), nil)
  508. }
  509. if segment.Key != nil && segment.Key.URI != "" {
  510. segment.Key.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, segment.Key.URI), nil)
  511. }
  512. if segment.Map != nil && segment.Map.URI != "" {
  513. segment.Map.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, segment.Map.URI), nil)
  514. }
  515. }
  516. rewrittenBodyBytes = []byte(mediapl.String())
  517. case m3u8.MASTER:
  518. masterpl := p.(*m3u8.MasterPlaylist)
  519. for _, variant := range masterpl.Variants {
  520. if variant == nil {
  521. break
  522. }
  523. if variant.URI != "" {
  524. variant.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, variant.URI), []string{"m3u8"})
  525. }
  526. for _, alternative := range variant.Alternatives {
  527. if alternative == nil {
  528. break
  529. }
  530. if alternative.URI != "" {
  531. alternative.URI = proxifyURL(localHTTPProxyIP, localHTTPProxyPort, toAbsoluteURL(response.Request.URL, alternative.URI), []string{"m3u8"})
  532. }
  533. }
  534. }
  535. rewrittenBodyBytes = []byte(masterpl.String())
  536. }
  537. var responseBodyBytes []byte
  538. if len(rewrittenBodyBytes) == 0 {
  539. responseBodyBytes = contentBodyBytes[:]
  540. } else {
  541. responseBodyBytes = rewrittenBodyBytes[:]
  542. // When rewriting the original URL so that it was URL-proxied, we lost the
  543. // file extension of it. That means we'd better make sure the Content-Type is set.
  544. response.Header.Set("Content-Type", "application/x-mpegurl")
  545. }
  546. response.Header.Set("Content-Length", strconv.FormatInt(int64(len(responseBodyBytes)), 10))
  547. response.Body = ioutil.NopCloser(bytes.NewReader(responseBodyBytes))
  548. return nil
  549. }