25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/bitmap"
28 "github.com/anacrolix/missinggo/pubsub"
29 "github.com/anacrolix/sync"
30 "github.com/anacrolix/utp"
31 "github.com/edsrzf/mmap-go"
33 "github.com/anacrolix/torrent/bencode"
34 filePkg "github.com/anacrolix/torrent/data/file"
35 "github.com/anacrolix/torrent/dht"
36 "github.com/anacrolix/torrent/iplist"
37 "github.com/anacrolix/torrent/metainfo"
38 "github.com/anacrolix/torrent/mse"
39 pp "github.com/anacrolix/torrent/peer_protocol"
40 "github.com/anacrolix/torrent/tracker"
44 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
45 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
46 chunksReceived = expvar.NewInt("chunksReceived")
48 peersAddedBySource = expvar.NewMap("peersAddedBySource")
50 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
51 unexpectedCancels = expvar.NewInt("unexpectedCancels")
52 postedCancels = expvar.NewInt("postedCancels")
53 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
55 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
56 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
58 unsuccessfulDials = expvar.NewInt("dialSuccessful")
59 successfulDials = expvar.NewInt("dialUnsuccessful")
61 acceptUTP = expvar.NewInt("acceptUTP")
62 acceptTCP = expvar.NewInt("acceptTCP")
63 acceptReject = expvar.NewInt("acceptReject")
65 peerExtensions = expvar.NewMap("peerExtensions")
66 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
67 // Count of connections to peer with same client ID.
68 connsToSelf = expvar.NewInt("connsToSelf")
69 // Number of completed connections to a client we're already connected with.
70 duplicateClientConns = expvar.NewInt("duplicateClientConns")
71 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
72 receivedKeepalives = expvar.NewInt("receivedKeepalives")
73 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
74 postedMessageTypes = expvar.NewMap("postedMessageTypes")
75 postedKeepalives = expvar.NewInt("postedKeepalives")
79 // Justification for set bits follows.
81 // Extension protocol ([5]|=0x10):
82 // http://www.bittorrent.org/beps/bep_0010.html
84 // Fast Extension ([7]|=0x04):
85 // http://bittorrent.org/beps/bep_0006.html.
86 // Disabled until AllowedFast is implemented.
89 // http://www.bittorrent.org/beps/bep_0005.html
90 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
92 socketsPerTorrent = 80
93 torrentPeersHighWater = 200
94 torrentPeersLowWater = 50
96 // Limit how long handshake can take. This is to reduce the lingering
97 // impact of a few bad apples. 4s loses 1% of successful handshakes that
98 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
99 btHandshakeTimeout = 4 * time.Second
100 handshakesTimeout = 20 * time.Second
102 // These are our extended message IDs.
103 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
106 // Updated occasionally to when there's been some changes to client
107 // behaviour in case other clients are assuming anything of us. See also
109 extendedHandshakeClientVersion = "go.torrent dev 20150624"
112 // Currently doesn't really queue, but should in the future.
113 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
114 piece := &t.Pieces[pieceIndex]
115 if piece.QueuedForHash {
118 piece.QueuedForHash = true
119 t.publishPieceChange(int(pieceIndex))
120 go cl.verifyPiece(t, int(pieceIndex))
123 // Queue a piece check if one isn't already queued, and the piece has never
124 // been checked before.
125 func (cl *Client) queueFirstHash(t *torrent, piece int) {
126 p := &t.Pieces[piece]
127 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
130 cl.queuePieceCheck(t, piece)
133 // Clients contain zero or more Torrents. A client manages a blocklist, the
134 // TCP/UDP protocol ports, and DHT as desired.
138 listeners []net.Listener
141 ipBlockList iplist.Ranger
142 bannedTorrents map[InfoHash]struct{}
144 pruneTimer *time.Timer
145 extensionBytes peerExtensionBytes
146 // Set of addresses that have our client ID. This intentionally will
147 // include ourselves if we end up trying to connect to our own address
148 // through legitimate channels.
149 dopplegangerAddrs map[string]struct{}
151 torrentDataOpener TorrentDataOpener
157 torrents map[InfoHash]*torrent
160 func (me *Client) IPBlockList() iplist.Ranger {
163 return me.ipBlockList
166 func (me *Client) SetIPBlockList(list iplist.Ranger) {
169 me.ipBlockList = list
171 me.dHT.SetIPBlockList(list)
175 func (me *Client) PeerID() string {
176 return string(me.peerID[:])
179 func (me *Client) ListenAddr() (addr net.Addr) {
180 for _, l := range me.listeners {
187 type hashSorter struct {
191 func (me hashSorter) Len() int {
192 return len(me.Hashes)
195 func (me hashSorter) Less(a, b int) bool {
196 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
199 func (me hashSorter) Swap(a, b int) {
200 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
203 func (cl *Client) sortedTorrents() (ret []*torrent) {
205 for ih := range cl.torrents {
206 hs.Hashes = append(hs.Hashes, ih)
209 for _, ih := range hs.Hashes {
210 ret = append(ret, cl.torrent(ih))
215 // Writes out a human readable status of the client, such as for writing to a
217 func (cl *Client) WriteStatus(_w io.Writer) {
219 defer cl.mu.RUnlock()
220 w := bufio.NewWriter(_w)
222 if addr := cl.ListenAddr(); addr != nil {
223 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
225 fmt.Fprintln(w, "Not listening!")
227 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
229 dhtStats := cl.dHT.Stats()
230 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
231 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
232 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
233 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
234 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
236 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
238 for _, t := range cl.sortedTorrents() {
240 fmt.Fprint(w, "<unknown name>")
242 fmt.Fprint(w, t.Name())
246 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.length)), t.length)
248 w.WriteString("<missing metainfo>")
256 // TODO: Make this non-blocking Read on Torrent.
257 func dataReadAt(d Data, b []byte, off int64) (n int, err error) {
259 // if err == io.ErrUnexpectedEOF && n != 0 {
263 // log.Println("data read at", len(b), off)
264 return d.ReadAt(b, off)
267 // Calculates the number of pieces to set to Readahead priority, after the
268 // Now, and Next pieces.
269 func readaheadPieces(readahead, pieceLength int64) (ret int) {
270 // Expand the readahead to fit any partial pieces. Subtract 1 for the
271 // "next" piece that is assigned.
272 ret = int((readahead+pieceLength-1)/pieceLength - 1)
273 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
274 // piece length is much larger than the readahead.
281 func (cl *Client) configDir() string {
282 if cl.config.ConfigDir == "" {
283 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
285 return cl.config.ConfigDir
288 // The directory where the Client expects to find and store configuration
289 // data. Defaults to $HOME/.config/torrent.
290 func (cl *Client) ConfigDir() string {
291 return cl.configDir()
294 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
295 f, err := os.Open(filename)
296 if os.IsNotExist(err) {
304 mm, err := mmap.Map(f, mmap.RDONLY, 0)
308 ret = iplist.NewFromPacked(mm)
312 func (cl *Client) setEnvBlocklist() (err error) {
313 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
314 defaultBlocklist := filename == ""
315 if defaultBlocklist {
316 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
320 if cl.ipBlockList != nil {
323 filename = filepath.Join(cl.configDir(), "blocklist")
325 f, err := os.Open(filename)
327 if defaultBlocklist {
333 cl.ipBlockList, err = iplist.NewFromReader(f)
337 func (cl *Client) initBannedTorrents() error {
338 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
340 if os.IsNotExist(err) {
343 return fmt.Errorf("error opening banned infohashes file: %s", err)
346 scanner := bufio.NewScanner(f)
347 cl.bannedTorrents = make(map[InfoHash]struct{})
349 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
353 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
355 return fmt.Errorf("error reading infohash: %s", err)
361 return errors.New("bad infohash")
365 cl.bannedTorrents[ih] = struct{}{}
367 if err := scanner.Err(); err != nil {
368 return fmt.Errorf("error scanning file: %s", err)
373 // Creates a new client.
374 func NewClient(cfg *Config) (cl *Client, err error) {
385 halfOpenLimit: socketsPerTorrent,
387 torrentDataOpener: func(md *metainfo.Info) Data {
388 return filePkg.TorrentData(md, cfg.DataDir)
390 dopplegangerAddrs: make(map[string]struct{}),
392 quit: make(chan struct{}),
393 torrents: make(map[InfoHash]*torrent),
395 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
397 if cfg.TorrentDataOpener != nil {
398 cl.torrentDataOpener = cfg.TorrentDataOpener
401 if cfg.IPBlocklist != nil {
402 cl.ipBlockList = cfg.IPBlocklist
403 } else if !cfg.NoDefaultBlocklist {
404 err = cl.setEnvBlocklist()
410 if err = cl.initBannedTorrents(); err != nil {
411 err = fmt.Errorf("error initing banned torrents: %s", err)
415 if cfg.PeerID != "" {
416 CopyExact(&cl.peerID, cfg.PeerID)
418 o := copy(cl.peerID[:], bep20)
419 _, err = rand.Read(cl.peerID[o:])
421 panic("error generating peer id")
425 // Returns the laddr string to listen on for the next Listen call.
426 listenAddr := func() string {
427 if addr := cl.ListenAddr(); addr != nil {
430 if cfg.ListenAddr == "" {
433 return cfg.ListenAddr
435 if !cl.config.DisableTCP {
437 l, err = net.Listen(func() string {
438 if cl.config.DisableIPv6 {
447 cl.listeners = append(cl.listeners, l)
448 go cl.acceptConnections(l, false)
450 if !cl.config.DisableUTP {
451 cl.utpSock, err = utp.NewSocket(func() string {
452 if cl.config.DisableIPv6 {
461 cl.listeners = append(cl.listeners, cl.utpSock)
462 go cl.acceptConnections(cl.utpSock, true)
465 dhtCfg := cfg.DHTConfig
466 if dhtCfg.IPBlocklist == nil {
467 dhtCfg.IPBlocklist = cl.ipBlockList
469 if dhtCfg.Addr == "" {
470 dhtCfg.Addr = listenAddr()
472 if dhtCfg.Conn == nil && cl.utpSock != nil {
473 dhtCfg.Conn = cl.utpSock
475 cl.dHT, err = dht.NewServer(&dhtCfg)
484 func (cl *Client) stopped() bool {
493 // Stops the client. All connections to peers are closed and all activity will
495 func (me *Client) Close() {
507 for _, l := range me.listeners {
510 for _, t := range me.torrents {
516 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
518 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
519 if cl.ipBlockList == nil {
523 // If blocklists are enabled, then block non-IPv4 addresses, because
524 // blocklists do not yet support IPv6.
526 if missinggo.CryHeard() {
527 log.Printf("blocking non-IPv4 address: %s", ip)
533 return cl.ipBlockList.Lookup(ip4)
536 func (cl *Client) waitAccept() {
540 for _, t := range cl.torrents {
554 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
557 // We accept all connections immediately, because we don't know what
558 // torrent they're for.
559 conn, err := l.Accept()
578 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
579 _, blocked := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
581 if blocked || doppleganger {
583 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
587 go cl.incomingConnection(conn, utp)
591 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
593 if tc, ok := nc.(*net.TCPConn); ok {
599 c.Discovery = peerSourceIncoming
601 err := cl.runReceivedConn(c)
607 // Returns a handle to the given torrent, if it's present in the client.
608 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
611 t, ok := cl.torrents[ih]
619 func (me *Client) torrent(ih InfoHash) *torrent {
620 return me.torrents[ih]
623 type dialResult struct {
628 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
629 conn, err := dial(addr, t)
634 conn = nil // Pedantic
636 ch <- dialResult{conn, utp}
638 successfulDials.Add(1)
641 unsuccessfulDials.Add(1)
644 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
645 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
646 if ret < minDialTimeout {
652 // Returns whether an address is known to connect to a client with our own ID.
653 func (me *Client) dopplegangerAddr(addr string) bool {
654 _, ok := me.dopplegangerAddrs[addr]
658 // Start the process of connecting to the given peer for the given torrent if
660 func (me *Client) initiateConn(peer Peer, t *torrent) {
661 if peer.Id == me.peerID {
664 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
665 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
666 duplicateConnsAvoided.Add(1)
669 if r, ok := me.ipBlockRange(peer.IP); ok {
670 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
673 t.HalfOpen[addr] = struct{}{}
674 go me.outgoingConnection(t, addr, peer.Source)
677 func (me *Client) dialTimeout(t *torrent) time.Duration {
679 pendingPeers := len(t.Peers)
681 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
684 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
685 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
687 c.(*net.TCPConn).SetLinger(0)
692 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
693 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
696 // Returns a connection over UTP or TCP, whichever is first to connect.
697 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
698 // Initiate connections via TCP and UTP simultaneously. Use the first one
701 if !me.config.DisableUTP {
704 if !me.config.DisableTCP {
707 resCh := make(chan dialResult, left)
708 if !me.config.DisableUTP {
709 go doDial(me.dialUTP, resCh, true, addr, t)
711 if !me.config.DisableTCP {
712 go doDial(me.dialTCP, resCh, false, addr, t)
715 // Wait for a successful connection.
716 for ; left > 0 && res.Conn == nil; left-- {
720 // There are still incompleted dials.
722 for ; left > 0; left-- {
723 conn := (<-resCh).Conn
735 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
736 if _, ok := t.HalfOpen[addr]; !ok {
737 panic("invariant broken")
739 delete(t.HalfOpen, addr)
743 // Performs initiator handshakes and returns a connection.
744 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
748 c.encrypted = encrypted
750 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
754 ok, err := me.initiateHandshakes(c, t)
761 // Returns nil connection and nil error if no connection could be established
762 // for valid reasons.
763 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
764 nc, utp := me.dialFirst(addr, t)
768 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
776 if me.config.DisableEncryption {
777 // We already tried without encryption.
780 // Try again without encryption, using whichever protocol type worked last
783 nc, err = me.dialUTP(addr, t)
785 nc, err = me.dialTCP(addr, t)
788 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
791 c, err = me.handshakesConnection(nc, t, false, utp)
798 // Called to dial out and run a connection. The addr we're given is already
799 // considered half-open.
800 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
801 c, err := me.establishOutgoingConn(t, addr)
804 // Don't release lock between here and addConnection, unless it's for
806 me.noLongerHalfOpen(t, addr)
815 err = me.runInitiatedHandshookConn(c, t)
821 // The port number for incoming peer connections. 0 if the client isn't
823 func (cl *Client) incomingPeerPort() int {
824 listenAddr := cl.ListenAddr()
825 if listenAddr == nil {
828 return addrPort(listenAddr)
831 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
832 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
833 func addrCompactIP(addr net.Addr) (string, error) {
834 host, _, err := net.SplitHostPort(addr.String())
838 ip := net.ParseIP(host)
839 if v4 := ip.To4(); v4 != nil {
843 return string(v4), nil
845 return string(ip.To16()), nil
848 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
860 peerExtensionBytes [8]byte
864 func (me *peerExtensionBytes) SupportsExtended() bool {
865 return me[5]&0x10 != 0
868 func (me *peerExtensionBytes) SupportsDHT() bool {
869 return me[7]&0x01 != 0
872 func (me *peerExtensionBytes) SupportsFast() bool {
873 return me[7]&0x04 != 0
876 type handshakeResult struct {
882 // ih is nil if we expect the peer to declare the InfoHash, such as when the
883 // peer initiated the connection. Returns ok if the handshake was successful,
884 // and err if there was an unexpected condition other than the peer simply
885 // abandoning the handshake.
886 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
887 // Bytes to be sent to the peer. Should never block the sender.
888 postCh := make(chan []byte, 4)
889 // A single error value sent when the writer completes.
890 writeDone := make(chan error, 1)
891 // Performs writes to the socket and ensures posts don't block.
892 go handshakeWriter(sock, postCh, writeDone)
895 close(postCh) // Done writing.
902 // Wait until writes complete before returning from handshake.
905 err = fmt.Errorf("error writing: %s", err)
909 post := func(bb []byte) {
913 panic("mustn't block while posting")
917 post([]byte(pp.Protocol))
919 if ih != nil { // We already know what we want.
924 _, err = io.ReadFull(sock, b[:68])
929 if string(b[:20]) != pp.Protocol {
932 CopyExact(&res.peerExtensionBytes, b[20:28])
933 CopyExact(&res.InfoHash, b[28:48])
934 CopyExact(&res.peerID, b[48:68])
935 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
937 // TODO: Maybe we can just drop peers here if we're not interested. This
938 // could prevent them trying to reconnect, falsely believing there was
940 if ih == nil { // We were waiting for the peer to tell us what they wanted.
941 post(res.InfoHash[:])
949 // Wraps a raw connection and provides the interface we want for using the
950 // connection in the message loop.
951 type deadlineReader struct {
956 func (me deadlineReader) Read(b []byte) (n int, err error) {
957 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
958 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
960 err = fmt.Errorf("error setting read deadline: %s", err)
962 n, err = me.r.Read(b)
963 // Convert common errors into io.EOF.
965 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
967 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
977 type readWriter struct {
982 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
983 var protocol [len(pp.Protocol)]byte
984 _, err = io.ReadFull(rw, protocol[:])
989 io.MultiReader(bytes.NewReader(protocol[:]), rw),
992 if string(protocol[:]) == pp.Protocol {
996 ret, err = mse.ReceiveHandshake(ret, skeys)
1000 func (cl *Client) receiveSkeys() (ret [][]byte) {
1001 for ih := range cl.torrents {
1002 ret = append(ret, ih[:])
1007 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1009 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1014 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1015 if ih != t.InfoHash {
1021 // Do encryption and bittorrent handshakes as receiver.
1022 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1024 skeys := cl.receiveSkeys()
1026 if !cl.config.DisableEncryption {
1027 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1029 if err == mse.ErrNoSecretKeyMatch {
1035 ih, ok, err := cl.connBTHandshake(c, nil)
1037 err = fmt.Errorf("error during bt handshake: %s", err)
1049 // Returns !ok if handshake failed for valid reasons.
1050 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1051 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1052 if err != nil || !ok {
1056 c.PeerExtensionBytes = res.peerExtensionBytes
1057 c.PeerID = res.peerID
1058 c.completedHandshake = time.Now()
1062 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1063 if c.PeerID == cl.peerID {
1064 // Only if we initiated the connection is the remote address a
1065 // listen addr for a doppleganger.
1067 addr := c.conn.RemoteAddr().String()
1068 cl.dopplegangerAddrs[addr] = struct{}{}
1071 return cl.runHandshookConn(c, t)
1074 func (cl *Client) runReceivedConn(c *connection) (err error) {
1075 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1079 t, err := cl.receiveHandshakes(c)
1081 err = fmt.Errorf("error receiving handshakes: %s", err)
1088 defer cl.mu.Unlock()
1089 if c.PeerID == cl.peerID {
1092 return cl.runHandshookConn(c, t)
1095 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1096 c.conn.SetWriteDeadline(time.Time{})
1098 deadlineReader{c.conn, c.rw},
1101 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1102 if !cl.addConnection(t, c) {
1105 defer cl.dropConnection(t, c)
1107 go c.writeOptimizer(time.Minute)
1108 cl.sendInitialMessages(c, t)
1109 err = cl.connectionLoop(t, c)
1111 err = fmt.Errorf("error during connection loop: %s", err)
1116 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1117 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1118 conn.Post(pp.Message{
1120 ExtendedID: pp.HandshakeExtendedID,
1121 ExtendedPayload: func() []byte {
1122 d := map[string]interface{}{
1123 "m": func() (ret map[string]int) {
1124 ret = make(map[string]int, 2)
1125 ret["ut_metadata"] = metadataExtendedId
1126 if !me.config.DisablePEX {
1127 ret["ut_pex"] = pexExtendedId
1131 "v": extendedHandshakeClientVersion,
1132 // No upload queue is implemented yet.
1135 if !me.config.DisableEncryption {
1138 if torrent.metadataSizeKnown() {
1139 d["metadata_size"] = torrent.metadataSize()
1141 if p := me.incomingPeerPort(); p != 0 {
1144 yourip, err := addrCompactIP(conn.remoteAddr())
1146 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1148 d["yourip"] = yourip
1150 // log.Printf("sending %v", d)
1151 b, err := bencode.Marshal(d)
1159 if torrent.haveAnyPieces() {
1160 conn.Bitfield(torrent.bitfield())
1161 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1162 conn.Post(pp.Message{
1166 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1167 conn.Post(pp.Message{
1169 Port: uint16(AddrPort(me.dHT.Addr())),
1174 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) error {
1177 if c.PeerPieces == nil {
1178 c.PeerPieces = make([]bool, t.numPieces())
1181 for piece >= len(c.PeerPieces) {
1182 c.PeerPieces = append(c.PeerPieces, false)
1185 if piece >= len(c.PeerPieces) {
1186 return errors.New("peer got out of range piece index")
1188 c.PeerPieces[piece] = true
1190 c.updatePiecePriority(piece)
1194 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1195 conn.updateRequests()
1198 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1201 postedCancels.Add(1)
1206 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1207 if !cn.RequestPending(r) {
1210 delete(cn.Requests, r)
1214 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1218 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1219 // Peer doesn't support this.
1222 // Request metadata pieces that we don't have in a random order.
1224 for index := 0; index < t.metadataPieceCount(); index++ {
1225 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1226 pending = append(pending, index)
1229 for _, i := range mathRand.Perm(len(pending)) {
1230 c.requestMetadataPiece(pending[i])
1234 func (cl *Client) completedMetadata(t *torrent) {
1238 CopyExact(&ih, h.Sum(nil))
1239 if ih != t.InfoHash {
1240 log.Print("bad metadata")
1241 t.invalidateMetadata()
1244 var info metainfo.Info
1245 err := bencode.Unmarshal(t.MetaData, &info)
1247 log.Printf("error unmarshalling metadata: %s", err)
1248 t.invalidateMetadata()
1251 // TODO(anacrolix): If this fails, I think something harsher should be
1253 err = cl.setMetaData(t, &info, t.MetaData)
1255 log.Printf("error setting metadata: %s", err)
1256 t.invalidateMetadata()
1259 if cl.config.Debug {
1260 log.Printf("%s: got metadata from peers", t)
1264 // Process incoming ut_metadata message.
1265 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1266 var d map[string]int
1267 err = bencode.Unmarshal(payload, &d)
1269 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1272 msgType, ok := d["msg_type"]
1274 err = errors.New("missing msg_type field")
1279 case pp.DataMetadataExtensionMsgType:
1283 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1284 if begin < 0 || begin >= len(payload) {
1285 log.Printf("got bad metadata piece")
1288 if !c.requestedMetadataPiece(piece) {
1289 log.Printf("got unexpected metadata piece %d", piece)
1292 c.metadataRequests[piece] = false
1293 t.saveMetadataPiece(piece, payload[begin:])
1294 c.UsefulChunksReceived++
1295 c.lastUsefulChunkReceived = time.Now()
1296 if !t.haveAllMetadataPieces() {
1299 cl.completedMetadata(t)
1300 case pp.RequestMetadataExtensionMsgType:
1301 if !t.haveMetadataPiece(piece) {
1302 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1305 start := (1 << 14) * piece
1306 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1307 case pp.RejectMetadataExtensionMsgType:
1309 err = errors.New("unknown msg_type value")
1314 // Extracts the port as an integer from an address string.
1315 func addrPort(addr net.Addr) int {
1316 return AddrPort(addr)
1319 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1320 cn.peerHasAll = true
1323 for i := 0; i < t.numPieces(); i++ {
1324 cl.peerGotPiece(t, cn, i)
1329 func (me *Client) upload(t *torrent, c *connection) {
1330 if me.config.NoUpload {
1333 if !c.PeerInterested {
1336 seeding := me.seeding(t)
1337 if !seeding && !t.connHasWantedPieces(c) {
1341 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1343 for r := range c.PeerRequests {
1344 err := me.sendChunk(t, c, r)
1346 log.Printf("error sending chunk %+v to peer: %s", r, err)
1348 delete(c.PeerRequests, r)
1356 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1357 // Count the chunk being sent, even if it isn't.
1359 b := make([]byte, r.Length)
1360 tp := &t.Pieces[r.Index]
1361 tp.waitNoPendingWrites()
1362 p := t.Info.Piece(int(r.Index))
1363 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1366 panic("expected error")
1376 uploadChunksPosted.Add(1)
1377 c.lastChunkSent = time.Now()
1381 // Processes incoming bittorrent messages. The client lock is held upon entry
1383 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1384 decoder := pp.Decoder{
1385 R: bufio.NewReader(c.rw),
1386 MaxLength: 256 * 1024,
1391 err := decoder.Decode(&msg)
1393 if me.stopped() || c.closed.IsSet() || err == io.EOF {
1399 c.lastMessageReceived = time.Now()
1401 receivedKeepalives.Add(1)
1404 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1409 // We can then reset our interest.
1412 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1415 c.PeerChoked = false
1416 me.peerUnchoked(t, c)
1418 c.PeerInterested = true
1420 case pp.NotInterested:
1421 c.PeerInterested = false
1424 me.peerGotPiece(t, c, int(msg.Index))
1429 if !c.PeerInterested {
1430 err = errors.New("peer sent request but isn't interested")
1433 if c.PeerRequests == nil {
1434 c.PeerRequests = make(map[request]struct{}, maxRequests)
1436 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1439 req := newRequest(msg.Index, msg.Begin, msg.Length)
1440 if !c.PeerCancel(req) {
1441 unexpectedCancels.Add(1)
1444 if c.PeerPieces != nil || c.peerHasAll {
1445 err = errors.New("received unexpected bitfield")
1449 if len(msg.Bitfield) < t.numPieces() {
1450 err = errors.New("received invalid bitfield")
1453 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1455 c.PeerPieces = msg.Bitfield
1456 for index, has := range c.PeerPieces {
1458 me.peerGotPiece(t, c, index)
1462 if c.PeerPieces != nil || c.peerHasAll {
1463 err = errors.New("unexpected have-all")
1468 if c.peerHasAll || c.PeerPieces != nil {
1469 err = errors.New("unexpected have-none")
1472 c.PeerPieces = make([]bool, func() int {
1474 return t.numPieces()
1480 me.downloadedChunk(t, c, &msg)
1482 switch msg.ExtendedID {
1483 case pp.HandshakeExtendedID:
1484 // TODO: Create a bencode struct for this.
1485 var d map[string]interface{}
1486 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1488 err = fmt.Errorf("error decoding extended message payload: %s", err)
1491 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1492 if reqq, ok := d["reqq"]; ok {
1493 if i, ok := reqq.(int64); ok {
1494 c.PeerMaxRequests = int(i)
1497 if v, ok := d["v"]; ok {
1498 c.PeerClientName = v.(string)
1502 err = errors.New("handshake missing m item")
1505 mTyped, ok := m.(map[string]interface{})
1507 err = errors.New("handshake m value is not dict")
1510 if c.PeerExtensionIDs == nil {
1511 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1513 for name, v := range mTyped {
1516 log.Printf("bad handshake m item extension ID type: %T", v)
1520 delete(c.PeerExtensionIDs, name)
1522 if c.PeerExtensionIDs[name] == 0 {
1523 supportedExtensionMessages.Add(name, 1)
1525 c.PeerExtensionIDs[name] = byte(id)
1528 metadata_sizeUntyped, ok := d["metadata_size"]
1530 metadata_size, ok := metadata_sizeUntyped.(int64)
1532 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1534 t.setMetadataSize(metadata_size, me)
1537 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1538 me.requestPendingMetadata(t, c)
1540 case metadataExtendedId:
1541 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1543 err = fmt.Errorf("error handling metadata extension message: %s", err)
1546 if me.config.DisablePEX {
1549 var pexMsg peerExchangeMessage
1550 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1552 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1557 me.addPeers(t, func() (ret []Peer) {
1558 for i, cp := range pexMsg.Added {
1560 IP: make([]byte, 4),
1562 Source: peerSourcePEX,
1564 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1565 p.SupportsEncryption = true
1567 CopyExact(p.IP, cp.IP[:])
1568 ret = append(ret, p)
1575 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1578 // That client uses its own extension IDs for outgoing message
1579 // types, which is incorrect.
1580 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1581 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1589 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1594 pingAddr.Port = int(msg.Port)
1596 _, err = me.dHT.Ping(pingAddr)
1598 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1606 // Returns true if connection is removed from torrent.Conns.
1607 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1608 for i0, _c := range t.Conns {
1612 i1 := len(t.Conns) - 1
1614 t.Conns[i0] = t.Conns[i1]
1616 t.Conns = t.Conns[:i1]
1622 func (me *Client) dropConnection(t *torrent, c *connection) {
1623 me.event.Broadcast()
1625 if me.deleteConnection(t, c) {
1630 // Returns true if the connection is added.
1631 func (me *Client) addConnection(t *torrent, c *connection) bool {
1636 case <-t.ceasingNetworking:
1640 if !me.wantConns(t) {
1643 for _, c0 := range t.Conns {
1644 if c.PeerID == c0.PeerID {
1645 // Already connected to a client with that ID.
1646 duplicateClientConns.Add(1)
1650 if len(t.Conns) >= socketsPerTorrent {
1651 c := t.worstBadConn(me)
1655 if me.config.Debug && missinggo.CryHeard() {
1656 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1659 me.deleteConnection(t, c)
1661 if len(t.Conns) >= socketsPerTorrent {
1664 t.Conns = append(t.Conns, c)
1669 func (t *torrent) readerPieces() (ret bitmap.Bitmap) {
1670 t.forReaderOffsetPieces(func(begin, end int) bool {
1671 ret.AddRange(begin, end)
1677 func (t *torrent) needData() bool {
1681 if t.pendingPieces.Len() != 0 {
1684 return !t.readerPieces().IterTyped(func(piece int) bool {
1685 return t.pieceComplete(piece)
1689 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1690 if c.closed.IsSet() {
1694 return c.supportsExtension("ut_metadata")
1697 return c.PeerInterested
1699 return t.connHasWantedPieces(c)
1702 func (me *Client) wantConns(t *torrent) bool {
1703 if !me.seeding(t) && !t.needData() {
1706 if len(t.Conns) < socketsPerTorrent {
1709 return t.worstBadConn(me) != nil
1712 func (me *Client) openNewConns(t *torrent) {
1714 case <-t.ceasingNetworking:
1718 for len(t.Peers) != 0 {
1719 if !me.wantConns(t) {
1722 if len(t.HalfOpen) >= me.halfOpenLimit {
1729 for k, p = range t.Peers {
1733 me.initiateConn(p, t)
1735 t.wantPeers.Broadcast()
1738 func (me *Client) addPeers(t *torrent, peers []Peer) {
1739 for _, p := range peers {
1740 if me.dopplegangerAddr(net.JoinHostPort(
1742 strconv.FormatInt(int64(p.Port), 10),
1746 if _, ok := me.ipBlockRange(p.IP); ok {
1750 // The spec says to scrub these yourselves. Fine.
1757 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1758 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1761 func (cl *Client) saveTorrentFile(t *torrent) error {
1762 path := cl.cachedMetaInfoFilename(t.InfoHash)
1763 os.MkdirAll(filepath.Dir(path), 0777)
1764 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1766 return fmt.Errorf("error opening file: %s", err)
1769 e := bencode.NewEncoder(f)
1770 err = e.Encode(t.MetaInfo())
1772 return fmt.Errorf("error marshalling metainfo: %s", err)
1774 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1776 // For example, a script kiddy makes us load too many files, and we're
1777 // able to save the torrent, but not load it again to check it.
1780 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1781 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1786 func (cl *Client) setStorage(t *torrent, td Data) (err error) {
1788 cl.event.Broadcast()
1792 type TorrentDataOpener func(*metainfo.Info) Data
1794 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1795 err = t.setMetadata(md, bytes)
1799 if !cl.config.DisableMetainfoCache {
1800 if err := cl.saveTorrentFile(t); err != nil {
1801 log.Printf("error saving torrent file for %s: %s", t, err)
1804 cl.event.Broadcast()
1805 close(t.gotMetainfo)
1806 td := cl.torrentDataOpener(md)
1807 err = cl.setStorage(t, td)
1811 // Prepare a Torrent without any attachment to a Client. That means we can
1812 // initialize fields all fields that don't require the Client without locking
1814 func newTorrent(ih InfoHash) (t *torrent) {
1817 chunkSize: defaultChunkSize,
1818 Peers: make(map[peersKey]Peer),
1820 closing: make(chan struct{}),
1821 ceasingNetworking: make(chan struct{}),
1823 gotMetainfo: make(chan struct{}),
1825 HalfOpen: make(map[string]struct{}),
1826 pieceStateChanges: pubsub.NewPubSub(),
1832 // For shuffling the tracker tiers.
1833 mathRand.Seed(time.Now().Unix())
1836 type trackerTier []string
1838 // The trackers within each tier must be shuffled before use.
1839 // http://stackoverflow.com/a/12267471/149482
1840 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1841 func shuffleTier(tier trackerTier) {
1842 for i := range tier {
1843 j := mathRand.Intn(i + 1)
1844 tier[i], tier[j] = tier[j], tier[i]
1848 func copyTrackers(base []trackerTier) (copy []trackerTier) {
1849 for _, tier := range base {
1850 copy = append(copy, append(trackerTier(nil), tier...))
1855 func mergeTier(tier trackerTier, newURLs []string) trackerTier {
1857 for _, url := range newURLs {
1858 for _, trURL := range tier {
1863 tier = append(tier, url)
1868 func (t *torrent) addTrackers(announceList [][]string) {
1869 newTrackers := copyTrackers(t.Trackers)
1870 for tierIndex, tier := range announceList {
1871 if tierIndex < len(newTrackers) {
1872 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1874 newTrackers = append(newTrackers, mergeTier(nil, tier))
1876 shuffleTier(newTrackers[tierIndex])
1878 t.Trackers = newTrackers
1881 // Don't call this before the info is available.
1882 func (t *torrent) bytesCompleted() int64 {
1886 return t.Info.TotalLength() - t.bytesLeft()
1889 // A file-like handle to some torrent data resource.
1890 type Handle interface {
1897 // Returns handles to the files in the torrent. This requires the metainfo is
1899 func (t Torrent) Files() (ret []File) {
1907 for _, fi := range info.UpvertedFiles() {
1908 ret = append(ret, File{
1910 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1920 func (t Torrent) AddPeers(pp []Peer) error {
1923 defer cl.mu.Unlock()
1924 cl.addPeers(t.torrent, pp)
1928 // Marks the entire torrent for download. Requires the info first, see
1930 func (t Torrent) DownloadAll() {
1932 defer t.cl.mu.Unlock()
1933 t.torrent.pendPieceRange(0, t.torrent.numPieces())
1936 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1937 // metainfo has the correct infohash.
1938 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1939 if cl.config.DisableMetainfoCache {
1942 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1944 if os.IsNotExist(err) {
1950 dec := bencode.NewDecoder(f)
1951 err = dec.Decode(&mi)
1955 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1956 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1962 // Specifies a new torrent for adding to a client. There are helpers for
1963 // magnet URIs and torrent metainfo files.
1964 type TorrentSpec struct {
1965 // The tiered tracker URIs.
1968 Info *metainfo.InfoEx
1969 // The name to use if the Name field from the Info isn't available.
1971 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1976 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1977 m, err := ParseMagnetURI(uri)
1981 spec = &TorrentSpec{
1982 Trackers: [][]string{m.Trackers},
1983 DisplayName: m.DisplayName,
1984 InfoHash: m.InfoHash,
1989 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1990 spec = &TorrentSpec{
1991 Trackers: mi.AnnounceList,
1993 DisplayName: mi.Info.Name,
1996 if len(spec.Trackers) == 0 {
1997 spec.Trackers = [][]string{[]string{mi.Announce}}
1999 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
2002 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2006 // Add or merge a torrent spec. If the torrent is already present, the
2007 // trackers will be merged with the existing ones. If the Info isn't yet
2008 // known, it will be set. The display name is replaced if the new spec
2009 // provides one. Returns new if the torrent wasn't already in the client.
2010 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2013 defer cl.mu.Unlock()
2015 t, ok := cl.torrents[spec.InfoHash]
2019 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2020 err = errors.New("banned torrent")
2023 // TODO: Tidy this up?
2024 t = newTorrent(spec.InfoHash)
2026 t.wantPeers.L = &cl.mu
2027 if spec.ChunkSize != 0 {
2028 t.chunkSize = pp.Integer(spec.ChunkSize)
2031 if spec.DisplayName != "" {
2032 t.setDisplayName(spec.DisplayName)
2034 // Try to merge in info we have on the torrent. Any err left will
2035 // terminate the function.
2037 if spec.Info != nil {
2038 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2040 var mi *metainfo.MetaInfo
2041 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2043 log.Printf("error getting cached metainfo: %s", err)
2045 } else if mi != nil {
2046 t.addTrackers(mi.AnnounceList)
2047 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2054 t.addTrackers(spec.Trackers)
2056 cl.torrents[spec.InfoHash] = t
2059 // From this point onwards, we can consider the torrent a part of the
2062 if !cl.config.DisableTrackers {
2063 go cl.announceTorrentTrackers(T.torrent)
2066 go cl.announceTorrentDHT(T.torrent, true)
2072 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2073 t, ok := me.torrents[infoHash]
2075 err = fmt.Errorf("no such torrent")
2082 delete(me.torrents, infoHash)
2086 // Returns true when peers are required, or false if the torrent is closing.
2087 func (cl *Client) waitWantPeers(t *torrent) bool {
2089 defer cl.mu.Unlock()
2092 case <-t.ceasingNetworking:
2096 if len(t.Peers) > torrentPeersLowWater {
2099 if t.needData() || cl.seeding(t) {
2107 // Returns whether the client should make effort to seed the torrent.
2108 func (cl *Client) seeding(t *torrent) bool {
2109 if cl.config.NoUpload {
2112 if !cl.config.Seed {
2121 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2122 for cl.waitWantPeers(t) {
2123 // log.Printf("getting peers for %q from DHT", t)
2124 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2126 log.Printf("error getting peers from dht: %s", err)
2129 // Count all the unique addresses we got during this announce.
2130 allAddrs := make(map[string]struct{})
2134 case v, ok := <-ps.Peers:
2138 addPeers := make([]Peer, 0, len(v.Peers))
2139 for _, cp := range v.Peers {
2141 // Can't do anything with this.
2144 addPeers = append(addPeers, Peer{
2147 Source: peerSourceDHT,
2149 key := (&net.UDPAddr{
2153 allAddrs[key] = struct{}{}
2156 cl.addPeers(t, addPeers)
2157 numPeers := len(t.Peers)
2159 if numPeers >= torrentPeersHighWater {
2162 case <-t.ceasingNetworking:
2168 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2172 func (cl *Client) trackerBlockedUnlocked(trRawURL string) (blocked bool, err error) {
2173 url_, err := url.Parse(trRawURL)
2177 host, _, err := net.SplitHostPort(url_.Host)
2181 addr, err := net.ResolveIPAddr("ip", host)
2186 _, blocked = cl.ipBlockRange(addr.IP)
2191 func (cl *Client) announceTorrentSingleTracker(tr string, req *tracker.AnnounceRequest, t *torrent) error {
2192 blocked, err := cl.trackerBlockedUnlocked(tr)
2194 return fmt.Errorf("error determining if tracker blocked: %s", err)
2197 return fmt.Errorf("tracker blocked: %s", tr)
2199 resp, err := tracker.Announce(tr, req)
2201 return fmt.Errorf("error announcing: %s", err)
2204 for _, peer := range resp.Peers {
2205 peers = append(peers, Peer{
2211 cl.addPeers(t, peers)
2214 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2216 time.Sleep(time.Second * time.Duration(resp.Interval))
2220 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers []trackerTier, t *torrent) (atLeastOne bool) {
2221 oks := make(chan bool)
2223 for _, tier := range trackers {
2224 for _, tr := range tier {
2226 go func(tr string) {
2227 err := cl.announceTorrentSingleTracker(tr, req, t)
2232 for outstanding > 0 {
2242 // Announce torrent to its trackers.
2243 func (cl *Client) announceTorrentTrackers(t *torrent) {
2244 req := tracker.AnnounceRequest{
2245 Event: tracker.Started,
2247 Port: uint16(cl.incomingPeerPort()),
2249 InfoHash: t.InfoHash,
2251 if !cl.waitWantPeers(t) {
2255 req.Left = uint64(t.bytesLeft())
2256 trackers := t.Trackers
2258 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2259 req.Event = tracker.None
2262 for cl.waitWantPeers(t) {
2264 req.Left = uint64(t.bytesLeft())
2265 trackers = t.Trackers
2267 numTrackersTried := 0
2268 for _, tier := range trackers {
2269 for trIndex, tr := range tier {
2271 err := cl.announceTorrentSingleTracker(tr, &req, t)
2275 // Float the successful announce to the top of the tier. If
2276 // the trackers list has been changed, we'll be modifying an
2277 // old copy so it won't matter.
2279 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2282 req.Event = tracker.None
2283 continue newAnnounce
2286 if numTrackersTried != 0 {
2287 log.Printf("%s: all trackers failed", t)
2289 // TODO: Wait until trackers are added if there are none.
2290 time.Sleep(10 * time.Second)
2294 func (cl *Client) allTorrentsCompleted() bool {
2295 for _, t := range cl.torrents {
2299 if t.numPiecesCompleted() != t.numPieces() {
2306 // Returns true when all torrents are completely downloaded and false if the
2307 // client is stopped before that.
2308 func (me *Client) WaitAll() bool {
2310 defer me.mu.Unlock()
2311 for !me.allTorrentsCompleted() {
2320 // Handle a received chunk from a peer.
2321 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) {
2322 chunksReceived.Add(1)
2324 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2326 // Request has been satisfied.
2327 if me.connDeleteRequest(t, c, req) {
2328 defer c.updateRequests()
2330 unexpectedChunksReceived.Add(1)
2333 index := int(req.Index)
2334 piece := &t.Pieces[index]
2336 // Do we actually want this chunk?
2337 if !t.wantChunk(req) {
2338 unwantedChunksReceived.Add(1)
2339 c.UnwantedChunksReceived++
2343 c.UsefulChunksReceived++
2344 c.lastUsefulChunkReceived = time.Now()
2348 // Need to record that it hasn't been written yet, before we attempt to do
2349 // anything with it.
2350 piece.incrementPendingWrites()
2351 // Record that we have the chunk.
2352 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2354 // Cancel pending requests for this chunk.
2355 for _, c := range t.Conns {
2356 if me.connCancel(t, c, req) {
2362 // Write the chunk out.
2363 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2366 piece.decrementPendingWrites()
2369 log.Printf("error writing chunk: %s", err)
2374 // It's important that the piece is potentially queued before we check if
2375 // the piece is still wanted, because if it is queued, it won't be wanted.
2376 if t.pieceAllDirty(index) {
2377 me.queuePieceCheck(t, int(req.Index))
2380 if c.peerTouchedPieces == nil {
2381 c.peerTouchedPieces = make(map[int]struct{})
2383 c.peerTouchedPieces[index] = struct{}{}
2385 me.event.Broadcast()
2386 t.publishPieceChange(int(req.Index))
2390 // Return the connections that touched a piece, and clear the entry while
2392 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2393 for _, c := range t.Conns {
2394 if _, ok := c.peerTouchedPieces[piece]; ok {
2395 ret = append(ret, c)
2396 delete(c.peerTouchedPieces, piece)
2402 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2403 p := &t.Pieces[piece]
2405 // Don't score the first time a piece is hashed, it could be an
2408 pieceHashedCorrect.Add(1)
2410 log.Printf("%s: piece %d failed hash", t, piece)
2411 pieceHashedNotCorrect.Add(1)
2415 touchers := me.reapPieceTouches(t, int(piece))
2417 err := t.data.PieceCompleted(int(piece))
2419 log.Printf("%T: error completing piece %d: %s", t.data, piece, err)
2421 t.updatePieceCompletion(piece)
2422 } else if len(touchers) != 0 {
2423 log.Printf("dropping %d conns that touched piece", len(touchers))
2424 for _, c := range touchers {
2425 me.dropConnection(t, c)
2428 me.pieceChanged(t, int(piece))
2431 func (me *Client) onCompletedPiece(t *torrent, piece int) {
2432 t.pendingPieces.Remove(piece)
2433 for _, conn := range t.Conns {
2435 for r := range conn.Requests {
2436 if int(r.Index) == piece {
2440 // Could check here if peer doesn't have piece, but due to caching
2441 // some peers may have said they have a piece but they don't.
2446 func (me *Client) onFailedPiece(t *torrent, piece int) {
2447 if t.pieceAllDirty(piece) {
2448 t.pendAllChunkSpecs(piece)
2450 if !t.wantPiece(piece) {
2454 for _, conn := range t.Conns {
2455 if conn.PeerHasPiece(piece) {
2456 conn.updateRequests()
2461 func (me *Client) pieceChanged(t *torrent, piece int) {
2462 correct := t.pieceComplete(piece)
2463 defer me.event.Broadcast()
2465 me.onCompletedPiece(t, piece)
2467 me.onFailedPiece(t, piece)
2469 if t.updatePiecePriority(piece) {
2470 t.piecePriorityChanged(piece)
2472 t.publishPieceChange(piece)
2475 func (cl *Client) verifyPiece(t *torrent, piece int) {
2477 defer cl.mu.Unlock()
2478 p := &t.Pieces[piece]
2479 for p.Hashing || t.data == nil {
2482 p.QueuedForHash = false
2483 if t.isClosed() || t.pieceComplete(piece) {
2484 t.updatePiecePriority(piece)
2485 t.publishPieceChange(piece)
2489 t.publishPieceChange(piece)
2491 sum := t.hashPiece(piece)
2499 cl.pieceHashed(t, piece, sum == p.Hash)
2502 // Returns handles to all the torrents loaded in the Client.
2503 func (me *Client) Torrents() (ret []Torrent) {
2505 for _, t := range me.torrents {
2506 ret = append(ret, Torrent{me, t})
2512 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2513 spec, err := TorrentSpecFromMagnetURI(uri)
2517 T, _, err = me.AddTorrentSpec(spec)
2521 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2522 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2526 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2527 mi, err := metainfo.LoadFromFile(filename)
2531 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2535 func (me *Client) DHT() *dht.Server {