net.go 28 KB

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