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 func (info *Info) BuildFromFilePath(root string) (err error) {
58 info.Name = filepath.Base(root)
60 err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
61 log.Println(path, root, err)
63 // Directories are implicit in torrent files.
65 } else if path == root {
66 // The root is a file.
67 info.Length = fi.Size()
70 relPath, err := filepath.Rel(root, path)
71 log.Println(relPath, err)
73 return fmt.Errorf("error getting relative path: %s", err)
75 info.Files = append(info.Files, FileInfo{
76 Path: strings.Split(relPath, string(filepath.Separator)),
84 err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
85 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
88 err = fmt.Errorf("error generating pieces: %s", err)
93 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
94 for _, fi := range info.UpvertedFiles() {
97 return fmt.Errorf("error opening %v: %s", fi, err)
99 wn, err := io.CopyN(w, r, fi.Length)
101 if wn != fi.Length || err != nil {
102 return fmt.Errorf("error hashing %v: %s", fi, err)
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")
115 err := info.writeFiles(pw, open)
116 pw.CloseWithError(err)
122 wn, err := io.CopyN(hasher, pr, info.PieceLength)
132 pieces = hasher.Sum(pieces)
133 if wn < info.PieceLength {
141 func (me *Info) TotalLength() (ret int64) {
143 for _, fi := range me.Files {
152 func (me *Info) NumPieces() int {
153 if len(me.Pieces)%20 != 0 {
154 panic(len(me.Pieces))
156 return len(me.Pieces) / 20
159 func (me *InfoEx) Piece(i int) Piece {
163 func (i *Info) IsDir() bool {
164 return len(i.Files) != 0
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 (i *Info) UpvertedFiles() []FileInfo {
171 if len(i.Files) == 0 {
174 // Callers should determine that Info.Name is the basename, and
175 // thus a regular file.
182 // The info dictionary with its hash and raw bytes exposed, as these are
183 // important to Bittorrent.
191 _ bencode.Marshaler = InfoEx{}
192 _ bencode.Unmarshaler = &InfoEx{}
195 func (this *InfoEx) UnmarshalBencode(data []byte) error {
196 this.Bytes = append(make([]byte, 0, len(data)), data...)
198 _, err := h.Write(this.Bytes)
202 this.Hash = new(Hash)
203 missinggo.CopyExact(this.Hash, h.Sum(nil))
204 return bencode.Unmarshal(data, &this.Info)
207 func (this InfoEx) MarshalBencode() ([]byte, error) {
208 if this.Bytes != nil {
209 return this.Bytes, nil
211 return bencode.Marshal(&this.Info)
214 type MetaInfo struct {
215 Info InfoEx `bencode:"info"`
216 Announce string `bencode:"announce,omitempty"`
217 AnnounceList [][]string `bencode:"announce-list,omitempty"`
218 Nodes []Node `bencode:"nodes,omitempty"`
219 CreationDate int64 `bencode:"creation date,omitempty"`
220 Comment string `bencode:"comment,omitempty"`
221 CreatedBy string `bencode:"created by,omitempty"`
222 Encoding string `bencode:"encoding,omitempty"`
223 URLList interface{} `bencode:"url-list,omitempty"`
226 // Encode to bencoded form.
227 func (mi *MetaInfo) Write(w io.Writer) error {
228 return bencode.NewEncoder(w).Encode(mi)
231 // Set good default values in preparation for creating a new MetaInfo file.
232 func (mi *MetaInfo) SetDefaults() {
233 mi.Comment = "yoloham"
234 mi.CreatedBy = "github.com/anacrolix/torrent"
235 mi.CreationDate = time.Now().Unix()
236 mi.Info.PieceLength = 256 * 1024
239 // Magnetize creates a Magnet from a MetaInfo
240 func (mi *MetaInfo) Magnet() (m Magnet) {
241 for _, tier := range mi.AnnounceList {
242 for _, tracker := range tier {
243 m.Trackers = append(m.Trackers, tracker)
246 m.DisplayName = mi.Info.Name
247 m.InfoHash = *mi.Info.Hash