net.go 28 KB

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