]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/info.go
Avoid allocating memory when checking interface (#588)
[btrtrc.git] / metainfo / info.go
1 package metainfo
2
3 import (
4         "errors"
5         "fmt"
6         "io"
7         "os"
8         "path/filepath"
9         "strings"
10
11         "github.com/anacrolix/missinggo/slices"
12 )
13
14 // The info dictionary.
15 type Info struct {
16         PieceLength int64  `bencode:"piece length"`      // BEP3
17         Pieces      []byte `bencode:"pieces"`            // BEP3
18         Name        string `bencode:"name"`              // BEP3
19         Length      int64  `bencode:"length,omitempty"`  // BEP3, mutually exclusive with Files
20         Private     *bool  `bencode:"private,omitempty"` // BEP27
21         // TODO: Document this field.
22         Source string     `bencode:"source,omitempty"`
23         Files  []FileInfo `bencode:"files,omitempty"` // BEP3, mutually exclusive with Length
24 }
25
26 // The Info.Name field is "advisory". For multi-file torrents it's usually a suggested directory
27 // name. There are situations where we don't want a directory (like using the contents of a torrent
28 // as the immediate contents of a directory), or the name is invalid. Transmission will inject the
29 // name of the torrent file if it doesn't like the name, resulting in a different infohash
30 // (https://github.com/transmission/transmission/issues/1775). To work around these situations, we
31 // will use a sentinel name for compatibility with Transmission and to signal to our own client that
32 // we intended to have no directory name. By exposing it in the API we can check for references to
33 // this behaviour within this implementation.
34 const NoName = "-"
35
36 // This is a helper that sets Files and Pieces from a root path and its children.
37 func (info *Info) BuildFromFilePath(root string) (err error) {
38         info.Name = func() string {
39                 b := filepath.Base(root)
40                 switch b {
41                 case ".", "..", string(filepath.Separator):
42                         return NoName
43                 default:
44                         return b
45                 }
46         }()
47         info.Files = nil
48         err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
49                 if err != nil {
50                         return err
51                 }
52                 if fi.IsDir() {
53                         // Directories are implicit in torrent files.
54                         return nil
55                 } else if path == root {
56                         // The root is a file.
57                         info.Length = fi.Size()
58                         return nil
59                 }
60                 relPath, err := filepath.Rel(root, path)
61                 if err != nil {
62                         return fmt.Errorf("error getting relative path: %s", err)
63                 }
64                 info.Files = append(info.Files, FileInfo{
65                         Path:   strings.Split(relPath, string(filepath.Separator)),
66                         Length: fi.Size(),
67                 })
68                 return nil
69         })
70         if err != nil {
71                 return
72         }
73         slices.Sort(info.Files, func(l, r FileInfo) bool {
74                 return strings.Join(l.Path, "/") < strings.Join(r.Path, "/")
75         })
76         err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
77                 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
78         })
79         if err != nil {
80                 err = fmt.Errorf("error generating pieces: %s", err)
81         }
82         return
83 }
84
85 // Concatenates all the files in the torrent into w. open is a function that
86 // gets at the contents of the given file.
87 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
88         for _, fi := range info.UpvertedFiles() {
89                 r, err := open(fi)
90                 if err != nil {
91                         return fmt.Errorf("error opening %v: %s", fi, err)
92                 }
93                 wn, err := io.CopyN(w, r, fi.Length)
94                 r.Close()
95                 if wn != fi.Length {
96                         return fmt.Errorf("error copying %v: %s", fi, err)
97                 }
98         }
99         return nil
100 }
101
102 // Sets Pieces (the block of piece hashes in the Info) by using the passed
103 // function to get at the torrent data.
104 func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) (err error) {
105         if info.PieceLength == 0 {
106                 return errors.New("piece length must be non-zero")
107         }
108         pr, pw := io.Pipe()
109         go func() {
110                 err := info.writeFiles(pw, open)
111                 pw.CloseWithError(err)
112         }()
113         defer pr.Close()
114         info.Pieces, err = GeneratePieces(pr, info.PieceLength, nil)
115         return
116 }
117
118 func (info *Info) TotalLength() (ret int64) {
119         if info.IsDir() {
120                 for _, fi := range info.Files {
121                         ret += fi.Length
122                 }
123         } else {
124                 ret = info.Length
125         }
126         return
127 }
128
129 func (info *Info) NumPieces() int {
130         return len(info.Pieces) / 20
131 }
132
133 func (info *Info) IsDir() bool {
134         return len(info.Files) != 0
135 }
136
137 // The files field, converted up from the old single-file in the parent info
138 // dict if necessary. This is a helper to avoid having to conditionally handle
139 // single and multi-file torrent infos.
140 func (info *Info) UpvertedFiles() []FileInfo {
141         if len(info.Files) == 0 {
142                 return []FileInfo{{
143                         Length: info.Length,
144                         // Callers should determine that Info.Name is the basename, and
145                         // thus a regular file.
146                         Path: nil,
147                 }}
148         }
149         return info.Files
150 }
151
152 func (info *Info) Piece(index int) Piece {
153         return Piece{info, pieceIndex(index)}
154 }