2014-04-03 20:16:59 +08:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
2014-11-21 14:04:07 +08:00
|
|
|
"bufio"
|
2015-06-29 17:37:52 +08:00
|
|
|
"bytes"
|
2014-07-16 15:09:30 +08:00
|
|
|
"errors"
|
2014-06-26 15:29:12 +08:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2016-09-11 12:32:56 +08:00
|
|
|
"log"
|
2016-05-16 16:46:38 +08:00
|
|
|
"math/rand"
|
2014-04-03 20:16:59 +08:00
|
|
|
"net"
|
2016-02-09 21:45:47 +08:00
|
|
|
"strconv"
|
2016-09-11 12:32:56 +08:00
|
|
|
"strings"
|
2016-05-07 16:56:44 +08:00
|
|
|
"sync"
|
2014-04-03 20:16:59 +08:00
|
|
|
"time"
|
|
|
|
|
2016-02-01 18:08:52 +08:00
|
|
|
"github.com/anacrolix/missinggo"
|
2016-03-22 09:07:03 +08:00
|
|
|
"github.com/anacrolix/missinggo/bitmap"
|
2017-01-14 17:39:48 +08:00
|
|
|
"github.com/anacrolix/missinggo/iter"
|
2016-02-01 18:11:41 +08:00
|
|
|
"github.com/anacrolix/missinggo/prioritybitmap"
|
|
|
|
|
2015-04-27 12:55:01 +08:00
|
|
|
"github.com/anacrolix/torrent/bencode"
|
2017-12-01 15:12:29 +08:00
|
|
|
"github.com/anacrolix/torrent/mse"
|
2015-03-20 13:37:44 +08:00
|
|
|
pp "github.com/anacrolix/torrent/peer_protocol"
|
2014-04-03 20:16:59 +08:00
|
|
|
)
|
|
|
|
|
2016-11-26 21:05:19 +08:00
|
|
|
type peerSource string
|
2014-07-16 15:06:18 +08:00
|
|
|
|
|
|
|
const (
|
2016-11-26 21:05:19 +08:00
|
|
|
peerSourceTracker = "T" // It's the default.
|
|
|
|
peerSourceIncoming = "I"
|
|
|
|
peerSourceDHTGetPeers = "Hg"
|
|
|
|
peerSourceDHTAnnouncePeer = "Ha"
|
|
|
|
peerSourcePEX = "X"
|
2014-07-16 15:06:18 +08:00
|
|
|
)
|
|
|
|
|
2014-04-03 20:16:59 +08:00
|
|
|
// Maintains the state of a connection with a peer.
|
2014-04-09 00:36:05 +08:00
|
|
|
type connection struct {
|
2016-10-10 13:30:51 +08:00
|
|
|
t *Torrent
|
|
|
|
// The actual Conn, used for closing, and setting socket options.
|
|
|
|
conn net.Conn
|
|
|
|
// The Reader and Writer for this Conn, with hooks installed for stats,
|
|
|
|
// limiting, deadlines etc.
|
|
|
|
w io.Writer
|
|
|
|
r io.Reader
|
|
|
|
// True if the connection is operating over MSE obfuscation.
|
2017-09-13 16:20:20 +08:00
|
|
|
headerEncrypted bool
|
|
|
|
cryptoMethod uint32
|
|
|
|
Discovery peerSource
|
|
|
|
uTP bool
|
|
|
|
closed missinggo.Event
|
2014-12-03 08:22:38 +08:00
|
|
|
|
2018-02-02 16:04:56 +08:00
|
|
|
stats ConnStats
|
2014-08-28 07:32:49 +08:00
|
|
|
|
|
|
|
lastMessageReceived time.Time
|
|
|
|
completedHandshake time.Time
|
|
|
|
lastUsefulChunkReceived time.Time
|
2015-06-16 14:57:47 +08:00
|
|
|
lastChunkSent time.Time
|
2014-08-28 07:32:49 +08:00
|
|
|
|
2014-04-03 20:16:59 +08:00
|
|
|
// Stuff controlled by the local peer.
|
2014-12-05 14:58:43 +08:00
|
|
|
Interested bool
|
|
|
|
Choked bool
|
2017-08-31 21:48:52 +08:00
|
|
|
requests map[request]struct{}
|
2014-12-05 14:58:43 +08:00
|
|
|
requestsLowWater int
|
2015-03-27 12:36:59 +08:00
|
|
|
// Indexed by metadata piece, set to true if posted and pending a
|
|
|
|
// response.
|
|
|
|
metadataRequests []bool
|
2016-01-04 19:37:49 +08:00
|
|
|
sentHaves []bool
|
2014-04-03 20:16:59 +08:00
|
|
|
|
|
|
|
// Stuff controlled by the remote peer.
|
2018-01-06 12:50:45 +08:00
|
|
|
PeerID PeerID
|
2014-08-21 16:12:49 +08:00
|
|
|
PeerInterested bool
|
|
|
|
PeerChoked bool
|
|
|
|
PeerRequests map[request]struct{}
|
|
|
|
PeerExtensionBytes peerExtensionBytes
|
2016-03-22 09:07:03 +08:00
|
|
|
// The pieces the peer has claimed to have.
|
|
|
|
peerPieces bitmap.Bitmap
|
|
|
|
// The peer has everything. This can occur due to a special message, when
|
|
|
|
// we may not even know the number of pieces in the torrent yet.
|
2018-01-29 15:18:08 +08:00
|
|
|
peerSentHaveAll bool
|
2016-03-22 09:07:03 +08:00
|
|
|
// The highest possible number of pieces the torrent could have based on
|
|
|
|
// communication with the peer. Generally only useful until we have the
|
|
|
|
// torrent info.
|
|
|
|
peerMinPieces int
|
2015-08-03 23:12:09 +08:00
|
|
|
// Pieces we've accepted chunks for from the peer.
|
|
|
|
peerTouchedPieces map[int]struct{}
|
2015-03-12 17:06:23 +08:00
|
|
|
|
2014-06-26 22:57:07 +08:00
|
|
|
PeerMaxRequests int // Maximum pending requests the peer allows.
|
2015-03-27 12:36:59 +08:00
|
|
|
PeerExtensionIDs map[string]byte
|
2014-06-29 16:57:49 +08:00
|
|
|
PeerClientName string
|
2016-02-01 18:11:41 +08:00
|
|
|
|
|
|
|
pieceInclination []int
|
|
|
|
pieceRequestOrder prioritybitmap.PriorityBitmap
|
2016-05-07 16:56:44 +08:00
|
|
|
|
2017-08-31 14:26:45 +08:00
|
|
|
postedBuffer bytes.Buffer
|
2017-09-18 10:09:08 +08:00
|
|
|
uploadTimer *time.Timer
|
2017-08-31 14:26:45 +08:00
|
|
|
writerCond sync.Cond
|
2016-05-07 16:56:44 +08:00
|
|
|
}
|
|
|
|
|
2018-01-29 15:18:08 +08:00
|
|
|
func (cn *connection) peerHasAllPieces() (all bool, known bool) {
|
|
|
|
if cn.peerSentHaveAll {
|
|
|
|
return true, true
|
|
|
|
}
|
|
|
|
if !cn.t.haveInfo() {
|
|
|
|
return false, false
|
|
|
|
}
|
|
|
|
return bitmap.Flip(cn.peerPieces, 0, cn.t.numPieces()).IsEmpty(), true
|
|
|
|
}
|
|
|
|
|
2016-05-07 16:56:44 +08:00
|
|
|
func (cn *connection) mu() sync.Locker {
|
|
|
|
return &cn.t.cl.mu
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2015-03-13 03:21:13 +08:00
|
|
|
func (cn *connection) remoteAddr() net.Addr {
|
|
|
|
return cn.conn.RemoteAddr()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) localAddr() net.Addr {
|
|
|
|
return cn.conn.LocalAddr()
|
|
|
|
}
|
|
|
|
|
2014-12-03 15:07:50 +08:00
|
|
|
func (cn *connection) supportsExtension(ext string) bool {
|
|
|
|
_, ok := cn.PeerExtensionIDs[ext]
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2016-03-22 09:07:03 +08:00
|
|
|
// The best guess at number of pieces in the torrent for this peer.
|
|
|
|
func (cn *connection) bestPeerNumPieces() int {
|
|
|
|
if cn.t.haveInfo() {
|
|
|
|
return cn.t.numPieces()
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
2016-03-22 09:07:03 +08:00
|
|
|
return cn.peerMinPieces
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) completedString() string {
|
|
|
|
return fmt.Sprintf("%d/%d", cn.peerPieces.Len(), cn.bestPeerNumPieces())
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
|
|
|
|
2014-07-16 15:09:30 +08:00
|
|
|
// Correct the PeerPieces slice length. Return false if the existing slice is
|
|
|
|
// invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
|
|
|
|
// messages.
|
|
|
|
func (cn *connection) setNumPieces(num int) error {
|
2016-03-22 09:07:03 +08:00
|
|
|
cn.peerPieces.RemoveRange(num, -1)
|
|
|
|
cn.peerPiecesChanged()
|
2014-07-16 15:09:30 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-09-11 18:30:13 +08:00
|
|
|
func eventAgeString(t time.Time) string {
|
|
|
|
if t.IsZero() {
|
|
|
|
return "never"
|
|
|
|
}
|
2017-11-07 13:11:59 +08:00
|
|
|
return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
|
2014-09-11 18:30:13 +08:00
|
|
|
}
|
|
|
|
|
2015-08-02 02:06:22 +08:00
|
|
|
func (cn *connection) connectionFlags() (ret string) {
|
2014-06-26 15:29:12 +08:00
|
|
|
c := func(b byte) {
|
2015-03-18 15:38:29 +08:00
|
|
|
ret += string([]byte{b})
|
2014-12-09 14:26:06 +08:00
|
|
|
}
|
2017-09-13 16:20:20 +08:00
|
|
|
if cn.cryptoMethod == mse.CryptoMethodRC4 {
|
2015-03-18 15:38:29 +08:00
|
|
|
c('E')
|
2017-09-13 16:20:20 +08:00
|
|
|
} else if cn.headerEncrypted {
|
|
|
|
c('e')
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
2016-11-26 21:05:19 +08:00
|
|
|
ret += string(cn.Discovery)
|
2014-11-17 03:29:31 +08:00
|
|
|
if cn.uTP {
|
|
|
|
c('T')
|
|
|
|
}
|
2015-08-02 02:06:22 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Inspired by https://trac.transmissionbt.com/wiki/PeerStatusText
|
|
|
|
func (cn *connection) statusFlags() (ret string) {
|
|
|
|
c := func(b byte) {
|
|
|
|
ret += string([]byte{b})
|
|
|
|
}
|
|
|
|
if cn.Interested {
|
|
|
|
c('i')
|
|
|
|
}
|
|
|
|
if cn.Choked {
|
|
|
|
c('c')
|
|
|
|
}
|
|
|
|
c('-')
|
|
|
|
ret += cn.connectionFlags()
|
2015-03-18 15:38:29 +08:00
|
|
|
c('-')
|
|
|
|
if cn.PeerInterested {
|
|
|
|
c('i')
|
|
|
|
}
|
|
|
|
if cn.PeerChoked {
|
|
|
|
c('c')
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-29 17:37:52 +08:00
|
|
|
func (cn *connection) String() string {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
cn.WriteStatus(&buf, nil)
|
|
|
|
return buf.String()
|
|
|
|
}
|
|
|
|
|
2016-04-03 16:40:43 +08:00
|
|
|
func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
|
2015-03-18 15:38:29 +08:00
|
|
|
// \t isn't preserved in <pre> blocks?
|
2018-01-06 09:34:31 +08:00
|
|
|
fmt.Fprintf(w, "%-40s: %s-%s\n", cn.PeerID, cn.localAddr(), cn.remoteAddr())
|
2018-02-01 15:45:58 +08:00
|
|
|
fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s\n",
|
2015-03-18 15:38:29 +08:00
|
|
|
eventAgeString(cn.lastMessageReceived),
|
|
|
|
eventAgeString(cn.completedHandshake),
|
2018-02-01 15:45:58 +08:00
|
|
|
eventAgeString(cn.lastHelpful()))
|
2015-05-15 06:39:53 +08:00
|
|
|
fmt.Fprintf(w,
|
2015-08-03 23:12:09 +08:00
|
|
|
" %s completed, %d pieces touched, good chunks: %d/%d-%d reqq: %d-%d, flags: %s\n",
|
2016-03-22 09:07:03 +08:00
|
|
|
cn.completedString(),
|
2015-08-03 23:12:09 +08:00
|
|
|
len(cn.peerTouchedPieces),
|
2018-02-02 16:04:56 +08:00
|
|
|
cn.stats.ChunksReadUseful,
|
|
|
|
cn.stats.ChunksReadUnwanted+cn.stats.ChunksReadUseful,
|
|
|
|
cn.stats.ChunksWritten,
|
2017-08-31 21:48:52 +08:00
|
|
|
cn.numLocalRequests(),
|
2015-03-18 15:38:29 +08:00
|
|
|
len(cn.PeerRequests),
|
2015-05-15 06:39:53 +08:00
|
|
|
cn.statusFlags(),
|
|
|
|
)
|
2017-09-23 13:25:47 +08:00
|
|
|
roi := cn.pieceRequestOrderIter()
|
|
|
|
fmt.Fprintf(w, " next pieces: %v%s\n",
|
|
|
|
iter.ToSlice(iter.Head(10, roi)),
|
|
|
|
func() string {
|
|
|
|
if cn.shouldRequestWithoutBias() {
|
|
|
|
return " (fastest)"
|
|
|
|
} else {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}())
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) Close() {
|
2017-09-18 11:40:36 +08:00
|
|
|
if !cn.closed.Set() {
|
|
|
|
return
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.discardPieceInclination()
|
|
|
|
cn.pieceRequestOrder.Clear()
|
2016-05-11 21:50:21 +08:00
|
|
|
if cn.conn != nil {
|
2017-10-12 14:51:47 +08:00
|
|
|
go cn.conn.Close()
|
2016-05-11 21:50:21 +08:00
|
|
|
}
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) PeerHasPiece(piece int) bool {
|
2018-01-29 15:18:08 +08:00
|
|
|
return cn.peerSentHaveAll || cn.peerPieces.Contains(piece)
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) Post(msg pp.Message) {
|
2017-09-01 08:53:59 +08:00
|
|
|
messageTypesPosted.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
|
2017-08-31 14:26:45 +08:00
|
|
|
cn.postedBuffer.Write(msg.MustMarshalBinary())
|
2017-09-01 13:26:50 +08:00
|
|
|
cn.tickleWriter()
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) requestMetadataPiece(index int) {
|
|
|
|
eID := cn.PeerExtensionIDs["ut_metadata"]
|
2015-03-27 12:36:59 +08:00
|
|
|
if eID == 0 {
|
|
|
|
return
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
|
2015-03-27 12:36:59 +08:00
|
|
|
return
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.Post(pp.Message{
|
2015-03-27 12:36:59 +08:00
|
|
|
Type: pp.Extended,
|
|
|
|
ExtendedID: eID,
|
|
|
|
ExtendedPayload: func() []byte {
|
|
|
|
b, err := bencode.Marshal(map[string]int{
|
|
|
|
"msg_type": pp.RequestMetadataExtensionMsgType,
|
|
|
|
"piece": index,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
}(),
|
|
|
|
})
|
2016-04-19 12:11:11 +08:00
|
|
|
for index >= len(cn.metadataRequests) {
|
|
|
|
cn.metadataRequests = append(cn.metadataRequests, false)
|
2015-03-27 12:36:59 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.metadataRequests[index] = true
|
2015-03-27 12:36:59 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) requestedMetadataPiece(index int) bool {
|
|
|
|
return index < len(cn.metadataRequests) && cn.metadataRequests[index]
|
2015-03-27 12:36:59 +08:00
|
|
|
}
|
|
|
|
|
2016-02-08 13:09:12 +08:00
|
|
|
// The actual value to use as the maximum outbound requests.
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) nominalMaxRequests() (ret int) {
|
|
|
|
ret = cn.PeerMaxRequests
|
2016-02-08 13:09:12 +08:00
|
|
|
if ret > 64 {
|
|
|
|
ret = 64
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-04-16 15:33:33 +08:00
|
|
|
// Returns true if an unsatisfied request was canceled.
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) PeerCancel(r request) bool {
|
|
|
|
if cn.PeerRequests == nil {
|
2014-04-16 15:33:33 +08:00
|
|
|
return false
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
if _, ok := cn.PeerRequests[r]; !ok {
|
2014-04-16 15:33:33 +08:00
|
|
|
return false
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
delete(cn.PeerRequests, r)
|
2014-04-16 15:33:33 +08:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2017-09-18 10:09:08 +08:00
|
|
|
func (cn *connection) Choke(msg func(pp.Message) bool) bool {
|
2016-04-19 12:11:11 +08:00
|
|
|
if cn.Choked {
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2014-05-21 15:49:28 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.PeerRequests = nil
|
|
|
|
cn.Choked = true
|
2017-09-18 10:09:08 +08:00
|
|
|
return msg(pp.Message{
|
|
|
|
Type: pp.Choke,
|
|
|
|
})
|
2014-05-21 15:49:28 +08:00
|
|
|
}
|
|
|
|
|
2017-09-18 10:09:08 +08:00
|
|
|
func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
|
2016-04-19 12:11:11 +08:00
|
|
|
if !cn.Choked {
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
2017-09-18 10:09:08 +08:00
|
|
|
cn.Choked = false
|
|
|
|
return msg(pp.Message{
|
2014-08-21 16:12:49 +08:00
|
|
|
Type: pp.Unchoke,
|
2014-04-03 20:16:59 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-08-31 21:48:52 +08:00
|
|
|
func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
|
2016-04-19 12:11:11 +08:00
|
|
|
if cn.Interested == interested {
|
2017-08-31 21:48:52 +08:00
|
|
|
return true
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
2017-08-31 21:48:52 +08:00
|
|
|
cn.Interested = interested
|
|
|
|
// log.Printf("%p: setting interest: %v", cn, interested)
|
|
|
|
return msg(pp.Message{
|
2014-08-21 16:12:49 +08:00
|
|
|
Type: func() pp.MessageType {
|
2014-04-03 20:16:59 +08:00
|
|
|
if interested {
|
2014-08-21 16:12:49 +08:00
|
|
|
return pp.Interested
|
2014-04-03 20:16:59 +08:00
|
|
|
} else {
|
2014-08-21 16:12:49 +08:00
|
|
|
return pp.NotInterested
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
}(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-11-06 11:53:00 +08:00
|
|
|
// The function takes a message to be sent, and returns true if more messages
|
|
|
|
// are okay.
|
|
|
|
type messageWriter func(pp.Message) bool
|
|
|
|
|
2018-02-02 10:36:18 +08:00
|
|
|
// Proxies the messageWriter's response.
|
2017-11-06 11:53:00 +08:00
|
|
|
func (cn *connection) request(r request, mw messageWriter) bool {
|
|
|
|
if cn.requests == nil {
|
|
|
|
cn.requests = make(map[request]struct{}, cn.nominalMaxRequests())
|
|
|
|
}
|
|
|
|
if _, ok := cn.requests[r]; ok {
|
|
|
|
panic("chunk already requested")
|
|
|
|
}
|
|
|
|
if !cn.PeerHasPiece(r.Index.Int()) {
|
|
|
|
panic("requesting piece peer doesn't have")
|
|
|
|
}
|
|
|
|
cn.requests[r] = struct{}{}
|
2018-02-02 10:36:18 +08:00
|
|
|
if _, ok := cn.t.conns[cn]; !ok {
|
|
|
|
panic("requesting but not in active conns")
|
|
|
|
}
|
2018-02-01 11:46:03 +08:00
|
|
|
cn.t.pendingRequests[r]++
|
2017-11-06 11:53:00 +08:00
|
|
|
return mw(pp.Message{
|
|
|
|
Type: pp.Request,
|
|
|
|
Index: r.Index,
|
|
|
|
Begin: r.Begin,
|
|
|
|
Length: r.Length,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-08-31 21:48:52 +08:00
|
|
|
func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
|
2017-09-01 08:36:43 +08:00
|
|
|
numFillBuffers.Add(1)
|
2017-09-02 08:36:43 +08:00
|
|
|
cancel, new, i := cn.desiredRequestState()
|
2017-08-31 21:48:52 +08:00
|
|
|
if !cn.SetInterested(i, msg) {
|
|
|
|
return
|
|
|
|
}
|
2017-09-02 08:36:43 +08:00
|
|
|
if cancel && len(cn.requests) != 0 {
|
|
|
|
fillBufferSentCancels.Add(1)
|
|
|
|
for r := range cn.requests {
|
2017-09-01 13:26:50 +08:00
|
|
|
cn.deleteRequest(r)
|
2017-08-31 21:48:52 +08:00
|
|
|
// log.Printf("%p: cancelling request: %v", cn, r)
|
2017-09-18 11:42:42 +08:00
|
|
|
if !msg(makeCancelMessage(r)) {
|
2017-08-31 21:48:52 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-09-02 08:36:43 +08:00
|
|
|
if len(new) != 0 {
|
|
|
|
fillBufferSentRequests.Add(1)
|
|
|
|
for _, r := range new {
|
2017-11-06 11:53:00 +08:00
|
|
|
if !cn.request(r, msg) {
|
|
|
|
// If we didn't completely top up the requests, we shouldn't
|
|
|
|
// mark the low water, since we'll want to top up the requests
|
|
|
|
// as soon as we have more write buffer space.
|
2017-08-31 21:48:52 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2017-09-02 08:36:43 +08:00
|
|
|
cn.requestsLowWater = len(cn.requests) / 2
|
2017-09-01 08:36:43 +08:00
|
|
|
}
|
2017-09-18 10:09:08 +08:00
|
|
|
cn.upload(msg)
|
2017-08-31 21:48:52 +08:00
|
|
|
}
|
|
|
|
|
2017-12-02 21:35:09 +08:00
|
|
|
// Routine that writes to the peer. Some of what to write is buffered by
|
|
|
|
// activity elsewhere in the Client, and some is determined locally when the
|
|
|
|
// connection is writable.
|
2016-05-07 16:56:44 +08:00
|
|
|
func (cn *connection) writer(keepAliveTimeout time.Duration) {
|
2017-08-31 14:26:45 +08:00
|
|
|
var (
|
|
|
|
buf bytes.Buffer
|
|
|
|
lastWrite time.Time = time.Now()
|
|
|
|
)
|
|
|
|
var keepAliveTimer *time.Timer
|
|
|
|
keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
|
2016-05-07 16:56:44 +08:00
|
|
|
cn.mu().Lock()
|
|
|
|
defer cn.mu().Unlock()
|
2017-08-31 14:26:45 +08:00
|
|
|
if time.Since(lastWrite) >= keepAliveTimeout {
|
2017-09-01 13:26:50 +08:00
|
|
|
cn.tickleWriter()
|
2017-08-31 14:26:45 +08:00
|
|
|
}
|
|
|
|
keepAliveTimer.Reset(keepAliveTimeout)
|
|
|
|
})
|
|
|
|
cn.mu().Lock()
|
|
|
|
defer cn.mu().Unlock()
|
|
|
|
defer cn.Close()
|
|
|
|
defer keepAliveTimer.Stop()
|
2014-08-21 16:12:49 +08:00
|
|
|
for {
|
2018-02-02 10:36:18 +08:00
|
|
|
if cn.closed.IsSet() {
|
|
|
|
return
|
|
|
|
}
|
2017-08-31 14:26:45 +08:00
|
|
|
buf.Write(cn.postedBuffer.Bytes())
|
|
|
|
cn.postedBuffer.Reset()
|
2017-08-31 21:48:52 +08:00
|
|
|
if buf.Len() == 0 {
|
|
|
|
cn.fillWriteBuffer(func(msg pp.Message) bool {
|
2017-09-01 08:53:59 +08:00
|
|
|
cn.wroteMsg(&msg)
|
2017-08-31 21:48:52 +08:00
|
|
|
buf.Write(msg.MustMarshalBinary())
|
|
|
|
return buf.Len() < 1<<16
|
|
|
|
})
|
|
|
|
}
|
2017-08-31 14:26:45 +08:00
|
|
|
if buf.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
|
|
|
|
buf.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
|
|
|
|
postedKeepalives.Add(1)
|
|
|
|
}
|
|
|
|
if buf.Len() == 0 {
|
2017-11-05 12:26:23 +08:00
|
|
|
// TODO: Minimize wakeups....
|
2017-08-31 14:26:45 +08:00
|
|
|
cn.writerCond.Wait()
|
|
|
|
continue
|
2016-05-07 16:56:44 +08:00
|
|
|
}
|
|
|
|
cn.mu().Unlock()
|
2017-08-31 14:26:45 +08:00
|
|
|
// log.Printf("writing %d bytes", buf.Len())
|
|
|
|
n, err := cn.w.Write(buf.Bytes())
|
|
|
|
cn.mu().Lock()
|
|
|
|
if n != 0 {
|
|
|
|
lastWrite = time.Now()
|
2016-05-07 16:56:44 +08:00
|
|
|
keepAliveTimer.Reset(keepAliveTimeout)
|
|
|
|
}
|
2017-08-31 14:26:45 +08:00
|
|
|
if err != nil {
|
2014-08-21 16:12:49 +08:00
|
|
|
return
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
2017-08-31 14:26:45 +08:00
|
|
|
if n != buf.Len() {
|
|
|
|
panic("short write")
|
|
|
|
}
|
|
|
|
buf.Reset()
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
}
|
2016-01-04 19:37:49 +08:00
|
|
|
|
|
|
|
func (cn *connection) Have(piece int) {
|
|
|
|
for piece >= len(cn.sentHaves) {
|
|
|
|
cn.sentHaves = append(cn.sentHaves, false)
|
|
|
|
}
|
|
|
|
if cn.sentHaves[piece] {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cn.Post(pp.Message{
|
|
|
|
Type: pp.Have,
|
|
|
|
Index: pp.Integer(piece),
|
|
|
|
})
|
|
|
|
cn.sentHaves[piece] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) Bitfield(haves []bool) {
|
2016-01-04 19:56:36 +08:00
|
|
|
if cn.sentHaves != nil {
|
2016-01-04 19:37:49 +08:00
|
|
|
panic("bitfield must be first have-related message sent")
|
|
|
|
}
|
|
|
|
cn.Post(pp.Message{
|
|
|
|
Type: pp.Bitfield,
|
|
|
|
Bitfield: haves,
|
|
|
|
})
|
2016-05-11 21:50:21 +08:00
|
|
|
// Make a copy of haves, as that's read when the message is marshalled
|
|
|
|
// without the lock. Also it obviously shouldn't change in the Msg due to
|
|
|
|
// changes in .sentHaves.
|
|
|
|
cn.sentHaves = append([]bool(nil), haves...)
|
2016-01-04 19:37:49 +08:00
|
|
|
}
|
2016-01-24 12:21:17 +08:00
|
|
|
|
2018-02-01 11:46:48 +08:00
|
|
|
// Determines interest and requests to send to a connected peer.
|
2017-08-17 23:51:02 +08:00
|
|
|
func nextRequestState(
|
|
|
|
networkingEnabled bool,
|
|
|
|
currentRequests map[request]struct{},
|
|
|
|
peerChoking bool,
|
2018-02-01 13:14:13 +08:00
|
|
|
iterPendingRequests func(f func(request) bool),
|
2017-08-17 23:51:02 +08:00
|
|
|
requestsLowWater int,
|
|
|
|
requestsHighWater int,
|
|
|
|
) (
|
2017-09-23 13:25:47 +08:00
|
|
|
cancelExisting bool, // Cancel all our pending requests
|
|
|
|
newRequests []request, // Chunks to request that we currently aren't
|
|
|
|
interested bool, // Whether we should indicate interest, even if we don't request anything
|
2017-08-17 23:51:02 +08:00
|
|
|
) {
|
2017-09-23 13:25:47 +08:00
|
|
|
if !networkingEnabled {
|
2017-09-02 08:36:43 +08:00
|
|
|
return true, nil, false
|
2017-08-17 23:51:02 +08:00
|
|
|
}
|
2017-09-23 13:25:47 +08:00
|
|
|
if len(currentRequests) > requestsLowWater {
|
|
|
|
return false, nil, true
|
2017-08-17 23:51:02 +08:00
|
|
|
}
|
2018-02-01 13:14:13 +08:00
|
|
|
iterPendingRequests(func(r request) bool {
|
2017-09-23 13:25:47 +08:00
|
|
|
interested = true
|
|
|
|
if peerChoking {
|
|
|
|
return false
|
|
|
|
}
|
2018-02-01 13:14:13 +08:00
|
|
|
if _, ok := currentRequests[r]; !ok {
|
|
|
|
if newRequests == nil {
|
|
|
|
newRequests = make([]request, 0, requestsHighWater-len(currentRequests))
|
2017-09-02 08:36:43 +08:00
|
|
|
}
|
2018-02-01 13:14:13 +08:00
|
|
|
newRequests = append(newRequests, r)
|
|
|
|
}
|
|
|
|
return len(currentRequests)+len(newRequests) < requestsHighWater
|
2017-08-17 23:51:02 +08:00
|
|
|
})
|
2017-09-23 13:25:47 +08:00
|
|
|
return
|
2017-08-17 23:51:02 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) updateRequests() {
|
2018-01-25 14:18:36 +08:00
|
|
|
// log.Print("update requests")
|
2017-09-01 13:26:50 +08:00
|
|
|
cn.tickleWriter()
|
2017-08-31 21:48:52 +08:00
|
|
|
}
|
|
|
|
|
2017-11-06 11:53:00 +08:00
|
|
|
// Emits the indices in the Bitmaps bms in order, never repeating any index.
|
|
|
|
// skip is mutated during execution, and its initial values will never be
|
|
|
|
// emitted.
|
2017-09-23 13:25:47 +08:00
|
|
|
func iterBitmapsDistinct(skip bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
|
|
|
|
return func(cb iter.Callback) {
|
|
|
|
for _, bm := range bms {
|
|
|
|
if !iter.All(func(i interface{}) bool {
|
|
|
|
skip.Add(i.(int))
|
|
|
|
return cb(i)
|
|
|
|
}, bitmap.Sub(bm, skip).Iter) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) unbiasedPieceRequestOrder() iter.Func {
|
|
|
|
now, readahead := cn.t.readerPiecePriorities()
|
2017-12-02 21:35:09 +08:00
|
|
|
// Pieces to skip include pieces the peer doesn't have
|
2017-11-06 11:53:00 +08:00
|
|
|
skip := bitmap.Flip(cn.peerPieces, 0, cn.t.numPieces())
|
2017-12-02 21:35:09 +08:00
|
|
|
// And pieces that we already have.
|
2017-11-06 11:53:00 +08:00
|
|
|
skip.Union(cn.t.completedPieces)
|
2017-12-02 21:35:09 +08:00
|
|
|
// Return an iterator over the different priority classes, minus the skip
|
|
|
|
// pieces.
|
2018-01-12 09:24:37 +08:00
|
|
|
return iter.Chain(
|
|
|
|
iterBitmapsDistinct(skip, now, readahead),
|
|
|
|
func(cb iter.Callback) {
|
|
|
|
cn.t.pendingPieces.IterTyped(func(piece int) bool {
|
|
|
|
if skip.Contains(piece) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
more := cb(piece)
|
|
|
|
skip.Add(piece)
|
|
|
|
return more
|
|
|
|
})
|
|
|
|
},
|
|
|
|
)
|
2017-09-23 13:25:47 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// The connection should download highest priority pieces first, without any
|
|
|
|
// inclination toward avoiding wastage. Generally we might do this if there's
|
|
|
|
// a single connection, or this is the fastest connection, and we have active
|
|
|
|
// readers that signal an ordering preference. It's conceivable that the best
|
|
|
|
// connection should do this, since it's least likely to waste our time if
|
|
|
|
// assigned to the highest priority pieces, and assigning more than one this
|
|
|
|
// role would cause significant wasted bandwidth.
|
|
|
|
func (cn *connection) shouldRequestWithoutBias() bool {
|
|
|
|
if cn.t.requestStrategy != 2 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if len(cn.t.readers) == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if len(cn.t.conns) == 1 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if cn == cn.t.fastestConn {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) pieceRequestOrderIter() iter.Func {
|
|
|
|
if cn.shouldRequestWithoutBias() {
|
|
|
|
return cn.unbiasedPieceRequestOrder()
|
|
|
|
} else {
|
|
|
|
return cn.pieceRequestOrder.Iter
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-01 13:14:13 +08:00
|
|
|
func (cn *connection) iterPendingRequests(f func(request) bool) {
|
|
|
|
cn.pieceRequestOrderIter()(func(_piece interface{}) bool {
|
|
|
|
piece := _piece.(int)
|
|
|
|
return iterUndirtiedChunks(piece, cn.t, func(cs chunkSpec) bool {
|
|
|
|
r := request{pp.Integer(piece), cs}
|
|
|
|
// log.Println(r, cn.t.pendingRequests[r], cn.requests)
|
|
|
|
// if _, ok := cn.requests[r]; !ok && cn.t.pendingRequests[r] != 0 {
|
|
|
|
// return true
|
|
|
|
// }
|
|
|
|
return f(r)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-09-02 08:36:43 +08:00
|
|
|
func (cn *connection) desiredRequestState() (bool, []request, bool) {
|
2017-08-31 21:48:52 +08:00
|
|
|
return nextRequestState(
|
2017-08-17 23:51:02 +08:00
|
|
|
cn.t.networkingEnabled,
|
2017-08-31 21:48:52 +08:00
|
|
|
cn.requests,
|
2017-08-17 23:51:02 +08:00
|
|
|
cn.PeerChoked,
|
2018-02-01 13:14:13 +08:00
|
|
|
cn.iterPendingRequests,
|
2017-08-17 23:51:02 +08:00
|
|
|
cn.requestsLowWater,
|
2017-08-31 21:48:52 +08:00
|
|
|
cn.nominalMaxRequests(),
|
|
|
|
)
|
2016-01-24 12:21:17 +08:00
|
|
|
}
|
|
|
|
|
2018-02-01 13:14:13 +08:00
|
|
|
func iterUndirtiedChunks(piece int, t *Torrent, f func(chunkSpec) bool) bool {
|
2017-08-17 23:51:02 +08:00
|
|
|
chunkIndices := t.pieces[piece].undirtiedChunkIndices().ToSortedSlice()
|
2018-02-01 11:46:48 +08:00
|
|
|
// TODO: Use "math/rand".Shuffle >= Go 1.10
|
2017-08-17 23:51:02 +08:00
|
|
|
return iter.ForPerm(len(chunkIndices), func(i int) bool {
|
|
|
|
return f(t.chunkIndexSpec(chunkIndices[i], piece))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-09-01 13:26:50 +08:00
|
|
|
// check callers updaterequests
|
|
|
|
func (cn *connection) stopRequestingPiece(piece int) bool {
|
|
|
|
return cn.pieceRequestOrder.Remove(piece)
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
|
|
|
|
2016-10-31 13:22:07 +08:00
|
|
|
// This is distinct from Torrent piece priority, which is the user's
|
2018-01-25 14:02:52 +08:00
|
|
|
// preference. Connection piece priority is specific to a connection and is
|
|
|
|
// used to pseudorandomly avoid connections always requesting the same pieces
|
|
|
|
// and thus wasting effort.
|
2017-09-01 13:26:50 +08:00
|
|
|
func (cn *connection) updatePiecePriority(piece int) bool {
|
2016-04-19 12:11:11 +08:00
|
|
|
tpp := cn.t.piecePriority(piece)
|
|
|
|
if !cn.PeerHasPiece(piece) {
|
2016-02-09 21:47:53 +08:00
|
|
|
tpp = PiecePriorityNone
|
2016-01-24 12:21:17 +08:00
|
|
|
}
|
2016-02-01 18:11:41 +08:00
|
|
|
if tpp == PiecePriorityNone {
|
2017-09-01 13:26:50 +08:00
|
|
|
return cn.stopRequestingPiece(piece)
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
prio := cn.getPieceInclination()[piece]
|
2017-09-23 13:25:47 +08:00
|
|
|
switch cn.t.requestStrategy {
|
|
|
|
case 1:
|
|
|
|
switch tpp {
|
|
|
|
case PiecePriorityNormal:
|
|
|
|
case PiecePriorityReadahead:
|
|
|
|
prio -= cn.t.numPieces()
|
|
|
|
case PiecePriorityNext, PiecePriorityNow:
|
|
|
|
prio -= 2 * cn.t.numPieces()
|
|
|
|
default:
|
|
|
|
panic(tpp)
|
|
|
|
}
|
|
|
|
prio += piece / 3
|
2016-02-01 18:11:41 +08:00
|
|
|
default:
|
|
|
|
}
|
2018-01-25 14:18:36 +08:00
|
|
|
return cn.pieceRequestOrder.Set(piece, prio) || cn.shouldRequestWithoutBias()
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) getPieceInclination() []int {
|
|
|
|
if cn.pieceInclination == nil {
|
|
|
|
cn.pieceInclination = cn.t.getConnPieceInclination()
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
return cn.pieceInclination
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) discardPieceInclination() {
|
|
|
|
if cn.pieceInclination == nil {
|
2016-02-01 18:11:41 +08:00
|
|
|
return
|
2016-01-24 12:21:17 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.t.putPieceInclination(cn.pieceInclination)
|
|
|
|
cn.pieceInclination = nil
|
2016-01-24 12:21:17 +08:00
|
|
|
}
|
2016-03-21 11:17:15 +08:00
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) peerPiecesChanged() {
|
|
|
|
if cn.t.haveInfo() {
|
2017-09-01 13:26:50 +08:00
|
|
|
prioritiesChanged := false
|
2016-04-19 12:11:11 +08:00
|
|
|
for i := range iter.N(cn.t.numPieces()) {
|
2017-09-01 13:26:50 +08:00
|
|
|
if cn.updatePiecePriority(i) {
|
|
|
|
prioritiesChanged = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if prioritiesChanged {
|
|
|
|
cn.updateRequests()
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2016-03-22 09:07:03 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) raisePeerMinPieces(newMin int) {
|
|
|
|
if newMin > cn.peerMinPieces {
|
|
|
|
cn.peerMinPieces = newMin
|
2016-03-22 09:07:03 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) peerSentHave(piece int) error {
|
2018-01-09 14:26:01 +08:00
|
|
|
if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
|
2016-03-22 09:07:03 +08:00
|
|
|
return errors.New("invalid piece")
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
if cn.PeerHasPiece(piece) {
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.raisePeerMinPieces(piece + 1)
|
|
|
|
cn.peerPieces.Set(piece, true)
|
2017-09-01 13:26:50 +08:00
|
|
|
if cn.updatePiecePriority(piece) {
|
|
|
|
cn.updateRequests()
|
|
|
|
}
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) peerSentBitfield(bf []bool) error {
|
2018-01-29 15:18:08 +08:00
|
|
|
cn.peerSentHaveAll = false
|
2016-03-22 09:07:03 +08:00
|
|
|
if len(bf)%8 != 0 {
|
|
|
|
panic("expected bitfield length divisible by 8")
|
|
|
|
}
|
|
|
|
// We know that the last byte means that at most the last 7 bits are
|
|
|
|
// wasted.
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.raisePeerMinPieces(len(bf) - 7)
|
2016-04-30 02:08:02 +08:00
|
|
|
if cn.t.haveInfo() && len(bf) > cn.t.numPieces() {
|
2016-03-22 09:07:03 +08:00
|
|
|
// Ignore known excess pieces.
|
2016-04-19 12:11:11 +08:00
|
|
|
bf = bf[:cn.t.numPieces()]
|
2016-03-22 09:07:03 +08:00
|
|
|
}
|
|
|
|
for i, have := range bf {
|
|
|
|
if have {
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.raisePeerMinPieces(i + 1)
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.peerPieces.Set(i, have)
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.peerPiecesChanged()
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-01-29 15:18:08 +08:00
|
|
|
func (cn *connection) onPeerSentHaveAll() error {
|
|
|
|
cn.peerSentHaveAll = true
|
2016-03-22 09:07:03 +08:00
|
|
|
cn.peerPieces.Clear()
|
|
|
|
cn.peerPiecesChanged()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (cn *connection) peerSentHaveNone() error {
|
|
|
|
cn.peerPieces.Clear()
|
2018-01-29 15:18:08 +08:00
|
|
|
cn.peerSentHaveAll = false
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.peerPiecesChanged()
|
2016-03-21 11:17:15 +08:00
|
|
|
return nil
|
|
|
|
}
|
2016-05-16 16:46:38 +08:00
|
|
|
|
|
|
|
func (c *connection) requestPendingMetadata() {
|
|
|
|
if c.t.haveInfo() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if c.PeerExtensionIDs["ut_metadata"] == 0 {
|
|
|
|
// Peer doesn't support this.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Request metadata pieces that we don't have in a random order.
|
|
|
|
var pending []int
|
|
|
|
for index := 0; index < c.t.metadataPieceCount(); index++ {
|
|
|
|
if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
|
|
|
|
pending = append(pending, index)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, i := range rand.Perm(len(pending)) {
|
|
|
|
c.requestMetadataPiece(pending[i])
|
|
|
|
}
|
|
|
|
}
|
2016-07-05 13:52:33 +08:00
|
|
|
|
2016-07-12 14:42:04 +08:00
|
|
|
func (cn *connection) wroteMsg(msg *pp.Message) {
|
2017-09-01 08:53:59 +08:00
|
|
|
messageTypesSent.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
|
2016-07-05 13:52:33 +08:00
|
|
|
cn.stats.wroteMsg(msg)
|
|
|
|
cn.t.stats.wroteMsg(msg)
|
|
|
|
}
|
|
|
|
|
2016-07-12 14:42:04 +08:00
|
|
|
func (cn *connection) readMsg(msg *pp.Message) {
|
|
|
|
cn.stats.readMsg(msg)
|
|
|
|
cn.t.stats.readMsg(msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) wroteBytes(n int64) {
|
|
|
|
cn.stats.wroteBytes(n)
|
|
|
|
if cn.t != nil {
|
|
|
|
cn.t.stats.wroteBytes(n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) readBytes(n int64) {
|
|
|
|
cn.stats.readBytes(n)
|
|
|
|
if cn.t != nil {
|
|
|
|
cn.t.stats.readBytes(n)
|
|
|
|
}
|
2016-07-05 13:52:33 +08:00
|
|
|
}
|
2016-07-05 14:23:17 +08:00
|
|
|
|
2018-02-01 15:49:53 +08:00
|
|
|
// Returns whether the connection could be useful to us. We're seeding and
|
2016-07-05 14:23:17 +08:00
|
|
|
// they want data, we don't have metainfo and they can provide it, etc.
|
|
|
|
func (c *connection) useful() bool {
|
|
|
|
t := c.t
|
|
|
|
if c.closed.IsSet() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if !t.haveInfo() {
|
|
|
|
return c.supportsExtension("ut_metadata")
|
|
|
|
}
|
2018-02-01 15:49:53 +08:00
|
|
|
if t.seeding() && c.PeerInterested {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if c.peerHasWantedPieces() {
|
|
|
|
return true
|
2016-07-05 14:23:17 +08:00
|
|
|
}
|
2018-02-01 15:49:53 +08:00
|
|
|
return false
|
2016-07-05 14:23:17 +08:00
|
|
|
}
|
2016-07-05 22:42:16 +08:00
|
|
|
|
2016-08-14 20:39:23 +08:00
|
|
|
func (c *connection) lastHelpful() (ret time.Time) {
|
|
|
|
ret = c.lastUsefulChunkReceived
|
|
|
|
if c.t.seeding() && c.lastChunkSent.After(ret) {
|
|
|
|
ret = c.lastChunkSent
|
2016-07-05 22:42:16 +08:00
|
|
|
}
|
2016-08-14 20:39:23 +08:00
|
|
|
return
|
2016-07-05 22:42:16 +08:00
|
|
|
}
|
2016-09-11 12:32:56 +08:00
|
|
|
|
2018-02-02 16:19:14 +08:00
|
|
|
func (c *connection) onReadRequest(r request) error {
|
|
|
|
requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
|
|
|
|
if c.Choked {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if len(c.PeerRequests) >= maxRequests {
|
|
|
|
// TODO: Should we drop them or Choke them instead?
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if !c.t.havePiece(r.Index.Int()) {
|
|
|
|
// This isn't necessarily them screwing up. We can drop pieces
|
|
|
|
// from our storage, and can't communicate this to peers
|
|
|
|
// except by reconnecting.
|
|
|
|
requestsReceivedForMissingPieces.Add(1)
|
|
|
|
return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
|
|
|
|
}
|
|
|
|
if c.PeerRequests == nil {
|
|
|
|
c.PeerRequests = make(map[request]struct{}, maxRequests)
|
|
|
|
}
|
|
|
|
c.PeerRequests[r] = struct{}{}
|
|
|
|
c.tickleWriter()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-09-11 12:32:56 +08:00
|
|
|
// Processes incoming bittorrent messages. The client lock is held upon entry
|
|
|
|
// and exit. Returning will end the connection.
|
|
|
|
func (c *connection) mainReadLoop() error {
|
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
2016-09-12 15:10:11 +08:00
|
|
|
|
2016-09-11 12:32:56 +08:00
|
|
|
decoder := pp.Decoder{
|
2017-09-21 17:29:56 +08:00
|
|
|
R: bufio.NewReaderSize(c.r, 1<<17),
|
2016-09-11 12:32:56 +08:00
|
|
|
MaxLength: 256 * 1024,
|
2016-10-05 12:57:00 +08:00
|
|
|
Pool: t.chunkPool,
|
2016-09-11 12:32:56 +08:00
|
|
|
}
|
|
|
|
for {
|
2017-08-31 14:25:49 +08:00
|
|
|
var (
|
|
|
|
msg pp.Message
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
func() {
|
|
|
|
cl.mu.Unlock()
|
|
|
|
defer cl.mu.Lock()
|
|
|
|
err = decoder.Decode(&msg)
|
|
|
|
}()
|
2016-09-11 12:32:56 +08:00
|
|
|
if cl.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.readMsg(&msg)
|
|
|
|
c.lastMessageReceived = time.Now()
|
|
|
|
if msg.Keepalive {
|
|
|
|
receivedKeepalives.Add(1)
|
|
|
|
continue
|
|
|
|
}
|
2017-09-01 08:53:59 +08:00
|
|
|
messageTypesReceived.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
|
2016-09-11 12:32:56 +08:00
|
|
|
switch msg.Type {
|
|
|
|
case pp.Choke:
|
|
|
|
c.PeerChoked = true
|
2018-02-01 11:46:03 +08:00
|
|
|
c.deleteAllRequests()
|
2016-09-11 12:32:56 +08:00
|
|
|
// We can then reset our interest.
|
|
|
|
c.updateRequests()
|
|
|
|
case pp.Reject:
|
2018-02-02 16:19:14 +08:00
|
|
|
if c.deleteRequest(newRequestFromMessage(&msg)) {
|
2017-09-01 13:26:50 +08:00
|
|
|
c.updateRequests()
|
|
|
|
}
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Unchoke:
|
|
|
|
c.PeerChoked = false
|
2017-09-01 13:26:50 +08:00
|
|
|
c.tickleWriter()
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Interested:
|
|
|
|
c.PeerInterested = true
|
2017-09-18 10:09:08 +08:00
|
|
|
c.tickleWriter()
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.NotInterested:
|
|
|
|
c.PeerInterested = false
|
2017-09-18 10:09:08 +08:00
|
|
|
c.PeerRequests = nil
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Have:
|
|
|
|
err = c.peerSentHave(int(msg.Index))
|
|
|
|
case pp.Request:
|
2018-02-02 16:19:14 +08:00
|
|
|
r := newRequestFromMessage(&msg)
|
|
|
|
err = c.onReadRequest(r)
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Cancel:
|
2018-02-02 16:19:14 +08:00
|
|
|
req := newRequestFromMessage(&msg)
|
2016-09-11 12:32:56 +08:00
|
|
|
if !c.PeerCancel(req) {
|
|
|
|
unexpectedCancels.Add(1)
|
|
|
|
}
|
|
|
|
case pp.Bitfield:
|
|
|
|
err = c.peerSentBitfield(msg.Bitfield)
|
|
|
|
case pp.HaveAll:
|
2018-01-29 15:18:08 +08:00
|
|
|
err = c.onPeerSentHaveAll()
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.HaveNone:
|
|
|
|
err = c.peerSentHaveNone()
|
|
|
|
case pp.Piece:
|
2016-11-22 11:18:09 +08:00
|
|
|
c.receiveChunk(&msg)
|
2016-09-12 15:10:11 +08:00
|
|
|
if len(msg.Piece) == int(t.chunkSize) {
|
2017-11-07 13:11:59 +08:00
|
|
|
t.chunkPool.Put(&msg.Piece)
|
2016-09-12 15:10:11 +08:00
|
|
|
}
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Extended:
|
|
|
|
switch msg.ExtendedID {
|
|
|
|
case pp.HandshakeExtendedID:
|
|
|
|
// TODO: Create a bencode struct for this.
|
|
|
|
var d map[string]interface{}
|
|
|
|
err = bencode.Unmarshal(msg.ExtendedPayload, &d)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error decoding extended message payload: %s", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
// log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
|
|
|
|
if reqq, ok := d["reqq"]; ok {
|
|
|
|
if i, ok := reqq.(int64); ok {
|
|
|
|
c.PeerMaxRequests = int(i)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if v, ok := d["v"]; ok {
|
|
|
|
c.PeerClientName = v.(string)
|
|
|
|
}
|
2017-11-08 16:29:55 +08:00
|
|
|
if m, ok := d["m"]; ok {
|
|
|
|
mTyped, ok := m.(map[string]interface{})
|
2016-09-11 12:32:56 +08:00
|
|
|
if !ok {
|
2017-11-08 16:29:55 +08:00
|
|
|
err = errors.New("handshake m value is not dict")
|
|
|
|
break
|
2016-09-11 12:32:56 +08:00
|
|
|
}
|
2017-11-08 16:29:55 +08:00
|
|
|
if c.PeerExtensionIDs == nil {
|
|
|
|
c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
|
|
|
|
}
|
|
|
|
for name, v := range mTyped {
|
|
|
|
id, ok := v.(int64)
|
|
|
|
if !ok {
|
|
|
|
log.Printf("bad handshake m item extension ID type: %T", v)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if id == 0 {
|
|
|
|
delete(c.PeerExtensionIDs, name)
|
|
|
|
} else {
|
|
|
|
if c.PeerExtensionIDs[name] == 0 {
|
|
|
|
supportedExtensionMessages.Add(name, 1)
|
|
|
|
}
|
|
|
|
c.PeerExtensionIDs[name] = byte(id)
|
2016-09-11 12:32:56 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
metadata_sizeUntyped, ok := d["metadata_size"]
|
|
|
|
if ok {
|
|
|
|
metadata_size, ok := metadata_sizeUntyped.(int64)
|
|
|
|
if !ok {
|
|
|
|
log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
|
|
|
|
} else {
|
|
|
|
err = t.setMetadataSize(metadata_size)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error setting metadata size to %d", metadata_size)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
|
|
|
|
c.requestPendingMetadata()
|
|
|
|
}
|
|
|
|
case metadataExtendedId:
|
|
|
|
err = cl.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error handling metadata extension message: %s", err)
|
|
|
|
}
|
|
|
|
case pexExtendedId:
|
|
|
|
if cl.config.DisablePEX {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
var pexMsg peerExchangeMessage
|
|
|
|
err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error unmarshalling PEX message: %s", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
cl.mu.Lock()
|
|
|
|
t.addPeers(func() (ret []Peer) {
|
|
|
|
for i, cp := range pexMsg.Added {
|
|
|
|
p := Peer{
|
|
|
|
IP: make([]byte, 4),
|
|
|
|
Port: cp.Port,
|
|
|
|
Source: peerSourcePEX,
|
|
|
|
}
|
|
|
|
if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
|
|
|
|
p.SupportsEncryption = true
|
|
|
|
}
|
|
|
|
missinggo.CopyExact(p.IP, cp.IP[:])
|
|
|
|
ret = append(ret, p)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}())
|
|
|
|
cl.mu.Unlock()
|
|
|
|
}()
|
|
|
|
default:
|
|
|
|
err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
// That client uses its own extension IDs for outgoing message
|
|
|
|
// types, which is incorrect.
|
|
|
|
if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
|
|
|
|
strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case pp.Port:
|
|
|
|
if cl.dHT == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if msg.Port != 0 {
|
|
|
|
pingAddr.Port = int(msg.Port)
|
|
|
|
}
|
2017-07-20 22:40:49 +08:00
|
|
|
go cl.dHT.Ping(pingAddr, nil)
|
2016-09-11 12:32:56 +08:00
|
|
|
default:
|
|
|
|
err = fmt.Errorf("received unknown message type: %#v", msg.Type)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-10-10 13:30:51 +08:00
|
|
|
|
|
|
|
// Set both the Reader and Writer for the connection from a single ReadWriter.
|
|
|
|
func (cn *connection) setRW(rw io.ReadWriter) {
|
|
|
|
cn.r = rw
|
|
|
|
cn.w = rw
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns the Reader and Writer as a combined ReadWriter.
|
|
|
|
func (cn *connection) rw() io.ReadWriter {
|
|
|
|
return struct {
|
|
|
|
io.Reader
|
|
|
|
io.Writer
|
|
|
|
}{cn.r, cn.w}
|
|
|
|
}
|
2016-11-22 11:16:18 +08:00
|
|
|
|
|
|
|
// Handle a received chunk from a peer.
|
2016-11-22 11:18:09 +08:00
|
|
|
func (c *connection) receiveChunk(msg *pp.Message) {
|
2016-11-22 11:17:30 +08:00
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
2016-11-22 11:16:18 +08:00
|
|
|
chunksReceived.Add(1)
|
|
|
|
|
2018-02-02 16:19:14 +08:00
|
|
|
req := newRequestFromMessage(msg)
|
2016-11-22 11:16:18 +08:00
|
|
|
|
|
|
|
// Request has been satisfied.
|
2017-09-01 13:26:50 +08:00
|
|
|
if c.deleteRequest(req) {
|
|
|
|
c.updateRequests()
|
|
|
|
} else {
|
2016-11-22 11:16:18 +08:00
|
|
|
unexpectedChunksReceived.Add(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do we actually want this chunk?
|
|
|
|
if !t.wantPiece(req) {
|
|
|
|
unwantedChunksReceived.Add(1)
|
2018-02-02 16:04:56 +08:00
|
|
|
c.stats.ChunksReadUnwanted++
|
2016-11-22 11:16:18 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-11-22 11:20:48 +08:00
|
|
|
index := int(req.Index)
|
|
|
|
piece := &t.pieces[index]
|
|
|
|
|
2018-02-02 16:04:56 +08:00
|
|
|
c.stats.ChunksReadUseful++
|
2016-11-22 11:16:18 +08:00
|
|
|
c.lastUsefulChunkReceived = time.Now()
|
2017-11-07 13:11:59 +08:00
|
|
|
// if t.fastestConn != c {
|
|
|
|
// log.Printf("setting fastest connection %p", c)
|
|
|
|
// }
|
2017-09-23 13:25:47 +08:00
|
|
|
t.fastestConn = c
|
2016-11-22 11:16:18 +08:00
|
|
|
|
|
|
|
// Need to record that it hasn't been written yet, before we attempt to do
|
|
|
|
// anything with it.
|
|
|
|
piece.incrementPendingWrites()
|
2017-12-29 09:16:05 +08:00
|
|
|
// Record that we have the chunk, so we aren't trying to download it while
|
|
|
|
// waiting for it to be written to storage.
|
2016-11-22 11:16:18 +08:00
|
|
|
piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
|
|
|
|
|
|
|
|
// Cancel pending requests for this chunk.
|
2016-11-23 08:48:44 +08:00
|
|
|
for c := range t.conns {
|
2017-09-18 11:47:49 +08:00
|
|
|
c.postCancel(req)
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
|
|
|
|
2017-12-29 09:15:33 +08:00
|
|
|
err := func() error {
|
|
|
|
cl.mu.Unlock()
|
|
|
|
defer cl.mu.Lock()
|
|
|
|
// Write the chunk out. Note that the upper bound on chunk writing
|
|
|
|
// concurrency will be the number of connections. We write inline with
|
|
|
|
// receiving the chunk (with this lock dance), because we want to
|
|
|
|
// handle errors synchronously and I haven't thought of a nice way to
|
|
|
|
// defer any concurrency to the storage and have that notify the
|
|
|
|
// client of errors. TODO: Do that instead.
|
|
|
|
return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
|
|
|
|
}()
|
2016-11-22 11:16:18 +08:00
|
|
|
|
|
|
|
piece.decrementPendingWrites()
|
|
|
|
|
|
|
|
if err != nil {
|
2018-01-07 16:24:00 +08:00
|
|
|
log.Printf("%s (%s): error writing chunk %v: %s", t, t.infoHash, req, err)
|
2016-11-22 11:16:18 +08:00
|
|
|
t.pendRequest(req)
|
|
|
|
t.updatePieceCompletion(int(msg.Index))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// It's important that the piece is potentially queued before we check if
|
|
|
|
// the piece is still wanted, because if it is queued, it won't be wanted.
|
|
|
|
if t.pieceAllDirty(index) {
|
2017-01-01 08:02:37 +08:00
|
|
|
t.queuePieceCheck(int(req.Index))
|
2017-12-28 20:59:30 +08:00
|
|
|
t.pendAllChunkSpecs(index)
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if c.peerTouchedPieces == nil {
|
|
|
|
c.peerTouchedPieces = make(map[int]struct{})
|
|
|
|
}
|
|
|
|
c.peerTouchedPieces[index] = struct{}{}
|
|
|
|
|
|
|
|
cl.event.Broadcast()
|
|
|
|
t.publishPieceChange(int(req.Index))
|
|
|
|
}
|
2016-11-22 18:12:53 +08:00
|
|
|
|
2018-02-02 16:04:56 +08:00
|
|
|
func (c *connection) uploadAllowed() bool {
|
|
|
|
if c.t.cl.config.NoUpload {
|
|
|
|
return false
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2018-02-02 16:04:56 +08:00
|
|
|
if c.t.seeding() {
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2018-02-02 16:04:56 +08:00
|
|
|
if !c.peerHasWantedPieces() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// Don't upload more than 100 KiB more than we download.
|
|
|
|
if c.stats.DataBytesWritten >= c.stats.DataBytesRead+100<<10 {
|
|
|
|
return false
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2018-02-02 16:04:56 +08:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *connection) setRetryUploadTimer(delay time.Duration) {
|
|
|
|
if c.uploadTimer == nil {
|
|
|
|
c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
|
|
|
|
} else {
|
|
|
|
c.uploadTimer.Reset(delay)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Also handles choking and unchoking of the remote peer.
|
|
|
|
func (c *connection) upload(msg func(pp.Message) bool) bool {
|
2016-11-22 18:12:53 +08:00
|
|
|
// Breaking or completing this loop means we don't want to upload to the
|
|
|
|
// peer anymore, and we choke them.
|
|
|
|
another:
|
2018-02-02 16:04:56 +08:00
|
|
|
for c.uploadAllowed() {
|
2016-11-22 18:12:53 +08:00
|
|
|
// We want to upload to the peer.
|
2017-09-18 10:09:08 +08:00
|
|
|
if !c.Unchoke(msg) {
|
|
|
|
return false
|
|
|
|
}
|
2016-11-22 18:12:53 +08:00
|
|
|
for r := range c.PeerRequests {
|
2018-02-02 16:04:56 +08:00
|
|
|
res := c.t.cl.uploadLimit.ReserveN(time.Now(), int(r.Length))
|
2017-09-18 10:09:08 +08:00
|
|
|
if !res.OK() {
|
2017-11-04 13:58:38 +08:00
|
|
|
panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
|
2017-09-18 10:09:08 +08:00
|
|
|
}
|
2016-11-22 18:12:53 +08:00
|
|
|
delay := res.Delay()
|
|
|
|
if delay > 0 {
|
|
|
|
res.Cancel()
|
2018-02-02 16:04:56 +08:00
|
|
|
c.setRetryUploadTimer(delay)
|
2017-09-18 10:09:08 +08:00
|
|
|
// Hard to say what to return here.
|
|
|
|
return true
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2018-02-02 10:34:35 +08:00
|
|
|
more, err := c.sendChunk(r, msg)
|
2016-11-22 18:12:53 +08:00
|
|
|
if err != nil {
|
|
|
|
i := int(r.Index)
|
2018-02-02 16:04:56 +08:00
|
|
|
if c.t.pieceComplete(i) {
|
|
|
|
c.t.updatePieceCompletion(i)
|
|
|
|
if !c.t.pieceComplete(i) {
|
2016-11-22 18:12:53 +08:00
|
|
|
// We had the piece, but not anymore.
|
|
|
|
break another
|
|
|
|
}
|
|
|
|
}
|
|
|
|
log.Printf("error sending chunk %+v to peer: %s", r, err)
|
|
|
|
// If we failed to send a chunk, choke the peer to ensure they
|
|
|
|
// flush all their requests. We've probably dropped a piece,
|
|
|
|
// but there's no way to communicate this to the peer. If they
|
|
|
|
// ask for it again, we'll kick them to allow us to send them
|
|
|
|
// an updated bitfield.
|
|
|
|
break another
|
|
|
|
}
|
|
|
|
delete(c.PeerRequests, r)
|
2017-09-18 10:09:08 +08:00
|
|
|
if !more {
|
|
|
|
return false
|
|
|
|
}
|
2016-11-22 18:12:53 +08:00
|
|
|
goto another
|
|
|
|
}
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2017-09-18 10:09:08 +08:00
|
|
|
return c.Choke(msg)
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2016-11-23 08:52:41 +08:00
|
|
|
|
|
|
|
func (cn *connection) Drop() {
|
|
|
|
cn.t.dropConnection(cn)
|
|
|
|
}
|
|
|
|
|
2018-02-02 16:04:56 +08:00
|
|
|
func (cn *connection) netGoodPiecesDirtied() int64 {
|
|
|
|
return cn.stats.GoodPiecesDirtied - cn.stats.BadPiecesDirtied
|
2016-11-23 09:59:23 +08:00
|
|
|
}
|
2017-08-17 23:48:19 +08:00
|
|
|
|
|
|
|
func (c *connection) peerHasWantedPieces() bool {
|
|
|
|
return !c.pieceRequestOrder.IsEmpty()
|
|
|
|
}
|
2017-08-31 21:48:52 +08:00
|
|
|
|
|
|
|
func (c *connection) numLocalRequests() int {
|
|
|
|
return len(c.requests)
|
|
|
|
}
|
2017-09-01 10:09:41 +08:00
|
|
|
|
|
|
|
func (c *connection) deleteRequest(r request) bool {
|
|
|
|
if _, ok := c.requests[r]; !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
delete(c.requests, r)
|
2018-02-01 11:46:03 +08:00
|
|
|
c.t.pendingRequests[r]--
|
2017-09-01 10:09:41 +08:00
|
|
|
return true
|
|
|
|
}
|
2017-11-04 14:08:02 +08:00
|
|
|
|
2018-02-01 11:46:03 +08:00
|
|
|
func (c *connection) deleteAllRequests() {
|
|
|
|
for r := range c.requests {
|
|
|
|
c.deleteRequest(r)
|
|
|
|
}
|
|
|
|
// for c := range c.t.conns {
|
|
|
|
// c.tickleWriter()
|
|
|
|
// }
|
|
|
|
}
|
|
|
|
|
2017-09-01 13:26:50 +08:00
|
|
|
func (c *connection) tickleWriter() {
|
|
|
|
c.writerCond.Broadcast()
|
|
|
|
}
|
2017-09-18 11:47:49 +08:00
|
|
|
|
|
|
|
func (c *connection) postCancel(r request) bool {
|
|
|
|
if !c.deleteRequest(r) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
c.Post(makeCancelMessage(r))
|
|
|
|
return true
|
|
|
|
}
|
2018-02-02 10:26:04 +08:00
|
|
|
|
|
|
|
func (c *connection) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
|
|
|
|
// Count the chunk being sent, even if it isn't.
|
|
|
|
b := make([]byte, r.Length)
|
|
|
|
p := c.t.info.Piece(int(r.Index))
|
|
|
|
n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
|
|
|
|
if n != len(b) {
|
|
|
|
if err == nil {
|
|
|
|
panic("expected error")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
} else if err == io.EOF {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
more = msg(pp.Message{
|
|
|
|
Type: pp.Piece,
|
|
|
|
Index: r.Index,
|
|
|
|
Begin: r.Begin,
|
|
|
|
Piece: b,
|
|
|
|
})
|
|
|
|
uploadChunksPosted.Add(1)
|
|
|
|
c.lastChunkSent = time.Now()
|
|
|
|
return
|
|
|
|
}
|
2018-02-02 16:07:20 +08:00
|
|
|
|
|
|
|
func (c *connection) setTorrent(t *Torrent) {
|
|
|
|
if c.t != nil {
|
|
|
|
panic("connection already associated with a torrent")
|
|
|
|
}
|
|
|
|
c.t = t
|
|
|
|
t.conns[c] = struct{}{}
|
|
|
|
}
|