16 "github.com/anacrolix/log"
18 "github.com/anacrolix/missinggo"
19 "github.com/anacrolix/missinggo/bitmap"
20 "github.com/anacrolix/missinggo/iter"
21 "github.com/anacrolix/missinggo/prioritybitmap"
23 "github.com/anacrolix/torrent/bencode"
24 "github.com/anacrolix/torrent/mse"
25 pp "github.com/anacrolix/torrent/peer_protocol"
28 type peerSource string
31 peerSourceTracker = "T" // It's the default.
32 peerSourceIncoming = "I"
33 peerSourceDHTGetPeers = "Hg"
34 peerSourceDHTAnnouncePeer = "Ha"
38 // Maintains the state of a connection with a peer.
39 type connection struct {
41 // The actual Conn, used for closing, and setting socket options.
43 // The Reader and Writer for this Conn, with hooks installed for stats,
44 // limiting, deadlines etc.
47 // True if the connection is operating over MSE obfuscation.
52 closed missinggo.Event
56 lastMessageReceived time.Time
57 completedHandshake time.Time
58 lastUsefulChunkReceived time.Time
59 lastChunkSent time.Time
61 // Stuff controlled by the local peer.
63 lastBecameInterested time.Time
64 priorInterest time.Duration
67 requests map[request]struct{}
69 // Indexed by metadata piece, set to true if posted and pending a
71 metadataRequests []bool
72 sentHaves bitmap.Bitmap
74 // Stuff controlled by the remote peer.
78 PeerRequests map[request]struct{}
79 PeerExtensionBytes peerExtensionBytes
80 // The pieces the peer has claimed to have.
81 peerPieces bitmap.Bitmap
82 // The peer has everything. This can occur due to a special message, when
83 // we may not even know the number of pieces in the torrent yet.
85 // The highest possible number of pieces the torrent could have based on
86 // communication with the peer. Generally only useful until we have the
89 // Pieces we've accepted chunks for from the peer.
90 peerTouchedPieces map[int]struct{}
91 peerAllowedFast bitmap.Bitmap
93 PeerMaxRequests int // Maximum pending requests the peer allows.
94 PeerExtensionIDs map[string]byte
97 pieceInclination []int
98 pieceRequestOrder prioritybitmap.PriorityBitmap
100 writeBuffer *bytes.Buffer
101 uploadTimer *time.Timer
105 func (cn *connection) cumInterest() time.Duration {
106 ret := cn.priorInterest
108 ret += time.Since(cn.lastBecameInterested)
113 func (cn *connection) peerHasAllPieces() (all bool, known bool) {
114 if cn.peerSentHaveAll {
117 if !cn.t.haveInfo() {
120 return bitmap.Flip(cn.peerPieces, 0, cn.t.numPieces()).IsEmpty(), true
123 func (cn *connection) mu() sync.Locker {
127 func (cn *connection) remoteAddr() net.Addr {
128 return cn.conn.RemoteAddr()
131 func (cn *connection) localAddr() net.Addr {
132 return cn.conn.LocalAddr()
135 func (cn *connection) supportsExtension(ext string) bool {
136 _, ok := cn.PeerExtensionIDs[ext]
140 // The best guess at number of pieces in the torrent for this peer.
141 func (cn *connection) bestPeerNumPieces() int {
143 return cn.t.numPieces()
145 return cn.peerMinPieces
148 func (cn *connection) completedString() string {
149 have := cn.peerPieces.Len()
150 if cn.peerSentHaveAll {
151 have = cn.bestPeerNumPieces()
153 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
156 // Correct the PeerPieces slice length. Return false if the existing slice is
157 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
159 func (cn *connection) setNumPieces(num int) error {
160 cn.peerPieces.RemoveRange(num, bitmap.ToEnd)
161 cn.peerPiecesChanged()
165 func eventAgeString(t time.Time) string {
169 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
172 func (cn *connection) connectionFlags() (ret string) {
174 ret += string([]byte{b})
176 if cn.cryptoMethod == mse.CryptoMethodRC4 {
178 } else if cn.headerEncrypted {
181 ret += string(cn.Discovery)
188 // Inspired by https://trac.transmissionbt.com/wiki/PeerStatusText
189 func (cn *connection) statusFlags() (ret string) {
191 ret += string([]byte{b})
200 ret += cn.connectionFlags()
202 if cn.PeerInterested {
211 // func (cn *connection) String() string {
212 // var buf bytes.Buffer
213 // cn.WriteStatus(&buf, nil)
214 // return buf.String()
217 func (cn *connection) downloadRate() float64 {
218 return float64(cn.stats.BytesReadUsefulData) / cn.cumInterest().Seconds()
221 func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
222 // \t isn't preserved in <pre> blocks?
223 fmt.Fprintf(w, "%+-55q %s %s-%s\n", cn.PeerID, cn.PeerExtensionBytes, cn.localAddr(), cn.remoteAddr())
224 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s\n",
225 eventAgeString(cn.lastMessageReceived),
226 eventAgeString(cn.completedHandshake),
227 eventAgeString(cn.lastHelpful()),
231 " %s completed, %d pieces touched, good chunks: %d/%d-%d reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
232 cn.completedString(),
233 len(cn.peerTouchedPieces),
234 cn.stats.ChunksReadUseful,
236 cn.stats.ChunksWritten,
238 cn.numLocalRequests(),
239 cn.nominalMaxRequests(),
240 len(cn.PeerRequests),
242 cn.downloadRate()/(1<<10),
244 roi := cn.pieceRequestOrderIter()
245 fmt.Fprintf(w, " next pieces: %v%s\n",
246 iter.ToSlice(iter.Head(10, roi)),
248 if cn.shouldRequestWithoutBias() {
256 func (cn *connection) Close() {
257 if !cn.closed.Set() {
261 cn.discardPieceInclination()
262 cn.pieceRequestOrder.Clear()
268 func (cn *connection) PeerHasPiece(piece int) bool {
269 return cn.peerSentHaveAll || cn.peerPieces.Contains(piece)
272 // Writes a message into the write buffer.
273 func (cn *connection) Post(msg pp.Message) {
274 messageTypesPosted.Add(msg.Type.String(), 1)
275 // We don't need to track bytes here because a connection.w Writer wrapper
276 // takes care of that (although there's some delay between us recording
277 // the message, and the connection writer flushing it out.).
278 cn.writeBuffer.Write(msg.MustMarshalBinary())
279 // Last I checked only Piece messages affect stats, and we don't post
285 func (cn *connection) requestMetadataPiece(index int) {
286 eID := cn.PeerExtensionIDs["ut_metadata"]
290 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
296 ExtendedPayload: func() []byte {
297 b, err := bencode.Marshal(map[string]int{
298 "msg_type": pp.RequestMetadataExtensionMsgType,
307 for index >= len(cn.metadataRequests) {
308 cn.metadataRequests = append(cn.metadataRequests, false)
310 cn.metadataRequests[index] = true
313 func (cn *connection) requestedMetadataPiece(index int) bool {
314 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
317 func clamp(min, value, max int64) int64 {
330 func max(as ...int64) int64 {
332 for _, a := range as[1:] {
340 // The actual value to use as the maximum outbound requests.
341 func (cn *connection) nominalMaxRequests() (ret int) {
342 return int(clamp(1, int64(cn.PeerMaxRequests), max(64, cn.stats.ChunksReadUseful-(cn.stats.ChunksRead-cn.stats.ChunksReadUseful))))
345 func (cn *connection) onPeerSentCancel(r request) {
346 if _, ok := cn.PeerRequests[r]; !ok {
347 torrent.Add("unexpected cancels received", 1)
350 if cn.fastEnabled() {
353 delete(cn.PeerRequests, r)
357 func (cn *connection) Choke(msg messageWriter) (more bool) {
362 more = msg(pp.Message{
365 if cn.fastEnabled() {
366 for r := range cn.PeerRequests {
367 // TODO: Don't reject pieces in allowed fast set.
371 cn.PeerRequests = nil
376 func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
381 return msg(pp.Message{
386 func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
387 if cn.Interested == interested {
390 cn.Interested = interested
392 cn.lastBecameInterested = time.Now()
393 } else if !cn.lastBecameInterested.IsZero() {
394 cn.priorInterest += time.Since(cn.lastBecameInterested)
396 // log.Printf("%p: setting interest: %v", cn, interested)
397 return msg(pp.Message{
398 Type: func() pp.MessageType {
402 return pp.NotInterested
408 // The function takes a message to be sent, and returns true if more messages
410 type messageWriter func(pp.Message) bool
412 // Proxies the messageWriter's response.
413 func (cn *connection) request(r request, mw messageWriter) bool {
414 if cn.requests == nil {
415 cn.requests = make(map[request]struct{}, cn.nominalMaxRequests())
417 if _, ok := cn.requests[r]; ok {
418 panic("chunk already requested")
420 if !cn.PeerHasPiece(r.Index.Int()) {
421 panic("requesting piece peer doesn't have")
423 cn.requests[r] = struct{}{}
424 if _, ok := cn.t.conns[cn]; !ok {
425 panic("requesting but not in active conns")
428 if cn.peerAllowedFast.Get(int(r.Index)) {
429 torrent.Add("allowed fast requests sent", 1)
431 panic("requesting while choked and not allowed fast")
434 cn.t.pendingRequests[r]++
435 return mw(pp.Message{
443 func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
444 numFillBuffers.Add(1)
445 cancel, new, i := cn.desiredRequestState()
446 if !cn.SetInterested(i, msg) {
449 if cancel && len(cn.requests) != 0 {
450 fillBufferSentCancels.Add(1)
451 for r := range cn.requests {
453 // log.Printf("%p: cancelling request: %v", cn, r)
454 if !msg(makeCancelMessage(r)) {
460 fillBufferSentRequests.Add(1)
461 for _, r := range new {
462 if !cn.request(r, msg) {
463 // If we didn't completely top up the requests, we shouldn't
464 // mark the low water, since we'll want to top up the requests
465 // as soon as we have more write buffer space.
469 cn.requestsLowWater = len(cn.requests) / 2
474 // Routine that writes to the peer. Some of what to write is buffered by
475 // activity elsewhere in the Client, and some is determined locally when the
476 // connection is writable.
477 func (cn *connection) writer(keepAliveTimeout time.Duration) {
479 lastWrite time.Time = time.Now()
480 keepAliveTimer *time.Timer
482 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
484 defer cn.mu().Unlock()
485 if time.Since(lastWrite) >= keepAliveTimeout {
488 keepAliveTimer.Reset(keepAliveTimeout)
491 defer cn.mu().Unlock()
493 defer keepAliveTimer.Stop()
494 frontBuf := new(bytes.Buffer)
496 if cn.closed.IsSet() {
499 if cn.writeBuffer.Len() == 0 {
500 cn.fillWriteBuffer(func(msg pp.Message) bool {
502 cn.writeBuffer.Write(msg.MustMarshalBinary())
503 return cn.writeBuffer.Len() < 1<<16
506 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
507 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
508 postedKeepalives.Add(1)
510 if cn.writeBuffer.Len() == 0 {
511 // TODO: Minimize wakeups....
516 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
518 n, err := cn.w.Write(frontBuf.Bytes())
521 lastWrite = time.Now()
522 keepAliveTimer.Reset(keepAliveTimeout)
527 if n != frontBuf.Len() {
534 func (cn *connection) Have(piece int) {
535 if cn.sentHaves.Get(piece) {
540 Index: pp.Integer(piece),
542 cn.sentHaves.Add(piece)
545 func (cn *connection) PostBitfield() {
546 if cn.sentHaves.Len() != 0 {
547 panic("bitfield must be first have-related message sent")
549 if !cn.t.haveAnyPieces() {
554 Bitfield: cn.t.bitfield(),
556 cn.sentHaves = cn.t.completedPieces.Copy()
559 // Determines interest and requests to send to a connected peer.
560 func nextRequestState(
561 networkingEnabled bool,
562 currentRequests map[request]struct{},
564 iterPendingRequests func(f func(request) bool),
565 requestsLowWater int,
566 requestsHighWater int,
567 allowedFast bitmap.Bitmap,
569 cancelExisting bool, // Cancel all our pending requests
570 newRequests []request, // Chunks to request that we currently aren't
571 interested bool, // Whether we should indicate interest, even if we don't request anything
573 if !networkingEnabled {
574 return true, nil, false
576 if len(currentRequests) > requestsLowWater {
577 return false, nil, true
579 iterPendingRequests(func(r request) bool {
582 if allowedFast.IsEmpty() {
585 if !allowedFast.Get(int(r.Index)) {
589 if len(currentRequests)+len(newRequests) >= requestsHighWater {
592 if _, ok := currentRequests[r]; !ok {
593 if newRequests == nil {
594 newRequests = make([]request, 0, requestsHighWater-len(currentRequests))
596 newRequests = append(newRequests, r)
603 func (cn *connection) updateRequests() {
604 // log.Print("update requests")
608 // Emits the indices in the Bitmaps bms in order, never repeating any index.
609 // skip is mutated during execution, and its initial values will never be
611 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
612 return func(cb iter.Callback) {
613 for _, bm := range bms {
614 if !iter.All(func(i interface{}) bool {
617 }, bitmap.Sub(bm, *skip).Iter) {
624 func (cn *connection) unbiasedPieceRequestOrder() iter.Func {
625 now, readahead := cn.t.readerPiecePriorities()
626 var skip bitmap.Bitmap
627 if !cn.peerSentHaveAll {
628 // Pieces to skip include pieces the peer doesn't have
629 skip = bitmap.Flip(cn.peerPieces, 0, cn.t.numPieces())
631 // And pieces that we already have.
632 skip.Union(cn.t.completedPieces)
633 // Return an iterator over the different priority classes, minus the skip
636 iterBitmapsDistinct(&skip, now, readahead),
637 func(cb iter.Callback) {
638 cn.t.pendingPieces.IterTyped(func(piece int) bool {
639 if skip.Contains(piece) {
650 // The connection should download highest priority pieces first, without any
651 // inclination toward avoiding wastage. Generally we might do this if there's
652 // a single connection, or this is the fastest connection, and we have active
653 // readers that signal an ordering preference. It's conceivable that the best
654 // connection should do this, since it's least likely to waste our time if
655 // assigned to the highest priority pieces, and assigning more than one this
656 // role would cause significant wasted bandwidth.
657 func (cn *connection) shouldRequestWithoutBias() bool {
658 if cn.t.requestStrategy != 2 {
661 if len(cn.t.readers) == 0 {
664 if len(cn.t.conns) == 1 {
667 if cn == cn.t.fastestConn {
673 func (cn *connection) pieceRequestOrderIter() iter.Func {
674 if cn.shouldRequestWithoutBias() {
675 return cn.unbiasedPieceRequestOrder()
677 return cn.pieceRequestOrder.Iter
681 func (cn *connection) iterPendingRequests(f func(request) bool) {
682 cn.pieceRequestOrderIter()(func(_piece interface{}) bool {
683 piece := _piece.(int)
684 return iterUndirtiedChunks(piece, cn.t, func(cs chunkSpec) bool {
685 r := request{pp.Integer(piece), cs}
686 // log.Println(r, cn.t.pendingRequests[r], cn.requests)
687 // if _, ok := cn.requests[r]; !ok && cn.t.pendingRequests[r] != 0 {
695 func (cn *connection) desiredRequestState() (bool, []request, bool) {
696 return nextRequestState(
697 cn.t.networkingEnabled,
700 cn.iterPendingRequests,
702 cn.nominalMaxRequests(),
707 func iterUndirtiedChunks(piece int, t *Torrent, f func(chunkSpec) bool) bool {
708 chunkIndices := t.pieces[piece].undirtiedChunkIndices().ToSortedSlice()
709 // TODO: Use "math/rand".Shuffle >= Go 1.10
710 return iter.ForPerm(len(chunkIndices), func(i int) bool {
711 return f(t.chunkIndexSpec(chunkIndices[i], piece))
715 // check callers updaterequests
716 func (cn *connection) stopRequestingPiece(piece int) bool {
717 return cn.pieceRequestOrder.Remove(piece)
720 // This is distinct from Torrent piece priority, which is the user's
721 // preference. Connection piece priority is specific to a connection and is
722 // used to pseudorandomly avoid connections always requesting the same pieces
723 // and thus wasting effort.
724 func (cn *connection) updatePiecePriority(piece int) bool {
725 tpp := cn.t.piecePriority(piece)
726 if !cn.PeerHasPiece(piece) {
727 tpp = PiecePriorityNone
729 if tpp == PiecePriorityNone {
730 return cn.stopRequestingPiece(piece)
732 prio := cn.getPieceInclination()[piece]
733 switch cn.t.requestStrategy {
736 case PiecePriorityNormal:
737 case PiecePriorityReadahead:
738 prio -= cn.t.numPieces()
739 case PiecePriorityNext, PiecePriorityNow:
740 prio -= 2 * cn.t.numPieces()
747 return cn.pieceRequestOrder.Set(piece, prio) || cn.shouldRequestWithoutBias()
750 func (cn *connection) getPieceInclination() []int {
751 if cn.pieceInclination == nil {
752 cn.pieceInclination = cn.t.getConnPieceInclination()
754 return cn.pieceInclination
757 func (cn *connection) discardPieceInclination() {
758 if cn.pieceInclination == nil {
761 cn.t.putPieceInclination(cn.pieceInclination)
762 cn.pieceInclination = nil
765 func (cn *connection) peerPiecesChanged() {
767 prioritiesChanged := false
768 for i := range iter.N(cn.t.numPieces()) {
769 if cn.updatePiecePriority(i) {
770 prioritiesChanged = true
773 if prioritiesChanged {
779 func (cn *connection) raisePeerMinPieces(newMin int) {
780 if newMin > cn.peerMinPieces {
781 cn.peerMinPieces = newMin
785 func (cn *connection) peerSentHave(piece int) error {
786 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
787 return errors.New("invalid piece")
789 if cn.PeerHasPiece(piece) {
792 cn.raisePeerMinPieces(piece + 1)
793 cn.peerPieces.Set(piece, true)
794 if cn.updatePiecePriority(piece) {
800 func (cn *connection) peerSentBitfield(bf []bool) error {
801 cn.peerSentHaveAll = false
803 panic("expected bitfield length divisible by 8")
805 // We know that the last byte means that at most the last 7 bits are
807 cn.raisePeerMinPieces(len(bf) - 7)
808 if cn.t.haveInfo() && len(bf) > cn.t.numPieces() {
809 // Ignore known excess pieces.
810 bf = bf[:cn.t.numPieces()]
812 for i, have := range bf {
814 cn.raisePeerMinPieces(i + 1)
816 cn.peerPieces.Set(i, have)
818 cn.peerPiecesChanged()
822 func (cn *connection) onPeerSentHaveAll() error {
823 cn.peerSentHaveAll = true
824 cn.peerPieces.Clear()
825 cn.peerPiecesChanged()
829 func (cn *connection) peerSentHaveNone() error {
830 cn.peerPieces.Clear()
831 cn.peerSentHaveAll = false
832 cn.peerPiecesChanged()
836 func (c *connection) requestPendingMetadata() {
840 if c.PeerExtensionIDs["ut_metadata"] == 0 {
841 // Peer doesn't support this.
844 // Request metadata pieces that we don't have in a random order.
846 for index := 0; index < c.t.metadataPieceCount(); index++ {
847 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
848 pending = append(pending, index)
851 for _, i := range rand.Perm(len(pending)) {
852 c.requestMetadataPiece(pending[i])
856 func (cn *connection) wroteMsg(msg *pp.Message) {
857 messageTypesSent.Add(msg.Type.String(), 1)
858 cn.stats.wroteMsg(msg)
859 cn.t.stats.wroteMsg(msg)
862 func (cn *connection) readMsg(msg *pp.Message) {
863 cn.stats.readMsg(msg)
864 cn.t.stats.readMsg(msg)
867 func (cn *connection) wroteBytes(n int64) {
868 cn.stats.wroteBytes(n)
870 cn.t.stats.wroteBytes(n)
874 func (cn *connection) readBytes(n int64) {
875 cn.stats.readBytes(n)
877 cn.t.stats.readBytes(n)
881 // Returns whether the connection could be useful to us. We're seeding and
882 // they want data, we don't have metainfo and they can provide it, etc.
883 func (c *connection) useful() bool {
885 if c.closed.IsSet() {
889 return c.supportsExtension("ut_metadata")
891 if t.seeding() && c.PeerInterested {
894 if c.peerHasWantedPieces() {
900 func (c *connection) lastHelpful() (ret time.Time) {
901 ret = c.lastUsefulChunkReceived
902 if c.t.seeding() && c.lastChunkSent.After(ret) {
903 ret = c.lastChunkSent
908 func (c *connection) fastEnabled() bool {
909 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
912 func (c *connection) reject(r request) {
913 if !c.fastEnabled() {
914 panic("fast not enabled")
916 c.Post(r.ToMsg(pp.Reject))
917 delete(c.PeerRequests, r)
920 func (c *connection) onReadRequest(r request) error {
921 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
922 if r.Begin+r.Length > c.t.pieceLength(int(r.Index)) {
923 torrent.Add("bad requests received", 1)
924 return errors.New("bad request")
926 if _, ok := c.PeerRequests[r]; ok {
927 torrent.Add("duplicate requests received", 1)
931 torrent.Add("requests received while choking", 1)
933 torrent.Add("requests rejected while choking", 1)
938 if len(c.PeerRequests) >= maxRequests {
939 torrent.Add("requests received while queue full", 1)
943 // BEP 6 says we may close here if we choose.
946 if !c.t.havePiece(r.Index.Int()) {
947 // This isn't necessarily them screwing up. We can drop pieces
948 // from our storage, and can't communicate this to peers
949 // except by reconnecting.
950 requestsReceivedForMissingPieces.Add(1)
951 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
953 if c.PeerRequests == nil {
954 c.PeerRequests = make(map[request]struct{}, maxRequests)
956 c.PeerRequests[r] = struct{}{}
961 // Processes incoming bittorrent messages. The client lock is held upon entry
962 // and exit. Returning will end the connection.
963 func (c *connection) mainReadLoop() error {
967 decoder := pp.Decoder{
968 R: bufio.NewReaderSize(c.r, 1<<17),
969 MaxLength: 256 * 1024,
980 err = decoder.Decode(&msg)
982 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
989 c.lastMessageReceived = time.Now()
991 receivedKeepalives.Add(1)
994 messageTypesReceived.Add(msg.Type.String(), 1)
995 if msg.Type.FastExtension() && !c.fastEnabled() {
996 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1001 c.deleteAllRequests()
1002 // We can then reset our interest.
1005 c.deleteRequest(newRequestFromMessage(&msg))
1007 c.PeerChoked = false
1010 c.PeerInterested = true
1012 case pp.NotInterested:
1013 c.PeerInterested = false
1015 c.PeerRequests = nil
1017 err = c.peerSentHave(int(msg.Index))
1019 r := newRequestFromMessage(&msg)
1020 err = c.onReadRequest(r)
1022 req := newRequestFromMessage(&msg)
1023 c.onPeerSentCancel(req)
1025 err = c.peerSentBitfield(msg.Bitfield)
1027 err = c.onPeerSentHaveAll()
1029 err = c.peerSentHaveNone()
1031 c.receiveChunk(&msg)
1032 if len(msg.Piece) == int(t.chunkSize) {
1033 t.chunkPool.Put(&msg.Piece)
1036 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1041 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1046 pingAddr.Port = int(msg.Port)
1048 go cl.dHT.Ping(pingAddr, nil)
1049 case pp.AllowedFast:
1050 torrent.Add("allowed fasts received", 1)
1051 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1052 c.peerAllowedFast.Add(int(msg.Index))
1055 torrent.Add("suggests received", 1)
1056 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1059 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1067 func (c *connection) onReadExtendedMsg(id byte, payload []byte) (err error) {
1069 // TODO: Should we still do this?
1071 // These clients use their own extension IDs for outgoing message
1072 // types, which is incorrect.
1073 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1081 case pp.HandshakeExtendedID:
1082 // TODO: Create a bencode struct for this.
1083 var d map[string]interface{}
1084 err := bencode.Unmarshal(payload, &d)
1086 return fmt.Errorf("error decoding extended message payload: %s", err)
1088 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1089 if reqq, ok := d["reqq"]; ok {
1090 if i, ok := reqq.(int64); ok {
1091 c.PeerMaxRequests = int(i)
1094 if v, ok := d["v"]; ok {
1095 c.PeerClientName = v.(string)
1097 if m, ok := d["m"]; ok {
1098 mTyped, ok := m.(map[string]interface{})
1100 return errors.New("handshake m value is not dict")
1102 if c.PeerExtensionIDs == nil {
1103 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1105 for name, v := range mTyped {
1108 log.Printf("bad handshake m item extension ID type: %T", v)
1112 delete(c.PeerExtensionIDs, name)
1114 if c.PeerExtensionIDs[name] == 0 {
1115 supportedExtensionMessages.Add(name, 1)
1117 c.PeerExtensionIDs[name] = byte(id)
1121 metadata_sizeUntyped, ok := d["metadata_size"]
1123 metadata_size, ok := metadata_sizeUntyped.(int64)
1125 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1127 err = t.setMetadataSize(metadata_size)
1129 return fmt.Errorf("error setting metadata size to %d", metadata_size)
1133 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1134 c.requestPendingMetadata()
1137 case metadataExtendedId:
1138 err := cl.gotMetadataExtensionMsg(payload, t, c)
1140 return fmt.Errorf("error handling metadata extension message: %s", err)
1144 if cl.config.DisablePEX {
1145 // TODO: Maybe close the connection. Check that we're not
1146 // advertising that we support PEX if it's disabled.
1149 var pexMsg peerExchangeMessage
1150 err := bencode.Unmarshal(payload, &pexMsg)
1152 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1155 ps := pexMsg.AddedPeers()
1162 return fmt.Errorf("unexpected extended message ID: %v", id)
1166 // Set both the Reader and Writer for the connection from a single ReadWriter.
1167 func (cn *connection) setRW(rw io.ReadWriter) {
1172 // Returns the Reader and Writer as a combined ReadWriter.
1173 func (cn *connection) rw() io.ReadWriter {
1180 // Handle a received chunk from a peer.
1181 func (c *connection) receiveChunk(msg *pp.Message) {
1184 chunksReceived.Add(1)
1186 req := newRequestFromMessage(msg)
1188 // Request has been satisfied.
1189 if c.deleteRequest(req) {
1192 unexpectedChunksReceived.Add(1)
1196 torrent.Add("chunks received while choked", 1)
1197 if c.peerAllowedFast.Get(int(req.Index)) {
1198 torrent.Add("chunks received due to allowed fast", 1)
1202 // Do we actually want this chunk?
1203 if !t.wantPiece(req) {
1204 unwantedChunksReceived.Add(1)
1205 c.stats.ChunksReadUnwanted++
1206 c.t.stats.ChunksReadUnwanted++
1210 index := int(req.Index)
1211 piece := &t.pieces[index]
1213 c.stats.ChunksReadUseful++
1214 c.t.stats.ChunksReadUseful++
1215 c.stats.BytesReadUsefulData += int64(len(msg.Piece))
1216 c.t.stats.BytesReadUsefulData += int64(len(msg.Piece))
1217 c.lastUsefulChunkReceived = time.Now()
1218 // if t.fastestConn != c {
1219 // log.Printf("setting fastest connection %p", c)
1223 // Need to record that it hasn't been written yet, before we attempt to do
1224 // anything with it.
1225 piece.incrementPendingWrites()
1226 // Record that we have the chunk, so we aren't trying to download it while
1227 // waiting for it to be written to storage.
1228 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1230 // Cancel pending requests for this chunk.
1231 for c := range t.conns {
1235 err := func() error {
1238 // Write the chunk out. Note that the upper bound on chunk writing
1239 // concurrency will be the number of connections. We write inline with
1240 // receiving the chunk (with this lock dance), because we want to
1241 // handle errors synchronously and I haven't thought of a nice way to
1242 // defer any concurrency to the storage and have that notify the
1243 // client of errors. TODO: Do that instead.
1244 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1247 piece.decrementPendingWrites()
1250 log.Printf("%s (%s): error writing chunk %v: %s", t, t.infoHash, req, err)
1252 t.updatePieceCompletion(int(msg.Index))
1256 // It's important that the piece is potentially queued before we check if
1257 // the piece is still wanted, because if it is queued, it won't be wanted.
1258 if t.pieceAllDirty(index) {
1259 t.queuePieceCheck(int(req.Index))
1260 t.pendAllChunkSpecs(index)
1263 c.onDirtiedPiece(index)
1265 cl.event.Broadcast()
1266 t.publishPieceChange(int(req.Index))
1269 func (c *connection) onDirtiedPiece(piece int) {
1270 if c.peerTouchedPieces == nil {
1271 c.peerTouchedPieces = make(map[int]struct{})
1273 c.peerTouchedPieces[piece] = struct{}{}
1274 ds := &c.t.pieces[piece].dirtiers
1276 *ds = make(map[*connection]struct{})
1278 (*ds)[c] = struct{}{}
1281 func (c *connection) uploadAllowed() bool {
1282 if c.t.cl.config.NoUpload {
1288 if !c.peerHasWantedPieces() {
1291 // Don't upload more than 100 KiB more than we download.
1292 if c.stats.BytesWrittenData >= c.stats.BytesReadData+100<<10 {
1298 func (c *connection) setRetryUploadTimer(delay time.Duration) {
1299 if c.uploadTimer == nil {
1300 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1302 c.uploadTimer.Reset(delay)
1306 // Also handles choking and unchoking of the remote peer.
1307 func (c *connection) upload(msg func(pp.Message) bool) bool {
1308 // Breaking or completing this loop means we don't want to upload to the
1309 // peer anymore, and we choke them.
1311 for c.uploadAllowed() {
1312 // We want to upload to the peer.
1313 if !c.Unchoke(msg) {
1316 for r := range c.PeerRequests {
1317 res := c.t.cl.uploadLimit.ReserveN(time.Now(), int(r.Length))
1319 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1321 delay := res.Delay()
1324 c.setRetryUploadTimer(delay)
1325 // Hard to say what to return here.
1328 more, err := c.sendChunk(r, msg)
1331 if c.t.pieceComplete(i) {
1332 c.t.updatePieceCompletion(i)
1333 if !c.t.pieceComplete(i) {
1334 // We had the piece, but not anymore.
1338 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1339 // If we failed to send a chunk, choke the peer to ensure they
1340 // flush all their requests. We've probably dropped a piece,
1341 // but there's no way to communicate this to the peer. If they
1342 // ask for it again, we'll kick them to allow us to send them
1343 // an updated bitfield.
1346 delete(c.PeerRequests, r)
1357 func (cn *connection) Drop() {
1358 cn.t.dropConnection(cn)
1361 func (cn *connection) netGoodPiecesDirtied() int64 {
1362 return cn.stats.PiecesDirtiedGood - cn.stats.PiecesDirtiedBad
1365 func (c *connection) peerHasWantedPieces() bool {
1366 return !c.pieceRequestOrder.IsEmpty()
1369 func (c *connection) numLocalRequests() int {
1370 return len(c.requests)
1373 func (c *connection) deleteRequest(r request) bool {
1374 if _, ok := c.requests[r]; !ok {
1377 delete(c.requests, r)
1378 c.t.pendingRequests[r]--
1383 func (c *connection) deleteAllRequests() {
1384 for r := range c.requests {
1387 // for c := range c.t.conns {
1392 func (c *connection) tickleWriter() {
1393 c.writerCond.Broadcast()
1396 func (c *connection) postCancel(r request) bool {
1397 if !c.deleteRequest(r) {
1400 c.Post(makeCancelMessage(r))
1404 func (c *connection) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1405 // Count the chunk being sent, even if it isn't.
1406 b := make([]byte, r.Length)
1407 p := c.t.info.Piece(int(r.Index))
1408 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1411 panic("expected error")
1414 } else if err == io.EOF {
1417 more = msg(pp.Message{
1423 c.lastChunkSent = time.Now()
1427 func (c *connection) setTorrent(t *Torrent) {
1429 panic("connection already associated with a torrent")
1432 t.conns[c] = struct{}{}