net.go 21 KB

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