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