7 "github.com/anacrolix/torrent/metainfo"
8 pp "github.com/anacrolix/torrent/peer_protocol"
11 type chunkSpec struct {
12 Begin, Length pp.Integer
20 func newRequest(index, begin, length pp.Integer) request {
21 return request{index, chunkSpec{begin, length}}
24 // The size in bytes of a metadata extension piece.
25 func metadataPieceSize(totalSize int, piece int) int {
26 ret := totalSize - piece*(1<<14)
33 // Return the request that would include the given offset into the torrent data.
34 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
36 if offset < 0 || offset >= torrentLength {
39 r.Index = pp.Integer(offset / pieceSize)
40 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
41 r.Length = pp.Integer(chunkSize)
42 pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
43 if r.Length > pieceLeft {
46 torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
47 if int64(r.Length) > torrentLeft {
48 r.Length = pp.Integer(torrentLeft)
54 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
55 off = int64(r.Index)*pieceSize + int64(r.Begin)
56 if off < 0 || off >= torrentLength {
57 panic("invalid request")
62 func validateInfo(info *metainfo.Info) error {
63 if len(info.Pieces)%20 != 0 {
64 return errors.New("pieces has invalid length")
66 if info.PieceLength == 0 {
67 if info.TotalLength() != 0 {
68 return errors.New("zero piece length")
71 if int((info.TotalLength()+info.PieceLength-1)/info.PieceLength) != info.NumPieces() {
72 return errors.New("piece count and file lengths are at odds")
78 func chunkIndexSpec(index int, pieceLength, chunkSize pp.Integer) chunkSpec {
79 ret := chunkSpec{pp.Integer(index) * chunkSize, chunkSize}
80 if ret.Begin+ret.Length > pieceLength {
81 ret.Length = pieceLength - ret.Begin
86 func connLessTrusted(l, r *connection) bool {
87 return l.netGoodPiecesDirtied() < r.netGoodPiecesDirtied()
90 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
91 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
92 func addrCompactIP(addr net.Addr) (string, error) {
93 host, _, err := net.SplitHostPort(addr.String())
97 ip := net.ParseIP(host)
98 if v4 := ip.To4(); v4 != nil {
102 return string(v4), nil
104 return string(ip.To16()), nil