net.go 23 KB

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