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