net.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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,
  368. tlsCache utls.ClientSessionCache) (*http.Client, func() common.APIParameters, error) {
  369. frontedHTTPClient, err := newFrontedHTTPClientInstance(
  370. config, tunnel, frontingSpecs, selectedFrontingProviderID,
  371. useDeviceBinder, skipVerify, disableSystemRootCAs, payloadSecure, tlsCache)
  372. if err != nil {
  373. return nil, nil, errors.Trace(err)
  374. }
  375. getParams := func() common.APIParameters {
  376. return common.APIParameters(frontedHTTPClient.frontedHTTPDialParameters.GetMetrics())
  377. }
  378. return &http.Client{
  379. Transport: common.NewHTTPRoundTripper(frontedHTTPClient.RoundTrip),
  380. }, getParams, nil
  381. }
  382. // meekHTTPResponseReadCloser wraps an http.Response.Body received over a
  383. // MeekConn in MeekModePlaintextRoundTrip and exposes an io.ReadCloser. Close
  384. // closes the meek conn and response body.
  385. type meekHTTPResponseReadCloser struct {
  386. conn *MeekConn
  387. responseBody io.ReadCloser
  388. }
  389. // newMeekHTTPResponseReadCloser creates a meekHTTPResponseReadCloser.
  390. func newMeekHTTPResponseReadCloser(meekConn *MeekConn, responseBody io.ReadCloser) *meekHTTPResponseReadCloser {
  391. return &meekHTTPResponseReadCloser{
  392. conn: meekConn,
  393. responseBody: responseBody,
  394. }
  395. }
  396. // Read implements the io.Reader interface.
  397. func (meek *meekHTTPResponseReadCloser) Read(p []byte) (n int, err error) {
  398. return meek.responseBody.Read(p)
  399. }
  400. // Read implements the io.Closer interface.
  401. func (meek *meekHTTPResponseReadCloser) Close() error {
  402. err := meek.responseBody.Close()
  403. _ = meek.conn.Close()
  404. return err
  405. }
  406. // MakeUntunneledHTTPClient returns a net/http.Client which is configured to
  407. // use custom dialing features -- including BindToDevice, etc. A function is
  408. // returned which, if non-nil, can be called after each request made with the
  409. // net/http.Client completes to retrieve the set of API parameter values
  410. // applied to the request.
  411. //
  412. // The context is applied to underlying TCP dials. The caller is responsible
  413. // for applying the context to requests made with the returned http.Client.
  414. func MakeUntunneledHTTPClient(
  415. ctx context.Context,
  416. config *Config,
  417. untunneledDialConfig *DialConfig,
  418. tlsCache utls.ClientSessionCache,
  419. skipVerify bool,
  420. disableSystemRootCAs bool,
  421. payloadSecure bool,
  422. frontingSpecs parameters.FrontingSpecs,
  423. frontingUseDeviceBinder bool,
  424. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  425. if untunneledDialConfig != nil && len(frontingSpecs) != 0 ||
  426. untunneledDialConfig == nil && len(frontingSpecs) == 0 {
  427. return nil, nil, errors.TraceNew("expected either dial configuration or fronting specs")
  428. }
  429. if len(frontingSpecs) > 0 {
  430. // Ignore skipVerify because it only applies when there are no
  431. // fronting specs.
  432. httpClient, getParams, err := makeFrontedHTTPClient(
  433. config,
  434. nil,
  435. frontingSpecs,
  436. selectedFrontingProviderID,
  437. frontingUseDeviceBinder,
  438. false,
  439. disableSystemRootCAs,
  440. payloadSecure,
  441. tlsCache,
  442. )
  443. if err != nil {
  444. return nil, nil, errors.Trace(err)
  445. }
  446. return httpClient, getParams, nil
  447. }
  448. dialer := NewTCPDialer(untunneledDialConfig)
  449. tlsConfig := &CustomTLSConfig{
  450. Parameters: config.GetParameters(),
  451. Dial: dialer,
  452. UseDialAddrSNI: true,
  453. SNIServerName: "",
  454. SkipVerify: skipVerify,
  455. DisableSystemRootCAs: disableSystemRootCAs,
  456. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  457. ClientSessionCache: tlsCache,
  458. }
  459. tlsDialer := NewCustomTLSDialer(tlsConfig)
  460. transport := &http.Transport{
  461. Dial: func(network, addr string) (net.Conn, error) {
  462. return dialer(ctx, network, addr)
  463. },
  464. DialTLS: func(network, addr string) (net.Conn, error) {
  465. return tlsDialer(ctx, network, addr)
  466. },
  467. }
  468. httpClient := &http.Client{
  469. Transport: transport,
  470. }
  471. return httpClient, nil, nil
  472. }
  473. // MakeTunneledHTTPClient returns a net/http.Client which is
  474. // configured to use custom dialing features including tunneled
  475. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  476. // This http.Client uses stock TLS for HTTPS.
  477. func MakeTunneledHTTPClient(
  478. ctx context.Context,
  479. config *Config,
  480. tunnel *Tunnel,
  481. tlsCache utls.ClientSessionCache,
  482. skipVerify,
  483. disableSystemRootCAs,
  484. payloadSecure bool,
  485. frontingSpecs parameters.FrontingSpecs,
  486. selectedFrontingProviderID func(string)) (*http.Client, func() common.APIParameters, error) {
  487. // Note: there is no dial context since SSH port forward dials cannot
  488. // be interrupted directly. Closing the tunnel will interrupt the dials.
  489. if len(frontingSpecs) > 0 {
  490. // Ignore skipVerify because it only applies when there are no
  491. // fronting specs.
  492. httpClient, getParams, err := makeFrontedHTTPClient(
  493. config,
  494. tunnel,
  495. frontingSpecs,
  496. selectedFrontingProviderID,
  497. false,
  498. false,
  499. disableSystemRootCAs,
  500. payloadSecure,
  501. tlsCache)
  502. if err != nil {
  503. return nil, nil, errors.Trace(err)
  504. }
  505. return httpClient, getParams, nil
  506. }
  507. tunneledDialer := func(_, addr string) (net.Conn, error) {
  508. // Set alwaysTunneled to ensure the http.Client traffic is always tunneled,
  509. // even when split tunnel mode is enabled.
  510. conn, _, err := tunnel.DialTCPChannel(addr, true, nil)
  511. return conn, errors.Trace(err)
  512. }
  513. transport := &http.Transport{
  514. Dial: tunneledDialer,
  515. }
  516. if skipVerify {
  517. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  518. } else if config.TrustedCACertificatesFilename != "" {
  519. rootCAs := x509.NewCertPool()
  520. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  521. if err != nil {
  522. return nil, nil, errors.Trace(err)
  523. }
  524. rootCAs.AppendCertsFromPEM(certData)
  525. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  526. }
  527. return &http.Client{
  528. Transport: transport,
  529. }, nil, nil
  530. }
  531. // MakeDownloadHTTPClient is a helper that sets up a http.Client for use either
  532. // untunneled or through a tunnel. True is returned if the http.Client is setup
  533. // for use through a tunnel; otherwise it is setup for untunneled use. A
  534. // function is returned which, if non-nil, can be called after each request
  535. // made with the http.Client completes to retrieve the set of API
  536. // parameter values applied to the request.
  537. func MakeDownloadHTTPClient(
  538. ctx context.Context,
  539. config *Config,
  540. tunnel *Tunnel,
  541. untunneledDialConfig *DialConfig,
  542. tlsCache utls.ClientSessionCache,
  543. skipVerify,
  544. disableSystemRootCAs,
  545. payloadSecure bool,
  546. frontingSpecs parameters.FrontingSpecs,
  547. frontingUseDeviceBinder bool,
  548. selectedFrontingProviderID func(string)) (*http.Client, bool, func() common.APIParameters, error) {
  549. var httpClient *http.Client
  550. var getParams func() common.APIParameters
  551. var err error
  552. tunneled := tunnel != nil
  553. if tunneled {
  554. httpClient, getParams, err = MakeTunneledHTTPClient(
  555. ctx,
  556. config,
  557. tunnel,
  558. tlsCache,
  559. skipVerify || disableSystemRootCAs,
  560. disableSystemRootCAs,
  561. payloadSecure,
  562. frontingSpecs,
  563. selectedFrontingProviderID)
  564. if err != nil {
  565. return nil, false, nil, errors.Trace(err)
  566. }
  567. } else {
  568. var dialConfig *DialConfig
  569. if len(frontingSpecs) == 0 {
  570. // Must only set DialConfig if there are no fronting specs.
  571. dialConfig = untunneledDialConfig
  572. }
  573. httpClient, getParams, err = MakeUntunneledHTTPClient(
  574. ctx,
  575. config,
  576. dialConfig,
  577. tlsCache,
  578. skipVerify,
  579. disableSystemRootCAs,
  580. payloadSecure,
  581. frontingSpecs,
  582. frontingUseDeviceBinder,
  583. selectedFrontingProviderID)
  584. if err != nil {
  585. return nil, false, nil, errors.Trace(err)
  586. }
  587. }
  588. return httpClient, tunneled, getParams, nil
  589. }
  590. // ResumeDownload is a reusable helper that downloads requestUrl via the
  591. // httpClient, storing the result in downloadFilename when the download is
  592. // complete. Intermediate, partial downloads state is stored in
  593. // downloadFilename.part and downloadFilename.part.etag.
  594. // Any existing downloadFilename file will be overwritten.
  595. //
  596. // In the case where the remote object has changed while a partial download
  597. // is to be resumed, the partial state is reset and resumeDownload fails.
  598. // The caller must restart the download.
  599. //
  600. // When ifNoneMatchETag is specified, no download is made if the remote
  601. // object has the same ETag. ifNoneMatchETag has an effect only when no
  602. // partial download is in progress.
  603. func ResumeDownload(
  604. ctx context.Context,
  605. httpClient *http.Client,
  606. downloadURL string,
  607. userAgent string,
  608. downloadFilename string,
  609. ifNoneMatchETag string) (int64, string, error) {
  610. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  611. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  612. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  613. if err != nil {
  614. return 0, "", errors.Trace(err)
  615. }
  616. defer file.Close()
  617. fileInfo, err := file.Stat()
  618. if err != nil {
  619. return 0, "", errors.Trace(err)
  620. }
  621. // A partial download should have an ETag which is to be sent with the
  622. // Range request to ensure that the source object is the same as the
  623. // one that is partially downloaded.
  624. var partialETag []byte
  625. if fileInfo.Size() > 0 {
  626. partialETag, err = ioutil.ReadFile(partialETagFilename)
  627. // When the ETag can't be loaded, delete the partial download. To keep the
  628. // code simple, there is no immediate, inline retry here, on the assumption
  629. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  630. // again.
  631. if err != nil {
  632. // On Windows, file must be closed before it can be deleted
  633. file.Close()
  634. tempErr := os.Remove(partialFilename)
  635. if tempErr != nil && !os.IsNotExist(tempErr) {
  636. NoticeWarning("reset partial download failed: %s", tempErr)
  637. }
  638. tempErr = os.Remove(partialETagFilename)
  639. if tempErr != nil && !os.IsNotExist(tempErr) {
  640. NoticeWarning("reset partial download ETag failed: %s", tempErr)
  641. }
  642. return 0, "", errors.Tracef(
  643. "failed to load partial download ETag: %s", err)
  644. }
  645. }
  646. request, err := http.NewRequest("GET", downloadURL, nil)
  647. if err != nil {
  648. return 0, "", errors.Trace(err)
  649. }
  650. request = request.WithContext(ctx)
  651. request.Header.Set("User-Agent", userAgent)
  652. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  653. if partialETag != nil {
  654. // Note: not using If-Range, since not all host servers support it.
  655. // Using If-Match means we need to check for status code 412 and reset
  656. // when the ETag has changed since the last partial download.
  657. request.Header.Add("If-Match", string(partialETag))
  658. } else if ifNoneMatchETag != "" {
  659. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  660. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  661. // So for downloaders that store an ETag and wish to use that to prevent
  662. // redundant downloads, that ETag is sent as If-None-Match in the case
  663. // where a partial download is not in progress. When a partial download
  664. // is in progress, the partial ETag is sent as If-Match: either that's
  665. // a version that was never fully received, or it's no longer current in
  666. // which case the response will be StatusPreconditionFailed, the partial
  667. // download will be discarded, and then the next retry will use
  668. // If-None-Match.
  669. // Note: in this case, fileInfo.Size() == 0
  670. request.Header.Add("If-None-Match", ifNoneMatchETag)
  671. }
  672. response, err := httpClient.Do(request)
  673. // The resumeable download may ask for bytes past the resource range
  674. // since it doesn't store the "completed download" state. In this case,
  675. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  676. // receive 412 on ETag mismatch.
  677. if err == nil &&
  678. (response.StatusCode != http.StatusPartialContent &&
  679. // Certain http servers return 200 OK where we expect 206, so accept that.
  680. response.StatusCode != http.StatusOK &&
  681. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  682. response.StatusCode != http.StatusPreconditionFailed &&
  683. response.StatusCode != http.StatusNotModified) {
  684. response.Body.Close()
  685. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  686. }
  687. if err != nil {
  688. // Redact URL from "net/http" error message.
  689. if !GetEmitNetworkParameters() {
  690. errStr := err.Error()
  691. err = std_errors.New(strings.Replace(errStr, downloadURL, "[redacted]", -1))
  692. }
  693. return 0, "", errors.Trace(err)
  694. }
  695. defer response.Body.Close()
  696. responseETag := response.Header.Get("ETag")
  697. if response.StatusCode == http.StatusPreconditionFailed {
  698. // When the ETag no longer matches, delete the partial download. As above,
  699. // simply failing and relying on the caller's retry schedule.
  700. os.Remove(partialFilename)
  701. os.Remove(partialETagFilename)
  702. return 0, "", errors.TraceNew("partial download ETag mismatch")
  703. } else if response.StatusCode == http.StatusNotModified {
  704. // This status code is possible in the "If-None-Match" case. Don't leave
  705. // any partial download in progress. Caller should check that responseETag
  706. // matches ifNoneMatchETag.
  707. os.Remove(partialFilename)
  708. os.Remove(partialETagFilename)
  709. return 0, responseETag, nil
  710. }
  711. // Not making failure to write ETag file fatal, in case the entire download
  712. // succeeds in this one request.
  713. _ = ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  714. // A partial download occurs when this copy is interrupted. The io.Copy
  715. // will fail, leaving a partial download in place (.part and .part.etag).
  716. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  717. // From this point, n bytes are indicated as downloaded, even if there is
  718. // an error; the caller may use this to report partial download progress.
  719. if err != nil {
  720. return n, "", errors.Trace(err)
  721. }
  722. // Ensure the file is flushed to disk. The deferred close
  723. // will be a noop when this succeeds.
  724. err = file.Close()
  725. if err != nil {
  726. return n, "", errors.Trace(err)
  727. }
  728. // Remove if exists, to enable rename
  729. os.Remove(downloadFilename)
  730. err = os.Rename(partialFilename, downloadFilename)
  731. if err != nil {
  732. return n, "", errors.Trace(err)
  733. }
  734. os.Remove(partialETagFilename)
  735. return n, responseETag, nil
  736. }