16 "github.com/anacrolix/torrent/bencode"
17 pp "github.com/anacrolix/torrent/peer_protocol"
20 var optimizedCancels = expvar.NewInt("optimizedCancels")
25 peerSourceTracker = '\x00' // It's the default.
26 peerSourceIncoming = 'I'
31 // Maintains the state of a connection with a peer.
32 type connection struct {
34 rw io.ReadWriter // The real slim shady
39 mu sync.Mutex // Only for closing.
43 UnwantedChunksReceived int
44 UsefulChunksReceived int
47 lastMessageReceived time.Time
48 completedHandshake time.Time
49 lastUsefulChunkReceived time.Time
50 lastChunkSent time.Time
52 // Stuff controlled by the local peer.
55 Requests map[request]struct{}
57 // Indexed by metadata piece, set to true if posted and pending a
59 metadataRequests []bool
62 // Stuff controlled by the remote peer.
66 PeerRequests map[request]struct{}
67 PeerExtensionBytes peerExtensionBytes
68 // Whether the peer has the given piece. nil if they've not sent any
69 // related messages yet.
72 // Pieces we've accepted chunks for from the peer.
73 peerTouchedPieces map[int]struct{}
75 PeerMaxRequests int // Maximum pending requests the peer allows.
76 PeerExtensionIDs map[string]byte
80 func newConnection() (c *connection) {
86 closing: make(chan struct{}),
87 writeCh: make(chan []byte),
88 post: make(chan pp.Message),
93 func (cn *connection) remoteAddr() net.Addr {
94 return cn.conn.RemoteAddr()
97 func (cn *connection) localAddr() net.Addr {
98 return cn.conn.LocalAddr()
101 func (cn *connection) supportsExtension(ext string) bool {
102 _, ok := cn.PeerExtensionIDs[ext]
106 func (cn *connection) completedString(t *torrent) string {
107 if cn.PeerPieces == nil && !cn.peerHasAll {
110 return fmt.Sprintf("%d/%d", func() int {
118 for _, b := range cn.PeerPieces {
125 if cn.peerHasAll || cn.PeerPieces == nil {
131 return len(cn.PeerPieces)
135 // Correct the PeerPieces slice length. Return false if the existing slice is
136 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
138 func (cn *connection) setNumPieces(num int) error {
142 if cn.PeerPieces == nil {
145 if len(cn.PeerPieces) == num {
146 } else if len(cn.PeerPieces) < num {
147 cn.PeerPieces = append(cn.PeerPieces, make([]bool, num-len(cn.PeerPieces))...)
148 } else if len(cn.PeerPieces) <= (num+7)/8*8 {
149 for _, have := range cn.PeerPieces[num:] {
151 return errors.New("peer has invalid piece")
154 cn.PeerPieces = cn.PeerPieces[:num]
156 return fmt.Errorf("peer bitfield is excessively long: expected %d, have %d", num, len(cn.PeerPieces))
158 if len(cn.PeerPieces) != num {
164 func eventAgeString(t time.Time) string {
168 return fmt.Sprintf("%.2fs ago", time.Now().Sub(t).Seconds())
171 func (cn *connection) connectionFlags() (ret string) {
173 ret += string([]byte{b})
178 if cn.Discovery != 0 {
179 c(byte(cn.Discovery))
187 // Inspired by https://trac.transmissionbt.com/wiki/PeerStatusText
188 func (cn *connection) statusFlags() (ret string) {
190 ret += string([]byte{b})
199 ret += cn.connectionFlags()
201 if cn.PeerInterested {
210 func (cn *connection) String() string {
212 cn.WriteStatus(&buf, nil)
216 func (cn *connection) WriteStatus(w io.Writer, t *torrent) {
217 // \t isn't preserved in <pre> blocks?
218 fmt.Fprintf(w, "%+q: %s-%s\n", cn.PeerID, cn.localAddr(), cn.remoteAddr())
219 fmt.Fprintf(w, " last msg: %s, connected: %s, last useful chunk: %s\n",
220 eventAgeString(cn.lastMessageReceived),
221 eventAgeString(cn.completedHandshake),
222 eventAgeString(cn.lastUsefulChunkReceived))
224 " %s completed, %d pieces touched, good chunks: %d/%d-%d reqq: %d-%d, flags: %s\n",
225 cn.completedString(t),
226 len(cn.peerTouchedPieces),
227 cn.UsefulChunksReceived,
228 cn.UnwantedChunksReceived+cn.UsefulChunksReceived,
231 len(cn.PeerRequests),
236 func (c *connection) Close() {
245 // TODO: This call blocks sometimes, why?
249 func (c *connection) PeerHasPiece(piece int) bool {
253 if piece >= len(c.PeerPieces) {
256 return c.PeerPieces[piece]
259 func (c *connection) Post(msg pp.Message) {
266 func (c *connection) RequestPending(r request) bool {
267 _, ok := c.Requests[r]
271 func (c *connection) requestMetadataPiece(index int) {
272 eID := c.PeerExtensionIDs["ut_metadata"]
276 if index < len(c.metadataRequests) && c.metadataRequests[index] {
282 ExtendedPayload: func() []byte {
283 b, err := bencode.Marshal(map[string]int{
284 "msg_type": pp.RequestMetadataExtensionMsgType,
293 for index >= len(c.metadataRequests) {
294 c.metadataRequests = append(c.metadataRequests, false)
296 c.metadataRequests[index] = true
299 func (c *connection) requestedMetadataPiece(index int) bool {
300 return index < len(c.metadataRequests) && c.metadataRequests[index]
303 // Returns true if more requests can be sent.
304 func (c *connection) Request(chunk request) bool {
305 if len(c.Requests) >= c.PeerMaxRequests {
308 if !c.PeerHasPiece(int(chunk.Index)) {
311 if c.RequestPending(chunk) {
314 c.SetInterested(true)
318 if c.Requests == nil {
319 c.Requests = make(map[request]struct{}, c.PeerMaxRequests)
321 c.Requests[chunk] = struct{}{}
322 c.requestsLowWater = len(c.Requests) / 2
327 Length: chunk.Length,
332 // Returns true if an unsatisfied request was canceled.
333 func (c *connection) Cancel(r request) bool {
334 if c.Requests == nil {
337 if _, ok := c.Requests[r]; !ok {
340 delete(c.Requests, r)
350 // Returns true if an unsatisfied request was canceled.
351 func (c *connection) PeerCancel(r request) bool {
352 if c.PeerRequests == nil {
355 if _, ok := c.PeerRequests[r]; !ok {
358 delete(c.PeerRequests, r)
362 func (c *connection) Choke() {
373 func (c *connection) Unchoke() {
383 func (c *connection) SetInterested(interested bool) {
384 if c.Interested == interested {
388 Type: func() pp.MessageType {
392 return pp.NotInterested
396 c.Interested = interested
400 // Track connection writer buffer writes and flushes, to determine its
402 connectionWriterFlush = expvar.NewInt("connectionWriterFlush")
403 connectionWriterWrite = expvar.NewInt("connectionWriterWrite")
406 // Writes buffers to the socket from the write channel.
407 func (conn *connection) writer() {
408 // Reduce write syscalls.
409 buf := bufio.NewWriter(conn.rw)
411 if buf.Buffered() == 0 {
412 // There's nothing to write, so block until we get something.
414 case b, ok := <-conn.writeCh:
418 connectionWriterWrite.Add(1)
419 _, err := buf.Write(b)
428 // We already have something to write, so flush if there's nothing
431 case b, ok := <-conn.writeCh:
435 connectionWriterWrite.Add(1)
436 _, err := buf.Write(b)
444 connectionWriterFlush.Add(1)
455 func (conn *connection) writeOptimizer(keepAliveDelay time.Duration) {
456 defer close(conn.writeCh) // Responsible for notifying downstream routines.
457 pending := list.New() // Message queue.
458 var nextWrite []byte // Set to nil if we need to need to marshal the next message.
459 timer := time.NewTimer(keepAliveDelay)
461 lastWrite := time.Now()
463 write := conn.writeCh // Set to nil if there's nothing to write.
464 if pending.Len() == 0 {
466 } else if nextWrite == nil {
468 nextWrite, err = pending.Front().Value.(encoding.BinaryMarshaler).MarshalBinary()
476 if pending.Len() != 0 {
479 keepAliveTime := lastWrite.Add(keepAliveDelay)
480 if time.Now().Before(keepAliveTime) {
481 timer.Reset(keepAliveTime.Sub(time.Now()))
484 pending.PushBack(pp.Message{Keepalive: true})
485 case msg, ok := <-conn.post:
489 if msg.Type == pp.Cancel {
490 for e := pending.Back(); e != nil; e = e.Prev() {
491 elemMsg := e.Value.(pp.Message)
492 if elemMsg.Type == pp.Request && msg.Index == elemMsg.Index && msg.Begin == elemMsg.Begin && msg.Length == elemMsg.Length {
494 optimizedCancels.Add(1)
499 pending.PushBack(msg)
500 case write <- nextWrite:
501 pending.Remove(pending.Front())
503 lastWrite = time.Now()
504 if pending.Len() == 0 {
505 timer.Reset(keepAliveDelay)
513 func (cn *connection) Have(piece int) {
514 for piece >= len(cn.sentHaves) {
515 cn.sentHaves = append(cn.sentHaves, false)
517 if cn.sentHaves[piece] {
522 Index: pp.Integer(piece),
524 cn.sentHaves[piece] = true
527 func (cn *connection) Bitfield(haves []bool) {
528 if cn.sentHaves != nil {
529 panic("bitfield must be first have-related message sent")