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
164 func (me Piece) Length() int64 {
165 if me.i == me.Info.NumPieces()-1 {
166 return me.Info.TotalLength() - int64(me.i)*me.Info.PieceLength
168 return me.Info.PieceLength
171 func (me Piece) Offset() int64 {
172 return int64(me.i) * me.Info.PieceLength
175 func (me Piece) Hash() (ret InfoHash) {
176 missinggo.CopyExact(&ret, me.Info.Pieces[me.i*20:(me.i+1)*20])
180 func (me *Info) Piece(i int) Piece {
184 func (i *Info) IsDir() bool {
185 return len(i.Files) != 0
188 // The files field, converted up from the old single-file in the parent info
189 // dict if necessary. This is a helper to avoid having to conditionally handle
190 // single and multi-file torrent infos.
191 func (i *Info) UpvertedFiles() []FileInfo {
192 if len(i.Files) == 0 {
195 // Callers should determine that Info.Name is the basename, and
196 // thus a regular file.
203 // The info dictionary with its hash and raw bytes exposed, as these are
204 // important to Bittorrent.
212 _ bencode.Marshaler = InfoEx{}
213 _ bencode.Unmarshaler = &InfoEx{}
216 func (this *InfoEx) UnmarshalBencode(data []byte) error {
217 this.Bytes = make([]byte, 0, len(data))
218 this.Bytes = append(this.Bytes, data...)
220 _, err := h.Write(this.Bytes)
224 this.Hash = h.Sum(nil)
225 return bencode.Unmarshal(data, &this.Info)
228 func (this InfoEx) MarshalBencode() ([]byte, error) {
229 if this.Bytes != nil {
230 return this.Bytes, nil
232 return bencode.Marshal(&this.Info)
235 type MetaInfo struct {
236 Info InfoEx `bencode:"info"`
237 Announce string `bencode:"announce,omitempty"`
238 AnnounceList [][]string `bencode:"announce-list,omitempty"`
239 Nodes []Node `bencode:"nodes,omitempty"`
240 CreationDate int64 `bencode:"creation date,omitempty"`
241 Comment string `bencode:"comment,omitempty"`
242 CreatedBy string `bencode:"created by,omitempty"`
243 Encoding string `bencode:"encoding,omitempty"`
244 URLList interface{} `bencode:"url-list,omitempty"`
247 // Encode to bencoded form.
248 func (mi *MetaInfo) Write(w io.Writer) error {
249 return bencode.NewEncoder(w).Encode(mi)
252 // Set good default values in preparation for creating a new MetaInfo file.
253 func (mi *MetaInfo) SetDefaults() {
254 mi.Comment = "yoloham"
255 mi.CreatedBy = "github.com/anacrolix/torrent"
256 mi.CreationDate = time.Now().Unix()
257 mi.Info.PieceLength = 256 * 1024
260 type InfoHash [20]byte