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