]> Sergey Matveev's repositories - btrtrc.git/blob - cmd/torrent-verify/main.go
525cced890ca4e88ea58c5f856797278e71485bb
[btrtrc.git] / cmd / torrent-verify / main.go
1 package main
2
3 import (
4         "bytes"
5         "crypto/sha1"
6         "fmt"
7         "io"
8         "log"
9         "os"
10         "path/filepath"
11
12         "github.com/anacrolix/tagflag"
13         "github.com/anacrolix/torrent/metainfo"
14         "github.com/anacrolix/torrent/mmap_span"
15         "github.com/bradfitz/iter"
16         "github.com/edsrzf/mmap-go"
17 )
18
19 func mmapFile(name string) (mm mmap.MMap, err error) {
20         f, err := os.Open(name)
21         if err != nil {
22                 return
23         }
24         defer f.Close()
25         fi, err := f.Stat()
26         if err != nil {
27                 return
28         }
29         if fi.Size() == 0 {
30                 return
31         }
32         return mmap.MapRegion(f, -1, mmap.RDONLY, mmap.COPY, 0)
33 }
34
35 func verifyTorrent(info *metainfo.Info, root string) error {
36         span := new(mmap_span.MMapSpan)
37         for _, file := range info.UpvertedFiles() {
38                 filename := filepath.Join(append([]string{root, info.Name}, file.Path...)...)
39                 mm, err := mmapFile(filename)
40                 if err != nil {
41                         return err
42                 }
43                 if int64(len(mm)) != file.Length {
44                         return fmt.Errorf("file %q has wrong length", filename)
45                 }
46                 span.Append(mm)
47         }
48         for i := range iter.N(info.NumPieces()) {
49                 p := info.Piece(i)
50                 hash := sha1.New()
51                 _, err := io.Copy(hash, io.NewSectionReader(span, p.Offset(), p.Length()))
52                 if err != nil {
53                         return err
54                 }
55                 good := bytes.Equal(hash.Sum(nil), p.Hash().Bytes())
56                 if !good {
57                         return fmt.Errorf("hash mismatch at piece %d", i)
58                 }
59                 fmt.Printf("%d: %x: %v\n", i, p.Hash(), good)
60         }
61         return nil
62 }
63
64 func main() {
65         log.SetFlags(log.Flags() | log.Lshortfile)
66         var flags = struct {
67                 DataDir string
68                 tagflag.StartPos
69                 TorrentFile string
70         }{}
71         tagflag.Parse(&flags)
72         metaInfo, err := metainfo.LoadFromFile(flags.TorrentFile)
73         if err != nil {
74                 log.Fatal(err)
75         }
76         info, err := metaInfo.UnmarshalInfo()
77         if err != nil {
78                 log.Fatalf("error unmarshalling info: %s", err)
79         }
80         err = verifyTorrent(&info, flags.DataDir)
81         if err != nil {
82                 log.Fatalf("torrent failed verification: %s", err)
83         }
84 }