net.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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(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 := io.Copy(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 := io.Copy(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. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  227. // periodically check for network connectivity. It returns true if
  228. // no NetworkConnectivityChecker is provided (waiting is disabled)
  229. // or when NetworkConnectivityChecker.HasNetworkConnectivity()
  230. // indicates connectivity. It waits and polls the checker once a second.
  231. // When the context is done, false is returned immediately.
  232. func WaitForNetworkConnectivity(
  233. ctx context.Context, connectivityChecker NetworkConnectivityChecker) bool {
  234. if connectivityChecker == nil || connectivityChecker.HasNetworkConnectivity() == 1 {
  235. return true
  236. }
  237. NoticeInfo("waiting for network connectivity")
  238. ticker := time.NewTicker(1 * time.Second)
  239. defer ticker.Stop()
  240. for {
  241. if connectivityChecker.HasNetworkConnectivity() == 1 {
  242. return true
  243. }
  244. select {
  245. case <-ticker.C:
  246. // Check HasNetworkConnectivity again
  247. case <-ctx.Done():
  248. return false
  249. }
  250. }
  251. }
  252. // ResolveIP uses a custom dns stack to make a DNS query over the
  253. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  254. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  255. // when we need to ensure that a DNS connection is tunneled.
  256. // Caller must set timeouts or interruptibility as required for conn.
  257. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  258. // Send the DNS query
  259. dnsConn := &dns.Conn{Conn: conn}
  260. defer dnsConn.Close()
  261. query := new(dns.Msg)
  262. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  263. query.RecursionDesired = true
  264. dnsConn.WriteMsg(query)
  265. // Process the response
  266. response, err := dnsConn.ReadMsg()
  267. if err != nil {
  268. return nil, nil, errors.Trace(err)
  269. }
  270. addrs = make([]net.IP, 0)
  271. ttls = make([]time.Duration, 0)
  272. for _, answer := range response.Answer {
  273. if a, ok := answer.(*dns.A); ok {
  274. addrs = append(addrs, a.A)
  275. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  276. ttls = append(ttls, ttl)
  277. }
  278. }
  279. return addrs, ttls, nil
  280. }
  281. // MakeUntunneledHTTPClient returns a net/http.Client which is configured to
  282. // use custom dialing features -- including BindToDevice, etc.
  283. //
  284. // The context is applied to underlying TCP dials. The caller is responsible
  285. // for applying the context to requests made with the returned http.Client.
  286. func MakeUntunneledHTTPClient(
  287. ctx context.Context,
  288. config *Config,
  289. untunneledDialConfig *DialConfig,
  290. skipVerify bool) (*http.Client, error) {
  291. dialer := NewTCPDialer(untunneledDialConfig)
  292. tlsConfig := &CustomTLSConfig{
  293. Parameters: config.GetParameters(),
  294. Dial: dialer,
  295. UseDialAddrSNI: true,
  296. SNIServerName: "",
  297. SkipVerify: skipVerify,
  298. TrustedCACertificatesFilename: untunneledDialConfig.TrustedCACertificatesFilename,
  299. }
  300. tlsConfig.EnableClientSessionCache()
  301. tlsDialer := NewCustomTLSDialer(tlsConfig)
  302. transport := &http.Transport{
  303. Dial: func(network, addr string) (net.Conn, error) {
  304. return dialer(ctx, network, addr)
  305. },
  306. DialTLS: func(network, addr string) (net.Conn, error) {
  307. return tlsDialer(ctx, network, addr)
  308. },
  309. }
  310. httpClient := &http.Client{
  311. Transport: transport,
  312. }
  313. return httpClient, nil
  314. }
  315. // MakeTunneledHTTPClient returns a net/http.Client which is
  316. // configured to use custom dialing features including tunneled
  317. // dialing and, optionally, UseTrustedCACertificatesForStockTLS.
  318. // This http.Client uses stock TLS for HTTPS.
  319. func MakeTunneledHTTPClient(
  320. config *Config,
  321. tunnel *Tunnel,
  322. skipVerify bool) (*http.Client, error) {
  323. // Note: there is no dial context since SSH port forward dials cannot
  324. // be interrupted directly. Closing the tunnel will interrupt the dials.
  325. tunneledDialer := func(_, addr string) (net.Conn, error) {
  326. // Set alwaysTunneled to ensure the http.Client traffic is always tunneled,
  327. // even when split tunnel mode is enabled.
  328. conn, _, err := tunnel.DialTCPChannel(addr, true, nil)
  329. return conn, errors.Trace(err)
  330. }
  331. transport := &http.Transport{
  332. Dial: tunneledDialer,
  333. }
  334. if skipVerify {
  335. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  336. } else if config.TrustedCACertificatesFilename != "" {
  337. rootCAs := x509.NewCertPool()
  338. certData, err := ioutil.ReadFile(config.TrustedCACertificatesFilename)
  339. if err != nil {
  340. return nil, errors.Trace(err)
  341. }
  342. rootCAs.AppendCertsFromPEM(certData)
  343. transport.TLSClientConfig = &tls.Config{RootCAs: rootCAs}
  344. }
  345. return &http.Client{
  346. Transport: transport,
  347. }, nil
  348. }
  349. // MakeDownloadHTTPClient is a helper that sets up a http.Client
  350. // for use either untunneled or through a tunnel.
  351. func MakeDownloadHTTPClient(
  352. ctx context.Context,
  353. config *Config,
  354. tunnel *Tunnel,
  355. untunneledDialConfig *DialConfig,
  356. skipVerify bool) (*http.Client, bool, error) {
  357. var httpClient *http.Client
  358. var err error
  359. tunneled := tunnel != nil
  360. if tunneled {
  361. httpClient, err = MakeTunneledHTTPClient(
  362. config, tunnel, skipVerify)
  363. if err != nil {
  364. return nil, false, errors.Trace(err)
  365. }
  366. } else {
  367. httpClient, err = MakeUntunneledHTTPClient(
  368. ctx, config, untunneledDialConfig, skipVerify)
  369. if err != nil {
  370. return nil, false, errors.Trace(err)
  371. }
  372. }
  373. return httpClient, tunneled, nil
  374. }
  375. // ResumeDownload is a reusable helper that downloads requestUrl via the
  376. // httpClient, storing the result in downloadFilename when the download is
  377. // complete. Intermediate, partial downloads state is stored in
  378. // downloadFilename.part and downloadFilename.part.etag.
  379. // Any existing downloadFilename file will be overwritten.
  380. //
  381. // In the case where the remote object has changed while a partial download
  382. // is to be resumed, the partial state is reset and resumeDownload fails.
  383. // The caller must restart the download.
  384. //
  385. // When ifNoneMatchETag is specified, no download is made if the remote
  386. // object has the same ETag. ifNoneMatchETag has an effect only when no
  387. // partial download is in progress.
  388. //
  389. func ResumeDownload(
  390. ctx context.Context,
  391. httpClient *http.Client,
  392. downloadURL string,
  393. userAgent string,
  394. downloadFilename string,
  395. ifNoneMatchETag string) (int64, string, error) {
  396. partialFilename := fmt.Sprintf("%s.part", downloadFilename)
  397. partialETagFilename := fmt.Sprintf("%s.part.etag", downloadFilename)
  398. file, err := os.OpenFile(partialFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  399. if err != nil {
  400. return 0, "", errors.Trace(err)
  401. }
  402. defer file.Close()
  403. fileInfo, err := file.Stat()
  404. if err != nil {
  405. return 0, "", errors.Trace(err)
  406. }
  407. // A partial download should have an ETag which is to be sent with the
  408. // Range request to ensure that the source object is the same as the
  409. // one that is partially downloaded.
  410. var partialETag []byte
  411. if fileInfo.Size() > 0 {
  412. partialETag, err = ioutil.ReadFile(partialETagFilename)
  413. // When the ETag can't be loaded, delete the partial download. To keep the
  414. // code simple, there is no immediate, inline retry here, on the assumption
  415. // that the controller's upgradeDownloader will shortly call DownloadUpgrade
  416. // again.
  417. if err != nil {
  418. // On Windows, file must be closed before it can be deleted
  419. file.Close()
  420. tempErr := os.Remove(partialFilename)
  421. if tempErr != nil && !os.IsNotExist(tempErr) {
  422. NoticeWarning("reset partial download failed: %s", tempErr)
  423. }
  424. tempErr = os.Remove(partialETagFilename)
  425. if tempErr != nil && !os.IsNotExist(tempErr) {
  426. NoticeWarning("reset partial download ETag failed: %s", tempErr)
  427. }
  428. return 0, "", errors.Tracef(
  429. "failed to load partial download ETag: %s", err)
  430. }
  431. }
  432. request, err := http.NewRequest("GET", downloadURL, nil)
  433. if err != nil {
  434. return 0, "", errors.Trace(err)
  435. }
  436. request = request.WithContext(ctx)
  437. request.Header.Set("User-Agent", userAgent)
  438. request.Header.Add("Range", fmt.Sprintf("bytes=%d-", fileInfo.Size()))
  439. if partialETag != nil {
  440. // Note: not using If-Range, since not all host servers support it.
  441. // Using If-Match means we need to check for status code 412 and reset
  442. // when the ETag has changed since the last partial download.
  443. request.Header.Add("If-Match", string(partialETag))
  444. } else if ifNoneMatchETag != "" {
  445. // Can't specify both If-Match and If-None-Match. Behavior is undefined.
  446. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  447. // So for downloaders that store an ETag and wish to use that to prevent
  448. // redundant downloads, that ETag is sent as If-None-Match in the case
  449. // where a partial download is not in progress. When a partial download
  450. // is in progress, the partial ETag is sent as If-Match: either that's
  451. // a version that was never fully received, or it's no longer current in
  452. // which case the response will be StatusPreconditionFailed, the partial
  453. // download will be discarded, and then the next retry will use
  454. // If-None-Match.
  455. // Note: in this case, fileInfo.Size() == 0
  456. request.Header.Add("If-None-Match", ifNoneMatchETag)
  457. }
  458. response, err := httpClient.Do(request)
  459. // The resumeable download may ask for bytes past the resource range
  460. // since it doesn't store the "completed download" state. In this case,
  461. // the HTTP server returns 416. Otherwise, we expect 206. We may also
  462. // receive 412 on ETag mismatch.
  463. if err == nil &&
  464. (response.StatusCode != http.StatusPartialContent &&
  465. // Certain http servers return 200 OK where we expect 206, so accept that.
  466. response.StatusCode != http.StatusOK &&
  467. response.StatusCode != http.StatusRequestedRangeNotSatisfiable &&
  468. response.StatusCode != http.StatusPreconditionFailed &&
  469. response.StatusCode != http.StatusNotModified) {
  470. response.Body.Close()
  471. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  472. }
  473. if err != nil {
  474. // Redact URL from "net/http" error message.
  475. if !GetEmitNetworkParameters() {
  476. errStr := err.Error()
  477. err = std_errors.New(strings.Replace(errStr, downloadURL, "[redacted]", -1))
  478. }
  479. return 0, "", errors.Trace(err)
  480. }
  481. defer response.Body.Close()
  482. responseETag := response.Header.Get("ETag")
  483. if response.StatusCode == http.StatusPreconditionFailed {
  484. // When the ETag no longer matches, delete the partial download. As above,
  485. // simply failing and relying on the caller's retry schedule.
  486. os.Remove(partialFilename)
  487. os.Remove(partialETagFilename)
  488. return 0, "", errors.TraceNew("partial download ETag mismatch")
  489. } else if response.StatusCode == http.StatusNotModified {
  490. // This status code is possible in the "If-None-Match" case. Don't leave
  491. // any partial download in progress. Caller should check that responseETag
  492. // matches ifNoneMatchETag.
  493. os.Remove(partialFilename)
  494. os.Remove(partialETagFilename)
  495. return 0, responseETag, nil
  496. }
  497. // Not making failure to write ETag file fatal, in case the entire download
  498. // succeeds in this one request.
  499. ioutil.WriteFile(partialETagFilename, []byte(responseETag), 0600)
  500. // A partial download occurs when this copy is interrupted. The io.Copy
  501. // will fail, leaving a partial download in place (.part and .part.etag).
  502. n, err := io.Copy(NewSyncFileWriter(file), response.Body)
  503. // From this point, n bytes are indicated as downloaded, even if there is
  504. // an error; the caller may use this to report partial download progress.
  505. if err != nil {
  506. return n, "", errors.Trace(err)
  507. }
  508. // Ensure the file is flushed to disk. The deferred close
  509. // will be a noop when this succeeds.
  510. err = file.Close()
  511. if err != nil {
  512. return n, "", errors.Trace(err)
  513. }
  514. // Remove if exists, to enable rename
  515. os.Remove(downloadFilename)
  516. err = os.Rename(partialFilename, downloadFilename)
  517. if err != nil {
  518. return n, "", errors.Trace(err)
  519. }
  520. os.Remove(partialETagFilename)
  521. return n, responseETag, nil
  522. }