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