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