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