17 "github.com/anacrolix/dht"
18 "github.com/anacrolix/log"
20 "github.com/anacrolix/missinggo"
21 "github.com/anacrolix/missinggo/bitmap"
22 "github.com/anacrolix/missinggo/iter"
23 "github.com/anacrolix/missinggo/prioritybitmap"
25 "github.com/anacrolix/torrent/bencode"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
30 type peerSource string
33 peerSourceTracker = "Tr"
34 peerSourceIncoming = "I"
35 peerSourceDHTGetPeers = "Hg" // Peers we found by searching a DHT.
36 peerSourceDHTAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
40 // Maintains the state of a connection with a peer.
41 type connection struct {
42 // First to ensure 64-bit alignment for atomics. See #262.
46 // The actual Conn, used for closing, and setting socket options.
49 // The Reader and Writer for this Conn, with hooks installed for stats,
50 // limiting, deadlines etc.
53 // True if the connection is operating over MSE obfuscation.
55 cryptoMethod mse.CryptoMethod
57 closed missinggo.Event
58 // Set true after we've added our ConnStats generated during handshake to
59 // other ConnStat instances as determined when the *Torrent became known.
60 reconciledHandshakeStats bool
62 lastMessageReceived time.Time
63 completedHandshake time.Time
64 lastUsefulChunkReceived time.Time
65 lastChunkSent time.Time
67 // Stuff controlled by the local peer.
69 lastBecameInterested time.Time
70 priorInterest time.Duration
72 lastStartedExpectingToReceiveChunks time.Time
73 cumulativeExpectedToReceiveChunks time.Duration
74 chunksReceivedWhileExpecting int64
77 requests map[request]struct{}
79 // Chunks that we might reasonably expect to receive from the peer. Due to
80 // latency, buffering, and implementation differences, we may receive
81 // chunks that are no longer in the set of requests actually want.
82 validReceiveChunks map[request]struct{}
83 // Indexed by metadata piece, set to true if posted and pending a
85 metadataRequests []bool
86 sentHaves bitmap.Bitmap
88 // Stuff controlled by the remote peer.
92 PeerRequests map[request]struct{}
93 PeerExtensionBytes pp.PeerExtensionBits
94 // The pieces the peer has claimed to have.
95 peerPieces bitmap.Bitmap
96 // The peer has everything. This can occur due to a special message, when
97 // we may not even know the number of pieces in the torrent yet.
99 // The highest possible number of pieces the torrent could have based on
100 // communication with the peer. Generally only useful until we have the
103 // Pieces we've accepted chunks for from the peer.
104 peerTouchedPieces map[int]struct{}
105 peerAllowedFast bitmap.Bitmap
107 PeerMaxRequests int // Maximum pending requests the peer allows.
108 PeerExtensionIDs map[string]byte
109 PeerClientName string
111 pieceInclination []int
112 pieceRequestOrder prioritybitmap.PriorityBitmap
114 writeBuffer *bytes.Buffer
115 uploadTimer *time.Timer
119 func (cn *connection) updateExpectingChunks() {
120 if cn.expectingChunks() {
121 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
122 cn.lastStartedExpectingToReceiveChunks = time.Now()
125 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
126 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
127 cn.lastStartedExpectingToReceiveChunks = time.Time{}
132 func (cn *connection) expectingChunks() bool {
133 return cn.Interested && !cn.PeerChoked
136 // Returns true if the connection is over IPv6.
137 func (cn *connection) ipv6() bool {
138 ip := missinggo.AddrIP(cn.remoteAddr())
142 return len(ip) == net.IPv6len
145 // Returns true the dialer has the lower client peer ID. TODO: Find the
146 // specification for this.
147 func (cn *connection) isPreferredDirection() bool {
148 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
151 // Returns whether the left connection should be preferred over the right one,
152 // considering only their networking properties. If ok is false, we can't
154 func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) {
156 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
157 ml.NextBool(!l.utp(), !r.utp())
158 ml.NextBool(l.ipv6(), r.ipv6())
162 func (cn *connection) cumInterest() time.Duration {
163 ret := cn.priorInterest
165 ret += time.Since(cn.lastBecameInterested)
170 func (cn *connection) peerHasAllPieces() (all bool, known bool) {
171 if cn.peerSentHaveAll {
174 if !cn.t.haveInfo() {
177 return bitmap.Flip(cn.peerPieces, 0, cn.t.numPieces()).IsEmpty(), true
180 func (cn *connection) mu() sync.Locker {
184 func (cn *connection) remoteAddr() net.Addr {
185 return cn.conn.RemoteAddr()
188 func (cn *connection) localAddr() net.Addr {
189 return cn.conn.LocalAddr()
192 func (cn *connection) supportsExtension(ext string) bool {
193 _, ok := cn.PeerExtensionIDs[ext]
197 // The best guess at number of pieces in the torrent for this peer.
198 func (cn *connection) bestPeerNumPieces() int {
200 return cn.t.numPieces()
202 return cn.peerMinPieces
205 func (cn *connection) completedString() string {
206 have := cn.peerPieces.Len()
207 if cn.peerSentHaveAll {
208 have = cn.bestPeerNumPieces()
210 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
213 // Correct the PeerPieces slice length. Return false if the existing slice is
214 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
216 func (cn *connection) setNumPieces(num int) error {
217 cn.peerPieces.RemoveRange(num, bitmap.ToEnd)
218 cn.peerPiecesChanged()
222 func eventAgeString(t time.Time) string {
226 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
229 func (cn *connection) connectionFlags() (ret string) {
231 ret += string([]byte{b})
233 if cn.cryptoMethod == mse.CryptoMethodRC4 {
235 } else if cn.headerEncrypted {
238 ret += string(cn.Discovery)
245 func (cn *connection) utp() bool {
246 return strings.Contains(cn.remoteAddr().Network(), "utp")
249 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
250 func (cn *connection) statusFlags() (ret string) {
252 ret += string([]byte{b})
261 ret += cn.connectionFlags()
263 if cn.PeerInterested {
272 // func (cn *connection) String() string {
273 // var buf bytes.Buffer
274 // cn.WriteStatus(&buf, nil)
275 // return buf.String()
278 func (cn *connection) downloadRate() float64 {
279 return float64(cn.stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
282 func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
283 // \t isn't preserved in <pre> blocks?
284 fmt.Fprintf(w, "%+-55q %s %s-%s\n", cn.PeerID, cn.PeerExtensionBytes, cn.localAddr(), cn.remoteAddr())
285 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
286 eventAgeString(cn.lastMessageReceived),
287 eventAgeString(cn.completedHandshake),
288 eventAgeString(cn.lastHelpful()),
290 cn.totalExpectingTime(),
293 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
294 cn.completedString(),
295 len(cn.peerTouchedPieces),
296 &cn.stats.ChunksReadUseful,
297 &cn.stats.ChunksRead,
298 &cn.stats.ChunksWritten,
300 cn.numLocalRequests(),
301 cn.nominalMaxRequests(),
302 len(cn.PeerRequests),
304 cn.downloadRate()/(1<<10),
306 fmt.Fprintf(w, " next pieces: %v%s\n",
307 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
309 if cn.shouldRequestWithoutBias() {
317 func (cn *connection) Close() {
318 if !cn.closed.Set() {
322 cn.discardPieceInclination()
323 cn.pieceRequestOrder.Clear()
329 func (cn *connection) PeerHasPiece(piece int) bool {
330 return cn.peerSentHaveAll || cn.peerPieces.Contains(piece)
333 // Writes a message into the write buffer.
334 func (cn *connection) Post(msg pp.Message) {
335 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
336 // We don't need to track bytes here because a connection.w Writer wrapper
337 // takes care of that (although there's some delay between us recording
338 // the message, and the connection writer flushing it out.).
339 cn.writeBuffer.Write(msg.MustMarshalBinary())
340 // Last I checked only Piece messages affect stats, and we don't post
346 func (cn *connection) requestMetadataPiece(index int) {
347 eID := cn.PeerExtensionIDs["ut_metadata"]
351 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
357 ExtendedPayload: func() []byte {
358 b, err := bencode.Marshal(map[string]int{
359 "msg_type": pp.RequestMetadataExtensionMsgType,
368 for index >= len(cn.metadataRequests) {
369 cn.metadataRequests = append(cn.metadataRequests, false)
371 cn.metadataRequests[index] = true
374 func (cn *connection) requestedMetadataPiece(index int) bool {
375 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
378 // The actual value to use as the maximum outbound requests.
379 func (cn *connection) nominalMaxRequests() (ret int) {
380 if cn.t.requestStrategy == 3 {
381 expectingTime := int64(cn.totalExpectingTime())
382 if expectingTime == 0 {
383 expectingTime = math.MaxInt64
389 int64(cn.PeerMaxRequests),
391 // It makes sense to always pipeline at least one connection,
392 // since latency must be non-zero.
394 // Request only as many as we expect to receive in the
395 // dupliateRequestTimeout window. We are trying to avoid having to
396 // duplicate requests.
397 cn.chunksReceivedWhileExpecting*int64(cn.t.duplicateRequestTimeout)/expectingTime,
403 int64(cn.PeerMaxRequests),
405 cn.stats.ChunksReadUseful.Int64()-(cn.stats.ChunksRead.Int64()-cn.stats.ChunksReadUseful.Int64()))))
408 func (cn *connection) totalExpectingTime() (ret time.Duration) {
409 ret = cn.cumulativeExpectedToReceiveChunks
410 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
411 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
417 func (cn *connection) onPeerSentCancel(r request) {
418 if _, ok := cn.PeerRequests[r]; !ok {
419 torrent.Add("unexpected cancels received", 1)
422 if cn.fastEnabled() {
425 delete(cn.PeerRequests, r)
429 func (cn *connection) Choke(msg messageWriter) (more bool) {
434 more = msg(pp.Message{
437 if cn.fastEnabled() {
438 for r := range cn.PeerRequests {
439 // TODO: Don't reject pieces in allowed fast set.
443 cn.PeerRequests = nil
448 func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
453 return msg(pp.Message{
458 func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
459 if cn.Interested == interested {
462 cn.Interested = interested
464 cn.lastBecameInterested = time.Now()
465 } else if !cn.lastBecameInterested.IsZero() {
466 cn.priorInterest += time.Since(cn.lastBecameInterested)
468 cn.updateExpectingChunks()
469 // log.Printf("%p: setting interest: %v", cn, interested)
470 return msg(pp.Message{
471 Type: func() pp.MessageType {
475 return pp.NotInterested
481 // The function takes a message to be sent, and returns true if more messages
483 type messageWriter func(pp.Message) bool
485 // Proxies the messageWriter's response.
486 func (cn *connection) request(r request, mw messageWriter) bool {
487 if _, ok := cn.requests[r]; ok {
488 panic("chunk already requested")
490 if !cn.PeerHasPiece(r.Index.Int()) {
491 panic("requesting piece peer doesn't have")
493 if _, ok := cn.t.conns[cn]; !ok {
494 panic("requesting but not in active conns")
496 if cn.closed.IsSet() {
497 panic("requesting when connection is closed")
500 if cn.peerAllowedFast.Get(int(r.Index)) {
501 torrent.Add("allowed fast requests sent", 1)
503 panic("requesting while choked and not allowed fast")
506 if cn.t.hashingPiece(pieceIndex(r.Index)) {
507 panic("piece is being hashed")
509 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
510 panic("piece is queued for hash")
512 if cn.requests == nil {
513 cn.requests = make(map[request]struct{})
515 cn.requests[r] = struct{}{}
516 if cn.validReceiveChunks == nil {
517 cn.validReceiveChunks = make(map[request]struct{})
519 cn.validReceiveChunks[r] = struct{}{}
520 cn.t.pendingRequests[r]++
521 cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() {
522 torrent.Add("duplicate request timeouts", 1)
524 defer cn.mu().Unlock()
525 delete(cn.t.lastRequested, r)
526 for cn := range cn.t.conns {
527 if cn.PeerHasPiece(pieceIndex(r.Index)) {
532 cn.updateExpectingChunks()
533 return mw(pp.Message{
541 func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
542 if !cn.t.networkingEnabled {
543 if !cn.SetInterested(false, msg) {
546 if len(cn.requests) != 0 {
547 for r := range cn.requests {
549 // log.Printf("%p: cancelling request: %v", cn, r)
550 if !msg(makeCancelMessage(r)) {
556 if len(cn.requests) <= cn.requestsLowWater {
557 filledBuffer := false
558 cn.iterPendingPieces(func(pieceIndex int) bool {
559 cn.iterPendingRequests(pieceIndex, func(r request) bool {
560 if !cn.SetInterested(true, msg) {
564 if len(cn.requests) >= cn.nominalMaxRequests() {
567 // Choking is looked at here because our interest is dependent
568 // on whether we'd make requests in its absence.
570 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
574 if _, ok := cn.requests[r]; ok {
577 filledBuffer = !cn.request(r, msg)
583 // If we didn't completely top up the requests, we shouldn't mark
584 // the low water, since we'll want to top up the requests as soon
585 // as we have more write buffer space.
588 cn.requestsLowWater = len(cn.requests) / 2
594 // Routine that writes to the peer. Some of what to write is buffered by
595 // activity elsewhere in the Client, and some is determined locally when the
596 // connection is writable.
597 func (cn *connection) writer(keepAliveTimeout time.Duration) {
599 lastWrite time.Time = time.Now()
600 keepAliveTimer *time.Timer
602 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
604 defer cn.mu().Unlock()
605 if time.Since(lastWrite) >= keepAliveTimeout {
608 keepAliveTimer.Reset(keepAliveTimeout)
611 defer cn.mu().Unlock()
613 defer keepAliveTimer.Stop()
614 frontBuf := new(bytes.Buffer)
616 if cn.closed.IsSet() {
619 if cn.writeBuffer.Len() == 0 {
620 cn.fillWriteBuffer(func(msg pp.Message) bool {
622 cn.writeBuffer.Write(msg.MustMarshalBinary())
623 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
624 return cn.writeBuffer.Len() < 1<<16 // 64KiB
627 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
628 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
629 postedKeepalives.Add(1)
631 if cn.writeBuffer.Len() == 0 {
632 // TODO: Minimize wakeups....
637 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
639 n, err := cn.w.Write(frontBuf.Bytes())
642 lastWrite = time.Now()
643 keepAliveTimer.Reset(keepAliveTimeout)
648 if n != frontBuf.Len() {
655 func (cn *connection) Have(piece int) {
656 if cn.sentHaves.Get(piece) {
661 Index: pp.Integer(piece),
663 cn.sentHaves.Add(piece)
666 func (cn *connection) PostBitfield() {
667 if cn.sentHaves.Len() != 0 {
668 panic("bitfield must be first have-related message sent")
670 if !cn.t.haveAnyPieces() {
675 Bitfield: cn.t.bitfield(),
677 cn.sentHaves = cn.t.completedPieces.Copy()
680 func (cn *connection) updateRequests() {
681 // log.Print("update requests")
685 // Emits the indices in the Bitmaps bms in order, never repeating any index.
686 // skip is mutated during execution, and its initial values will never be
688 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
689 return func(cb iter.Callback) {
690 for _, bm := range bms {
691 if !iter.All(func(i interface{}) bool {
694 }, bitmap.Sub(bm, *skip).Iter) {
701 func (cn *connection) iterUnbiasedPieceRequestOrder(f func(piece int) bool) bool {
702 now, readahead := cn.t.readerPiecePriorities()
703 var skip bitmap.Bitmap
704 if !cn.peerSentHaveAll {
705 // Pieces to skip include pieces the peer doesn't have.
706 skip = bitmap.Flip(cn.peerPieces, 0, cn.t.numPieces())
708 // And pieces that we already have.
709 skip.Union(cn.t.completedPieces)
710 skip.Union(cn.t.piecesQueuedForHash)
711 // Return an iterator over the different priority classes, minus the skip
714 func(_piece interface{}) bool {
715 i := _piece.(pieceIndex)
716 if cn.t.hashingPiece(i) {
721 iterBitmapsDistinct(&skip, now, readahead),
722 func(cb iter.Callback) {
723 cn.t.pendingPieces.IterTyped(func(piece int) bool {
724 if skip.Contains(piece) {
735 // The connection should download highest priority pieces first, without any
736 // inclination toward avoiding wastage. Generally we might do this if there's
737 // a single connection, or this is the fastest connection, and we have active
738 // readers that signal an ordering preference. It's conceivable that the best
739 // connection should do this, since it's least likely to waste our time if
740 // assigned to the highest priority pieces, and assigning more than one this
741 // role would cause significant wasted bandwidth.
742 func (cn *connection) shouldRequestWithoutBias() bool {
743 if cn.t.requestStrategy != 2 {
746 if len(cn.t.readers) == 0 {
749 if len(cn.t.conns) == 1 {
752 if cn == cn.t.fastestConn {
758 func (cn *connection) iterPendingPieces(f func(int) bool) bool {
759 if !cn.t.haveInfo() {
762 if cn.t.requestStrategy == 3 {
763 return cn.iterUnbiasedPieceRequestOrder(f)
765 if cn.shouldRequestWithoutBias() {
766 return cn.iterUnbiasedPieceRequestOrder(f)
768 return cn.pieceRequestOrder.IterTyped(f)
772 func (cn *connection) iterPendingPiecesUntyped(f iter.Callback) {
773 cn.iterPendingPieces(func(i int) bool { return f(i) })
776 func (cn *connection) iterPendingRequests(piece int, f func(request) bool) bool {
777 return iterUndirtiedChunks(piece, cn.t, func(cs chunkSpec) bool {
778 r := request{pp.Integer(piece), cs}
779 if cn.t.requestStrategy == 3 {
780 if _, ok := cn.t.lastRequested[r]; ok {
781 // This piece has been requested on another connection, and
782 // the duplicate request timer is still running.
790 func iterUndirtiedChunks(piece int, t *Torrent, f func(chunkSpec) bool) bool {
791 chunkIndices := t.pieces[piece].undirtiedChunkIndices().ToSortedSlice()
792 // TODO: Use "math/rand".Shuffle >= Go 1.10
793 return iter.ForPerm(len(chunkIndices), func(i int) bool {
794 return f(t.chunkIndexSpec(chunkIndices[i], piece))
798 // check callers updaterequests
799 func (cn *connection) stopRequestingPiece(piece int) bool {
800 return cn.pieceRequestOrder.Remove(piece)
803 // This is distinct from Torrent piece priority, which is the user's
804 // preference. Connection piece priority is specific to a connection and is
805 // used to pseudorandomly avoid connections always requesting the same pieces
806 // and thus wasting effort.
807 func (cn *connection) updatePiecePriority(piece int) bool {
808 tpp := cn.t.piecePriority(piece)
809 if !cn.PeerHasPiece(piece) {
810 tpp = PiecePriorityNone
812 if tpp == PiecePriorityNone {
813 return cn.stopRequestingPiece(piece)
815 prio := cn.getPieceInclination()[piece]
816 switch cn.t.requestStrategy {
819 case PiecePriorityNormal:
820 case PiecePriorityReadahead:
821 prio -= cn.t.numPieces()
822 case PiecePriorityNext, PiecePriorityNow:
823 prio -= 2 * cn.t.numPieces()
830 return cn.pieceRequestOrder.Set(piece, prio) || cn.shouldRequestWithoutBias()
833 func (cn *connection) getPieceInclination() []int {
834 if cn.pieceInclination == nil {
835 cn.pieceInclination = cn.t.getConnPieceInclination()
837 return cn.pieceInclination
840 func (cn *connection) discardPieceInclination() {
841 if cn.pieceInclination == nil {
844 cn.t.putPieceInclination(cn.pieceInclination)
845 cn.pieceInclination = nil
848 func (cn *connection) peerPiecesChanged() {
850 prioritiesChanged := false
851 for i := range iter.N(cn.t.numPieces()) {
852 if cn.updatePiecePriority(i) {
853 prioritiesChanged = true
856 if prioritiesChanged {
862 func (cn *connection) raisePeerMinPieces(newMin int) {
863 if newMin > cn.peerMinPieces {
864 cn.peerMinPieces = newMin
868 func (cn *connection) peerSentHave(piece int) error {
869 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
870 return errors.New("invalid piece")
872 if cn.PeerHasPiece(piece) {
875 cn.raisePeerMinPieces(piece + 1)
876 cn.peerPieces.Set(piece, true)
877 if cn.updatePiecePriority(piece) {
883 func (cn *connection) peerSentBitfield(bf []bool) error {
884 cn.peerSentHaveAll = false
886 panic("expected bitfield length divisible by 8")
888 // We know that the last byte means that at most the last 7 bits are
890 cn.raisePeerMinPieces(len(bf) - 7)
891 if cn.t.haveInfo() && len(bf) > cn.t.numPieces() {
892 // Ignore known excess pieces.
893 bf = bf[:cn.t.numPieces()]
895 for i, have := range bf {
897 cn.raisePeerMinPieces(i + 1)
899 cn.peerPieces.Set(i, have)
901 cn.peerPiecesChanged()
905 func (cn *connection) onPeerSentHaveAll() error {
906 cn.peerSentHaveAll = true
907 cn.peerPieces.Clear()
908 cn.peerPiecesChanged()
912 func (cn *connection) peerSentHaveNone() error {
913 cn.peerPieces.Clear()
914 cn.peerSentHaveAll = false
915 cn.peerPiecesChanged()
919 func (c *connection) requestPendingMetadata() {
923 if c.PeerExtensionIDs["ut_metadata"] == 0 {
924 // Peer doesn't support this.
927 // Request metadata pieces that we don't have in a random order.
929 for index := 0; index < c.t.metadataPieceCount(); index++ {
930 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
931 pending = append(pending, index)
934 for _, i := range rand.Perm(len(pending)) {
935 c.requestMetadataPiece(pending[i])
939 func (cn *connection) wroteMsg(msg *pp.Message) {
940 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
941 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
944 func (cn *connection) readMsg(msg *pp.Message) {
945 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
948 // After handshake, we know what Torrent and Client stats to include for a
950 func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
956 // All ConnStats that include this connection. Some objects are not known
957 // until the handshake is complete, after which it's expected to reconcile the
959 func (cn *connection) allStats(f func(*ConnStats)) {
961 if cn.reconciledHandshakeStats {
962 cn.postHandshakeStats(f)
966 func (cn *connection) wroteBytes(n int64) {
967 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
970 func (cn *connection) readBytes(n int64) {
971 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
974 // Returns whether the connection could be useful to us. We're seeding and
975 // they want data, we don't have metainfo and they can provide it, etc.
976 func (c *connection) useful() bool {
978 if c.closed.IsSet() {
982 return c.supportsExtension("ut_metadata")
984 if t.seeding() && c.PeerInterested {
987 if c.peerHasWantedPieces() {
993 func (c *connection) lastHelpful() (ret time.Time) {
994 ret = c.lastUsefulChunkReceived
995 if c.t.seeding() && c.lastChunkSent.After(ret) {
996 ret = c.lastChunkSent
1001 func (c *connection) fastEnabled() bool {
1002 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
1005 func (c *connection) reject(r request) {
1006 if !c.fastEnabled() {
1007 panic("fast not enabled")
1009 c.Post(r.ToMsg(pp.Reject))
1010 delete(c.PeerRequests, r)
1013 func (c *connection) onReadRequest(r request) error {
1014 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1015 if r.Begin+r.Length > c.t.pieceLength(int(r.Index)) {
1016 torrent.Add("bad requests received", 1)
1017 return errors.New("bad request")
1019 if _, ok := c.PeerRequests[r]; ok {
1020 torrent.Add("duplicate requests received", 1)
1024 torrent.Add("requests received while choking", 1)
1025 if c.fastEnabled() {
1026 torrent.Add("requests rejected while choking", 1)
1031 if len(c.PeerRequests) >= maxRequests {
1032 torrent.Add("requests received while queue full", 1)
1033 if c.fastEnabled() {
1036 // BEP 6 says we may close here if we choose.
1039 if !c.t.havePiece(r.Index.Int()) {
1040 // This isn't necessarily them screwing up. We can drop pieces
1041 // from our storage, and can't communicate this to peers
1042 // except by reconnecting.
1043 requestsReceivedForMissingPieces.Add(1)
1044 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1046 if c.PeerRequests == nil {
1047 c.PeerRequests = make(map[request]struct{}, maxRequests)
1049 c.PeerRequests[r] = struct{}{}
1054 // Processes incoming bittorrent messages. The client lock is held upon entry
1055 // and exit. Returning will end the connection.
1056 func (c *connection) mainReadLoop() (err error) {
1059 torrent.Add("connection.mainReadLoop returned with error", 1)
1061 torrent.Add("connection.mainReadLoop returned with no error", 1)
1067 decoder := pp.Decoder{
1068 R: bufio.NewReaderSize(c.r, 1<<17),
1069 MaxLength: 256 * 1024,
1077 err = decoder.Decode(&msg)
1079 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1086 c.lastMessageReceived = time.Now()
1088 receivedKeepalives.Add(1)
1091 messageTypesReceived.Add(msg.Type.String(), 1)
1092 if msg.Type.FastExtension() && !c.fastEnabled() {
1093 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1098 c.deleteAllRequests()
1099 // We can then reset our interest.
1101 c.updateExpectingChunks()
1103 c.deleteRequest(newRequestFromMessage(&msg))
1104 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1106 c.PeerChoked = false
1108 c.updateExpectingChunks()
1110 c.PeerInterested = true
1112 case pp.NotInterested:
1113 c.PeerInterested = false
1114 // We don't clear their requests since it isn't clear in the spec.
1115 // We'll probably choke them for this, which will clear them if
1116 // appropriate, and is clearly specified.
1118 err = c.peerSentHave(int(msg.Index))
1120 r := newRequestFromMessage(&msg)
1121 err = c.onReadRequest(r)
1123 req := newRequestFromMessage(&msg)
1124 c.onPeerSentCancel(req)
1126 err = c.peerSentBitfield(msg.Bitfield)
1128 err = c.onPeerSentHaveAll()
1130 err = c.peerSentHaveNone()
1132 err = c.receiveChunk(&msg)
1133 if len(msg.Piece) == int(t.chunkSize) {
1134 t.chunkPool.Put(&msg.Piece)
1137 err = fmt.Errorf("receiving chunk: %s", err)
1140 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1142 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1147 pingAddr.Port = int(msg.Port)
1149 cl.eachDhtServer(func(s *dht.Server) {
1150 go s.Ping(pingAddr, nil)
1152 case pp.AllowedFast:
1153 torrent.Add("allowed fasts received", 1)
1154 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1155 c.peerAllowedFast.Add(int(msg.Index))
1158 torrent.Add("suggests received", 1)
1159 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1162 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1170 func (c *connection) onReadExtendedMsg(id byte, payload []byte) (err error) {
1172 // TODO: Should we still do this?
1174 // These clients use their own extension IDs for outgoing message
1175 // types, which is incorrect.
1176 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1184 case pp.HandshakeExtendedID:
1185 // TODO: Create a bencode struct for this.
1186 var d map[string]interface{}
1187 err := bencode.Unmarshal(payload, &d)
1189 return fmt.Errorf("error decoding extended message payload: %s", err)
1191 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1192 if reqq, ok := d["reqq"]; ok {
1193 if i, ok := reqq.(int64); ok {
1194 c.PeerMaxRequests = int(i)
1197 if v, ok := d["v"]; ok {
1198 c.PeerClientName = v.(string)
1200 if m, ok := d["m"]; ok {
1201 mTyped, ok := m.(map[string]interface{})
1203 return errors.New("handshake m value is not dict")
1205 if c.PeerExtensionIDs == nil {
1206 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1208 for name, v := range mTyped {
1211 log.Printf("bad handshake m item extension ID type: %T", v)
1215 delete(c.PeerExtensionIDs, name)
1217 if c.PeerExtensionIDs[name] == 0 {
1218 supportedExtensionMessages.Add(name, 1)
1220 c.PeerExtensionIDs[name] = byte(id)
1224 metadata_sizeUntyped, ok := d["metadata_size"]
1226 metadata_size, ok := metadata_sizeUntyped.(int64)
1228 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1230 err = t.setMetadataSize(metadata_size)
1232 return fmt.Errorf("error setting metadata size to %d", metadata_size)
1236 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1237 c.requestPendingMetadata()
1240 case metadataExtendedId:
1241 err := cl.gotMetadataExtensionMsg(payload, t, c)
1243 return fmt.Errorf("error handling metadata extension message: %s", err)
1247 if cl.config.DisablePEX {
1248 // TODO: Maybe close the connection. Check that we're not
1249 // advertising that we support PEX if it's disabled.
1252 var pexMsg peerExchangeMessage
1253 err := bencode.Unmarshal(payload, &pexMsg)
1255 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1257 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1258 t.addPeers(pexMsg.AddedPeers())
1261 return fmt.Errorf("unexpected extended message ID: %v", id)
1265 // Set both the Reader and Writer for the connection from a single ReadWriter.
1266 func (cn *connection) setRW(rw io.ReadWriter) {
1271 // Returns the Reader and Writer as a combined ReadWriter.
1272 func (cn *connection) rw() io.ReadWriter {
1279 // Handle a received chunk from a peer.
1280 func (c *connection) receiveChunk(msg *pp.Message) error {
1283 torrent.Add("chunks received", 1)
1285 req := newRequestFromMessage(msg)
1288 torrent.Add("chunks received while choked", 1)
1291 if _, ok := c.validReceiveChunks[req]; !ok {
1292 torrent.Add("chunks received unexpected", 1)
1293 return errors.New("received unexpected chunk")
1295 delete(c.validReceiveChunks, req)
1297 if c.PeerChoked && c.peerAllowedFast.Get(int(req.Index)) {
1298 torrent.Add("chunks received due to allowed fast", 1)
1301 // Request has been satisfied.
1302 if c.deleteRequest(req) {
1303 if c.expectingChunks() {
1304 c.chunksReceivedWhileExpecting++
1307 torrent.Add("chunks received unwanted", 1)
1310 // Do we actually want this chunk?
1311 if t.haveChunk(req) {
1312 torrent.Add("chunks received wasted", 1)
1313 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1317 index := int(req.Index)
1318 piece := &t.pieces[index]
1320 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1321 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1322 c.lastUsefulChunkReceived = time.Now()
1323 // if t.fastestConn != c {
1324 // log.Printf("setting fastest connection %p", c)
1328 // Need to record that it hasn't been written yet, before we attempt to do
1329 // anything with it.
1330 piece.incrementPendingWrites()
1331 // Record that we have the chunk, so we aren't trying to download it while
1332 // waiting for it to be written to storage.
1333 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1335 // Cancel pending requests for this chunk.
1336 for c := range t.conns {
1340 err := func() error {
1343 // Write the chunk out. Note that the upper bound on chunk writing
1344 // concurrency will be the number of connections. We write inline with
1345 // receiving the chunk (with this lock dance), because we want to
1346 // handle errors synchronously and I haven't thought of a nice way to
1347 // defer any concurrency to the storage and have that notify the
1348 // client of errors. TODO: Do that instead.
1349 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1352 piece.decrementPendingWrites()
1355 log.Printf("%s (%s): error writing chunk %v: %s", t, t.infoHash, req, err)
1357 t.updatePieceCompletion(int(msg.Index))
1361 // It's important that the piece is potentially queued before we check if
1362 // the piece is still wanted, because if it is queued, it won't be wanted.
1363 if t.pieceAllDirty(index) {
1364 t.queuePieceCheck(int(req.Index))
1365 t.pendAllChunkSpecs(index)
1368 c.onDirtiedPiece(index)
1370 cl.event.Broadcast()
1371 t.publishPieceChange(int(req.Index))
1376 func (c *connection) onDirtiedPiece(piece int) {
1377 if c.peerTouchedPieces == nil {
1378 c.peerTouchedPieces = make(map[int]struct{})
1380 c.peerTouchedPieces[piece] = struct{}{}
1381 ds := &c.t.pieces[piece].dirtiers
1383 *ds = make(map[*connection]struct{})
1385 (*ds)[c] = struct{}{}
1388 func (c *connection) uploadAllowed() bool {
1389 if c.t.cl.config.NoUpload {
1395 if !c.peerHasWantedPieces() {
1398 // Don't upload more than 100 KiB more than we download.
1399 if c.stats.BytesWrittenData.Int64() >= c.stats.BytesReadData.Int64()+100<<10 {
1405 func (c *connection) setRetryUploadTimer(delay time.Duration) {
1406 if c.uploadTimer == nil {
1407 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1409 c.uploadTimer.Reset(delay)
1413 // Also handles choking and unchoking of the remote peer.
1414 func (c *connection) upload(msg func(pp.Message) bool) bool {
1415 // Breaking or completing this loop means we don't want to upload to the
1416 // peer anymore, and we choke them.
1418 for c.uploadAllowed() {
1419 // We want to upload to the peer.
1420 if !c.Unchoke(msg) {
1423 for r := range c.PeerRequests {
1424 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1426 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1428 delay := res.Delay()
1431 c.setRetryUploadTimer(delay)
1432 // Hard to say what to return here.
1435 more, err := c.sendChunk(r, msg)
1438 if c.t.pieceComplete(i) {
1439 c.t.updatePieceCompletion(i)
1440 if !c.t.pieceComplete(i) {
1441 // We had the piece, but not anymore.
1445 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1446 // If we failed to send a chunk, choke the peer to ensure they
1447 // flush all their requests. We've probably dropped a piece,
1448 // but there's no way to communicate this to the peer. If they
1449 // ask for it again, we'll kick them to allow us to send them
1450 // an updated bitfield.
1453 delete(c.PeerRequests, r)
1464 func (cn *connection) Drop() {
1465 cn.t.dropConnection(cn)
1468 func (cn *connection) netGoodPiecesDirtied() int64 {
1469 return cn.stats.PiecesDirtiedGood.Int64() - cn.stats.PiecesDirtiedBad.Int64()
1472 func (c *connection) peerHasWantedPieces() bool {
1473 return !c.pieceRequestOrder.IsEmpty()
1476 func (c *connection) numLocalRequests() int {
1477 return len(c.requests)
1480 func (c *connection) deleteRequest(r request) bool {
1481 if _, ok := c.requests[r]; !ok {
1484 delete(c.requests, r)
1485 c.updateExpectingChunks()
1486 if t, ok := c.t.lastRequested[r]; ok {
1488 delete(c.t.lastRequested, r)
1490 pr := c.t.pendingRequests
1503 func (c *connection) deleteAllRequests() {
1504 for r := range c.requests {
1507 if len(c.requests) != 0 {
1508 panic(len(c.requests))
1510 // for c := range c.t.conns {
1515 func (c *connection) tickleWriter() {
1516 c.writerCond.Broadcast()
1519 func (c *connection) postCancel(r request) bool {
1520 if !c.deleteRequest(r) {
1523 c.Post(makeCancelMessage(r))
1527 func (c *connection) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1528 // Count the chunk being sent, even if it isn't.
1529 b := make([]byte, r.Length)
1530 p := c.t.info.Piece(int(r.Index))
1531 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1534 panic("expected error")
1537 } else if err == io.EOF {
1540 more = msg(pp.Message{
1546 c.lastChunkSent = time.Now()
1550 func (c *connection) setTorrent(t *Torrent) {
1552 panic("connection already associated with a torrent")
1555 t.reconcileHandshakeStats(c)