]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Improvements to request refreshing
[btrtrc.git] / peerconn.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "errors"
7         "fmt"
8         "io"
9         "math/rand"
10         "net"
11         "sort"
12         "strconv"
13         "strings"
14         "time"
15
16         "github.com/RoaringBitmap/roaring"
17         "github.com/anacrolix/log"
18         "github.com/anacrolix/missinggo/iter"
19         "github.com/anacrolix/missinggo/v2/bitmap"
20         "github.com/anacrolix/multiless"
21
22         "github.com/anacrolix/chansync"
23         "github.com/anacrolix/torrent/bencode"
24         "github.com/anacrolix/torrent/metainfo"
25         "github.com/anacrolix/torrent/mse"
26         pp "github.com/anacrolix/torrent/peer_protocol"
27         request_strategy "github.com/anacrolix/torrent/request-strategy"
28 )
29
30 type PeerSource string
31
32 const (
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.
37         PeerSourcePex             = "X"
38         // The peer was given directly, such as through a magnet link.
39         PeerSourceDirect = "M"
40 )
41
42 type peerRequestState struct {
43         data []byte
44 }
45
46 type PeerRemoteAddr interface {
47         String() string
48 }
49
50 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
51 // indexable with the memory space available.
52 type (
53         maxRequests  = int
54         requestState = request_strategy.PeerNextRequestState
55 )
56
57 type Peer struct {
58         // First to ensure 64-bit alignment for atomics. See #262.
59         _stats ConnStats
60
61         t *Torrent
62
63         peerImpl
64         callbacks *Callbacks
65
66         outgoing   bool
67         Network    string
68         RemoteAddr PeerRemoteAddr
69         // True if the connection is operating over MSE obfuscation.
70         headerEncrypted bool
71         cryptoMethod    mse.CryptoMethod
72         Discovery       PeerSource
73         trusted         bool
74         closed          chansync.SetOnce
75         // Set true after we've added our ConnStats generated during handshake to
76         // other ConnStat instances as determined when the *Torrent became known.
77         reconciledHandshakeStats bool
78
79         lastMessageReceived     time.Time
80         completedHandshake      time.Time
81         lastUsefulChunkReceived time.Time
82         lastChunkSent           time.Time
83
84         // Stuff controlled by the local peer.
85         needRequestUpdate    string
86         actualRequestState   requestState
87         updateRequestsTimer  *time.Timer
88         cancelledRequests    roaring.Bitmap
89         lastBecameInterested time.Time
90         priorInterest        time.Duration
91
92         lastStartedExpectingToReceiveChunks time.Time
93         cumulativeExpectedToReceiveChunks   time.Duration
94         _chunksReceivedWhileExpecting       int64
95
96         choking                                bool
97         piecesReceivedSinceLastRequestUpdate   maxRequests
98         maxPiecesReceivedBetweenRequestUpdates maxRequests
99         // Chunks that we might reasonably expect to receive from the peer. Due to
100         // latency, buffering, and implementation differences, we may receive
101         // chunks that are no longer in the set of requests actually want.
102         validReceiveChunks map[RequestIndex]int
103         // Indexed by metadata piece, set to true if posted and pending a
104         // response.
105         metadataRequests []bool
106         sentHaves        bitmap.Bitmap
107
108         // Stuff controlled by the remote peer.
109         peerInterested        bool
110         peerChoking           bool
111         peerRequests          map[Request]*peerRequestState
112         PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
113         PeerListenPort        int
114         // The pieces the peer has claimed to have.
115         _peerPieces roaring.Bitmap
116         // The peer has everything. This can occur due to a special message, when
117         // we may not even know the number of pieces in the torrent yet.
118         peerSentHaveAll bool
119         // The highest possible number of pieces the torrent could have based on
120         // communication with the peer. Generally only useful until we have the
121         // torrent info.
122         peerMinPieces pieceIndex
123         // Pieces we've accepted chunks for from the peer.
124         peerTouchedPieces map[pieceIndex]struct{}
125         peerAllowedFast   roaring.Bitmap
126
127         PeerMaxRequests  maxRequests // Maximum pending requests the peer allows.
128         PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
129         PeerClientName   string
130
131         logger log.Logger
132 }
133
134 // Maintains the state of a BitTorrent-protocol based connection with a peer.
135 type PeerConn struct {
136         Peer
137
138         // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
139         // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
140         connString string
141
142         // See BEP 3 etc.
143         PeerID             PeerID
144         PeerExtensionBytes pp.PeerExtensionBits
145
146         // The actual Conn, used for closing, and setting socket options.
147         conn net.Conn
148         // The Reader and Writer for this Conn, with hooks installed for stats,
149         // limiting, deadlines etc.
150         w io.Writer
151         r io.Reader
152
153         messageWriter peerConnMsgWriter
154
155         uploadTimer *time.Timer
156         pex         pexConnState
157 }
158
159 func (cn *PeerConn) connStatusString() string {
160         return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
161 }
162
163 func (cn *Peer) updateExpectingChunks() {
164         if cn.expectingChunks() {
165                 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
166                         cn.lastStartedExpectingToReceiveChunks = time.Now()
167                 }
168         } else {
169                 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
170                         cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
171                         cn.lastStartedExpectingToReceiveChunks = time.Time{}
172                 }
173         }
174 }
175
176 func (cn *Peer) expectingChunks() bool {
177         if cn.actualRequestState.Requests.IsEmpty() {
178                 return false
179         }
180         if !cn.actualRequestState.Interested {
181                 return false
182         }
183         if !cn.peerChoking {
184                 return true
185         }
186         haveAllowedFastRequests := false
187         cn.peerAllowedFast.Iterate(func(i uint32) bool {
188                 haveAllowedFastRequests = roaringBitmapRangeCardinality(
189                         &cn.actualRequestState.Requests,
190                         cn.t.pieceRequestIndexOffset(pieceIndex(i)),
191                         cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
192                 ) == 0
193                 return !haveAllowedFastRequests
194         })
195         return haveAllowedFastRequests
196 }
197
198 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
199         return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
200 }
201
202 // Returns true if the connection is over IPv6.
203 func (cn *PeerConn) ipv6() bool {
204         ip := cn.remoteIp()
205         if ip.To4() != nil {
206                 return false
207         }
208         return len(ip) == net.IPv6len
209 }
210
211 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
212 // specification for this.
213 func (cn *PeerConn) isPreferredDirection() bool {
214         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
215 }
216
217 // Returns whether the left connection should be preferred over the right one,
218 // considering only their networking properties. If ok is false, we can't
219 // decide.
220 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
221         var ml multiLess
222         ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
223         ml.NextBool(!l.utp(), !r.utp())
224         ml.NextBool(l.ipv6(), r.ipv6())
225         return ml.FinalOk()
226 }
227
228 func (cn *Peer) cumInterest() time.Duration {
229         ret := cn.priorInterest
230         if cn.actualRequestState.Interested {
231                 ret += time.Since(cn.lastBecameInterested)
232         }
233         return ret
234 }
235
236 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
237         if cn.peerSentHaveAll {
238                 return true, true
239         }
240         if !cn.t.haveInfo() {
241                 return false, false
242         }
243         return roaring.Flip(&cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
244 }
245
246 func (cn *PeerConn) locker() *lockWithDeferreds {
247         return cn.t.cl.locker()
248 }
249
250 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
251         _, ok := cn.PeerExtensionIDs[ext]
252         return ok
253 }
254
255 // The best guess at number of pieces in the torrent for this peer.
256 func (cn *Peer) bestPeerNumPieces() pieceIndex {
257         if cn.t.haveInfo() {
258                 return cn.t.numPieces()
259         }
260         return cn.peerMinPieces
261 }
262
263 func (cn *Peer) completedString() string {
264         have := pieceIndex(cn._peerPieces.GetCardinality())
265         if cn.peerSentHaveAll {
266                 have = cn.bestPeerNumPieces()
267         }
268         return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
269 }
270
271 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
272         cn.setNumPieces(info.NumPieces())
273 }
274
275 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
276 // receiving badly sized BITFIELD, or invalid HAVE messages.
277 func (cn *PeerConn) setNumPieces(num pieceIndex) {
278         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
279         cn.peerPiecesChanged()
280 }
281
282 func eventAgeString(t time.Time) string {
283         if t.IsZero() {
284                 return "never"
285         }
286         return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
287 }
288
289 func (cn *PeerConn) connectionFlags() (ret string) {
290         c := func(b byte) {
291                 ret += string([]byte{b})
292         }
293         if cn.cryptoMethod == mse.CryptoMethodRC4 {
294                 c('E')
295         } else if cn.headerEncrypted {
296                 c('e')
297         }
298         ret += string(cn.Discovery)
299         if cn.utp() {
300                 c('U')
301         }
302         return
303 }
304
305 func (cn *PeerConn) utp() bool {
306         return parseNetworkString(cn.Network).Udp
307 }
308
309 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
310 func (cn *Peer) statusFlags() (ret string) {
311         c := func(b byte) {
312                 ret += string([]byte{b})
313         }
314         if cn.actualRequestState.Interested {
315                 c('i')
316         }
317         if cn.choking {
318                 c('c')
319         }
320         c('-')
321         ret += cn.connectionFlags()
322         c('-')
323         if cn.peerInterested {
324                 c('i')
325         }
326         if cn.peerChoking {
327                 c('c')
328         }
329         return
330 }
331
332 func (cn *Peer) downloadRate() float64 {
333         num := cn._stats.BytesReadUsefulData.Int64()
334         if num == 0 {
335                 return 0
336         }
337         return float64(num) / cn.totalExpectingTime().Seconds()
338 }
339
340 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
341         ret = make(map[pieceIndex]int)
342         cn.actualRequestState.Requests.Iterate(func(x uint32) bool {
343                 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
344                 return true
345         })
346         return
347 }
348
349 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
350         // \t isn't preserved in <pre> blocks?
351         if cn.closed.IsSet() {
352                 fmt.Fprint(w, "CLOSED: ")
353         }
354         fmt.Fprintln(w, cn.connStatusString())
355         prio, err := cn.peerPriority()
356         prioStr := fmt.Sprintf("%08x", prio)
357         if err != nil {
358                 prioStr += ": " + err.Error()
359         }
360         fmt.Fprintf(w, "    bep40-prio: %v\n", prioStr)
361         fmt.Fprintf(w, "    last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
362                 eventAgeString(cn.lastMessageReceived),
363                 eventAgeString(cn.completedHandshake),
364                 eventAgeString(cn.lastHelpful()),
365                 cn.cumInterest(),
366                 cn.totalExpectingTime(),
367         )
368         fmt.Fprintf(w,
369                 "    %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
370                 cn.completedString(),
371                 len(cn.peerTouchedPieces),
372                 &cn._stats.ChunksReadUseful,
373                 &cn._stats.ChunksRead,
374                 &cn._stats.ChunksWritten,
375                 cn.actualRequestState.Requests.GetCardinality(),
376                 cn.nominalMaxRequests(),
377                 cn.PeerMaxRequests,
378                 len(cn.peerRequests),
379                 localClientReqq,
380                 cn.statusFlags(),
381                 cn.downloadRate()/(1<<10),
382         )
383         fmt.Fprintf(w, "    requested pieces:")
384         type pieceNumRequestsType struct {
385                 piece       pieceIndex
386                 numRequests int
387         }
388         var pieceNumRequests []pieceNumRequestsType
389         for piece, count := range cn.numRequestsByPiece() {
390                 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
391         }
392         sort.Slice(pieceNumRequests, func(i, j int) bool {
393                 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
394         })
395         for _, elem := range pieceNumRequests {
396                 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
397         }
398         fmt.Fprintf(w, "\n")
399 }
400
401 func (p *Peer) close() {
402         if !p.closed.Set() {
403                 return
404         }
405         p.peerImpl.onClose()
406         if p.t != nil {
407                 p.t.decPeerPieceAvailability(p)
408         }
409         for _, f := range p.callbacks.PeerClosed {
410                 f(p)
411         }
412 }
413
414 func (cn *PeerConn) onClose() {
415         if cn.pex.IsEnabled() {
416                 cn.pex.Close()
417         }
418         if cn.updateRequestsTimer != nil {
419                 cn.updateRequestsTimer.Stop()
420         }
421         cn.tickleWriter()
422         if cn.conn != nil {
423                 cn.conn.Close()
424         }
425         if cb := cn.callbacks.PeerConnClosed; cb != nil {
426                 cb(cn)
427         }
428 }
429
430 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
431         return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
432 }
433
434 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
435 // https://github.com/pion/datachannel/issues/59 is fixed.
436 const writeBufferHighWaterLen = 1 << 15
437
438 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
439 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
440 func (cn *PeerConn) write(msg pp.Message) bool {
441         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
442         // We don't need to track bytes here because the connection's Writer has that behaviour injected
443         // (although there's some delay between us buffering the message, and the connection writer
444         // flushing it out.).
445         notFull := cn.messageWriter.write(msg)
446         // Last I checked only Piece messages affect stats, and we don't write those.
447         cn.wroteMsg(&msg)
448         cn.tickleWriter()
449         return notFull
450 }
451
452 func (cn *PeerConn) requestMetadataPiece(index int) {
453         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
454         if eID == pp.ExtensionDeleteNumber {
455                 return
456         }
457         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
458                 return
459         }
460         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
461         cn.write(pp.MetadataExtensionRequestMsg(eID, index))
462         for index >= len(cn.metadataRequests) {
463                 cn.metadataRequests = append(cn.metadataRequests, false)
464         }
465         cn.metadataRequests[index] = true
466 }
467
468 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
469         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
470 }
471
472 // The actual value to use as the maximum outbound requests.
473 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
474         return maxRequests(clamp(1, int64(cn.PeerMaxRequests), 2048))
475 }
476
477 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
478         ret = cn.cumulativeExpectedToReceiveChunks
479         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
480                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
481         }
482         return
483
484 }
485
486 func (cn *PeerConn) onPeerSentCancel(r Request) {
487         if _, ok := cn.peerRequests[r]; !ok {
488                 torrent.Add("unexpected cancels received", 1)
489                 return
490         }
491         if cn.fastEnabled() {
492                 cn.reject(r)
493         } else {
494                 delete(cn.peerRequests, r)
495         }
496 }
497
498 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
499         if cn.choking {
500                 return true
501         }
502         cn.choking = true
503         more = msg(pp.Message{
504                 Type: pp.Choke,
505         })
506         if cn.fastEnabled() {
507                 for r := range cn.peerRequests {
508                         // TODO: Don't reject pieces in allowed fast set.
509                         cn.reject(r)
510                 }
511         } else {
512                 cn.peerRequests = nil
513         }
514         return
515 }
516
517 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
518         if !cn.choking {
519                 return true
520         }
521         cn.choking = false
522         return msg(pp.Message{
523                 Type: pp.Unchoke,
524         })
525 }
526
527 func (cn *Peer) setInterested(interested bool) bool {
528         if cn.actualRequestState.Interested == interested {
529                 return true
530         }
531         cn.actualRequestState.Interested = interested
532         if interested {
533                 cn.lastBecameInterested = time.Now()
534         } else if !cn.lastBecameInterested.IsZero() {
535                 cn.priorInterest += time.Since(cn.lastBecameInterested)
536         }
537         cn.updateExpectingChunks()
538         // log.Printf("%p: setting interest: %v", cn, interested)
539         return cn.writeInterested(interested)
540 }
541
542 func (pc *PeerConn) writeInterested(interested bool) bool {
543         return pc.write(pp.Message{
544                 Type: func() pp.MessageType {
545                         if interested {
546                                 return pp.Interested
547                         } else {
548                                 return pp.NotInterested
549                         }
550                 }(),
551         })
552 }
553
554 // The function takes a message to be sent, and returns true if more messages
555 // are okay.
556 type messageWriter func(pp.Message) bool
557
558 func (cn *Peer) shouldRequest(r RequestIndex) error {
559         pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
560         if !cn.peerHasPiece(pi) {
561                 return errors.New("requesting piece peer doesn't have")
562         }
563         if !cn.t.peerIsActive(cn) {
564                 panic("requesting but not in active conns")
565         }
566         if cn.closed.IsSet() {
567                 panic("requesting when connection is closed")
568         }
569         if cn.t.hashingPiece(pi) {
570                 panic("piece is being hashed")
571         }
572         if cn.t.pieceQueuedForHash(pi) {
573                 panic("piece is queued for hash")
574         }
575         if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
576                 panic("peer choking and piece not allowed fast")
577         }
578         return nil
579 }
580
581 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
582         if err := cn.shouldRequest(r); err != nil {
583                 panic(err)
584         }
585         if cn.actualRequestState.Requests.Contains(r) {
586                 return true, nil
587         }
588         if maxRequests(cn.actualRequestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
589                 return true, errors.New("too many outstanding requests")
590         }
591         cn.actualRequestState.Requests.Add(r)
592         if cn.validReceiveChunks == nil {
593                 cn.validReceiveChunks = make(map[RequestIndex]int)
594         }
595         cn.validReceiveChunks[r]++
596         cn.t.pendingRequests.Inc(r)
597         cn.updateExpectingChunks()
598         ppReq := cn.t.requestIndexToRequest(r)
599         for _, f := range cn.callbacks.SentRequest {
600                 f(PeerRequestEvent{cn, ppReq})
601         }
602         return cn.peerImpl._request(ppReq), nil
603 }
604
605 func (me *PeerConn) _request(r Request) bool {
606         return me.write(pp.Message{
607                 Type:   pp.Request,
608                 Index:  r.Index,
609                 Begin:  r.Begin,
610                 Length: r.Length,
611         })
612 }
613
614 func (me *Peer) cancel(r RequestIndex) bool {
615         if !me.actualRequestState.Requests.Contains(r) {
616                 return true
617         }
618         return me._cancel(r)
619 }
620
621 func (me *PeerConn) _cancel(r RequestIndex) bool {
622         if me.cancelledRequests.Contains(r) {
623                 // Already cancelled and waiting for a response.
624                 return true
625         }
626         if me.fastEnabled() {
627                 me.cancelledRequests.Add(r)
628         } else {
629                 if !me.deleteRequest(r) {
630                         panic("request not existing should have been guarded")
631                 }
632                 if me.actualRequestState.Requests.IsEmpty() {
633                         me.updateRequests("Peer.cancel")
634                 }
635         }
636         return me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
637 }
638
639 func (cn *PeerConn) fillWriteBuffer() {
640         if !cn.applyNextRequestState() {
641                 return
642         }
643         if cn.pex.IsEnabled() {
644                 if flow := cn.pex.Share(cn.write); !flow {
645                         return
646                 }
647         }
648         cn.upload(cn.write)
649 }
650
651 func (cn *PeerConn) have(piece pieceIndex) {
652         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
653                 return
654         }
655         cn.write(pp.Message{
656                 Type:  pp.Have,
657                 Index: pp.Integer(piece),
658         })
659         cn.sentHaves.Add(bitmap.BitIndex(piece))
660 }
661
662 func (cn *PeerConn) postBitfield() {
663         if cn.sentHaves.Len() != 0 {
664                 panic("bitfield must be first have-related message sent")
665         }
666         if !cn.t.haveAnyPieces() {
667                 return
668         }
669         cn.write(pp.Message{
670                 Type:     pp.Bitfield,
671                 Bitfield: cn.t.bitfield(),
672         })
673         cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
674 }
675
676 func (cn *PeerConn) updateRequests(reason string) {
677         if cn.needRequestUpdate != "" {
678                 return
679         }
680         cn.needRequestUpdate = reason
681         cn.tickleWriter()
682 }
683
684 // Emits the indices in the Bitmaps bms in order, never repeating any index.
685 // skip is mutated during execution, and its initial values will never be
686 // emitted.
687 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
688         return func(cb iter.Callback) {
689                 for _, bm := range bms {
690                         if !iter.All(
691                                 func(_i interface{}) bool {
692                                         i := _i.(int)
693                                         if skip.Contains(bitmap.BitIndex(i)) {
694                                                 return true
695                                         }
696                                         skip.Add(bitmap.BitIndex(i))
697                                         return cb(i)
698                                 },
699                                 bm.Iter,
700                         ) {
701                                 return
702                         }
703                 }
704         }
705 }
706
707 func (cn *Peer) peerPiecesChanged() {
708         cn.t.maybeDropMutuallyCompletePeer(cn)
709 }
710
711 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
712         if newMin > cn.peerMinPieces {
713                 cn.peerMinPieces = newMin
714         }
715 }
716
717 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
718         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
719                 return errors.New("invalid piece")
720         }
721         if cn.peerHasPiece(piece) {
722                 return nil
723         }
724         cn.raisePeerMinPieces(piece + 1)
725         if !cn.peerHasPiece(piece) {
726                 cn.t.incPieceAvailability(piece)
727         }
728         cn._peerPieces.Add(uint32(piece))
729         if cn.t.wantPieceIndex(piece) {
730                 cn.updateRequests("have")
731         }
732         cn.peerPiecesChanged()
733         return nil
734 }
735
736 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
737         if len(bf)%8 != 0 {
738                 panic("expected bitfield length divisible by 8")
739         }
740         // We know that the last byte means that at most the last 7 bits are wasted.
741         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
742         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
743                 // Ignore known excess pieces.
744                 bf = bf[:cn.t.numPieces()]
745         }
746         pp := cn.newPeerPieces()
747         cn.peerSentHaveAll = false
748         for i, have := range bf {
749                 if have {
750                         cn.raisePeerMinPieces(pieceIndex(i) + 1)
751                         if !pp.Contains(bitmap.BitIndex(i)) {
752                                 cn.t.incPieceAvailability(i)
753                         }
754                 } else {
755                         if pp.Contains(bitmap.BitIndex(i)) {
756                                 cn.t.decPieceAvailability(i)
757                         }
758                 }
759                 if have {
760                         cn._peerPieces.Add(uint32(i))
761                         if cn.t.wantPieceIndex(i) {
762                                 cn.updateRequests("bitfield")
763                         }
764                 } else {
765                         cn._peerPieces.Remove(uint32(i))
766                 }
767         }
768         cn.peerPiecesChanged()
769         return nil
770 }
771
772 func (cn *Peer) onPeerHasAllPieces() {
773         t := cn.t
774         if t.haveInfo() {
775                 npp, pc := cn.newPeerPieces(), t.numPieces()
776                 for i := 0; i < pc; i += 1 {
777                         if !npp.Contains(bitmap.BitIndex(i)) {
778                                 t.incPieceAvailability(i)
779                         }
780                 }
781         }
782         cn.peerSentHaveAll = true
783         cn._peerPieces.Clear()
784         if !cn.t._pendingPieces.IsEmpty() {
785                 cn.updateRequests("Peer.onPeerHasAllPieces")
786         }
787         cn.peerPiecesChanged()
788 }
789
790 func (cn *PeerConn) onPeerSentHaveAll() error {
791         cn.onPeerHasAllPieces()
792         return nil
793 }
794
795 func (cn *PeerConn) peerSentHaveNone() error {
796         cn.t.decPeerPieceAvailability(&cn.Peer)
797         cn._peerPieces.Clear()
798         cn.peerSentHaveAll = false
799         cn.peerPiecesChanged()
800         return nil
801 }
802
803 func (c *PeerConn) requestPendingMetadata() {
804         if c.t.haveInfo() {
805                 return
806         }
807         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
808                 // Peer doesn't support this.
809                 return
810         }
811         // Request metadata pieces that we don't have in a random order.
812         var pending []int
813         for index := 0; index < c.t.metadataPieceCount(); index++ {
814                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
815                         pending = append(pending, index)
816                 }
817         }
818         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
819         for _, i := range pending {
820                 c.requestMetadataPiece(i)
821         }
822 }
823
824 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
825         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
826         if msg.Type == pp.Extended {
827                 for name, id := range cn.PeerExtensionIDs {
828                         if id != msg.ExtendedID {
829                                 continue
830                         }
831                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
832                 }
833         }
834         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
835 }
836
837 // After handshake, we know what Torrent and Client stats to include for a
838 // connection.
839 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
840         t := cn.t
841         f(&t.stats)
842         f(&t.cl.stats)
843 }
844
845 // All ConnStats that include this connection. Some objects are not known
846 // until the handshake is complete, after which it's expected to reconcile the
847 // differences.
848 func (cn *Peer) allStats(f func(*ConnStats)) {
849         f(&cn._stats)
850         if cn.reconciledHandshakeStats {
851                 cn.postHandshakeStats(f)
852         }
853 }
854
855 func (cn *PeerConn) wroteBytes(n int64) {
856         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
857 }
858
859 func (cn *PeerConn) readBytes(n int64) {
860         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
861 }
862
863 // Returns whether the connection could be useful to us. We're seeding and
864 // they want data, we don't have metainfo and they can provide it, etc.
865 func (c *Peer) useful() bool {
866         t := c.t
867         if c.closed.IsSet() {
868                 return false
869         }
870         if !t.haveInfo() {
871                 return c.supportsExtension("ut_metadata")
872         }
873         if t.seeding() && c.peerInterested {
874                 return true
875         }
876         if c.peerHasWantedPieces() {
877                 return true
878         }
879         return false
880 }
881
882 func (c *Peer) lastHelpful() (ret time.Time) {
883         ret = c.lastUsefulChunkReceived
884         if c.t.seeding() && c.lastChunkSent.After(ret) {
885                 ret = c.lastChunkSent
886         }
887         return
888 }
889
890 func (c *PeerConn) fastEnabled() bool {
891         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
892 }
893
894 func (c *PeerConn) reject(r Request) {
895         if !c.fastEnabled() {
896                 panic("fast not enabled")
897         }
898         c.write(r.ToMsg(pp.Reject))
899         delete(c.peerRequests, r)
900 }
901
902 func (c *PeerConn) onReadRequest(r Request) error {
903         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
904         if _, ok := c.peerRequests[r]; ok {
905                 torrent.Add("duplicate requests received", 1)
906                 return nil
907         }
908         if c.choking {
909                 torrent.Add("requests received while choking", 1)
910                 if c.fastEnabled() {
911                         torrent.Add("requests rejected while choking", 1)
912                         c.reject(r)
913                 }
914                 return nil
915         }
916         // TODO: What if they've already requested this?
917         if len(c.peerRequests) >= localClientReqq {
918                 torrent.Add("requests received while queue full", 1)
919                 if c.fastEnabled() {
920                         c.reject(r)
921                 }
922                 // BEP 6 says we may close here if we choose.
923                 return nil
924         }
925         if !c.t.havePiece(pieceIndex(r.Index)) {
926                 // This isn't necessarily them screwing up. We can drop pieces
927                 // from our storage, and can't communicate this to peers
928                 // except by reconnecting.
929                 requestsReceivedForMissingPieces.Add(1)
930                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
931         }
932         // Check this after we know we have the piece, so that the piece length will be known.
933         if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
934                 torrent.Add("bad requests received", 1)
935                 return errors.New("bad Request")
936         }
937         if c.peerRequests == nil {
938                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
939         }
940         value := &peerRequestState{}
941         c.peerRequests[r] = value
942         go c.peerRequestDataReader(r, value)
943         //c.tickleWriter()
944         return nil
945 }
946
947 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
948         b, err := readPeerRequestData(r, c)
949         c.locker().Lock()
950         defer c.locker().Unlock()
951         if err != nil {
952                 c.peerRequestDataReadFailed(err, r)
953         } else {
954                 if b == nil {
955                         panic("data must be non-nil to trigger send")
956                 }
957                 prs.data = b
958                 c.tickleWriter()
959         }
960 }
961
962 // If this is maintained correctly, we might be able to support optional synchronous reading for
963 // chunk sending, the way it used to work.
964 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
965         c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
966         i := pieceIndex(r.Index)
967         if c.t.pieceComplete(i) {
968                 // There used to be more code here that just duplicated the following break. Piece
969                 // completions are currently cached, so I'm not sure how helpful this update is, except to
970                 // pull any completion changes pushed to the storage backend in failed reads that got us
971                 // here.
972                 c.t.updatePieceCompletion(i)
973         }
974         // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
975         // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
976         // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
977         // next connect. TODO: Support rejecting here too.
978         if c.choking {
979                 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
980         }
981         c.choke(c.write)
982 }
983
984 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
985         b := make([]byte, r.Length)
986         p := c.t.info.Piece(int(r.Index))
987         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
988         if n == len(b) {
989                 if err == io.EOF {
990                         err = nil
991                 }
992         } else {
993                 if err == nil {
994                         panic("expected error")
995                 }
996         }
997         return b, err
998 }
999
1000 func runSafeExtraneous(f func()) {
1001         if true {
1002                 go f()
1003         } else {
1004                 f()
1005         }
1006 }
1007
1008 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1009 // exit. Returning will end the connection.
1010 func (c *PeerConn) mainReadLoop() (err error) {
1011         defer func() {
1012                 if err != nil {
1013                         torrent.Add("connection.mainReadLoop returned with error", 1)
1014                 } else {
1015                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1016                 }
1017         }()
1018         t := c.t
1019         cl := t.cl
1020
1021         decoder := pp.Decoder{
1022                 R:         bufio.NewReaderSize(c.r, 1<<17),
1023                 MaxLength: 256 * 1024,
1024                 Pool:      &t.chunkPool,
1025         }
1026         for {
1027                 var msg pp.Message
1028                 func() {
1029                         cl.unlock()
1030                         defer cl.lock()
1031                         err = decoder.Decode(&msg)
1032                 }()
1033                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1034                         cb(c, &msg)
1035                 }
1036                 if t.closed.IsSet() || c.closed.IsSet() {
1037                         return nil
1038                 }
1039                 if err != nil {
1040                         return err
1041                 }
1042                 c.lastMessageReceived = time.Now()
1043                 if msg.Keepalive {
1044                         receivedKeepalives.Add(1)
1045                         continue
1046                 }
1047                 messageTypesReceived.Add(msg.Type.String(), 1)
1048                 if msg.Type.FastExtension() && !c.fastEnabled() {
1049                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1050                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1051                 }
1052                 switch msg.Type {
1053                 case pp.Choke:
1054                         if c.peerChoking {
1055                                 break
1056                         }
1057                         if !c.fastEnabled() {
1058                                 c.deleteAllRequests()
1059                         } else {
1060                                 c.actualRequestState.Requests.Iterate(func(x uint32) bool {
1061                                         if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1062                                                 c.t.pendingRequests.Dec(x)
1063                                         }
1064                                         return true
1065                                 })
1066                         }
1067                         c.peerChoking = true
1068                         // We can then reset our interest.
1069                         c.updateRequests("choked")
1070                         c.updateExpectingChunks()
1071                 case pp.Unchoke:
1072                         if !c.peerChoking {
1073                                 return errors.New("got unchoke but not choked")
1074                         }
1075                         c.peerChoking = false
1076                         preservedCount := 0
1077                         c.actualRequestState.Requests.Iterate(func(x uint32) bool {
1078                                 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1079                                         preservedCount++
1080                                         c.t.pendingRequests.Inc(x)
1081                                 }
1082                                 return true
1083                         })
1084                         if preservedCount != 0 {
1085                                 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1086                                 // right now.
1087                                 log.Printf(
1088                                         "%v requests were preserved while being choked (fast=%v)",
1089                                         preservedCount,
1090                                         c.fastEnabled())
1091                                 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1092                         }
1093                         c.updateRequests("unchoked")
1094                         c.updateExpectingChunks()
1095                 case pp.Interested:
1096                         c.peerInterested = true
1097                         c.tickleWriter()
1098                 case pp.NotInterested:
1099                         c.peerInterested = false
1100                         // We don't clear their requests since it isn't clear in the spec.
1101                         // We'll probably choke them for this, which will clear them if
1102                         // appropriate, and is clearly specified.
1103                 case pp.Have:
1104                         err = c.peerSentHave(pieceIndex(msg.Index))
1105                 case pp.Bitfield:
1106                         err = c.peerSentBitfield(msg.Bitfield)
1107                 case pp.Request:
1108                         r := newRequestFromMessage(&msg)
1109                         err = c.onReadRequest(r)
1110                 case pp.Piece:
1111                         c.doChunkReadStats(int64(len(msg.Piece)))
1112                         err = c.receiveChunk(&msg)
1113                         if len(msg.Piece) == int(t.chunkSize) {
1114                                 t.chunkPool.Put(&msg.Piece)
1115                         }
1116                         if err != nil {
1117                                 err = fmt.Errorf("receiving chunk: %w", err)
1118                         }
1119                 case pp.Cancel:
1120                         req := newRequestFromMessage(&msg)
1121                         c.onPeerSentCancel(req)
1122                 case pp.Port:
1123                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1124                         if !ok {
1125                                 break
1126                         }
1127                         pingAddr := net.UDPAddr{
1128                                 IP:   ipa.IP,
1129                                 Port: ipa.Port,
1130                         }
1131                         if msg.Port != 0 {
1132                                 pingAddr.Port = int(msg.Port)
1133                         }
1134                         cl.eachDhtServer(func(s DhtServer) {
1135                                 go s.Ping(&pingAddr)
1136                         })
1137                 case pp.Suggest:
1138                         torrent.Add("suggests received", 1)
1139                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1140                         c.updateRequests("suggested")
1141                 case pp.HaveAll:
1142                         err = c.onPeerSentHaveAll()
1143                 case pp.HaveNone:
1144                         err = c.peerSentHaveNone()
1145                 case pp.Reject:
1146                         c.remoteRejectedRequest(c.t.requestIndexFromRequest(newRequestFromMessage(&msg)))
1147                 case pp.AllowedFast:
1148                         torrent.Add("allowed fasts received", 1)
1149                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1150                         pieceIndex := msg.Index.Int()
1151                         // If we have outstanding requests that aren't currently counted toward the combined
1152                         // outstanding request count, increment them.
1153                         if c.peerAllowedFast.CheckedAdd(msg.Index.Uint32()) && c.peerChoking &&
1154                                 // The check here could be against having the info, but really what we need to know
1155                                 // is if there are any existing requests.
1156                                 !c.actualRequestState.Requests.IsEmpty() {
1157
1158                                 i := c.actualRequestState.Requests.Iterator()
1159                                 i.AdvanceIfNeeded(t.pieceRequestIndexOffset(pieceIndex))
1160                                 for i.HasNext() {
1161                                         r := i.Next()
1162                                         if r >= t.pieceRequestIndexOffset(pieceIndex+1) {
1163                                                 break
1164                                         }
1165                                         c.t.pendingRequests.Inc(r)
1166                                 }
1167                         }
1168                         c.updateRequests("PeerConn.mainReadLoop allowed fast")
1169                 case pp.Extended:
1170                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1171                 default:
1172                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1173                 }
1174                 if err != nil {
1175                         return err
1176                 }
1177         }
1178 }
1179
1180 func (c *Peer) remoteRejectedRequest(r RequestIndex) {
1181         if c.deleteRequest(r) {
1182                 if c.actualRequestState.Requests.IsEmpty() {
1183                         c.updateRequests("Peer.remoteRejectedRequest")
1184                 }
1185                 c.decExpectedChunkReceive(r)
1186         }
1187 }
1188
1189 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1190         count := c.validReceiveChunks[r]
1191         if count == 1 {
1192                 delete(c.validReceiveChunks, r)
1193         } else if count > 1 {
1194                 c.validReceiveChunks[r] = count - 1
1195         } else {
1196                 panic(r)
1197         }
1198 }
1199
1200 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1201         defer func() {
1202                 // TODO: Should we still do this?
1203                 if err != nil {
1204                         // These clients use their own extension IDs for outgoing message
1205                         // types, which is incorrect.
1206                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1207                                 err = nil
1208                         }
1209                 }
1210         }()
1211         t := c.t
1212         cl := t.cl
1213         switch id {
1214         case pp.HandshakeExtendedID:
1215                 var d pp.ExtendedHandshakeMessage
1216                 if err := bencode.Unmarshal(payload, &d); err != nil {
1217                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1218                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1219                 }
1220                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1221                         cb(c, &d)
1222                 }
1223                 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1224                 if d.Reqq != 0 {
1225                         c.PeerMaxRequests = d.Reqq
1226                 }
1227                 c.PeerClientName = d.V
1228                 if c.PeerExtensionIDs == nil {
1229                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1230                 }
1231                 c.PeerListenPort = d.Port
1232                 c.PeerPrefersEncryption = d.Encryption
1233                 for name, id := range d.M {
1234                         if _, ok := c.PeerExtensionIDs[name]; !ok {
1235                                 peersSupportingExtension.Add(string(name), 1)
1236                         }
1237                         c.PeerExtensionIDs[name] = id
1238                 }
1239                 if d.MetadataSize != 0 {
1240                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
1241                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1242                         }
1243                 }
1244                 c.requestPendingMetadata()
1245                 if !t.cl.config.DisablePEX {
1246                         t.pex.Add(c) // we learnt enough now
1247                         c.pex.Init(c)
1248                 }
1249                 return nil
1250         case metadataExtendedId:
1251                 err := cl.gotMetadataExtensionMsg(payload, t, c)
1252                 if err != nil {
1253                         return fmt.Errorf("handling metadata extension message: %w", err)
1254                 }
1255                 return nil
1256         case pexExtendedId:
1257                 if !c.pex.IsEnabled() {
1258                         return nil // or hang-up maybe?
1259                 }
1260                 return c.pex.Recv(payload)
1261         default:
1262                 return fmt.Errorf("unexpected extended message ID: %v", id)
1263         }
1264 }
1265
1266 // Set both the Reader and Writer for the connection from a single ReadWriter.
1267 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1268         cn.r = rw
1269         cn.w = rw
1270 }
1271
1272 // Returns the Reader and Writer as a combined ReadWriter.
1273 func (cn *PeerConn) rw() io.ReadWriter {
1274         return struct {
1275                 io.Reader
1276                 io.Writer
1277         }{cn.r, cn.w}
1278 }
1279
1280 func (c *Peer) doChunkReadStats(size int64) {
1281         c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1282 }
1283
1284 // Handle a received chunk from a peer.
1285 func (c *Peer) receiveChunk(msg *pp.Message) error {
1286         chunksReceived.Add("total", 1)
1287
1288         ppReq := newRequestFromMessage(msg)
1289         req := c.t.requestIndexFromRequest(ppReq)
1290
1291         if c.peerChoking {
1292                 chunksReceived.Add("while choked", 1)
1293         }
1294
1295         if c.validReceiveChunks[req] <= 0 {
1296                 chunksReceived.Add("unexpected", 1)
1297                 return errors.New("received unexpected chunk")
1298         }
1299         c.decExpectedChunkReceive(req)
1300
1301         if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
1302                 chunksReceived.Add("due to allowed fast", 1)
1303         }
1304
1305         // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1306         // have actually already received the piece, while we have the Client unlocked to write the data
1307         // out.
1308         deletedRequest := false
1309         {
1310                 if c.actualRequestState.Requests.Contains(req) {
1311                         for _, f := range c.callbacks.ReceivedRequested {
1312                                 f(PeerMessageEvent{c, msg})
1313                         }
1314                 }
1315                 // Request has been satisfied.
1316                 if c.deleteRequest(req) {
1317                         deletedRequest = true
1318                         if !c.peerChoking {
1319                                 c._chunksReceivedWhileExpecting++
1320                         }
1321                         if c.actualRequestState.Requests.IsEmpty() {
1322                                 c.updateRequests("Peer.receiveChunk deleted request")
1323                         }
1324                 } else {
1325                         chunksReceived.Add("unwanted", 1)
1326                 }
1327         }
1328
1329         t := c.t
1330         cl := t.cl
1331
1332         // Do we actually want this chunk?
1333         if t.haveChunk(ppReq) {
1334                 chunksReceived.Add("wasted", 1)
1335                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1336                 return nil
1337         }
1338
1339         piece := &t.pieces[ppReq.Index]
1340
1341         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1342         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1343         if deletedRequest {
1344                 c.piecesReceivedSinceLastRequestUpdate++
1345                 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1346         }
1347         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1348                 f(ReceivedUsefulDataEvent{c, msg})
1349         }
1350         c.lastUsefulChunkReceived = time.Now()
1351
1352         // Need to record that it hasn't been written yet, before we attempt to do
1353         // anything with it.
1354         piece.incrementPendingWrites()
1355         // Record that we have the chunk, so we aren't trying to download it while
1356         // waiting for it to be written to storage.
1357         piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1358
1359         // Cancel pending requests for this chunk from *other* peers.
1360         t.iterPeers(func(p *Peer) {
1361                 if p == c {
1362                         return
1363                 }
1364                 p.cancel(req)
1365         })
1366
1367         err := func() error {
1368                 cl.unlock()
1369                 defer cl.lock()
1370                 concurrentChunkWrites.Add(1)
1371                 defer concurrentChunkWrites.Add(-1)
1372                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1373                 // number of connections. We write inline with receiving the chunk (with this lock dance),
1374                 // because we want to handle errors synchronously and I haven't thought of a nice way to
1375                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1376                 // that instead.
1377                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1378         }()
1379
1380         piece.decrementPendingWrites()
1381
1382         if err != nil {
1383                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1384                 t.pendRequest(req)
1385                 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1386                 // request update runs while we're writing the chunk that just failed. Then we never do a
1387                 // fresh update after pending the failed request.
1388                 c.updateRequests("Peer.receiveChunk error writing chunk")
1389                 t.onWriteChunkErr(err)
1390                 return nil
1391         }
1392
1393         c.onDirtiedPiece(pieceIndex(ppReq.Index))
1394
1395         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1396         if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1397                 t.queuePieceCheck(pieceIndex(ppReq.Index))
1398                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1399                 // chunk status (such as the haveChunk call above) to have to check all the various other
1400                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1401                 // that chunk pieces are pended at an appropriate time later however.
1402         }
1403
1404         cl.event.Broadcast()
1405         // We do this because we've written a chunk, and may change PieceState.Partial.
1406         t.publishPieceChange(pieceIndex(ppReq.Index))
1407
1408         return nil
1409 }
1410
1411 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1412         if c.peerTouchedPieces == nil {
1413                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1414         }
1415         c.peerTouchedPieces[piece] = struct{}{}
1416         ds := &c.t.pieces[piece].dirtiers
1417         if *ds == nil {
1418                 *ds = make(map[*Peer]struct{})
1419         }
1420         (*ds)[c] = struct{}{}
1421 }
1422
1423 func (c *PeerConn) uploadAllowed() bool {
1424         if c.t.cl.config.NoUpload {
1425                 return false
1426         }
1427         if c.t.dataUploadDisallowed {
1428                 return false
1429         }
1430         if c.t.seeding() {
1431                 return true
1432         }
1433         if !c.peerHasWantedPieces() {
1434                 return false
1435         }
1436         // Don't upload more than 100 KiB more than we download.
1437         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1438                 return false
1439         }
1440         return true
1441 }
1442
1443 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1444         if c.uploadTimer == nil {
1445                 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1446         } else {
1447                 c.uploadTimer.Reset(delay)
1448         }
1449 }
1450
1451 // Also handles choking and unchoking of the remote peer.
1452 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1453         // Breaking or completing this loop means we don't want to upload to the
1454         // peer anymore, and we choke them.
1455 another:
1456         for c.uploadAllowed() {
1457                 // We want to upload to the peer.
1458                 if !c.unchoke(msg) {
1459                         return false
1460                 }
1461                 for r, state := range c.peerRequests {
1462                         if state.data == nil {
1463                                 continue
1464                         }
1465                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1466                         if !res.OK() {
1467                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1468                         }
1469                         delay := res.Delay()
1470                         if delay > 0 {
1471                                 res.Cancel()
1472                                 c.setRetryUploadTimer(delay)
1473                                 // Hard to say what to return here.
1474                                 return true
1475                         }
1476                         more := c.sendChunk(r, msg, state)
1477                         delete(c.peerRequests, r)
1478                         if !more {
1479                                 return false
1480                         }
1481                         goto another
1482                 }
1483                 return true
1484         }
1485         return c.choke(msg)
1486 }
1487
1488 func (cn *PeerConn) drop() {
1489         cn.t.dropConnection(cn)
1490 }
1491
1492 func (cn *Peer) netGoodPiecesDirtied() int64 {
1493         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1494 }
1495
1496 func (c *Peer) peerHasWantedPieces() bool {
1497         if c.peerSentHaveAll {
1498                 return !c.t.haveAllPieces()
1499         }
1500         if !c.t.haveInfo() {
1501                 return !c._peerPieces.IsEmpty()
1502         }
1503         return c._peerPieces.Intersects(&c.t._pendingPieces)
1504 }
1505
1506 func (c *Peer) deleteRequest(r RequestIndex) bool {
1507         if !c.actualRequestState.Requests.CheckedRemove(r) {
1508                 return false
1509         }
1510         c.cancelledRequests.Remove(r)
1511         for _, f := range c.callbacks.DeletedRequest {
1512                 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1513         }
1514         c.updateExpectingChunks()
1515         if !c.peerChoking || c.peerAllowedFast.Contains(r/c.t.chunksPerRegularPiece()) {
1516                 c.t.pendingRequests.Dec(r)
1517         }
1518         return true
1519 }
1520
1521 func (c *Peer) deleteAllRequests() {
1522         c.actualRequestState.Requests.Clone().Iterate(func(x uint32) bool {
1523                 c.deleteRequest(x)
1524                 return true
1525         })
1526         if !c.actualRequestState.Requests.IsEmpty() {
1527                 panic(c.actualRequestState.Requests.GetCardinality())
1528         }
1529         // for c := range c.t.conns {
1530         //      c.tickleWriter()
1531         // }
1532 }
1533
1534 // This is called when something has changed that should wake the writer, such as putting stuff into
1535 // the writeBuffer, or changing some state that the writer can act on.
1536 func (c *PeerConn) tickleWriter() {
1537         c.messageWriter.writeCond.Broadcast()
1538 }
1539
1540 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1541         c.lastChunkSent = time.Now()
1542         return msg(pp.Message{
1543                 Type:  pp.Piece,
1544                 Index: r.Index,
1545                 Begin: r.Begin,
1546                 Piece: state.data,
1547         })
1548 }
1549
1550 func (c *PeerConn) setTorrent(t *Torrent) {
1551         if c.t != nil {
1552                 panic("connection already associated with a torrent")
1553         }
1554         c.t = t
1555         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1556         t.reconcileHandshakeStats(c)
1557 }
1558
1559 func (c *Peer) peerPriority() (peerPriority, error) {
1560         return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1561 }
1562
1563 func (c *Peer) remoteIp() net.IP {
1564         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1565         return net.ParseIP(host)
1566 }
1567
1568 func (c *Peer) remoteIpPort() IpPort {
1569         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1570         return IpPort{ipa.IP, uint16(ipa.Port)}
1571 }
1572
1573 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1574         f := pp.PexPeerFlags(0)
1575         if c.PeerPrefersEncryption {
1576                 f |= pp.PexPrefersEncryption
1577         }
1578         if c.outgoing {
1579                 f |= pp.PexOutgoingConn
1580         }
1581         if c.utp() {
1582                 f |= pp.PexSupportsUtp
1583         }
1584         return f
1585 }
1586
1587 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1588 // advertised listen port.
1589 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1590         if !c.outgoing && c.PeerListenPort != 0 {
1591                 switch addr := c.RemoteAddr.(type) {
1592                 case *net.TCPAddr:
1593                         dialAddr := *addr
1594                         dialAddr.Port = c.PeerListenPort
1595                         return &dialAddr
1596                 case *net.UDPAddr:
1597                         dialAddr := *addr
1598                         dialAddr.Port = c.PeerListenPort
1599                         return &dialAddr
1600                 }
1601         }
1602         return c.RemoteAddr
1603 }
1604
1605 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1606         f := c.pexPeerFlags()
1607         addr := c.dialAddr()
1608         return pexEvent{t, addr, f}
1609 }
1610
1611 func (c *PeerConn) String() string {
1612         return fmt.Sprintf("connection %p", c)
1613 }
1614
1615 func (c *Peer) trust() connectionTrust {
1616         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1617 }
1618
1619 type connectionTrust struct {
1620         Implicit            bool
1621         NetGoodPiecesDirted int64
1622 }
1623
1624 func (l connectionTrust) Less(r connectionTrust) bool {
1625         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1626 }
1627
1628 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1629 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1630 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1631         cn.locker().RLock()
1632         defer cn.locker().RUnlock()
1633         return cn.newPeerPieces()
1634 }
1635
1636 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1637 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1638         // TODO: Can we use copy on write?
1639         ret := cn._peerPieces.Clone()
1640         if cn.peerSentHaveAll {
1641                 if cn.t.haveInfo() {
1642                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1643                 } else {
1644                         ret.AddRange(0, bitmap.ToEnd)
1645                 }
1646         }
1647         return ret
1648 }
1649
1650 func (cn *Peer) stats() *ConnStats {
1651         return &cn._stats
1652 }
1653
1654 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1655         pc, ok := p.peerImpl.(*PeerConn)
1656         return pc, ok
1657 }
1658
1659 func (p *PeerConn) onNextRequestStateChanged() {
1660         p.tickleWriter()
1661 }