]> Sergey Matveev's repositories - btrtrc.git/blob - cmd/torrent-verify/main.go
Fixes for changes to metainfo.MetaInfo.UnmarshalInfo
[btrtrc.git] / cmd / torrent-verify / main.go
1 package main
2
3 import (
4         "bytes"
5         "crypto/sha1"
6         "flag"
7         "fmt"
8         "io"
9         "log"
10         "os"
11         "path/filepath"
12
13         "github.com/bradfitz/iter"
14         "github.com/edsrzf/mmap-go"
15
16         "github.com/anacrolix/torrent/metainfo"
17         "github.com/anacrolix/torrent/mmap_span"
18 )
19
20 var (
21         torrentPath = flag.String("torrent", "/path/to/the.torrent", "path of the torrent file")
22         dataPath    = flag.String("path", "/torrent/data", "path of the torrent data")
23 )
24
25 func fileToMmap(filename string, length int64) mmap.MMap {
26         osFile, err := os.Open(filename)
27         if os.IsNotExist(err) {
28                 return nil
29         }
30         if err != nil {
31                 log.Fatal(err)
32         }
33         goMMap, err := mmap.MapRegion(osFile, int(length), mmap.RDONLY, mmap.COPY, 0)
34         if err != nil {
35                 log.Fatal(err)
36         }
37         if int64(len(goMMap)) != length {
38                 log.Printf("file mmap has wrong size: %#v", filename)
39         }
40         osFile.Close()
41
42         return goMMap
43 }
44
45 func main() {
46         log.SetFlags(log.Flags() | log.Lshortfile)
47         flag.Parse()
48         metaInfo, err := metainfo.LoadFromFile(*torrentPath)
49         if err != nil {
50                 log.Fatal(err)
51         }
52         info, err := metaInfo.UnmarshalInfo()
53         if err != nil {
54                 log.Fatalf("error unmarshalling info: %s", err)
55         }
56         mMapSpan := &mmap_span.MMapSpan{}
57         if len(info.Files) > 0 {
58                 for _, file := range info.Files {
59                         filename := filepath.Join(append([]string{*dataPath, info.Name}, file.Path...)...)
60                         goMMap := fileToMmap(filename, file.Length)
61                         mMapSpan.Append(goMMap)
62                 }
63                 log.Println(len(info.Files))
64         } else {
65                 goMMap := fileToMmap(*dataPath, info.Length)
66                 mMapSpan.Append(goMMap)
67         }
68         log.Println(mMapSpan.Size())
69         log.Println(len(info.Pieces))
70         for i := range iter.N(info.NumPieces()) {
71                 p := info.Piece(i)
72                 hash := sha1.New()
73                 _, err := io.Copy(hash, io.NewSectionReader(mMapSpan, p.Offset(), p.Length()))
74                 if err != nil {
75                         log.Fatal(err)
76                 }
77                 fmt.Printf("%d: %x: %v\n", i, p.Hash(), bytes.Equal(hash.Sum(nil), p.Hash().Bytes()))
78         }
79 }