httpProxy.go 21 KB

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