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