]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/metainfo.go
Allow encoding private=0 in metainfo, which fixes test for not using InfoEx.Bytes...
[btrtrc.git] / metainfo / metainfo.go
1 package metainfo
2
3 import (
4         "crypto/sha1"
5         "errors"
6         "fmt"
7         "io"
8         "log"
9         "os"
10         "path/filepath"
11         "strings"
12         "time"
13
14         "github.com/anacrolix/missinggo"
15
16         "github.com/anacrolix/torrent/bencode"
17 )
18
19 // Information specific to a single file inside the MetaInfo structure.
20 type FileInfo struct {
21         Length int64    `bencode:"length"`
22         Path   []string `bencode:"path"`
23 }
24
25 // Load a MetaInfo from an io.Reader. Returns a non-nil error in case of
26 // failure.
27 func Load(r io.Reader) (*MetaInfo, error) {
28         var mi MetaInfo
29         d := bencode.NewDecoder(r)
30         err := d.Decode(&mi)
31         if err != nil {
32                 return nil, err
33         }
34         return &mi, nil
35 }
36
37 // Convenience function for loading a MetaInfo from a file.
38 func LoadFromFile(filename string) (*MetaInfo, error) {
39         f, err := os.Open(filename)
40         if err != nil {
41                 return nil, err
42         }
43         defer f.Close()
44         return Load(f)
45 }
46
47 // The info dictionary.
48 type Info struct {
49         PieceLength int64      `bencode:"piece length"`
50         Pieces      []byte     `bencode:"pieces"`
51         Name        string     `bencode:"name"`
52         Length      int64      `bencode:"length,omitempty"`
53         Private     *bool      `bencode:"private,omitempty"`
54         Files       []FileInfo `bencode:"files,omitempty"`
55 }
56
57 func (info *Info) BuildFromFilePath(root string) (err error) {
58         info.Name = filepath.Base(root)
59         info.Files = nil
60         err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
61                 log.Println(path, root, err)
62                 if fi.IsDir() {
63                         // Directories are implicit in torrent files.
64                         return nil
65                 } else if path == root {
66                         // The root is a file.
67                         info.Length = fi.Size()
68                         return nil
69                 }
70                 relPath, err := filepath.Rel(root, path)
71                 log.Println(relPath, err)
72                 if err != nil {
73                         return fmt.Errorf("error getting relative path: %s", err)
74                 }
75                 info.Files = append(info.Files, FileInfo{
76                         Path:   strings.Split(relPath, string(filepath.Separator)),
77                         Length: fi.Size(),
78                 })
79                 return nil
80         })
81         if err != nil {
82                 return
83         }
84         err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
85                 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
86         })
87         if err != nil {
88                 err = fmt.Errorf("error generating pieces: %s", err)
89         }
90         return
91 }
92
93 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
94         for _, fi := range info.UpvertedFiles() {
95                 r, err := open(fi)
96                 if err != nil {
97                         return fmt.Errorf("error opening %v: %s", fi, err)
98                 }
99                 wn, err := io.CopyN(w, r, fi.Length)
100                 r.Close()
101                 if wn != fi.Length || err != nil {
102                         return fmt.Errorf("error hashing %v: %s", fi, err)
103                 }
104         }
105         return nil
106 }
107
108 // Set info.Pieces by hashing info.Files.
109 func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) error {
110         if info.PieceLength == 0 {
111                 return errors.New("piece length must be non-zero")
112         }
113         pr, pw := io.Pipe()
114         go func() {
115                 err := info.writeFiles(pw, open)
116                 pw.CloseWithError(err)
117         }()
118         defer pr.Close()
119         var pieces []byte
120         for {
121                 hasher := sha1.New()
122                 wn, err := io.CopyN(hasher, pr, info.PieceLength)
123                 if err == io.EOF {
124                         err = nil
125                 }
126                 if err != nil {
127                         return err
128                 }
129                 if wn == 0 {
130                         break
131                 }
132                 pieces = hasher.Sum(pieces)
133                 if wn < info.PieceLength {
134                         break
135                 }
136         }
137         info.Pieces = pieces
138         return nil
139 }
140
141 func (info *Info) TotalLength() (ret int64) {
142         if info.IsDir() {
143                 for _, fi := range info.Files {
144                         ret += fi.Length
145                 }
146         } else {
147                 ret = info.Length
148         }
149         return
150 }
151
152 func (info *Info) NumPieces() int {
153         if len(info.Pieces)%20 != 0 {
154                 panic(len(info.Pieces))
155         }
156         return len(info.Pieces) / 20
157 }
158
159 func (info *InfoEx) Piece(i int) Piece {
160         return Piece{info, i}
161 }
162
163 func (info *Info) IsDir() bool {
164         return len(info.Files) != 0
165 }
166
167 // The files field, converted up from the old single-file in the parent info
168 // dict if necessary. This is a helper to avoid having to conditionally handle
169 // single and multi-file torrent infos.
170 func (info *Info) UpvertedFiles() []FileInfo {
171         if len(info.Files) == 0 {
172                 return []FileInfo{{
173                         Length: info.Length,
174                         // Callers should determine that Info.Name is the basename, and
175                         // thus a regular file.
176                         Path: nil,
177                 }}
178         }
179         return info.Files
180 }
181
182 // The info dictionary with its hash and raw bytes exposed, as these are
183 // important to Bittorrent.
184 type InfoEx struct {
185         Info
186         Hash  Hash   // Only set when unmarshalling or UpdateHash.
187         Bytes []byte // Only set when unmarshalling or UpdateBytes.
188 }
189
190 var (
191         _ bencode.Marshaler   = InfoEx{}
192         _ bencode.Unmarshaler = &InfoEx{}
193 )
194
195 func (ie *InfoEx) UnmarshalBencode(data []byte) error {
196         ie.Bytes = append([]byte(nil), data...)
197         h := sha1.New()
198         _, err := h.Write(ie.Bytes)
199         if err != nil {
200                 panic(err)
201         }
202         missinggo.CopyExact(&ie.Hash, h.Sum(nil))
203         return bencode.Unmarshal(data, &ie.Info)
204 }
205
206 func (ie InfoEx) MarshalBencode() ([]byte, error) {
207         return bencode.Marshal(&ie.Info)
208 }
209
210 type MetaInfo struct {
211         Info         InfoEx      `bencode:"info"`
212         Announce     string      `bencode:"announce,omitempty"`
213         AnnounceList [][]string  `bencode:"announce-list,omitempty"`
214         Nodes        []Node      `bencode:"nodes,omitempty"`
215         CreationDate int64       `bencode:"creation date,omitempty"`
216         Comment      string      `bencode:"comment,omitempty"`
217         CreatedBy    string      `bencode:"created by,omitempty"`
218         Encoding     string      `bencode:"encoding,omitempty"`
219         URLList      interface{} `bencode:"url-list,omitempty"`
220 }
221
222 // Encode to bencoded form.
223 func (mi *MetaInfo) Write(w io.Writer) error {
224         return bencode.NewEncoder(w).Encode(mi)
225 }
226
227 // Set good default values in preparation for creating a new MetaInfo file.
228 func (mi *MetaInfo) SetDefaults() {
229         mi.Comment = "yoloham"
230         mi.CreatedBy = "github.com/anacrolix/torrent"
231         mi.CreationDate = time.Now().Unix()
232         mi.Info.PieceLength = 256 * 1024
233 }
234
235 // Magnetize creates a Magnet from a MetaInfo
236 func (mi *MetaInfo) Magnet() (m Magnet) {
237         for _, tier := range mi.AnnounceList {
238                 for _, tracker := range tier {
239                         m.Trackers = append(m.Trackers, tracker)
240                 }
241         }
242         m.DisplayName = mi.Info.Name
243         m.InfoHash = mi.Info.Hash
244         return
245 }