7 "github.com/anacrolix/missinggo/v2"
8 "golang.org/x/time/rate"
10 "github.com/anacrolix/torrent/metainfo"
11 pp "github.com/anacrolix/torrent/peer_protocol"
14 type chunkSpec struct {
15 Begin, Length pp.Integer
23 func (r request) ToMsg(mt pp.MessageType) pp.Message {
32 func newRequest(index, begin, length pp.Integer) request {
33 return request{index, chunkSpec{begin, length}}
36 func newRequestFromMessage(msg *pp.Message) request {
38 case pp.Request, pp.Cancel, pp.Reject:
39 return newRequest(msg.Index, msg.Begin, msg.Length)
41 return newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
47 // The size in bytes of a metadata extension piece.
48 func metadataPieceSize(totalSize int, piece int) int {
49 ret := totalSize - piece*(1<<14)
56 // Return the request that would include the given offset into the torrent data.
57 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
59 if offset < 0 || offset >= torrentLength {
62 r.Index = pp.Integer(offset / pieceSize)
63 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
64 r.Length = pp.Integer(chunkSize)
65 pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
66 if r.Length > pieceLeft {
69 torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
70 if int64(r.Length) > torrentLeft {
71 r.Length = pp.Integer(torrentLeft)
77 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
78 off = int64(r.Index)*pieceSize + int64(r.Begin)
79 if off < 0 || off >= torrentLength {
80 panic("invalid request")
85 func validateInfo(info *metainfo.Info) error {
86 if len(info.Pieces)%20 != 0 {
87 return errors.New("pieces has invalid length")
89 if info.PieceLength == 0 {
90 if info.TotalLength() != 0 {
91 return errors.New("zero piece length")
94 if int((info.TotalLength()+info.PieceLength-1)/info.PieceLength) != info.NumPieces() {
95 return errors.New("piece count and file lengths are at odds")
101 func chunkIndexSpec(index pp.Integer, pieceLength, chunkSize pp.Integer) chunkSpec {
102 ret := chunkSpec{pp.Integer(index) * chunkSize, chunkSize}
103 if ret.Begin+ret.Length > pieceLength {
104 ret.Length = pieceLength - ret.Begin
109 func connLessTrusted(l, r *connection) bool {
110 return l.trust().Less(r.trust())
113 func connIsIpv6(nc interface {
117 rip := missinggo.AddrIP(ra)
118 return rip.To4() == nil && rip.To16() != nil
121 func clamp(min, value, max int64) int64 {
134 func max(as ...int64) int64 {
136 for _, a := range as[1:] {
144 func min(as ...int64) int64 {
146 for _, a := range as[1:] {
154 var unlimited = rate.NewLimiter(rate.Inf, 0)
158 InfoHash = metainfo.Hash
159 IpPort = missinggo.IpPort