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