httpProxy.go 21 KB

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