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 func newRequestFromMessage(msg *pp.Message) request {
26 case pp.Request, pp.Cancel, pp.Reject:
27 return newRequest(msg.Index, msg.Begin, msg.Length)
29 return newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
35 // The size in bytes of a metadata extension piece.
36 func metadataPieceSize(totalSize int, piece int) int {
37 ret := totalSize - piece*(1<<14)
44 // Return the request that would include the given offset into the torrent data.
45 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
47 if offset < 0 || offset >= torrentLength {
50 r.Index = pp.Integer(offset / pieceSize)
51 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
52 r.Length = pp.Integer(chunkSize)
53 pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
54 if r.Length > pieceLeft {
57 torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
58 if int64(r.Length) > torrentLeft {
59 r.Length = pp.Integer(torrentLeft)
65 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
66 off = int64(r.Index)*pieceSize + int64(r.Begin)
67 if off < 0 || off >= torrentLength {
68 panic("invalid request")
73 func validateInfo(info *metainfo.Info) error {
74 if len(info.Pieces)%20 != 0 {
75 return errors.New("pieces has invalid length")
77 if info.PieceLength == 0 {
78 if info.TotalLength() != 0 {
79 return errors.New("zero piece length")
82 if int((info.TotalLength()+info.PieceLength-1)/info.PieceLength) != info.NumPieces() {
83 return errors.New("piece count and file lengths are at odds")
89 func chunkIndexSpec(index int, pieceLength, chunkSize pp.Integer) chunkSpec {
90 ret := chunkSpec{pp.Integer(index) * chunkSize, chunkSize}
91 if ret.Begin+ret.Length > pieceLength {
92 ret.Length = pieceLength - ret.Begin
97 func connLessTrusted(l, r *connection) bool {
98 return l.netGoodPiecesDirtied() < r.netGoodPiecesDirtied()
101 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
102 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
103 func addrCompactIP(addr net.Addr) (string, error) {
104 host, _, err := net.SplitHostPort(addr.String())
108 ip := net.ParseIP(host)
109 if v4 := ip.To4(); v4 != nil {
113 return string(v4), nil
115 return string(ip.To16()), nil