download.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package build
  17. import (
  18. "bufio"
  19. "crypto/sha256"
  20. "encoding/hex"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "log"
  25. "net/http"
  26. "os"
  27. "path/filepath"
  28. "strings"
  29. )
  30. // ChecksumDB keeps file checksums.
  31. type ChecksumDB struct {
  32. allChecksums []string
  33. }
  34. // MustLoadChecksums loads a file containing checksums.
  35. func MustLoadChecksums(file string) *ChecksumDB {
  36. content, err := ioutil.ReadFile(file)
  37. if err != nil {
  38. log.Fatal("can't load checksum file: " + err.Error())
  39. }
  40. return &ChecksumDB{strings.Split(string(content), "\n")}
  41. }
  42. // Verify checks whether the given file is valid according to the checksum database.
  43. func (db *ChecksumDB) Verify(path string) error {
  44. fd, err := os.Open(path)
  45. if err != nil {
  46. return err
  47. }
  48. defer fd.Close()
  49. h := sha256.New()
  50. if _, err := io.Copy(h, bufio.NewReader(fd)); err != nil {
  51. return err
  52. }
  53. fileHash := hex.EncodeToString(h.Sum(nil))
  54. if !db.findHash(filepath.Base(path), fileHash) {
  55. return fmt.Errorf("invalid file hash %s", fileHash)
  56. }
  57. return nil
  58. }
  59. func (db *ChecksumDB) findHash(basename, hash string) bool {
  60. want := hash + " " + basename
  61. for _, line := range db.allChecksums {
  62. if strings.TrimSpace(line) == want {
  63. return true
  64. }
  65. }
  66. return false
  67. }
  68. // DownloadFile downloads a file and verifies its checksum.
  69. func (db *ChecksumDB) DownloadFile(url, dstPath string) error {
  70. if err := db.Verify(dstPath); err == nil {
  71. fmt.Printf("%s is up-to-date\n", dstPath)
  72. return nil
  73. }
  74. fmt.Printf("%s is stale\n", dstPath)
  75. fmt.Printf("downloading from %s\n", url)
  76. resp, err := http.Get(url)
  77. if err != nil {
  78. return fmt.Errorf("download error: %v", err)
  79. } else if resp.StatusCode != http.StatusOK {
  80. return fmt.Errorf("download error: status %d", resp.StatusCode)
  81. }
  82. defer resp.Body.Close()
  83. if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
  84. return err
  85. }
  86. fd, err := os.OpenFile(dstPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  87. if err != nil {
  88. return err
  89. }
  90. dst := newDownloadWriter(fd, resp.ContentLength)
  91. _, err = io.Copy(dst, resp.Body)
  92. dst.Close()
  93. if err != nil {
  94. return err
  95. }
  96. return db.Verify(dstPath)
  97. }
  98. type downloadWriter struct {
  99. file *os.File
  100. dstBuf *bufio.Writer
  101. size int64
  102. written int64
  103. lastpct int64
  104. }
  105. func newDownloadWriter(dst *os.File, size int64) *downloadWriter {
  106. return &downloadWriter{
  107. file: dst,
  108. dstBuf: bufio.NewWriter(dst),
  109. size: size,
  110. }
  111. }
  112. func (w *downloadWriter) Write(buf []byte) (int, error) {
  113. n, err := w.dstBuf.Write(buf)
  114. // Report progress.
  115. w.written += int64(n)
  116. pct := w.written * 10 / w.size * 10
  117. if pct != w.lastpct {
  118. if w.lastpct != 0 {
  119. fmt.Print("...")
  120. }
  121. fmt.Print(pct, "%")
  122. w.lastpct = pct
  123. }
  124. return n, err
  125. }
  126. func (w *downloadWriter) Close() error {
  127. if w.lastpct > 0 {
  128. fmt.Println() // Finish the progress line.
  129. }
  130. flushErr := w.dstBuf.Flush()
  131. closeErr := w.file.Close()
  132. if flushErr != nil {
  133. return flushErr
  134. }
  135. return closeErr
  136. }