16 "github.com/anacrolix/missinggo"
17 "github.com/anacrolix/missinggo/bitmap"
18 "github.com/anacrolix/missinggo/prioritybitmap"
19 "github.com/bradfitz/iter"
21 "github.com/anacrolix/torrent/bencode"
22 pp "github.com/anacrolix/torrent/peer_protocol"
25 var optimizedCancels = expvar.NewInt("optimizedCancels")
30 peerSourceTracker = '\x00' // It's the default.
31 peerSourceIncoming = 'I'
36 // Maintains the state of a connection with a peer.
37 type connection struct {
40 rw io.ReadWriter // The real slim shady
44 closed missinggo.Event
48 UnwantedChunksReceived int
49 UsefulChunksReceived int
52 lastMessageReceived time.Time
53 completedHandshake time.Time
54 lastUsefulChunkReceived time.Time
55 lastChunkSent time.Time
57 // Stuff controlled by the local peer.
60 Requests map[request]struct{}
62 // Indexed by metadata piece, set to true if posted and pending a
64 metadataRequests []bool
67 // Stuff controlled by the remote peer.
71 PeerRequests map[request]struct{}
72 PeerExtensionBytes peerExtensionBytes
73 // The pieces the peer has claimed to have.
74 peerPieces bitmap.Bitmap
75 // The peer has everything. This can occur due to a special message, when
76 // we may not even know the number of pieces in the torrent yet.
78 // The highest possible number of pieces the torrent could have based on
79 // communication with the peer. Generally only useful until we have the
82 // Pieces we've accepted chunks for from the peer.
83 peerTouchedPieces map[int]struct{}
85 PeerMaxRequests int // Maximum pending requests the peer allows.
86 PeerExtensionIDs map[string]byte
89 pieceInclination []int
90 pieceRequestOrder prioritybitmap.PriorityBitmap
93 func newConnection() (c *connection) {
99 writeCh: make(chan []byte),
100 post: make(chan pp.Message),
105 func (cn *connection) remoteAddr() net.Addr {
106 return cn.conn.RemoteAddr()
109 func (cn *connection) localAddr() net.Addr {
110 return cn.conn.LocalAddr()
113 func (cn *connection) supportsExtension(ext string) bool {
114 _, ok := cn.PeerExtensionIDs[ext]
118 // The best guess at number of pieces in the torrent for this peer.
119 func (cn *connection) bestPeerNumPieces() int {
121 return cn.t.numPieces()
123 return cn.peerMinPieces
126 func (cn *connection) completedString() string {
127 return fmt.Sprintf("%d/%d", cn.peerPieces.Len(), cn.bestPeerNumPieces())
130 // Correct the PeerPieces slice length. Return false if the existing slice is
131 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
133 func (cn *connection) setNumPieces(num int) error {
134 cn.peerPieces.RemoveRange(num, -1)
135 cn.peerPiecesChanged()
139 func eventAgeString(t time.Time) string {
143 return fmt.Sprintf("%.2fs ago", time.Now().Sub(t).Seconds())
146 func (cn *connection) connectionFlags() (ret string) {
148 ret += string([]byte{b})
153 if cn.Discovery != 0 {
154 c(byte(cn.Discovery))
162 // Inspired by https://trac.transmissionbt.com/wiki/PeerStatusText
163 func (cn *connection) statusFlags() (ret string) {
165 ret += string([]byte{b})
174 ret += cn.connectionFlags()
176 if cn.PeerInterested {
185 func (cn *connection) String() string {
187 cn.WriteStatus(&buf, nil)
191 func (cn *connection) WriteStatus(w io.Writer, t *torrent) {
192 // \t isn't preserved in <pre> blocks?
193 fmt.Fprintf(w, "%+q: %s-%s\n", cn.PeerID, cn.localAddr(), cn.remoteAddr())
194 fmt.Fprintf(w, " last msg: %s, connected: %s, last useful chunk: %s\n",
195 eventAgeString(cn.lastMessageReceived),
196 eventAgeString(cn.completedHandshake),
197 eventAgeString(cn.lastUsefulChunkReceived))
199 " %s completed, %d pieces touched, good chunks: %d/%d-%d reqq: %d-%d, flags: %s\n",
200 cn.completedString(),
201 len(cn.peerTouchedPieces),
202 cn.UsefulChunksReceived,
203 cn.UnwantedChunksReceived+cn.UsefulChunksReceived,
206 len(cn.PeerRequests),
211 func (c *connection) Close() {
213 c.discardPieceInclination()
214 c.pieceRequestOrder.Clear()
215 // TODO: This call blocks sometimes, why?
219 func (c *connection) PeerHasPiece(piece int) bool {
220 return c.peerHasAll || c.peerPieces.Contains(piece)
223 func (c *connection) Post(msg pp.Message) {
226 postedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
231 func (c *connection) RequestPending(r request) bool {
232 _, ok := c.Requests[r]
236 func (c *connection) requestMetadataPiece(index int) {
237 eID := c.PeerExtensionIDs["ut_metadata"]
241 if index < len(c.metadataRequests) && c.metadataRequests[index] {
247 ExtendedPayload: func() []byte {
248 b, err := bencode.Marshal(map[string]int{
249 "msg_type": pp.RequestMetadataExtensionMsgType,
258 for index >= len(c.metadataRequests) {
259 c.metadataRequests = append(c.metadataRequests, false)
261 c.metadataRequests[index] = true
264 func (c *connection) requestedMetadataPiece(index int) bool {
265 return index < len(c.metadataRequests) && c.metadataRequests[index]
268 // The actual value to use as the maximum outbound requests.
269 func (c *connection) nominalMaxRequests() (ret int) {
270 ret = c.PeerMaxRequests
277 // Returns true if more requests can be sent.
278 func (c *connection) Request(chunk request) bool {
279 if len(c.Requests) >= c.nominalMaxRequests() {
282 if !c.PeerHasPiece(int(chunk.Index)) {
285 if c.RequestPending(chunk) {
288 c.SetInterested(true)
292 if c.Requests == nil {
293 c.Requests = make(map[request]struct{}, c.PeerMaxRequests)
295 c.Requests[chunk] = struct{}{}
296 c.requestsLowWater = len(c.Requests) / 2
301 Length: chunk.Length,
306 // Returns true if an unsatisfied request was canceled.
307 func (c *connection) Cancel(r request) bool {
308 if c.Requests == nil {
311 if _, ok := c.Requests[r]; !ok {
314 delete(c.Requests, r)
324 // Returns true if an unsatisfied request was canceled.
325 func (c *connection) PeerCancel(r request) bool {
326 if c.PeerRequests == nil {
329 if _, ok := c.PeerRequests[r]; !ok {
332 delete(c.PeerRequests, r)
336 func (c *connection) Choke() {
347 func (c *connection) Unchoke() {
357 func (c *connection) SetInterested(interested bool) {
358 if c.Interested == interested {
362 Type: func() pp.MessageType {
366 return pp.NotInterested
370 c.Interested = interested
374 // Track connection writer buffer writes and flushes, to determine its
376 connectionWriterFlush = expvar.NewInt("connectionWriterFlush")
377 connectionWriterWrite = expvar.NewInt("connectionWriterWrite")
380 // Writes buffers to the socket from the write channel.
381 func (conn *connection) writer() {
384 defer conn.t.cl.mu.Unlock()
387 // Reduce write syscalls.
388 buf := bufio.NewWriter(conn.rw)
390 if buf.Buffered() == 0 {
391 // There's nothing to write, so block until we get something.
393 case b, ok := <-conn.writeCh:
397 connectionWriterWrite.Add(1)
398 _, err := buf.Write(b)
402 case <-conn.closed.C():
406 // We already have something to write, so flush if there's nothing
409 case b, ok := <-conn.writeCh:
413 connectionWriterWrite.Add(1)
414 _, err := buf.Write(b)
418 case <-conn.closed.C():
421 connectionWriterFlush.Add(1)
431 func (conn *connection) writeOptimizer(keepAliveDelay time.Duration) {
432 defer close(conn.writeCh) // Responsible for notifying downstream routines.
433 pending := list.New() // Message queue.
434 var nextWrite []byte // Set to nil if we need to need to marshal the next message.
435 timer := time.NewTimer(keepAliveDelay)
437 lastWrite := time.Now()
439 write := conn.writeCh // Set to nil if there's nothing to write.
440 if pending.Len() == 0 {
442 } else if nextWrite == nil {
444 nextWrite, err = pending.Front().Value.(encoding.BinaryMarshaler).MarshalBinary()
452 if pending.Len() != 0 {
455 keepAliveTime := lastWrite.Add(keepAliveDelay)
456 if time.Now().Before(keepAliveTime) {
457 timer.Reset(keepAliveTime.Sub(time.Now()))
460 pending.PushBack(pp.Message{Keepalive: true})
461 postedKeepalives.Add(1)
462 case msg, ok := <-conn.post:
466 if msg.Type == pp.Cancel {
467 for e := pending.Back(); e != nil; e = e.Prev() {
468 elemMsg := e.Value.(pp.Message)
469 if elemMsg.Type == pp.Request && msg.Index == elemMsg.Index && msg.Begin == elemMsg.Begin && msg.Length == elemMsg.Length {
471 optimizedCancels.Add(1)
476 pending.PushBack(msg)
477 case write <- nextWrite:
478 pending.Remove(pending.Front())
480 lastWrite = time.Now()
481 if pending.Len() == 0 {
482 timer.Reset(keepAliveDelay)
484 case <-conn.closed.C():
490 func (cn *connection) Have(piece int) {
491 for piece >= len(cn.sentHaves) {
492 cn.sentHaves = append(cn.sentHaves, false)
494 if cn.sentHaves[piece] {
499 Index: pp.Integer(piece),
501 cn.sentHaves[piece] = true
504 func (cn *connection) Bitfield(haves []bool) {
505 if cn.sentHaves != nil {
506 panic("bitfield must be first have-related message sent")
515 func (c *connection) updateRequests() {
523 if len(c.Requests) > c.requestsLowWater {
528 if len(c.Requests) == 0 && !c.PeerChoked {
529 // So we're not choked, but we don't want anything right now. We may
530 // have completed readahead, and the readahead window has not rolled
531 // over to the next piece. Better to stay interested in case we're
532 // going to want data in the near future.
533 c.SetInterested(!c.t.haveAllPieces())
537 func (c *connection) fillRequests() {
538 c.pieceRequestOrder.IterTyped(func(piece int) (more bool) {
539 if c.t.cl.config.Debug && c.t.havePiece(piece) {
542 return c.requestPiecePendingChunks(piece)
546 func (c *connection) requestPiecePendingChunks(piece int) (again bool) {
547 return c.t.connRequestPiecePendingChunks(c, piece)
550 func (c *connection) stopRequestingPiece(piece int) {
551 c.pieceRequestOrder.Remove(piece)
554 func (c *connection) updatePiecePriority(piece int) {
555 tpp := c.t.piecePriority(piece)
556 if !c.PeerHasPiece(piece) {
557 tpp = PiecePriorityNone
559 if tpp == PiecePriorityNone {
560 c.stopRequestingPiece(piece)
563 prio := c.getPieceInclination()[piece]
565 case PiecePriorityNormal:
566 case PiecePriorityReadahead:
567 prio -= c.t.numPieces()
568 case PiecePriorityNext, PiecePriorityNow:
569 prio -= 2 * c.t.numPieces()
574 c.pieceRequestOrder.Set(piece, prio)
578 func (c *connection) getPieceInclination() []int {
579 if c.pieceInclination == nil {
580 c.pieceInclination = c.t.getConnPieceInclination()
582 return c.pieceInclination
585 func (c *connection) discardPieceInclination() {
586 if c.pieceInclination == nil {
589 c.t.putPieceInclination(c.pieceInclination)
590 c.pieceInclination = nil
593 func (c *connection) peerHasPieceChanged(piece int) {
594 c.updatePiecePriority(piece)
597 func (c *connection) peerPiecesChanged() {
599 for i := range iter.N(c.t.numPieces()) {
600 c.peerHasPieceChanged(i)
605 func (c *connection) raisePeerMinPieces(newMin int) {
606 if newMin > c.peerMinPieces {
607 c.peerMinPieces = newMin
611 func (c *connection) peerSentHave(piece int) error {
612 if c.t.haveInfo() && piece >= c.t.numPieces() {
613 return errors.New("invalid piece")
615 if c.PeerHasPiece(piece) {
618 c.raisePeerMinPieces(piece + 1)
619 c.peerPieces.Set(piece, true)
620 c.peerHasPieceChanged(piece)
624 func (c *connection) peerSentBitfield(bf []bool) error {
627 panic("expected bitfield length divisible by 8")
629 // We know that the last byte means that at most the last 7 bits are
631 c.raisePeerMinPieces(len(bf) - 7)
633 // Ignore known excess pieces.
634 bf = bf[:c.t.numPieces()]
636 for i, have := range bf {
638 c.raisePeerMinPieces(i + 1)
640 c.peerPieces.Set(i, have)
642 c.peerPiecesChanged()
646 func (cn *connection) peerSentHaveAll() error {
648 cn.peerPieces.Clear()
649 cn.peerPiecesChanged()
653 func (c *connection) peerSentHaveNone() error {
656 c.peerPiecesChanged()