net.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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. return true
  261. }
  262. NoticeInfo("waiting for network connectivity")
  263. ticker := time.NewTicker(1 * time.Second)
  264. defer ticker.Stop()
  265. for {
  266. if connectivityChecker.HasNetworkConnectivity() == 1 &&
  267. (additionalConditionChecker == nil || additionalConditionChecker()) {
  268. return true
  269. }
  270. select {
  271. case <-ticker.C:
  272. // Check HasNetworkConnectivity again
  273. case <-ctx.Done():
  274. return false
  275. }
  276. }
  277. }
  278. // New Resolver creates a new resolver using the specified config.
  279. // useBindToDevice indicates whether to apply config.BindToDevice, when it
  280. // exists; set useBindToDevice to false when the resolve doesn't need to be
  281. // excluded from any VPN routing.
  282. func NewResolver(config *Config, useBindToDevice bool) *resolver.Resolver {
  283. p := config.GetParameters().Get()
  284. networkConfig := &resolver.NetworkConfig{
  285. LogWarning: func(err error) { NoticeWarning("ResolveIP: %v", err) },
  286. LogHostnames: config.EmitDiagnosticNetworkParameters,
  287. CacheExtensionInitialTTL: p.Duration(parameters.DNSResolverCacheExtensionInitialTTL),
  288. CacheExtensionVerifiedTTL: p.Duration(parameters.DNSResolverCacheExtensionVerifiedTTL),
  289. }
  290. if config.DNSServerGetter != nil {
  291. networkConfig.GetDNSServers = config.DNSServerGetter.GetDNSServers
  292. }
  293. if useBindToDevice && config.DeviceBinder != nil {
  294. networkConfig.BindToDevice = config.DeviceBinder.BindToDevice
  295. networkConfig.AllowDefaultResolverWithBindToDevice =
  296. config.AllowDefaultDNSResolverWithBindToDevice
  297. }
  298. if config.IPv6Synthesizer != nil {
  299. networkConfig.IPv6Synthesize = config.IPv6Synthesizer.IPv6Synthesize
  300. }
  301. if config.HasIPv6RouteGetter != nil {
  302. networkConfig.HasIPv6Route = func() bool {
  303. return config.HasIPv6RouteGetter.HasIPv6Route() == 1
  304. }
  305. }
  306. return resolver.NewResolver(networkConfig, config.GetNetworkID())
  307. }
  308. // UntunneledResolveIP is used to resolve domains for untunneled dials,
  309. // including remote server list and upgrade downloads.
  310. func UntunneledResolveIP(
  311. ctx context.Context,
  312. config *Config,
  313. resolver *resolver.Resolver,
  314. hostname string,
  315. frontingProviderID string) ([]net.IP, error) {
  316. // Limitations: for untunneled resolves, there is currently no resolve
  317. // parameter replay.
  318. params, err := resolver.MakeResolveParameters(
  319. config.GetParameters().Get(), frontingProviderID, hostname)
  320. if err != nil {
  321. return nil, errors.Trace(err)
  322. }
  323. IPs, err := resolver.ResolveIP(
  324. ctx,
  325. config.GetNetworkID(),
  326. params,
  327. hostname)
  328. if err != nil {
  329. return nil, errors.Trace(err)
  330. }
  331. return IPs, nil
  332. }
  333. // makeFrontedHTTPClient returns a net/http.Client which is
  334. // configured to use domain fronting and custom dialing features -- including
  335. // BindToDevice, etc. One or more fronting specs must be provided, i.e.
  336. // len(frontingSpecs) must be greater than 0. A function is returned which,
  337. // if non-nil, can be called after each request made with the net/http.Client
  338. // completes to retrieve the set of API parameter values applied to the request.
  339. //
  340. // The context is applied to underlying TCP dials. The caller is responsible
  341. // for applying the context to requests made with the returned http.Client.
  342. //
  343. // payloadSecure must only be set if all HTTP plaintext payloads sent through
  344. // the returned net/http.Client will be wrapped in their own transport security
  345. // layer, which permits skipping of server certificate verification.
  346. func makeFrontedHTTPClient(
  347. config *Config,
  348. tunnel *Tunnel,
  349. frontingSpecs parameters.FrontingSpecs,
  350. selectedFrontingProviderID func(string),
  351. useDeviceBinder,
  352. skipVerify,
  353. disableSystemRootCAs,
  354. payloadSecure bool) (*http.Client, func() common.APIParameters, error) {
  355. frontedHTTPClient, err := newFrontedHTTPClientInstance(
  356. config, tunnel, frontingSpecs, selectedFrontingProviderID,
  357. useDeviceBinder, skipVerify, disableSystemRootCAs, payloadSecure)
  358. if err != nil {
  359. return nil, nil, errors.Trace(err)
  360. }
  361. getParams := func() common.APIParameters {
  362. return common.APIParameters(frontedHTTPClient.frontedHTTPDialParameters.GetMetrics())
  363. }
  364. return &http.Client{
  365. Transport: common.NewHTTPRoundTripper(frontedHTTPClient.RoundTrip),
  366. }, getParams, nil
  367. }
  368. // meekHTTPResponseReadCloser wraps an http.Response.Body received over a
  369. // MeekConn in MeekModePlaintextRoundTrip and exposes an io.ReadCloser. Close
  370. // closes the meek conn and response body.
  371. type meekHTTPResponseReadCloser struct {
  372. conn *MeekConn
  373. responseBody io.ReadCloser
  374. }
  375. // newMeekHTTPResponseReadCloser creates a meekHTTPResponseReadCloser.
  376. func newMeekHTTPResponseReadCloser(meekConn *MeekConn, responseBody io.ReadCloser) *meekHTTPResponseReadCloser {
  377. return &meekHTTPResponseReadCloser{
  378. conn: meekConn,
  379. responseBody: responseBody,
  380. }
  381. }
  382. // Read implements the io.Reader interface.
  383. func (meek *meekHTTPResponseReadCloser) Read(p []byte) (n int, err error) {
  384. return meek.responseBody.Read(p)
  385. }
  386. // Read implements the io.Closer interface.
  387. func (meek *meekHTTPResponseReadCloser) Close() error {
  388. err := meek.responseBody.Close()
  389. _ = meek.conn.Close()
  390. return err
  391. }
  392. // MakeUntunneledHTTPClient returns a net/http.Client which is configured to
  393. // use custom dialing features -- including BindToDevice, etc. A function is
  394. // returned which, if non-nil, can be called after each request made with the
  395. // net/http.Client completes to retrieve the set of API parameter values
  396. // applied to the request.
  397. //
  398. // The context is applied to underlying TCP dials. The caller is responsible
  399. // for applying the context to requests made with the returned http.Client.
  400. func MakeUntunneledHTTPClient(
  401. ctx context.Context,
  402. config *Config,
  403. untunneledDialConfig *DialConfig,
  404. skipVerify bool,
  405. disableSystemRootCAs bool,
  406. payloadSecure bool,
  407. frontingSpecs parameters.FrontingSpecs,
  408. frontingUseDeviceBinder bool,
  409. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  410. if untunneledDialConfig != nil && len(frontingSpecs) != 0 ||
  411. untunneledDialConfig == nil && len(frontingSpecs) == 0 {
  412. return nil, nil, errors.TraceNew("expected either dial configuration or fronting specs")
  413. }
  414. if len(frontingSpecs) > 0 {
  415. // Ignore skipVerify because it only applies when there are no
  416. // fronting specs.
  417. httpClient, getParams, err := makeFrontedHTTPClient(
  418. config,
  419. nil,
  420. frontingSpecs,
  421. selectedFrontingProviderID,
  422. frontingUseDeviceBinder,
  423. false,
  424. disableSystemRootCAs,
  425. payloadSecure)
  426. if err != nil {
  427. return nil, nil, errors.Trace(err)
  428. }
  429. return httpClient, getParams, nil
  430. }
  431. dialer := NewTCPDialer(untunneledDialConfig)
  432. tlsConfig := &CustomTLSConfig{
  433. Parameters: config.GetParameters(),
  434. Dial: dialer,
  435. UseDialAddrSNI: true,
  436. SNIServerName: "",
  437. SkipVerify: skipVerify,
  438. DisableSystemRootCAs: disableSystemRootCAs,
  439. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  440. ClientSessionCache: utls.NewLRUClientSessionCache(0),
  441. }
  442. tlsDialer := NewCustomTLSDialer(tlsConfig)
  443. transport := &http.Transport{
  444. Dial: func(network, addr string) (net.Conn, error) {
  445. return dialer(ctx, network, addr)
  446. },
  447. DialTLS: func(network, addr string) (net.Conn, error) {
  448. return tlsDialer(ctx, network, addr)
  449. },
  450. }
  451. httpClient := &http.Client{
  452. Transport: transport,
  453. }
  454. return httpClient, nil, nil
  455. }
  456. // MakeTunneledHTTPClient returns a net/http.Client which is
  457. // configured to use custom dialing features including tunneled
  458. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  459. // This http.Client uses stock TLS for HTTPS.
  460. func MakeTunneledHTTPClient(
  461. ctx context.Context,
  462. config *Config,
  463. tunnel *Tunnel,
  464. skipVerify,
  465. disableSystemRootCAs,
  466. payloadSecure bool,
  467. frontingSpecs parameters.FrontingSpecs,
  468. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  469. // Note: there is no dial context since SSH port forward dials cannot
  470. // be interrupted directly. Closing the tunnel will interrupt the dials.
  471. if len(frontingSpecs) > 0 {
  472. // Ignore skipVerify because it only applies when there are no
  473. // fronting specs.
  474. httpClient, getParams, err := makeFrontedHTTPClient(
  475. config,
  476. tunnel,
  477. frontingSpecs,
  478. selectedFrontingProviderID,
  479. false,
  480. false,
  481. disableSystemRootCAs,
  482. payloadSecure)
  483. if err != nil {
  484. return nil, nil, errors.Trace(err)
  485. }
  486. return httpClient, getParams, nil
  487. }
  488. tunneledDialer := func(_, addr string) (net.Conn, error) {
  489. // Set alwaysTunneled to ensure the http.Client traffic is always tunneled,
  490. // even when split tunnel mode is enabled.
  491. conn, _, err := tunnel.DialTCPChannel(addr, true, nil)
  492. return conn, errors.Trace(err)
  493. }
  494. transport := &http.Transport{
  495. Dial: tunneledDialer,
  496. }
  497. if skipVerify {
  498. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  499. } else if config.TrustedCACertificatesFilename != "" {
  500. rootCAs := x509.NewCertPool()
  501. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  502. if err != nil {
  503. return nil, nil, errors.Trace(err)
  504. }
  505. rootCAs.AppendCertsFromPEM(certData)
  506. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  507. }
  508. return &http.Client{
  509. Transport: transport,
  510. }, nil, nil
  511. }
  512. // MakeDownloadHTTPClient is a helper that sets up a http.Client for use either
  513. // untunneled or through a tunnel. True is returned if the http.Client is setup
  514. // for use through a tunnel; otherwise it is setup for untunneled use. A
  515. // function is returned which, if non-nil, can be called after each request
  516. // made with the http.Client completes to retrieve the set of API
  517. // parameter values applied to the request.
  518. func MakeDownloadHTTPClient(
  519. ctx context.Context,
  520. config *Config,
  521. tunnel *Tunnel,
  522. untunneledDialConfig *DialConfig,
  523. skipVerify,
  524. disableSystemRootCAs,
  525. payloadSecure bool,
  526. frontingSpecs parameters.FrontingSpecs,
  527. frontingUseDeviceBinder bool,
  528. selectedFrontingProviderID func(string)) (*http.Client, bool, func() common.APIParameters, error) {
  529. var httpClient *http.Client
  530. var getParams func() common.APIParameters
  531. var err error
  532. tunneled := tunnel != nil
  533. if tunneled {
  534. httpClient, getParams, err = MakeTunneledHTTPClient(
  535. ctx,
  536. config,
  537. tunnel,
  538. skipVerify || disableSystemRootCAs,
  539. disableSystemRootCAs,
  540. payloadSecure,
  541. frontingSpecs,
  542. selectedFrontingProviderID)
  543. if err != nil {
  544. return nil, false, nil, errors.Trace(err)
  545. }
  546. } else {
  547. var dialConfig *DialConfig
  548. if len(frontingSpecs) == 0 {
  549. // Must only set DialConfig if there are no fronting specs.
  550. dialConfig = untunneledDialConfig
  551. }
  552. httpClient, getParams, err = MakeUntunneledHTTPClient(
  553. ctx,
  554. config,
  555. dialConfig,
  556. skipVerify,
  557. disableSystemRootCAs,
  558. payloadSecure,
  559. frontingSpecs,
  560. frontingUseDeviceBinder,
  561. selectedFrontingProviderID)
  562. if err != nil {
  563. return nil, false, nil, errors.Trace(err)
  564. }
  565. }
  566. return httpClient, tunneled, getParams, nil
  567. }
  568. // ResumeDownload is a reusable helper that downloads requestUrl via the
  569. // httpClient, storing the result in downloadFilename when the download is
  570. // complete. Intermediate, partial downloads state is stored in
  571. // downloadFilename.part and downloadFilename.part.etag.
  572. // Any existing downloadFilename file will be overwritten.
  573. //
  574. // In the case where the remote object has changed while a partial download
  575. // is to be resumed, the partial state is reset and resumeDownload fails.
  576. // The caller must restart the download.
  577. //
  578. // When ifNoneMatchETag is specified, no download is made if the remote
  579. // object has the same ETag. ifNoneMatchETag has an effect only when no
  580. // partial download is in progress.
  581. func ResumeDownload(
  582. ctx context.Context,
  583. httpClient *http.Client,
  584. downloadURL string,
  585. userAgent string,
  586. downloadFilename string,
  587. ifNoneMatchETag string) (int64, string, error) {
  588. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  589. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  590. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  591. if err != nil {
  592. return 0, "", errors.Trace(err)
  593. }
  594. defer file.Close()
  595. fileInfo, err := file.Stat()
  596. if err != nil {
  597. return 0, "", errors.Trace(err)
  598. }
  599. // A partial download should have an ETag which is to be sent with the
  600. // Range request to ensure that the source object is the same as the
  601. // one that is partially downloaded.
  602. var partialETag []byte
  603. if fileInfo.Size() > 0 {
  604. partialETag, err = ioutil.ReadFile(partialETagFilename)
  605. // When the ETag can't be loaded, delete the partial download. To keep the
  606. // code simple, there is no immediate, inline retry here, on the assumption
  607. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  608. // again.
  609. if err != nil {
  610. // On Windows, file must be closed before it can be deleted
  611. file.Close()
  612. tempErr := os.Remove(partialFilename)
  613. if tempErr != nil && !os.IsNotExist(tempErr) {
  614. NoticeWarning("reset partial download failed: %s", tempErr)
  615. }
  616. tempErr = os.Remove(partialETagFilename)
  617. if tempErr != nil && !os.IsNotExist(tempErr) {
  618. NoticeWarning("reset partial download ETag failed: %s", tempErr)
  619. }
  620. return 0, "", errors.Tracef(
  621. "failed to load partial download ETag: %s", err)
  622. }
  623. }
  624. request, err := http.NewRequest("GET", downloadURL, nil)
  625. if err != nil {
  626. return 0, "", errors.Trace(err)
  627. }
  628. request = request.WithContext(ctx)
  629. request.Header.Set("User-Agent", userAgent)
  630. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  631. if partialETag != nil {
  632. // Note: not using If-Range, since not all host servers support it.
  633. // Using If-Match means we need to check for status code 412 and reset
  634. // when the ETag has changed since the last partial download.
  635. request.Header.Add("If-Match", string(partialETag))
  636. } else if ifNoneMatchETag != "" {
  637. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  638. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  639. // So for downloaders that store an ETag and wish to use that to prevent
  640. // redundant downloads, that ETag is sent as If-None-Match in the case
  641. // where a partial download is not in progress. When a partial download
  642. // is in progress, the partial ETag is sent as If-Match: either that's
  643. // a version that was never fully received, or it's no longer current in
  644. // which case the response will be StatusPreconditionFailed, the partial
  645. // download will be discarded, and then the next retry will use
  646. // If-None-Match.
  647. // Note: in this case, fileInfo.Size() == 0
  648. request.Header.Add("If-None-Match", ifNoneMatchETag)
  649. }
  650. response, err := httpClient.Do(request)
  651. // The resumeable download may ask for bytes past the resource range
  652. // since it doesn't store the "completed download" state. In this case,
  653. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  654. // receive 412 on ETag mismatch.
  655. if err == nil &&
  656. (response.StatusCode != http.StatusPartialContent &&
  657. // Certain http servers return 200 OK where we expect 206, so accept that.
  658. response.StatusCode != http.StatusOK &&
  659. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  660. response.StatusCode != http.StatusPreconditionFailed &&
  661. response.StatusCode != http.StatusNotModified) {
  662. response.Body.Close()
  663. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  664. }
  665. if err != nil {
  666. // Redact URL from "net/http" error message.
  667. if !GetEmitNetworkParameters() {
  668. errStr := err.Error()
  669. err = std_errors.New(strings.Replace(errStr, downloadURL, "[redacted]", -1))
  670. }
  671. return 0, "", errors.Trace(err)
  672. }
  673. defer response.Body.Close()
  674. responseETag := response.Header.Get("ETag")
  675. if response.StatusCode == http.StatusPreconditionFailed {
  676. // When the ETag no longer matches, delete the partial download. As above,
  677. // simply failing and relying on the caller's retry schedule.
  678. os.Remove(partialFilename)
  679. os.Remove(partialETagFilename)
  680. return 0, "", errors.TraceNew("partial download ETag mismatch")
  681. } else if response.StatusCode == http.StatusNotModified {
  682. // This status code is possible in the "If-None-Match" case. Don't leave
  683. // any partial download in progress. Caller should check that responseETag
  684. // matches ifNoneMatchETag.
  685. os.Remove(partialFilename)
  686. os.Remove(partialETagFilename)
  687. return 0, responseETag, nil
  688. }
  689. // Not making failure to write ETag file fatal, in case the entire download
  690. // succeeds in this one request.
  691. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  692. // A partial download occurs when this copy is interrupted. The io.Copy
  693. // will fail, leaving a partial download in place (.part and .part.etag).
  694. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  695. // From this point, n bytes are indicated as downloaded, even if there is
  696. // an error; the caller may use this to report partial download progress.
  697. if err != nil {
  698. return n, "", errors.Trace(err)
  699. }
  700. // Ensure the file is flushed to disk. The deferred close
  701. // will be a noop when this succeeds.
  702. err = file.Close()
  703. if err != nil {
  704. return n, "", errors.Trace(err)
  705. }
  706. // Remove if exists, to enable rename
  707. os.Remove(downloadFilename)
  708. err = os.Rename(partialFilename, downloadFilename)
  709. if err != nil {
  710. return n, "", errors.Trace(err)
  711. }
  712. os.Remove(partialETagFilename)
  713. return n, responseETag, nil
  714. }