net.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. /*
  2. * Copyright (c) 2015, 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. "context"
  22. "crypto/tls"
  23. "crypto/x509"
  24. std_errors "errors"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "net"
  29. "net/http"
  30. "os"
  31. "strings"
  32. "sync"
  33. "sync/atomic"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  40. utls "github.com/Psiphon-Labs/utls"
  41. "golang.org/x/net/bpf"
  42. )
  43. // DialConfig contains parameters to determine the behavior
  44. // of a Psiphon dialer (TCPDial, UDPDial, MeekDial, etc.)
  45. type DialConfig struct {
  46. // DiagnosticID is the server ID to record in any diagnostics notices.
  47. DiagnosticID string
  48. // UpstreamProxyURL specifies a proxy to connect through.
  49. // E.g., "http://proxyhost:8080"
  50. // "socks5://user:password@proxyhost:1080"
  51. // "socks4a://proxyhost:1080"
  52. // "http://NTDOMAIN\NTUser:password@proxyhost:3375"
  53. //
  54. // Certain tunnel protocols require HTTP CONNECT support
  55. // when a HTTP proxy is specified. If CONNECT is not
  56. // supported, those protocols will not connect.
  57. //
  58. // UpstreamProxyURL is not used by UDPDial.
  59. UpstreamProxyURL string
  60. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  61. // added to all plaintext HTTP requests and requests made through an HTTP
  62. // upstream proxy when specified by UpstreamProxyURL.
  63. CustomHeaders http.Header
  64. // BPFProgramInstructions specifies a BPF program to attach to the dial
  65. // socket before connecting.
  66. BPFProgramInstructions []bpf.RawInstruction
  67. // DeviceBinder, when not nil, is applied when dialing UDP/TCP. See:
  68. // DeviceBinder doc.
  69. DeviceBinder DeviceBinder
  70. // IPv6Synthesizer, when not nil, is applied when dialing UDP/TCP. See:
  71. // IPv6Synthesizer doc.
  72. IPv6Synthesizer IPv6Synthesizer
  73. // ResolveIP is used to resolve destination domains. ResolveIP should
  74. // return either at least one IP address or an error.
  75. ResolveIP func(context.Context, string) ([]net.IP, error)
  76. // ResolvedIPCallback, when set, is called with the IP address that was
  77. // dialed. This is either the specified IP address in the dial address,
  78. // or the resolved IP address in the case where the dial address is a
  79. // domain name.
  80. // The callback may be invoked by a concurrent goroutine.
  81. ResolvedIPCallback func(string)
  82. // TrustedCACertificatesFilename specifies a file containing trusted
  83. // CA certs. See Config.TrustedCACertificatesFilename.
  84. TrustedCACertificatesFilename string
  85. // FragmentorConfig specifies whether to layer a fragmentor.Conn on top
  86. // of dialed TCP conns, and the fragmentation configuration to use.
  87. FragmentorConfig *fragmentor.Config
  88. // UpstreamProxyErrorCallback is called when a dial fails due to an upstream
  89. // proxy error. As the upstream proxy is user configured, the error message
  90. // may need to be relayed to the user.
  91. UpstreamProxyErrorCallback func(error)
  92. // CustomDialer overrides the dialer created by NewNetDialer/NewTCPDialer.
  93. // When CustomDialer is set, all other DialConfig parameters are ignored by
  94. // NewNetDialer/NewTCPDialer. Other DialConfig consumers may still reference
  95. // other DialConfig parameters; for example MeekConfig still uses
  96. // TrustedCACertificatesFilename.
  97. CustomDialer common.Dialer
  98. }
  99. // NetworkConnectivityChecker defines the interface to the external
  100. // HasNetworkConnectivity provider, which call into the host application to
  101. // check for network connectivity.
  102. type NetworkConnectivityChecker interface {
  103. // TODO: change to bool return value once gobind supports that type
  104. HasNetworkConnectivity() int
  105. }
  106. // DeviceBinder defines the interface to the external BindToDevice provider
  107. // which calls into the host application to bind sockets to specific devices.
  108. // This is used for VPN routing exclusion.
  109. // The string return value should report device information for diagnostics.
  110. type DeviceBinder interface {
  111. BindToDevice(fileDescriptor int) (string, error)
  112. }
  113. // DNSServerGetter defines the interface to the external GetDNSServers provider
  114. // which calls into the host application to discover the native network DNS
  115. // server settings.
  116. type DNSServerGetter interface {
  117. GetDNSServers() []string
  118. }
  119. // IPv6Synthesizer defines the interface to the external IPv6Synthesize
  120. // provider which calls into the host application to synthesize IPv6 addresses
  121. // from IPv4 ones. This is used to correctly lookup IPs on DNS64/NAT64
  122. // networks.
  123. type IPv6Synthesizer interface {
  124. IPv6Synthesize(IPv4Addr string) string
  125. }
  126. // HasIPv6RouteGetter defines the interface to the external HasIPv6Route
  127. // provider which calls into the host application to determine if the host
  128. // has an IPv6 route.
  129. type HasIPv6RouteGetter interface {
  130. // TODO: change to bool return value once gobind supports that type
  131. HasIPv6Route() int
  132. }
  133. // NetworkIDGetter defines the interface to the external GetNetworkID
  134. // provider, which returns an identifier for the host's current active
  135. // network.
  136. //
  137. // The identifier is a string that should indicate the network type and
  138. // identity; for example "WIFI-<BSSID>" or "MOBILE-<MCC/MNC>". As this network
  139. // ID is personally identifying, it is only used locally in the client to
  140. // determine network context and is not sent to the Psiphon server. The
  141. // identifer will be logged in diagnostics messages; in this case only the
  142. // substring before the first "-" is logged, so all PII must appear after the
  143. // first "-".
  144. //
  145. // NetworkIDGetter.GetNetworkID should always return an identifier value, as
  146. // logic that uses GetNetworkID, including tactics, is intended to proceed
  147. // regardless of whether an accurate network identifier can be obtained. By
  148. // convention, the provider should return "UNKNOWN" when an accurate network
  149. // identifier cannot be obtained. Best-effort is acceptable: e.g., return just
  150. // "WIFI" when only the type of the network but no details can be determined.
  151. type NetworkIDGetter interface {
  152. GetNetworkID() string
  153. }
  154. // RefractionNetworkingDialer implements psiphon/common/refraction.Dialer.
  155. type RefractionNetworkingDialer struct {
  156. config *DialConfig
  157. }
  158. // NewRefractionNetworkingDialer creates a new RefractionNetworkingDialer.
  159. func NewRefractionNetworkingDialer(config *DialConfig) *RefractionNetworkingDialer {
  160. return &RefractionNetworkingDialer{
  161. config: config,
  162. }
  163. }
  164. func (d *RefractionNetworkingDialer) DialContext(
  165. ctx context.Context,
  166. network string,
  167. laddr string,
  168. raddr string) (net.Conn, error) {
  169. switch network {
  170. case "tcp", "tcp4", "tcp6":
  171. if laddr != "" {
  172. return nil, errors.TraceNew("unexpected laddr for tcp dial")
  173. }
  174. conn, err := DialTCP(ctx, raddr, d.config)
  175. if err != nil {
  176. return nil, errors.Trace(err)
  177. }
  178. return conn, nil
  179. case "udp", "udp4", "udp6":
  180. udpConn, _, err := NewUDPConn(ctx, network, true, laddr, raddr, d.config)
  181. if err != nil {
  182. return nil, errors.Trace(err)
  183. }
  184. // Ensure blocked packet writes eventually timeout.
  185. conn := &common.WriteTimeoutUDPConn{
  186. UDPConn: udpConn,
  187. }
  188. return conn, nil
  189. default:
  190. return nil, errors.Tracef("unsupported network: %s", network)
  191. }
  192. }
  193. // LocalProxyRelay sends to remoteConn bytes received from localConn,
  194. // and sends to localConn bytes received from remoteConn.
  195. //
  196. // LocalProxyRelay must close localConn in order to interrupt blocking
  197. // I/O calls when the upstream port forward is closed. remoteConn is
  198. // also closed before returning.
  199. func LocalProxyRelay(config *Config, proxyType string, localConn, remoteConn net.Conn) {
  200. closing := int32(0)
  201. copyWaitGroup := new(sync.WaitGroup)
  202. copyWaitGroup.Add(1)
  203. go func() {
  204. defer copyWaitGroup.Done()
  205. _, err := RelayCopyBuffer(config, localConn, remoteConn)
  206. if err != nil && atomic.LoadInt32(&closing) != 1 {
  207. NoticeLocalProxyError(proxyType, errors.TraceMsg(err, "Relay failed"))
  208. }
  209. // When the server closes a port forward, ex. due to idle timeout,
  210. // remoteConn.Read will return EOF, which causes the downstream io.Copy to
  211. // return (with a nil error). To ensure the downstream local proxy
  212. // connection also closes at this point, we interrupt the blocking upstream
  213. // io.Copy by closing localConn.
  214. atomic.StoreInt32(&closing, 1)
  215. localConn.Close()
  216. }()
  217. _, err := RelayCopyBuffer(config, remoteConn, localConn)
  218. if err != nil && atomic.LoadInt32(&closing) != 1 {
  219. NoticeLocalProxyError(proxyType, errors.TraceMsg(err, "Relay failed"))
  220. }
  221. // When a local proxy peer connection closes, localConn.Read will return EOF.
  222. // As above, close the other end of the relay to ensure immediate shutdown,
  223. // as no more data can be relayed.
  224. atomic.StoreInt32(&closing, 1)
  225. remoteConn.Close()
  226. copyWaitGroup.Wait()
  227. }
  228. // RelayCopyBuffer performs an io.Copy, optionally using a smaller buffer when
  229. // config.LimitRelayBufferSizes is set.
  230. func RelayCopyBuffer(config *Config, dst io.Writer, src io.Reader) (int64, error) {
  231. // By default, io.CopyBuffer will allocate a 32K buffer when a nil buffer
  232. // is passed in. When configured, make and specify a smaller buffer. But
  233. // only if src doesn't implement WriterTo and dst doesn't implement
  234. // ReaderFrom, as in those cases io.CopyBuffer entirely avoids a buffer
  235. // allocation.
  236. var buffer []byte
  237. if config.LimitRelayBufferSizes {
  238. _, isWT := src.(io.WriterTo)
  239. _, isRF := dst.(io.ReaderFrom)
  240. if !isWT && !isRF {
  241. buffer = make([]byte, 4096)
  242. }
  243. }
  244. // Do not wrap any I/O errors
  245. return io.CopyBuffer(dst, src, buffer)
  246. }
  247. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  248. // periodically check for network connectivity. It returns true if no
  249. // NetworkConnectivityChecker is provided (waiting is disabled) or when
  250. // NetworkConnectivityChecker.HasNetworkConnectivity() indicates
  251. // connectivity. It waits and polls the checker once a second. When
  252. // additionalConditionChecker is not nil, it must also return true for
  253. // WaitForNetworkConnectivity to return true. When the context is done, false
  254. // is returned immediately.
  255. func WaitForNetworkConnectivity(
  256. ctx context.Context,
  257. connectivityChecker NetworkConnectivityChecker,
  258. additionalConditionChecker func() bool) bool {
  259. if (connectivityChecker == nil || connectivityChecker.HasNetworkConnectivity() == 1) &&
  260. (additionalConditionChecker == nil || additionalConditionChecker()) {
  261. return true
  262. }
  263. NoticeInfo("waiting for network connectivity")
  264. ticker := time.NewTicker(1 * time.Second)
  265. defer ticker.Stop()
  266. for {
  267. if (connectivityChecker == nil || connectivityChecker.HasNetworkConnectivity() == 1) &&
  268. (additionalConditionChecker == nil || additionalConditionChecker()) {
  269. return true
  270. }
  271. select {
  272. case <-ticker.C:
  273. // Check HasNetworkConnectivity again
  274. case <-ctx.Done():
  275. return false
  276. }
  277. }
  278. }
  279. // New Resolver creates a new resolver using the specified config.
  280. // useBindToDevice indicates whether to apply config.BindToDevice, when it
  281. // exists; set useBindToDevice to false when the resolve doesn't need to be
  282. // excluded from any VPN routing.
  283. func NewResolver(config *Config, useBindToDevice bool) *resolver.Resolver {
  284. p := config.GetParameters().Get()
  285. networkConfig := &resolver.NetworkConfig{
  286. LogWarning: func(err error) { NoticeWarning("ResolveIP: %v", err) },
  287. LogHostnames: config.EmitDiagnosticNetworkParameters,
  288. CacheExtensionInitialTTL: p.Duration(parameters.DNSResolverCacheExtensionInitialTTL),
  289. CacheExtensionVerifiedTTL: p.Duration(parameters.DNSResolverCacheExtensionVerifiedTTL),
  290. }
  291. if config.DNSServerGetter != nil {
  292. networkConfig.GetDNSServers = config.DNSServerGetter.GetDNSServers
  293. }
  294. if useBindToDevice && config.DeviceBinder != nil {
  295. networkConfig.BindToDevice = config.DeviceBinder.BindToDevice
  296. networkConfig.AllowDefaultResolverWithBindToDevice =
  297. config.AllowDefaultDNSResolverWithBindToDevice
  298. }
  299. if config.IPv6Synthesizer != nil {
  300. networkConfig.IPv6Synthesize = config.IPv6Synthesizer.IPv6Synthesize
  301. }
  302. if config.HasIPv6RouteGetter != nil {
  303. networkConfig.HasIPv6Route = func() bool {
  304. return config.HasIPv6RouteGetter.HasIPv6Route() == 1
  305. }
  306. }
  307. return resolver.NewResolver(networkConfig, config.GetNetworkID())
  308. }
  309. // UntunneledResolveIP is used to resolve domains for untunneled dials,
  310. // including remote server list and upgrade downloads.
  311. func UntunneledResolveIP(
  312. ctx context.Context,
  313. config *Config,
  314. resolver *resolver.Resolver,
  315. hostname string,
  316. frontingProviderID string) ([]net.IP, error) {
  317. // Limitations: for untunneled resolves, there is currently no resolve
  318. // parameter replay.
  319. params, err := resolver.MakeResolveParameters(
  320. config.GetParameters().Get(), frontingProviderID, hostname)
  321. if err != nil {
  322. return nil, errors.Trace(err)
  323. }
  324. IPs, err := resolver.ResolveIP(
  325. ctx,
  326. config.GetNetworkID(),
  327. params,
  328. hostname)
  329. if err != nil {
  330. return nil, errors.Trace(err)
  331. }
  332. return IPs, nil
  333. }
  334. // makeFrontedHTTPClient returns a net/http.Client which is
  335. // configured to use domain fronting and custom dialing features -- including
  336. // BindToDevice, etc. One or more fronting specs must be provided, i.e.
  337. // len(frontingSpecs) must be greater than 0. A function is returned which,
  338. // if non-nil, can be called after each request made with the net/http.Client
  339. // completes to retrieve the set of API parameter values applied to the request.
  340. //
  341. // The context is applied to underlying TCP dials. The caller is responsible
  342. // for applying the context to requests made with the returned http.Client.
  343. //
  344. // payloadSecure must only be set if all HTTP plaintext payloads sent through
  345. // the returned net/http.Client will be wrapped in their own transport security
  346. // layer, which permits skipping of server certificate verification.
  347. func makeFrontedHTTPClient(
  348. config *Config,
  349. tunnel *Tunnel,
  350. frontingSpecs parameters.FrontingSpecs,
  351. selectedFrontingProviderID func(string),
  352. useDeviceBinder,
  353. skipVerify,
  354. disableSystemRootCAs,
  355. payloadSecure bool) (*http.Client, func() common.APIParameters, error) {
  356. frontedHTTPClient, err := newFrontedHTTPClientInstance(
  357. config, tunnel, frontingSpecs, selectedFrontingProviderID,
  358. useDeviceBinder, skipVerify, disableSystemRootCAs, payloadSecure)
  359. if err != nil {
  360. return nil, nil, errors.Trace(err)
  361. }
  362. getParams := func() common.APIParameters {
  363. return common.APIParameters(frontedHTTPClient.frontedHTTPDialParameters.GetMetrics())
  364. }
  365. return &http.Client{
  366. Transport: common.NewHTTPRoundTripper(frontedHTTPClient.RoundTrip),
  367. }, getParams, nil
  368. }
  369. // meekHTTPResponseReadCloser wraps an http.Response.Body received over a
  370. // MeekConn in MeekModePlaintextRoundTrip and exposes an io.ReadCloser. Close
  371. // closes the meek conn and response body.
  372. type meekHTTPResponseReadCloser struct {
  373. conn *MeekConn
  374. responseBody io.ReadCloser
  375. }
  376. // newMeekHTTPResponseReadCloser creates a meekHTTPResponseReadCloser.
  377. func newMeekHTTPResponseReadCloser(meekConn *MeekConn, responseBody io.ReadCloser) *meekHTTPResponseReadCloser {
  378. return &meekHTTPResponseReadCloser{
  379. conn: meekConn,
  380. responseBody: responseBody,
  381. }
  382. }
  383. // Read implements the io.Reader interface.
  384. func (meek *meekHTTPResponseReadCloser) Read(p []byte) (n int, err error) {
  385. return meek.responseBody.Read(p)
  386. }
  387. // Read implements the io.Closer interface.
  388. func (meek *meekHTTPResponseReadCloser) Close() error {
  389. err := meek.responseBody.Close()
  390. _ = meek.conn.Close()
  391. return err
  392. }
  393. // MakeUntunneledHTTPClient returns a net/http.Client which is configured to
  394. // use custom dialing features -- including BindToDevice, etc. A function is
  395. // returned which, if non-nil, can be called after each request made with the
  396. // net/http.Client completes to retrieve the set of API parameter values
  397. // applied to the request.
  398. //
  399. // The context is applied to underlying TCP dials. The caller is responsible
  400. // for applying the context to requests made with the returned http.Client.
  401. func MakeUntunneledHTTPClient(
  402. ctx context.Context,
  403. config *Config,
  404. untunneledDialConfig *DialConfig,
  405. skipVerify bool,
  406. disableSystemRootCAs bool,
  407. payloadSecure bool,
  408. frontingSpecs parameters.FrontingSpecs,
  409. frontingUseDeviceBinder bool,
  410. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  411. if untunneledDialConfig != nil && len(frontingSpecs) != 0 ||
  412. untunneledDialConfig == nil && len(frontingSpecs) == 0 {
  413. return nil, nil, errors.TraceNew("expected either dial configuration or fronting specs")
  414. }
  415. if len(frontingSpecs) > 0 {
  416. // Ignore skipVerify because it only applies when there are no
  417. // fronting specs.
  418. httpClient, getParams, err := makeFrontedHTTPClient(
  419. config,
  420. nil,
  421. frontingSpecs,
  422. selectedFrontingProviderID,
  423. frontingUseDeviceBinder,
  424. false,
  425. disableSystemRootCAs,
  426. payloadSecure)
  427. if err != nil {
  428. return nil, nil, errors.Trace(err)
  429. }
  430. return httpClient, getParams, nil
  431. }
  432. dialer := NewTCPDialer(untunneledDialConfig)
  433. tlsConfig := &CustomTLSConfig{
  434. Parameters: config.GetParameters(),
  435. Dial: dialer,
  436. UseDialAddrSNI: true,
  437. SNIServerName: "",
  438. SkipVerify: skipVerify,
  439. DisableSystemRootCAs: disableSystemRootCAs,
  440. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  441. ClientSessionCache: utls.NewLRUClientSessionCache(0),
  442. }
  443. tlsDialer := NewCustomTLSDialer(tlsConfig)
  444. transport := &http.Transport{
  445. Dial: func(network, addr string) (net.Conn, error) {
  446. return dialer(ctx, network, addr)
  447. },
  448. DialTLS: func(network, addr string) (net.Conn, error) {
  449. return tlsDialer(ctx, network, addr)
  450. },
  451. }
  452. httpClient := &http.Client{
  453. Transport: transport,
  454. }
  455. return httpClient, nil, nil
  456. }
  457. // MakeTunneledHTTPClient returns a net/http.Client which is
  458. // configured to use custom dialing features including tunneled
  459. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  460. // This http.Client uses stock TLS for HTTPS.
  461. func MakeTunneledHTTPClient(
  462. ctx context.Context,
  463. config *Config,
  464. tunnel *Tunnel,
  465. skipVerify,
  466. disableSystemRootCAs,
  467. payloadSecure bool,
  468. frontingSpecs parameters.FrontingSpecs,
  469. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  470. // Note: there is no dial context since SSH port forward dials cannot
  471. // be interrupted directly. Closing the tunnel will interrupt the dials.
  472. if len(frontingSpecs) > 0 {
  473. // Ignore skipVerify because it only applies when there are no
  474. // fronting specs.
  475. httpClient, getParams, err := makeFrontedHTTPClient(
  476. config,
  477. tunnel,
  478. frontingSpecs,
  479. selectedFrontingProviderID,
  480. false,
  481. false,
  482. disableSystemRootCAs,
  483. payloadSecure)
  484. if err != nil {
  485. return nil, nil, errors.Trace(err)
  486. }
  487. return httpClient, getParams, nil
  488. }
  489. tunneledDialer := func(_, addr string) (net.Conn, error) {
  490. // Set alwaysTunneled to ensure the http.Client traffic is always tunneled,
  491. // even when split tunnel mode is enabled.
  492. conn, _, err := tunnel.DialTCPChannel(addr, true, nil)
  493. return conn, errors.Trace(err)
  494. }
  495. transport := &http.Transport{
  496. Dial: tunneledDialer,
  497. }
  498. if skipVerify {
  499. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  500. } else if config.TrustedCACertificatesFilename != "" {
  501. rootCAs := x509.NewCertPool()
  502. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  503. if err != nil {
  504. return nil, nil, errors.Trace(err)
  505. }
  506. rootCAs.AppendCertsFromPEM(certData)
  507. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  508. }
  509. return &http.Client{
  510. Transport: transport,
  511. }, nil, nil
  512. }
  513. // MakeDownloadHTTPClient is a helper that sets up a http.Client for use either
  514. // untunneled or through a tunnel. True is returned if the http.Client is setup
  515. // for use through a tunnel; otherwise it is setup for untunneled use. A
  516. // function is returned which, if non-nil, can be called after each request
  517. // made with the http.Client completes to retrieve the set of API
  518. // parameter values applied to the request.
  519. func MakeDownloadHTTPClient(
  520. ctx context.Context,
  521. config *Config,
  522. tunnel *Tunnel,
  523. untunneledDialConfig *DialConfig,
  524. skipVerify,
  525. disableSystemRootCAs,
  526. payloadSecure bool,
  527. frontingSpecs parameters.FrontingSpecs,
  528. frontingUseDeviceBinder bool,
  529. selectedFrontingProviderID func(string)) (*http.Client, bool, func() common.APIParameters, error) {
  530. var httpClient *http.Client
  531. var getParams func() common.APIParameters
  532. var err error
  533. tunneled := tunnel != nil
  534. if tunneled {
  535. httpClient, getParams, err = MakeTunneledHTTPClient(
  536. ctx,
  537. config,
  538. tunnel,
  539. skipVerify || disableSystemRootCAs,
  540. disableSystemRootCAs,
  541. payloadSecure,
  542. frontingSpecs,
  543. selectedFrontingProviderID)
  544. if err != nil {
  545. return nil, false, nil, errors.Trace(err)
  546. }
  547. } else {
  548. var dialConfig *DialConfig
  549. if len(frontingSpecs) == 0 {
  550. // Must only set DialConfig if there are no fronting specs.
  551. dialConfig = untunneledDialConfig
  552. }
  553. httpClient, getParams, err = MakeUntunneledHTTPClient(
  554. ctx,
  555. config,
  556. dialConfig,
  557. skipVerify,
  558. disableSystemRootCAs,
  559. payloadSecure,
  560. frontingSpecs,
  561. frontingUseDeviceBinder,
  562. selectedFrontingProviderID)
  563. if err != nil {
  564. return nil, false, nil, errors.Trace(err)
  565. }
  566. }
  567. return httpClient, tunneled, getParams, nil
  568. }
  569. // ResumeDownload is a reusable helper that downloads requestUrl via the
  570. // httpClient, storing the result in downloadFilename when the download is
  571. // complete. Intermediate, partial downloads state is stored in
  572. // downloadFilename.part and downloadFilename.part.etag.
  573. // Any existing downloadFilename file will be overwritten.
  574. //
  575. // In the case where the remote object has changed while a partial download
  576. // is to be resumed, the partial state is reset and resumeDownload fails.
  577. // The caller must restart the download.
  578. //
  579. // When ifNoneMatchETag is specified, no download is made if the remote
  580. // object has the same ETag. ifNoneMatchETag has an effect only when no
  581. // partial download is in progress.
  582. func ResumeDownload(
  583. ctx context.Context,
  584. httpClient *http.Client,
  585. downloadURL string,
  586. userAgent string,
  587. downloadFilename string,
  588. ifNoneMatchETag string) (int64, string, error) {
  589. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  590. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  591. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  592. if err != nil {
  593. return 0, "", errors.Trace(err)
  594. }
  595. defer file.Close()
  596. fileInfo, err := file.Stat()
  597. if err != nil {
  598. return 0, "", errors.Trace(err)
  599. }
  600. // A partial download should have an ETag which is to be sent with the
  601. // Range request to ensure that the source object is the same as the
  602. // one that is partially downloaded.
  603. var partialETag []byte
  604. if fileInfo.Size() > 0 {
  605. partialETag, err = ioutil.ReadFile(partialETagFilename)
  606. // When the ETag can't be loaded, delete the partial download. To keep the
  607. // code simple, there is no immediate, inline retry here, on the assumption
  608. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  609. // again.
  610. if err != nil {
  611. // On Windows, file must be closed before it can be deleted
  612. file.Close()
  613. tempErr := os.Remove(partialFilename)
  614. if tempErr != nil && !os.IsNotExist(tempErr) {
  615. NoticeWarning("reset partial download failed: %s", tempErr)
  616. }
  617. tempErr = os.Remove(partialETagFilename)
  618. if tempErr != nil && !os.IsNotExist(tempErr) {
  619. NoticeWarning("reset partial download ETag failed: %s", tempErr)
  620. }
  621. return 0, "", errors.Tracef(
  622. "failed to load partial download ETag: %s", err)
  623. }
  624. }
  625. request, err := http.NewRequest("GET", downloadURL, nil)
  626. if err != nil {
  627. return 0, "", errors.Trace(err)
  628. }
  629. request = request.WithContext(ctx)
  630. request.Header.Set("User-Agent", userAgent)
  631. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  632. if partialETag != nil {
  633. // Note: not using If-Range, since not all host servers support it.
  634. // Using If-Match means we need to check for status code 412 and reset
  635. // when the ETag has changed since the last partial download.
  636. request.Header.Add("If-Match", string(partialETag))
  637. } else if ifNoneMatchETag != "" {
  638. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  639. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  640. // So for downloaders that store an ETag and wish to use that to prevent
  641. // redundant downloads, that ETag is sent as If-None-Match in the case
  642. // where a partial download is not in progress. When a partial download
  643. // is in progress, the partial ETag is sent as If-Match: either that's
  644. // a version that was never fully received, or it's no longer current in
  645. // which case the response will be StatusPreconditionFailed, the partial
  646. // download will be discarded, and then the next retry will use
  647. // If-None-Match.
  648. // Note: in this case, fileInfo.Size() == 0
  649. request.Header.Add("If-None-Match", ifNoneMatchETag)
  650. }
  651. response, err := httpClient.Do(request)
  652. // The resumeable download may ask for bytes past the resource range
  653. // since it doesn't store the "completed download" state. In this case,
  654. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  655. // receive 412 on ETag mismatch.
  656. if err == nil &&
  657. (response.StatusCode != http.StatusPartialContent &&
  658. // Certain http servers return 200 OK where we expect 206, so accept that.
  659. response.StatusCode != http.StatusOK &&
  660. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  661. response.StatusCode != http.StatusPreconditionFailed &&
  662. response.StatusCode != http.StatusNotModified) {
  663. response.Body.Close()
  664. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  665. }
  666. if err != nil {
  667. // Redact URL from "net/http" error message.
  668. if !GetEmitNetworkParameters() {
  669. errStr := err.Error()
  670. err = std_errors.New(strings.Replace(errStr, downloadURL, "[redacted]", -1))
  671. }
  672. return 0, "", errors.Trace(err)
  673. }
  674. defer response.Body.Close()
  675. responseETag := response.Header.Get("ETag")
  676. if response.StatusCode == http.StatusPreconditionFailed {
  677. // When the ETag no longer matches, delete the partial download. As above,
  678. // simply failing and relying on the caller's retry schedule.
  679. os.Remove(partialFilename)
  680. os.Remove(partialETagFilename)
  681. return 0, "", errors.TraceNew("partial download ETag mismatch")
  682. } else if response.StatusCode == http.StatusNotModified {
  683. // This status code is possible in the "If-None-Match" case. Don't leave
  684. // any partial download in progress. Caller should check that responseETag
  685. // matches ifNoneMatchETag.
  686. os.Remove(partialFilename)
  687. os.Remove(partialETagFilename)
  688. return 0, responseETag, nil
  689. }
  690. // Not making failure to write ETag file fatal, in case the entire download
  691. // succeeds in this one request.
  692. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  693. // A partial download occurs when this copy is interrupted. The io.Copy
  694. // will fail, leaving a partial download in place (.part and .part.etag).
  695. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  696. // From this point, n bytes are indicated as downloaded, even if there is
  697. // an error; the caller may use this to report partial download progress.
  698. if err != nil {
  699. return n, "", errors.Trace(err)
  700. }
  701. // Ensure the file is flushed to disk. The deferred close
  702. // will be a noop when this succeeds.
  703. err = file.Close()
  704. if err != nil {
  705. return n, "", errors.Trace(err)
  706. }
  707. // Remove if exists, to enable rename
  708. os.Remove(downloadFilename)
  709. err = os.Rename(partialFilename, downloadFilename)
  710. if err != nil {
  711. return n, "", errors.Trace(err)
  712. }
  713. os.Remove(partialETagFilename)
  714. return n, responseETag, nil
  715. }