14 "github.com/anacrolix/missinggo"
16 "github.com/anacrolix/torrent/bencode"
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"`
25 // Load a MetaInfo from an io.Reader. Returns a non-nil error in case of
27 func Load(r io.Reader) (*MetaInfo, error) {
29 d := bencode.NewDecoder(r)
37 // Convenience function for loading a MetaInfo from a file.
38 func LoadFromFile(filename string) (*MetaInfo, error) {
39 f, err := os.Open(filename)
47 // The info dictionary.
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"`
57 // This is a helper that sets Files and Pieces from a root path and its
59 func (info *Info) BuildFromFilePath(root string) (err error) {
60 info.Name = filepath.Base(root)
62 err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
63 log.Println(path, root, err)
65 // Directories are implicit in torrent files.
67 } else if path == root {
68 // The root is a file.
69 info.Length = fi.Size()
72 relPath, err := filepath.Rel(root, path)
73 log.Println(relPath, err)
75 return fmt.Errorf("error getting relative path: %s", err)
77 info.Files = append(info.Files, FileInfo{
78 Path: strings.Split(relPath, string(filepath.Separator)),
86 err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
87 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
90 err = fmt.Errorf("error generating pieces: %s", err)
95 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
96 for _, fi := range info.UpvertedFiles() {
99 return fmt.Errorf("error opening %v: %s", fi, err)
101 wn, err := io.CopyN(w, r, fi.Length)
103 if wn != fi.Length || err != nil {
104 return fmt.Errorf("error hashing %v: %s", fi, err)
110 // Set info.Pieces by hashing info.Files.
111 func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) error {
112 if info.PieceLength == 0 {
113 return errors.New("piece length must be non-zero")
117 err := info.writeFiles(pw, open)
118 pw.CloseWithError(err)
124 wn, err := io.CopyN(hasher, pr, info.PieceLength)
134 pieces = hasher.Sum(pieces)
135 if wn < info.PieceLength {
143 func (info *Info) TotalLength() (ret int64) {
145 for _, fi := range info.Files {
154 func (info *Info) NumPieces() int {
155 if len(info.Pieces)%20 != 0 {
156 panic(len(info.Pieces))
158 return len(info.Pieces) / 20
161 func (info *InfoEx) Piece(i int) Piece {
162 return Piece{info, i}
165 func (info *Info) IsDir() bool {
166 return len(info.Files) != 0
169 // The files field, converted up from the old single-file in the parent info
170 // dict if necessary. This is a helper to avoid having to conditionally handle
171 // single and multi-file torrent infos.
172 func (info *Info) UpvertedFiles() []FileInfo {
173 if len(info.Files) == 0 {
176 // Callers should determine that Info.Name is the basename, and
177 // thus a regular file.
184 // The info dictionary with its hash and raw bytes exposed, as these are
185 // important to Bittorrent.
188 Hash Hash // Only set when unmarshalling or UpdateHash.
189 Bytes []byte // Only set when unmarshalling or UpdateBytes.
193 _ bencode.Marshaler = InfoEx{}
194 _ bencode.Unmarshaler = &InfoEx{}
197 func (ie *InfoEx) UnmarshalBencode(data []byte) error {
198 ie.Bytes = append([]byte(nil), data...)
200 _, err := h.Write(ie.Bytes)
204 missinggo.CopyExact(&ie.Hash, h.Sum(nil))
205 return bencode.Unmarshal(data, &ie.Info)
208 func (ie InfoEx) MarshalBencode() ([]byte, error) {
209 return bencode.Marshal(&ie.Info)
212 type MetaInfo struct {
213 Info InfoEx `bencode:"info"`
214 Announce string `bencode:"announce,omitempty"`
215 AnnounceList [][]string `bencode:"announce-list,omitempty"`
216 Nodes []Node `bencode:"nodes,omitempty"`
217 CreationDate int64 `bencode:"creation date,omitempty"`
218 Comment string `bencode:"comment,omitempty"`
219 CreatedBy string `bencode:"created by,omitempty"`
220 Encoding string `bencode:"encoding,omitempty"`
221 URLList interface{} `bencode:"url-list,omitempty"`
224 // Encode to bencoded form.
225 func (mi *MetaInfo) Write(w io.Writer) error {
226 return bencode.NewEncoder(w).Encode(mi)
229 // Set good default values in preparation for creating a new MetaInfo file.
230 func (mi *MetaInfo) SetDefaults() {
231 mi.Comment = "yoloham"
232 mi.CreatedBy = "github.com/anacrolix/torrent"
233 mi.CreationDate = time.Now().Unix()
234 mi.Info.PieceLength = 256 * 1024
237 // Magnetize creates a Magnet from a MetaInfo
238 func (mi *MetaInfo) Magnet() (m Magnet) {
239 for _, tier := range mi.AnnounceList {
240 for _, tracker := range tier {
241 m.Trackers = append(m.Trackers, tracker)
244 m.DisplayName = mi.Info.Name
245 m.InfoHash = mi.Info.Hash