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