-
Notifications
You must be signed in to change notification settings - Fork 70
/
info.go
88 lines (81 loc) · 2.49 KB
/
info.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package metainfo
import (
"crypto/sha1" // nolint: gosec
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/zeebo/bencode"
)
// Info contains information about torrent.
type Info struct {
PieceLength uint32 `bencode:"piece length" json:"piece_length"`
Pieces []byte `bencode:"pieces" json:"pieces"`
Private byte `bencode:"private" json:"private"`
Name string `bencode:"name" json:"name"`
Length int64 `bencode:"length" json:"length"` // Single File Mode
Files []FileDict `bencode:"files" json:"files"` // Multiple File mode
// Calculated fileds
Hash [20]byte `bencode:"-" json:"-"`
PieceHashes [][]byte `bencode:"-" json:"-"`
TotalLength int64 `bencode:"-" json:"-"`
NumPieces uint32 `bencode:"-" json:"-"`
MultiFile bool `bencode:"-" json:"-"`
InfoSize uint32 `bencode:"-" json:"-"`
Bytes []byte `bencode:"-" json:"-"`
}
type FileDict struct {
Length int64 `bencode:"length" json:"length"`
Path []string `bencode:"path" json:"path"`
}
// NewInfo returns info from bencoded bytes in b.
func NewInfo(b []byte) (*Info, error) {
var i Info
if err := bencode.DecodeBytes(b, &i); err != nil {
return nil, err
}
if uint32(len(i.Pieces))%sha1.Size != 0 {
return nil, errors.New("invalid piece data")
}
// ".." is not allowed in file names
for _, file := range i.Files {
for _, path := range file.Path {
if strings.TrimSpace(path) == ".." {
return nil, fmt.Errorf("invalid file name: %q", filepath.Join(file.Path...))
}
}
}
i.NumPieces = uint32(len(i.Pieces)) / sha1.Size
i.MultiFile = len(i.Files) != 0
if !i.MultiFile {
i.TotalLength = i.Length
} else {
for _, f := range i.Files {
i.TotalLength += f.Length
}
}
totalPieceDataLength := int64(i.PieceLength) * int64(i.NumPieces)
delta := totalPieceDataLength - i.TotalLength
if delta >= int64(i.PieceLength) || delta < 0 {
return nil, errors.New("invalid piece data")
}
i.PieceHashes = make([][]byte, i.NumPieces)
for idx := uint32(0); idx < i.NumPieces; idx++ {
begin := idx * sha1.Size
end := begin + sha1.Size
i.PieceHashes[idx] = i.Pieces[begin:end]
}
i.InfoSize = uint32(len(b))
i.Bytes = b
hash := sha1.New() // nolint: gosec
hash.Write(b) // nolint: gosec
copy(i.Hash[:], hash.Sum(nil))
return &i, nil
}
// GetFiles returns the files in torrent as a slice, even if there is a single file.
func (i *Info) GetFiles() []FileDict {
if i.MultiFile {
return i.Files
}
return []FileDict{{i.Length, []string{i.Name}}}
}