download.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. "log"
  24. "net/http"
  25. "os"
  26. "path/filepath"
  27. "strings"
  28. )
  29. // ChecksumDB keeps file checksums.
  30. type ChecksumDB struct {
  31. allChecksums []string
  32. }
  33. // MustLoadChecksums loads a file containing checksums.
  34. func MustLoadChecksums(file string) *ChecksumDB {
  35. content, err := os.ReadFile(file)
  36. if err != nil {
  37. log.Fatal("can't load checksum file: " + err.Error())
  38. }
  39. return &ChecksumDB{strings.Split(string(content), "\n")}
  40. }
  41. // Verify checks whether the given file is valid according to the checksum database.
  42. func (db *ChecksumDB) Verify(path string) error {
  43. fd, err := os.Open(path)
  44. if err != nil {
  45. return err
  46. }
  47. defer fd.Close()
  48. h := sha256.New()
  49. if _, err := io.Copy(h, bufio.NewReader(fd)); err != nil {
  50. return err
  51. }
  52. fileHash := hex.EncodeToString(h.Sum(nil))
  53. if !db.findHash(filepath.Base(path), fileHash) {
  54. return fmt.Errorf("invalid file hash %s for %s", fileHash, filepath.Base(path))
  55. }
  56. return nil
  57. }
  58. func (db *ChecksumDB) findHash(basename, hash string) bool {
  59. want := hash + " " + basename
  60. for _, line := range db.allChecksums {
  61. if strings.TrimSpace(line) == want {
  62. return true
  63. }
  64. }
  65. return false
  66. }
  67. // DownloadFile downloads a file and verifies its checksum.
  68. func (db *ChecksumDB) DownloadFile(url, dstPath string) error {
  69. if err := db.Verify(dstPath); err == nil {
  70. fmt.Printf("%s is up-to-date\n", dstPath)
  71. return nil
  72. }
  73. fmt.Printf("%s is stale\n", dstPath)
  74. fmt.Printf("downloading from %s\n", url)
  75. resp, err := http.Get(url)
  76. if err != nil {
  77. return fmt.Errorf("download error: %v", err)
  78. } else if resp.StatusCode != http.StatusOK {
  79. return fmt.Errorf("download error: status %d", resp.StatusCode)
  80. }
  81. defer resp.Body.Close()
  82. if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
  83. return err
  84. }
  85. fd, err := os.OpenFile(dstPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  86. if err != nil {
  87. return err
  88. }
  89. dst := newDownloadWriter(fd, resp.ContentLength)
  90. _, err = io.Copy(dst, resp.Body)
  91. dst.Close()
  92. if err != nil {
  93. return err
  94. }
  95. return db.Verify(dstPath)
  96. }
  97. type downloadWriter struct {
  98. file *os.File
  99. dstBuf *bufio.Writer
  100. size int64
  101. written int64
  102. lastpct int64
  103. }
  104. func newDownloadWriter(dst *os.File, size int64) *downloadWriter {
  105. return &downloadWriter{
  106. file: dst,
  107. dstBuf: bufio.NewWriter(dst),
  108. size: size,
  109. }
  110. }
  111. func (w *downloadWriter) Write(buf []byte) (int, error) {
  112. n, err := w.dstBuf.Write(buf)
  113. // Report progress.
  114. w.written += int64(n)
  115. pct := w.written * 10 / w.size * 10
  116. if pct != w.lastpct {
  117. if w.lastpct != 0 {
  118. fmt.Print("...")
  119. }
  120. fmt.Print(pct, "%")
  121. w.lastpct = pct
  122. }
  123. return n, err
  124. }
  125. func (w *downloadWriter) Close() error {
  126. if w.lastpct > 0 {
  127. fmt.Println() // Finish the progress line.
  128. }
  129. flushErr := w.dstBuf.Flush()
  130. closeErr := w.file.Close()
  131. if flushErr != nil {
  132. return flushErr
  133. }
  134. return closeErr
  135. }