7 "github.com/anacrolix/missinggo"
8 "github.com/anacrolix/torrent/metainfo"
9 pp "github.com/anacrolix/torrent/peer_protocol"
12 type chunkSpec struct {
13 Begin, Length pp.Integer
21 func (r request) ToMsg(mt pp.MessageType) pp.Message {
30 func newRequest(index, begin, length pp.Integer) request {
31 return request{index, chunkSpec{begin, length}}
34 func newRequestFromMessage(msg *pp.Message) request {
36 case pp.Request, pp.Cancel, pp.Reject:
37 return newRequest(msg.Index, msg.Begin, msg.Length)
39 return newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
45 // The size in bytes of a metadata extension piece.
46 func metadataPieceSize(totalSize int, piece int) int {
47 ret := totalSize - piece*(1<<14)
54 // Return the request that would include the given offset into the torrent data.
55 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
57 if offset < 0 || offset >= torrentLength {
60 r.Index = pp.Integer(offset / pieceSize)
61 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
62 r.Length = pp.Integer(chunkSize)
63 pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
64 if r.Length > pieceLeft {
67 torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
68 if int64(r.Length) > torrentLeft {
69 r.Length = pp.Integer(torrentLeft)
75 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
76 off = int64(r.Index)*pieceSize + int64(r.Begin)
77 if off < 0 || off >= torrentLength {
78 panic("invalid request")
83 func validateInfo(info *metainfo.Info) error {
84 if len(info.Pieces)%20 != 0 {
85 return errors.New("pieces has invalid length")
87 if info.PieceLength == 0 {
88 if info.TotalLength() != 0 {
89 return errors.New("zero piece length")
92 if int((info.TotalLength()+info.PieceLength-1)/info.PieceLength) != info.NumPieces() {
93 return errors.New("piece count and file lengths are at odds")
99 func chunkIndexSpec(index int, pieceLength, chunkSize pp.Integer) chunkSpec {
100 ret := chunkSpec{pp.Integer(index) * chunkSize, chunkSize}
101 if ret.Begin+ret.Length > pieceLength {
102 ret.Length = pieceLength - ret.Begin
107 func connLessTrusted(l, r *connection) bool {
108 return l.netGoodPiecesDirtied() < r.netGoodPiecesDirtied()
111 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
112 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
113 func addrCompactIP(addr net.Addr) (string, error) {
114 host, _, err := net.SplitHostPort(addr.String())
118 ip := net.ParseIP(host)
119 if v4 := ip.To4(); v4 != nil {
123 return string(v4), nil
125 return string(ip.To16()), nil
128 func connIsIpv6(nc interface {
132 rip := missinggo.AddrIP(ra)
133 return rip.To4() == nil && rip.To16() != nil
136 func clamp(min, value, max int64) int64 {
149 func max(as ...int64) int64 {
151 for _, a := range as[1:] {
159 func min(as ...int64) int64 {
161 for _, a := range as[1:] {