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