net.go 20 KB

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