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