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