25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/bitmap"
28 "github.com/anacrolix/missinggo/pproffd"
29 "github.com/anacrolix/missinggo/pubsub"
30 "github.com/anacrolix/sync"
31 "github.com/anacrolix/utp"
32 "github.com/edsrzf/mmap-go"
34 "github.com/anacrolix/torrent/bencode"
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/storage"
41 "github.com/anacrolix/torrent/tracker"
44 // I could move a lot of these counters to their own file, but I suspect they
45 // may be attached to a Client someday.
47 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
48 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
49 chunksReceived = expvar.NewInt("chunksReceived")
51 peersAddedBySource = expvar.NewMap("peersAddedBySource")
53 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
54 unexpectedCancels = expvar.NewInt("unexpectedCancels")
55 postedCancels = expvar.NewInt("postedCancels")
56 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
58 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
59 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
61 unsuccessfulDials = expvar.NewInt("dialSuccessful")
62 successfulDials = expvar.NewInt("dialUnsuccessful")
64 acceptUTP = expvar.NewInt("acceptUTP")
65 acceptTCP = expvar.NewInt("acceptTCP")
66 acceptReject = expvar.NewInt("acceptReject")
68 peerExtensions = expvar.NewMap("peerExtensions")
69 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
70 // Count of connections to peer with same client ID.
71 connsToSelf = expvar.NewInt("connsToSelf")
72 // Number of completed connections to a client we're already connected with.
73 duplicateClientConns = expvar.NewInt("duplicateClientConns")
74 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
75 receivedKeepalives = expvar.NewInt("receivedKeepalives")
76 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
77 postedMessageTypes = expvar.NewMap("postedMessageTypes")
78 postedKeepalives = expvar.NewInt("postedKeepalives")
79 // Requests received for pieces we don't have.
80 requestsReceivedForMissingPieces = expvar.NewInt("requestsReceivedForMissingPieces")
84 // Justification for set bits follows.
86 // Extension protocol ([5]|=0x10):
87 // http://www.bittorrent.org/beps/bep_0010.html
89 // Fast Extension ([7]|=0x04):
90 // http://bittorrent.org/beps/bep_0006.html.
91 // Disabled until AllowedFast is implemented.
94 // http://www.bittorrent.org/beps/bep_0005.html
95 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
97 socketsPerTorrent = 80
98 torrentPeersHighWater = 200
99 torrentPeersLowWater = 50
101 // Limit how long handshake can take. This is to reduce the lingering
102 // impact of a few bad apples. 4s loses 1% of successful handshakes that
103 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
104 btHandshakeTimeout = 4 * time.Second
105 handshakesTimeout = 20 * time.Second
107 // These are our extended message IDs.
108 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
111 // Updated occasionally to when there's been some changes to client
112 // behaviour in case other clients are assuming anything of us. See also
114 extendedHandshakeClientVersion = "go.torrent dev 20150624"
117 // Currently doesn't really queue, but should in the future.
118 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
119 piece := &t.Pieces[pieceIndex]
120 if piece.QueuedForHash {
123 piece.QueuedForHash = true
124 t.publishPieceChange(int(pieceIndex))
125 go cl.verifyPiece(t, int(pieceIndex))
128 // Queue a piece check if one isn't already queued, and the piece has never
129 // been checked before.
130 func (cl *Client) queueFirstHash(t *torrent, piece int) {
131 p := &t.Pieces[piece]
132 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
135 cl.queuePieceCheck(t, piece)
138 // Clients contain zero or more Torrents. A client manages a blocklist, the
139 // TCP/UDP protocol ports, and DHT as desired.
143 listeners []net.Listener
146 ipBlockList iplist.Ranger
147 bannedTorrents map[InfoHash]struct{}
149 pruneTimer *time.Timer
150 extensionBytes peerExtensionBytes
151 // Set of addresses that have our client ID. This intentionally will
152 // include ourselves if we end up trying to connect to our own address
153 // through legitimate channels.
154 dopplegangerAddrs map[string]struct{}
156 defaultStorage storage.I
160 closed missinggo.Event
162 torrents map[InfoHash]*torrent
165 func (me *Client) IPBlockList() iplist.Ranger {
168 return me.ipBlockList
171 func (me *Client) SetIPBlockList(list iplist.Ranger) {
174 me.ipBlockList = list
176 me.dHT.SetIPBlockList(list)
180 func (me *Client) PeerID() string {
181 return string(me.peerID[:])
184 func (me *Client) ListenAddr() (addr net.Addr) {
185 for _, l := range me.listeners {
192 type hashSorter struct {
196 func (me hashSorter) Len() int {
197 return len(me.Hashes)
200 func (me hashSorter) Less(a, b int) bool {
201 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
204 func (me hashSorter) Swap(a, b int) {
205 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
208 func (cl *Client) sortedTorrents() (ret []*torrent) {
210 for ih := range cl.torrents {
211 hs.Hashes = append(hs.Hashes, ih)
214 for _, ih := range hs.Hashes {
215 ret = append(ret, cl.torrent(ih))
220 // Writes out a human readable status of the client, such as for writing to a
222 func (cl *Client) WriteStatus(_w io.Writer) {
224 defer cl.mu.RUnlock()
225 w := bufio.NewWriter(_w)
227 if addr := cl.ListenAddr(); addr != nil {
228 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
230 fmt.Fprintln(w, "Not listening!")
232 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
234 dhtStats := cl.dHT.Stats()
235 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
236 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
237 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(cl.dHT.Addr()))
238 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
239 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
241 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
243 for _, t := range cl.sortedTorrents() {
245 fmt.Fprint(w, "<unknown name>")
247 fmt.Fprint(w, t.Name())
251 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float64(t.bytesLeft())/float64(t.length)), t.length)
253 w.WriteString("<missing metainfo>")
261 // Calculates the number of pieces to set to Readahead priority, after the
262 // Now, and Next pieces.
263 func readaheadPieces(readahead, pieceLength int64) (ret int) {
264 // Expand the readahead to fit any partial pieces. Subtract 1 for the
265 // "next" piece that is assigned.
266 ret = int((readahead+pieceLength-1)/pieceLength - 1)
267 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
268 // piece length is much larger than the readahead.
275 func (cl *Client) configDir() string {
276 if cl.config.ConfigDir == "" {
277 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
279 return cl.config.ConfigDir
282 // The directory where the Client expects to find and store configuration
283 // data. Defaults to $HOME/.config/torrent.
284 func (cl *Client) ConfigDir() string {
285 return cl.configDir()
288 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
289 f, err := os.Open(filename)
290 if os.IsNotExist(err) {
298 mm, err := mmap.Map(f, mmap.RDONLY, 0)
302 ret = iplist.NewFromPacked(mm)
306 func (cl *Client) setEnvBlocklist() (err error) {
307 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
308 defaultBlocklist := filename == ""
309 if defaultBlocklist {
310 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
314 if cl.ipBlockList != nil {
317 filename = filepath.Join(cl.configDir(), "blocklist")
319 f, err := os.Open(filename)
321 if defaultBlocklist {
327 cl.ipBlockList, err = iplist.NewFromReader(f)
331 func (cl *Client) initBannedTorrents() error {
332 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
334 if os.IsNotExist(err) {
337 return fmt.Errorf("error opening banned infohashes file: %s", err)
340 scanner := bufio.NewScanner(f)
341 cl.bannedTorrents = make(map[InfoHash]struct{})
343 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
347 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
349 return fmt.Errorf("error reading infohash: %s", err)
355 return errors.New("bad infohash")
359 cl.bannedTorrents[ih] = struct{}{}
361 if err := scanner.Err(); err != nil {
362 return fmt.Errorf("error scanning file: %s", err)
367 // Creates a new client.
368 func NewClient(cfg *Config) (cl *Client, err error) {
379 halfOpenLimit: socketsPerTorrent,
381 defaultStorage: cfg.DefaultStorage,
382 dopplegangerAddrs: make(map[string]struct{}),
383 torrents: make(map[InfoHash]*torrent),
385 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
387 if cl.defaultStorage == nil {
388 cl.defaultStorage = storage.NewFile(cfg.DataDir)
390 if cfg.IPBlocklist != nil {
391 cl.ipBlockList = cfg.IPBlocklist
392 } else if !cfg.NoDefaultBlocklist {
393 err = cl.setEnvBlocklist()
399 if err = cl.initBannedTorrents(); err != nil {
400 err = fmt.Errorf("error initing banned torrents: %s", err)
404 if cfg.PeerID != "" {
405 CopyExact(&cl.peerID, cfg.PeerID)
407 o := copy(cl.peerID[:], bep20)
408 _, err = rand.Read(cl.peerID[o:])
410 panic("error generating peer id")
414 // Returns the laddr string to listen on for the next Listen call.
415 listenAddr := func() string {
416 if addr := cl.ListenAddr(); addr != nil {
419 if cfg.ListenAddr == "" {
422 return cfg.ListenAddr
424 if !cl.config.DisableTCP {
426 l, err = net.Listen(func() string {
427 if cl.config.DisableIPv6 {
436 cl.listeners = append(cl.listeners, l)
437 go cl.acceptConnections(l, false)
439 if !cl.config.DisableUTP {
440 cl.utpSock, err = utp.NewSocket(func() string {
441 if cl.config.DisableIPv6 {
450 cl.listeners = append(cl.listeners, cl.utpSock)
451 go cl.acceptConnections(cl.utpSock, true)
454 dhtCfg := cfg.DHTConfig
455 if dhtCfg.IPBlocklist == nil {
456 dhtCfg.IPBlocklist = cl.ipBlockList
458 if dhtCfg.Addr == "" {
459 dhtCfg.Addr = listenAddr()
461 if dhtCfg.Conn == nil && cl.utpSock != nil {
462 dhtCfg.Conn = cl.utpSock
464 cl.dHT, err = dht.NewServer(&dhtCfg)
473 // Stops the client. All connections to peers are closed and all activity will
475 func (me *Client) Close() {
482 for _, l := range me.listeners {
485 for _, t := range me.torrents {
491 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
493 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
494 if cl.ipBlockList == nil {
498 // If blocklists are enabled, then block non-IPv4 addresses, because
499 // blocklists do not yet support IPv6.
501 if missinggo.CryHeard() {
502 log.Printf("blocking non-IPv4 address: %s", ip)
508 return cl.ipBlockList.Lookup(ip4)
511 func (cl *Client) waitAccept() {
515 for _, t := range cl.torrents {
520 if cl.closed.IsSet() {
527 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
530 conn, err := l.Accept()
531 conn = pproffd.WrapNetConn(conn)
532 if cl.closed.IsSet() {
540 // I think something harsher should happen here? Our accept
541 // routine just fucked off.
550 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
551 _, blocked := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
553 if blocked || doppleganger {
555 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
559 go cl.incomingConnection(conn, utp)
563 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
565 if tc, ok := nc.(*net.TCPConn); ok {
571 c.Discovery = peerSourceIncoming
573 err := cl.runReceivedConn(c)
579 // Returns a handle to the given torrent, if it's present in the client.
580 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
583 t, ok := cl.torrents[ih]
591 func (me *Client) torrent(ih InfoHash) *torrent {
592 return me.torrents[ih]
595 type dialResult struct {
600 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
601 conn, err := dial(addr, t)
606 conn = nil // Pedantic
608 ch <- dialResult{conn, utp}
610 successfulDials.Add(1)
613 unsuccessfulDials.Add(1)
616 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
617 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
618 if ret < minDialTimeout {
624 // Returns whether an address is known to connect to a client with our own ID.
625 func (me *Client) dopplegangerAddr(addr string) bool {
626 _, ok := me.dopplegangerAddrs[addr]
630 // Start the process of connecting to the given peer for the given torrent if
632 func (me *Client) initiateConn(peer Peer, t *torrent) {
633 if peer.Id == me.peerID {
636 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
637 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
638 duplicateConnsAvoided.Add(1)
641 if r, ok := me.ipBlockRange(peer.IP); ok {
642 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
645 t.HalfOpen[addr] = struct{}{}
646 go me.outgoingConnection(t, addr, peer.Source)
649 func (me *Client) dialTimeout(t *torrent) time.Duration {
651 pendingPeers := len(t.Peers)
653 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
656 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
657 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
659 c.(*net.TCPConn).SetLinger(0)
664 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
665 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
668 // Returns a connection over UTP or TCP, whichever is first to connect.
669 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
670 // Initiate connections via TCP and UTP simultaneously. Use the first one
673 if !me.config.DisableUTP {
676 if !me.config.DisableTCP {
679 resCh := make(chan dialResult, left)
680 if !me.config.DisableUTP {
681 go doDial(me.dialUTP, resCh, true, addr, t)
683 if !me.config.DisableTCP {
684 go doDial(me.dialTCP, resCh, false, addr, t)
687 // Wait for a successful connection.
688 for ; left > 0 && res.Conn == nil; left-- {
692 // There are still incompleted dials.
694 for ; left > 0; left-- {
695 conn := (<-resCh).Conn
707 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
708 if _, ok := t.HalfOpen[addr]; !ok {
709 panic("invariant broken")
711 delete(t.HalfOpen, addr)
715 // Performs initiator handshakes and returns a connection. Returns nil
716 // *connection if no connection for valid reasons.
717 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
721 c.encrypted = encrypted
723 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
727 ok, err := me.initiateHandshakes(c, t)
734 // Returns nil connection and nil error if no connection could be established
735 // for valid reasons.
736 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
737 nc, utp := me.dialFirst(addr, t)
741 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
749 if me.config.DisableEncryption {
750 // We already tried without encryption.
753 // Try again without encryption, using whichever protocol type worked last
756 nc, err = me.dialUTP(addr, t)
758 nc, err = me.dialTCP(addr, t)
761 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
764 c, err = me.handshakesConnection(nc, t, false, utp)
765 if err != nil || c == nil {
771 // Called to dial out and run a connection. The addr we're given is already
772 // considered half-open.
773 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
774 c, err := me.establishOutgoingConn(t, addr)
777 // Don't release lock between here and addConnection, unless it's for
779 me.noLongerHalfOpen(t, addr)
782 log.Printf("error establishing outgoing connection: %s", err)
791 err = me.runInitiatedHandshookConn(c, t)
794 log.Printf("error in established outgoing connection: %s", err)
799 // The port number for incoming peer connections. 0 if the client isn't
801 func (cl *Client) incomingPeerPort() int {
802 listenAddr := cl.ListenAddr()
803 if listenAddr == nil {
806 return missinggo.AddrPort(listenAddr)
809 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
810 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
811 func addrCompactIP(addr net.Addr) (string, error) {
812 host, _, err := net.SplitHostPort(addr.String())
816 ip := net.ParseIP(host)
817 if v4 := ip.To4(); v4 != nil {
821 return string(v4), nil
823 return string(ip.To16()), nil
826 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
838 peerExtensionBytes [8]byte
842 func (me *peerExtensionBytes) SupportsExtended() bool {
843 return me[5]&0x10 != 0
846 func (me *peerExtensionBytes) SupportsDHT() bool {
847 return me[7]&0x01 != 0
850 func (me *peerExtensionBytes) SupportsFast() bool {
851 return me[7]&0x04 != 0
854 type handshakeResult struct {
860 // ih is nil if we expect the peer to declare the InfoHash, such as when the
861 // peer initiated the connection. Returns ok if the handshake was successful,
862 // and err if there was an unexpected condition other than the peer simply
863 // abandoning the handshake.
864 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
865 // Bytes to be sent to the peer. Should never block the sender.
866 postCh := make(chan []byte, 4)
867 // A single error value sent when the writer completes.
868 writeDone := make(chan error, 1)
869 // Performs writes to the socket and ensures posts don't block.
870 go handshakeWriter(sock, postCh, writeDone)
873 close(postCh) // Done writing.
880 // Wait until writes complete before returning from handshake.
883 err = fmt.Errorf("error writing: %s", err)
887 post := func(bb []byte) {
891 panic("mustn't block while posting")
895 post([]byte(pp.Protocol))
897 if ih != nil { // We already know what we want.
902 _, err = io.ReadFull(sock, b[:68])
907 if string(b[:20]) != pp.Protocol {
910 CopyExact(&res.peerExtensionBytes, b[20:28])
911 CopyExact(&res.InfoHash, b[28:48])
912 CopyExact(&res.peerID, b[48:68])
913 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
915 // TODO: Maybe we can just drop peers here if we're not interested. This
916 // could prevent them trying to reconnect, falsely believing there was
918 if ih == nil { // We were waiting for the peer to tell us what they wanted.
919 post(res.InfoHash[:])
927 // Wraps a raw connection and provides the interface we want for using the
928 // connection in the message loop.
929 type deadlineReader struct {
934 func (me deadlineReader) Read(b []byte) (n int, err error) {
935 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
936 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
938 err = fmt.Errorf("error setting read deadline: %s", err)
940 n, err = me.r.Read(b)
941 // Convert common errors into io.EOF.
943 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
945 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
955 type readWriter struct {
960 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
961 var protocol [len(pp.Protocol)]byte
962 _, err = io.ReadFull(rw, protocol[:])
967 io.MultiReader(bytes.NewReader(protocol[:]), rw),
970 if string(protocol[:]) == pp.Protocol {
974 ret, err = mse.ReceiveHandshake(ret, skeys)
978 func (cl *Client) receiveSkeys() (ret [][]byte) {
979 for ih := range cl.torrents {
980 ret = append(ret, ih[:])
985 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
987 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
992 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
993 if ih != t.InfoHash {
999 // Do encryption and bittorrent handshakes as receiver.
1000 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1002 skeys := cl.receiveSkeys()
1004 if !cl.config.DisableEncryption {
1005 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1007 if err == mse.ErrNoSecretKeyMatch {
1013 ih, ok, err := cl.connBTHandshake(c, nil)
1015 err = fmt.Errorf("error during bt handshake: %s", err)
1027 // Returns !ok if handshake failed for valid reasons.
1028 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1029 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1030 if err != nil || !ok {
1034 c.PeerExtensionBytes = res.peerExtensionBytes
1035 c.PeerID = res.peerID
1036 c.completedHandshake = time.Now()
1040 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1041 if c.PeerID == cl.peerID {
1042 // Only if we initiated the connection is the remote address a
1043 // listen addr for a doppleganger.
1045 addr := c.conn.RemoteAddr().String()
1046 cl.dopplegangerAddrs[addr] = struct{}{}
1049 return cl.runHandshookConn(c, t)
1052 func (cl *Client) runReceivedConn(c *connection) (err error) {
1053 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1057 t, err := cl.receiveHandshakes(c)
1059 err = fmt.Errorf("error receiving handshakes: %s", err)
1066 defer cl.mu.Unlock()
1067 if c.PeerID == cl.peerID {
1070 return cl.runHandshookConn(c, t)
1073 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1074 c.conn.SetWriteDeadline(time.Time{})
1076 deadlineReader{c.conn, c.rw},
1079 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1080 if !cl.addConnection(t, c) {
1083 defer cl.dropConnection(t, c)
1085 go c.writeOptimizer(time.Minute)
1086 cl.sendInitialMessages(c, t)
1087 err = cl.connectionLoop(t, c)
1089 err = fmt.Errorf("error during connection loop: %s", err)
1094 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1095 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1096 conn.Post(pp.Message{
1098 ExtendedID: pp.HandshakeExtendedID,
1099 ExtendedPayload: func() []byte {
1100 d := map[string]interface{}{
1101 "m": func() (ret map[string]int) {
1102 ret = make(map[string]int, 2)
1103 ret["ut_metadata"] = metadataExtendedId
1104 if !me.config.DisablePEX {
1105 ret["ut_pex"] = pexExtendedId
1109 "v": extendedHandshakeClientVersion,
1110 // No upload queue is implemented yet.
1113 if !me.config.DisableEncryption {
1116 if torrent.metadataSizeKnown() {
1117 d["metadata_size"] = torrent.metadataSize()
1119 if p := me.incomingPeerPort(); p != 0 {
1122 yourip, err := addrCompactIP(conn.remoteAddr())
1124 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1126 d["yourip"] = yourip
1128 // log.Printf("sending %v", d)
1129 b, err := bencode.Marshal(d)
1137 if torrent.haveAnyPieces() {
1138 conn.Bitfield(torrent.bitfield())
1139 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1140 conn.Post(pp.Message{
1144 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1145 conn.Post(pp.Message{
1147 Port: uint16(AddrPort(me.dHT.Addr())),
1152 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1153 conn.updateRequests()
1156 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1159 postedCancels.Add(1)
1164 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1165 if !cn.RequestPending(r) {
1168 delete(cn.Requests, r)
1172 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1176 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1177 // Peer doesn't support this.
1180 // Request metadata pieces that we don't have in a random order.
1182 for index := 0; index < t.metadataPieceCount(); index++ {
1183 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1184 pending = append(pending, index)
1187 for _, i := range mathRand.Perm(len(pending)) {
1188 c.requestMetadataPiece(pending[i])
1192 func (cl *Client) completedMetadata(t *torrent) {
1196 CopyExact(&ih, h.Sum(nil))
1197 if ih != t.InfoHash {
1198 log.Print("bad metadata")
1199 t.invalidateMetadata()
1202 var info metainfo.Info
1203 err := bencode.Unmarshal(t.MetaData, &info)
1205 log.Printf("error unmarshalling metadata: %s", err)
1206 t.invalidateMetadata()
1209 // TODO(anacrolix): If this fails, I think something harsher should be
1211 err = cl.setMetaData(t, &info, t.MetaData)
1213 log.Printf("error setting metadata: %s", err)
1214 t.invalidateMetadata()
1217 if cl.config.Debug {
1218 log.Printf("%s: got metadata from peers", t)
1222 // Process incoming ut_metadata message.
1223 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1224 var d map[string]int
1225 err = bencode.Unmarshal(payload, &d)
1227 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1230 msgType, ok := d["msg_type"]
1232 err = errors.New("missing msg_type field")
1237 case pp.DataMetadataExtensionMsgType:
1241 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1242 if begin < 0 || begin >= len(payload) {
1243 log.Printf("got bad metadata piece")
1246 if !c.requestedMetadataPiece(piece) {
1247 log.Printf("got unexpected metadata piece %d", piece)
1250 c.metadataRequests[piece] = false
1251 t.saveMetadataPiece(piece, payload[begin:])
1252 c.UsefulChunksReceived++
1253 c.lastUsefulChunkReceived = time.Now()
1254 if !t.haveAllMetadataPieces() {
1257 cl.completedMetadata(t)
1258 case pp.RequestMetadataExtensionMsgType:
1259 if !t.haveMetadataPiece(piece) {
1260 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1263 start := (1 << 14) * piece
1264 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1265 case pp.RejectMetadataExtensionMsgType:
1267 err = errors.New("unknown msg_type value")
1272 func (me *Client) upload(t *torrent, c *connection) {
1273 if me.config.NoUpload {
1276 if !c.PeerInterested {
1279 seeding := me.seeding(t)
1280 if !seeding && !t.connHasWantedPieces(c) {
1284 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1286 for r := range c.PeerRequests {
1287 err := me.sendChunk(t, c, r)
1289 if t.pieceComplete(int(r.Index)) && err == io.ErrUnexpectedEOF {
1290 // We had the piece, but not anymore.
1292 log.Printf("error sending chunk %+v to peer: %s", r, err)
1294 // If we failed to send a chunk, choke the peer to ensure they
1295 // flush all their requests. We've probably dropped a piece,
1296 // but there's no way to communicate this to the peer. If they
1297 // ask for it again, we'll kick them to allow us to send them
1298 // an updated bitfield.
1301 delete(c.PeerRequests, r)
1309 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1310 // Count the chunk being sent, even if it isn't.
1311 b := make([]byte, r.Length)
1312 p := t.Info.Piece(int(r.Index))
1313 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1316 panic("expected error")
1327 uploadChunksPosted.Add(1)
1328 c.lastChunkSent = time.Now()
1332 // Processes incoming bittorrent messages. The client lock is held upon entry
1334 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1335 decoder := pp.Decoder{
1336 R: bufio.NewReader(c.rw),
1337 MaxLength: 256 * 1024,
1342 err := decoder.Decode(&msg)
1344 if me.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1350 c.lastMessageReceived = time.Now()
1352 receivedKeepalives.Add(1)
1355 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1360 // We can then reset our interest.
1363 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1366 c.PeerChoked = false
1367 me.peerUnchoked(t, c)
1369 c.PeerInterested = true
1371 case pp.NotInterested:
1372 c.PeerInterested = false
1375 err = c.peerSentHave(int(msg.Index))
1380 if !c.PeerInterested {
1381 err = errors.New("peer sent request but isn't interested")
1384 if !t.havePiece(msg.Index.Int()) {
1385 // This isn't necessarily them screwing up. We can drop pieces
1386 // from our storage, and can't communicate this to peers
1387 // except by reconnecting.
1388 requestsReceivedForMissingPieces.Add(1)
1389 err = errors.New("peer requested piece we don't have")
1392 if c.PeerRequests == nil {
1393 c.PeerRequests = make(map[request]struct{}, maxRequests)
1395 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1398 req := newRequest(msg.Index, msg.Begin, msg.Length)
1399 if !c.PeerCancel(req) {
1400 unexpectedCancels.Add(1)
1403 err = c.peerSentBitfield(msg.Bitfield)
1405 err = c.peerSentHaveAll()
1407 err = c.peerSentHaveNone()
1409 me.downloadedChunk(t, c, &msg)
1411 switch msg.ExtendedID {
1412 case pp.HandshakeExtendedID:
1413 // TODO: Create a bencode struct for this.
1414 var d map[string]interface{}
1415 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1417 err = fmt.Errorf("error decoding extended message payload: %s", err)
1420 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1421 if reqq, ok := d["reqq"]; ok {
1422 if i, ok := reqq.(int64); ok {
1423 c.PeerMaxRequests = int(i)
1426 if v, ok := d["v"]; ok {
1427 c.PeerClientName = v.(string)
1431 err = errors.New("handshake missing m item")
1434 mTyped, ok := m.(map[string]interface{})
1436 err = errors.New("handshake m value is not dict")
1439 if c.PeerExtensionIDs == nil {
1440 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1442 for name, v := range mTyped {
1445 log.Printf("bad handshake m item extension ID type: %T", v)
1449 delete(c.PeerExtensionIDs, name)
1451 if c.PeerExtensionIDs[name] == 0 {
1452 supportedExtensionMessages.Add(name, 1)
1454 c.PeerExtensionIDs[name] = byte(id)
1457 metadata_sizeUntyped, ok := d["metadata_size"]
1459 metadata_size, ok := metadata_sizeUntyped.(int64)
1461 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1463 t.setMetadataSize(metadata_size, me)
1466 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1467 me.requestPendingMetadata(t, c)
1469 case metadataExtendedId:
1470 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1472 err = fmt.Errorf("error handling metadata extension message: %s", err)
1475 if me.config.DisablePEX {
1478 var pexMsg peerExchangeMessage
1479 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1481 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1486 me.addPeers(t, func() (ret []Peer) {
1487 for i, cp := range pexMsg.Added {
1489 IP: make([]byte, 4),
1491 Source: peerSourcePEX,
1493 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1494 p.SupportsEncryption = true
1496 CopyExact(p.IP, cp.IP[:])
1497 ret = append(ret, p)
1504 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1507 // That client uses its own extension IDs for outgoing message
1508 // types, which is incorrect.
1509 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1510 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1518 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1523 pingAddr.Port = int(msg.Port)
1525 _, err = me.dHT.Ping(pingAddr)
1527 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1535 // Returns true if connection is removed from torrent.Conns.
1536 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1537 for i0, _c := range t.Conns {
1541 i1 := len(t.Conns) - 1
1543 t.Conns[i0] = t.Conns[i1]
1545 t.Conns = t.Conns[:i1]
1551 func (me *Client) dropConnection(t *torrent, c *connection) {
1552 me.event.Broadcast()
1554 if me.deleteConnection(t, c) {
1559 // Returns true if the connection is added.
1560 func (me *Client) addConnection(t *torrent, c *connection) bool {
1561 if me.closed.IsSet() {
1565 case <-t.ceasingNetworking:
1569 if !me.wantConns(t) {
1572 for _, c0 := range t.Conns {
1573 if c.PeerID == c0.PeerID {
1574 // Already connected to a client with that ID.
1575 duplicateClientConns.Add(1)
1579 if len(t.Conns) >= socketsPerTorrent {
1580 c := t.worstBadConn(me)
1584 if me.config.Debug && missinggo.CryHeard() {
1585 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1588 me.deleteConnection(t, c)
1590 if len(t.Conns) >= socketsPerTorrent {
1593 t.Conns = append(t.Conns, c)
1598 func (t *torrent) readerPieces() (ret bitmap.Bitmap) {
1599 t.forReaderOffsetPieces(func(begin, end int) bool {
1600 ret.AddRange(begin, end)
1606 func (t *torrent) needData() bool {
1610 if t.pendingPieces.Len() != 0 {
1613 return !t.readerPieces().IterTyped(func(piece int) bool {
1614 return t.pieceComplete(piece)
1618 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1619 if c.closed.IsSet() {
1623 return c.supportsExtension("ut_metadata")
1626 return c.PeerInterested
1628 return t.connHasWantedPieces(c)
1631 func (me *Client) wantConns(t *torrent) bool {
1632 if !me.seeding(t) && !t.needData() {
1635 if len(t.Conns) < socketsPerTorrent {
1638 return t.worstBadConn(me) != nil
1641 func (me *Client) openNewConns(t *torrent) {
1643 case <-t.ceasingNetworking:
1647 for len(t.Peers) != 0 {
1648 if !me.wantConns(t) {
1651 if len(t.HalfOpen) >= me.halfOpenLimit {
1658 for k, p = range t.Peers {
1662 me.initiateConn(p, t)
1664 t.wantPeers.Broadcast()
1667 func (me *Client) addPeers(t *torrent, peers []Peer) {
1668 for _, p := range peers {
1669 if me.dopplegangerAddr(net.JoinHostPort(
1671 strconv.FormatInt(int64(p.Port), 10),
1675 if _, ok := me.ipBlockRange(p.IP); ok {
1679 // The spec says to scrub these yourselves. Fine.
1686 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1687 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1690 func (cl *Client) saveTorrentFile(t *torrent) error {
1691 path := cl.cachedMetaInfoFilename(t.InfoHash)
1692 os.MkdirAll(filepath.Dir(path), 0777)
1693 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1695 return fmt.Errorf("error opening file: %s", err)
1698 e := bencode.NewEncoder(f)
1699 err = e.Encode(t.MetaInfo())
1701 return fmt.Errorf("error marshalling metainfo: %s", err)
1703 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1705 // For example, a script kiddy makes us load too many files, and we're
1706 // able to save the torrent, but not load it again to check it.
1709 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1710 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1715 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1716 err = t.setMetadata(md, bytes)
1720 if !cl.config.DisableMetainfoCache {
1721 if err := cl.saveTorrentFile(t); err != nil {
1722 log.Printf("error saving torrent file for %s: %s", t, err)
1725 cl.event.Broadcast()
1726 close(t.gotMetainfo)
1730 // Prepare a Torrent without any attachment to a Client. That means we can
1731 // initialize fields all fields that don't require the Client without locking
1733 func newTorrent(ih InfoHash) (t *torrent) {
1736 chunkSize: defaultChunkSize,
1737 Peers: make(map[peersKey]Peer),
1739 closing: make(chan struct{}),
1740 ceasingNetworking: make(chan struct{}),
1742 gotMetainfo: make(chan struct{}),
1744 HalfOpen: make(map[string]struct{}),
1745 pieceStateChanges: pubsub.NewPubSub(),
1751 // For shuffling the tracker tiers.
1752 mathRand.Seed(time.Now().Unix())
1755 type trackerTier []string
1757 // The trackers within each tier must be shuffled before use.
1758 // http://stackoverflow.com/a/12267471/149482
1759 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1760 func shuffleTier(tier trackerTier) {
1761 for i := range tier {
1762 j := mathRand.Intn(i + 1)
1763 tier[i], tier[j] = tier[j], tier[i]
1767 func copyTrackers(base []trackerTier) (copy []trackerTier) {
1768 for _, tier := range base {
1769 copy = append(copy, append(trackerTier(nil), tier...))
1774 func mergeTier(tier trackerTier, newURLs []string) trackerTier {
1776 for _, url := range newURLs {
1777 for _, trURL := range tier {
1782 tier = append(tier, url)
1787 func (t *torrent) addTrackers(announceList [][]string) {
1788 newTrackers := copyTrackers(t.Trackers)
1789 for tierIndex, tier := range announceList {
1790 if tierIndex < len(newTrackers) {
1791 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1793 newTrackers = append(newTrackers, mergeTier(nil, tier))
1795 shuffleTier(newTrackers[tierIndex])
1797 t.Trackers = newTrackers
1800 // Don't call this before the info is available.
1801 func (t *torrent) bytesCompleted() int64 {
1805 return t.Info.TotalLength() - t.bytesLeft()
1808 // A file-like handle to some torrent data resource.
1809 type Handle interface {
1816 // Returns handles to the files in the torrent. This requires the metainfo is
1818 func (t Torrent) Files() (ret []File) {
1826 for _, fi := range info.UpvertedFiles() {
1827 ret = append(ret, File{
1829 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1839 func (t Torrent) AddPeers(pp []Peer) error {
1842 defer cl.mu.Unlock()
1843 cl.addPeers(t.torrent, pp)
1847 // Marks the entire torrent for download. Requires the info first, see
1849 func (t Torrent) DownloadAll() {
1851 defer t.cl.mu.Unlock()
1852 t.torrent.pendPieceRange(0, t.torrent.numPieces())
1855 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1856 // metainfo has the correct infohash.
1857 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1858 if cl.config.DisableMetainfoCache {
1861 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1863 if os.IsNotExist(err) {
1869 dec := bencode.NewDecoder(f)
1870 err = dec.Decode(&mi)
1874 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1875 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1881 // Specifies a new torrent for adding to a client. There are helpers for
1882 // magnet URIs and torrent metainfo files.
1883 type TorrentSpec struct {
1884 // The tiered tracker URIs.
1887 Info *metainfo.InfoEx
1888 // The name to use if the Name field from the Info isn't available.
1890 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1896 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1897 m, err := ParseMagnetURI(uri)
1901 spec = &TorrentSpec{
1902 Trackers: [][]string{m.Trackers},
1903 DisplayName: m.DisplayName,
1904 InfoHash: m.InfoHash,
1909 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1910 spec = &TorrentSpec{
1911 Trackers: mi.AnnounceList,
1913 DisplayName: mi.Info.Name,
1916 if len(spec.Trackers) == 0 {
1917 spec.Trackers = [][]string{[]string{mi.Announce}}
1919 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
1922 CopyExact(&spec.InfoHash, &mi.Info.Hash)
1926 // Add or merge a torrent spec. If the torrent is already present, the
1927 // trackers will be merged with the existing ones. If the Info isn't yet
1928 // known, it will be set. The display name is replaced if the new spec
1929 // provides one. Returns new if the torrent wasn't already in the client.
1930 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
1933 defer cl.mu.Unlock()
1935 t, ok := cl.torrents[spec.InfoHash]
1939 // TODO: This doesn't belong in the core client, it's more of a
1941 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
1942 err = errors.New("banned torrent")
1945 // TODO: Tidy this up?
1946 t = newTorrent(spec.InfoHash)
1948 t.wantPeers.L = &cl.mu
1949 if spec.ChunkSize != 0 {
1950 t.chunkSize = pp.Integer(spec.ChunkSize)
1952 t.storage = spec.Storage
1953 if t.storage == nil {
1954 t.storage = cl.defaultStorage
1957 if spec.DisplayName != "" {
1958 t.setDisplayName(spec.DisplayName)
1960 // Try to merge in info we have on the torrent. Any err left will
1961 // terminate the function.
1963 if spec.Info != nil {
1964 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
1966 var mi *metainfo.MetaInfo
1967 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
1969 log.Printf("error getting cached metainfo: %s", err)
1971 } else if mi != nil {
1972 t.addTrackers(mi.AnnounceList)
1973 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
1980 t.addTrackers(spec.Trackers)
1982 cl.torrents[spec.InfoHash] = t
1985 // From this point onwards, we can consider the torrent a part of the
1988 if !cl.config.DisableTrackers {
1989 go cl.announceTorrentTrackers(T.torrent)
1992 go cl.announceTorrentDHT(T.torrent, true)
1998 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
1999 t, ok := me.torrents[infoHash]
2001 err = fmt.Errorf("no such torrent")
2008 delete(me.torrents, infoHash)
2012 // Returns true when peers are required, or false if the torrent is closing.
2013 func (cl *Client) waitWantPeers(t *torrent) bool {
2015 defer cl.mu.Unlock()
2018 case <-t.ceasingNetworking:
2022 if len(t.Peers) > torrentPeersLowWater {
2025 if t.needData() || cl.seeding(t) {
2033 // Returns whether the client should make effort to seed the torrent.
2034 func (cl *Client) seeding(t *torrent) bool {
2035 if cl.config.NoUpload {
2038 if !cl.config.Seed {
2047 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2048 for cl.waitWantPeers(t) {
2049 // log.Printf("getting peers for %q from DHT", t)
2050 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2052 log.Printf("error getting peers from dht: %s", err)
2055 // Count all the unique addresses we got during this announce.
2056 allAddrs := make(map[string]struct{})
2060 case v, ok := <-ps.Peers:
2064 addPeers := make([]Peer, 0, len(v.Peers))
2065 for _, cp := range v.Peers {
2067 // Can't do anything with this.
2070 addPeers = append(addPeers, Peer{
2073 Source: peerSourceDHT,
2075 key := (&net.UDPAddr{
2079 allAddrs[key] = struct{}{}
2082 cl.addPeers(t, addPeers)
2083 numPeers := len(t.Peers)
2085 if numPeers >= torrentPeersHighWater {
2088 case <-t.ceasingNetworking:
2094 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2098 func (cl *Client) trackerBlockedUnlocked(trRawURL string) (blocked bool, err error) {
2099 url_, err := url.Parse(trRawURL)
2103 host, _, err := net.SplitHostPort(url_.Host)
2107 addr, err := net.ResolveIPAddr("ip", host)
2112 _, blocked = cl.ipBlockRange(addr.IP)
2117 func (cl *Client) announceTorrentSingleTracker(tr string, req *tracker.AnnounceRequest, t *torrent) error {
2118 blocked, err := cl.trackerBlockedUnlocked(tr)
2120 return fmt.Errorf("error determining if tracker blocked: %s", err)
2123 return fmt.Errorf("tracker blocked: %s", tr)
2125 resp, err := tracker.Announce(tr, req)
2127 return fmt.Errorf("error announcing: %s", err)
2130 for _, peer := range resp.Peers {
2131 peers = append(peers, Peer{
2137 cl.addPeers(t, peers)
2140 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2142 time.Sleep(time.Second * time.Duration(resp.Interval))
2146 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers []trackerTier, t *torrent) (atLeastOne bool) {
2147 oks := make(chan bool)
2149 for _, tier := range trackers {
2150 for _, tr := range tier {
2152 go func(tr string) {
2153 err := cl.announceTorrentSingleTracker(tr, req, t)
2158 for outstanding > 0 {
2168 // Announce torrent to its trackers.
2169 func (cl *Client) announceTorrentTrackers(t *torrent) {
2170 req := tracker.AnnounceRequest{
2171 Event: tracker.Started,
2173 Port: uint16(cl.incomingPeerPort()),
2175 InfoHash: t.InfoHash,
2177 if !cl.waitWantPeers(t) {
2181 req.Left = t.bytesLeftAnnounce()
2182 trackers := t.Trackers
2184 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2185 req.Event = tracker.None
2188 for cl.waitWantPeers(t) {
2190 req.Left = t.bytesLeftAnnounce()
2191 trackers = t.Trackers
2193 numTrackersTried := 0
2194 for _, tier := range trackers {
2195 for trIndex, tr := range tier {
2197 err := cl.announceTorrentSingleTracker(tr, &req, t)
2201 // Float the successful announce to the top of the tier. If
2202 // the trackers list has been changed, we'll be modifying an
2203 // old copy so it won't matter.
2205 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2208 req.Event = tracker.None
2209 continue newAnnounce
2212 if numTrackersTried != 0 {
2213 log.Printf("%s: all trackers failed", t)
2215 // TODO: Wait until trackers are added if there are none.
2216 time.Sleep(10 * time.Second)
2220 func (cl *Client) allTorrentsCompleted() bool {
2221 for _, t := range cl.torrents {
2225 if t.numPiecesCompleted() != t.numPieces() {
2232 // Returns true when all torrents are completely downloaded and false if the
2233 // client is stopped before that.
2234 func (me *Client) WaitAll() bool {
2236 defer me.mu.Unlock()
2237 for !me.allTorrentsCompleted() {
2238 if me.closed.IsSet() {
2246 // Handle a received chunk from a peer.
2247 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) {
2248 chunksReceived.Add(1)
2250 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2252 // Request has been satisfied.
2253 if me.connDeleteRequest(t, c, req) {
2254 defer c.updateRequests()
2256 unexpectedChunksReceived.Add(1)
2259 index := int(req.Index)
2260 piece := &t.Pieces[index]
2262 // Do we actually want this chunk?
2263 if !t.wantChunk(req) {
2264 unwantedChunksReceived.Add(1)
2265 c.UnwantedChunksReceived++
2269 c.UsefulChunksReceived++
2270 c.lastUsefulChunkReceived = time.Now()
2274 // Need to record that it hasn't been written yet, before we attempt to do
2275 // anything with it.
2276 piece.incrementPendingWrites()
2277 // Record that we have the chunk.
2278 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2280 // Cancel pending requests for this chunk.
2281 for _, c := range t.Conns {
2282 if me.connCancel(t, c, req) {
2288 // Write the chunk out.
2289 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2292 piece.decrementPendingWrites()
2295 log.Printf("error writing chunk: %s", err)
2296 // t.updatePieceCompletion(msg.Index)
2298 // t.updatePiecePriority(msg.Index)
2302 // It's important that the piece is potentially queued before we check if
2303 // the piece is still wanted, because if it is queued, it won't be wanted.
2304 if t.pieceAllDirty(index) {
2305 me.queuePieceCheck(t, int(req.Index))
2308 if c.peerTouchedPieces == nil {
2309 c.peerTouchedPieces = make(map[int]struct{})
2311 c.peerTouchedPieces[index] = struct{}{}
2313 me.event.Broadcast()
2314 t.publishPieceChange(int(req.Index))
2318 // Return the connections that touched a piece, and clear the entry while
2320 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2321 for _, c := range t.Conns {
2322 if _, ok := c.peerTouchedPieces[piece]; ok {
2323 ret = append(ret, c)
2324 delete(c.peerTouchedPieces, piece)
2330 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2331 p := &t.Pieces[piece]
2333 // Don't score the first time a piece is hashed, it could be an
2336 pieceHashedCorrect.Add(1)
2338 log.Printf("%s: piece %d failed hash", t, piece)
2339 pieceHashedNotCorrect.Add(1)
2343 touchers := me.reapPieceTouches(t, int(piece))
2345 err := p.Storage().MarkComplete()
2347 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
2349 t.updatePieceCompletion(piece)
2350 } else if len(touchers) != 0 {
2351 log.Printf("dropping %d conns that touched piece", len(touchers))
2352 for _, c := range touchers {
2353 me.dropConnection(t, c)
2356 me.pieceChanged(t, int(piece))
2359 func (me *Client) onCompletedPiece(t *torrent, piece int) {
2360 t.pendingPieces.Remove(piece)
2361 t.pendAllChunkSpecs(piece)
2362 for _, conn := range t.Conns {
2364 for r := range conn.Requests {
2365 if int(r.Index) == piece {
2369 // Could check here if peer doesn't have piece, but due to caching
2370 // some peers may have said they have a piece but they don't.
2375 func (me *Client) onFailedPiece(t *torrent, piece int) {
2376 if t.pieceAllDirty(piece) {
2377 t.pendAllChunkSpecs(piece)
2379 if !t.wantPiece(piece) {
2383 for _, conn := range t.Conns {
2384 if conn.PeerHasPiece(piece) {
2385 conn.updateRequests()
2390 func (me *Client) pieceChanged(t *torrent, piece int) {
2391 correct := t.pieceComplete(piece)
2392 defer me.event.Broadcast()
2394 me.onCompletedPiece(t, piece)
2396 me.onFailedPiece(t, piece)
2398 if t.updatePiecePriority(piece) {
2399 t.piecePriorityChanged(piece)
2401 t.publishPieceChange(piece)
2404 func (cl *Client) verifyPiece(t *torrent, piece int) {
2406 defer cl.mu.Unlock()
2407 p := &t.Pieces[piece]
2408 for p.Hashing || t.storage == nil {
2411 p.QueuedForHash = false
2412 if t.isClosed() || t.pieceComplete(piece) {
2413 t.updatePiecePriority(piece)
2414 t.publishPieceChange(piece)
2418 t.publishPieceChange(piece)
2420 sum := t.hashPiece(piece)
2428 cl.pieceHashed(t, piece, sum == p.Hash)
2431 // Returns handles to all the torrents loaded in the Client.
2432 func (me *Client) Torrents() (ret []Torrent) {
2434 for _, t := range me.torrents {
2435 ret = append(ret, Torrent{me, t})
2441 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2442 spec, err := TorrentSpecFromMagnetURI(uri)
2446 T, _, err = me.AddTorrentSpec(spec)
2450 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2451 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2453 missinggo.CastSlice(&ss, mi.Nodes)
2458 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2459 mi, err := metainfo.LoadFromFile(filename)
2463 return me.AddTorrent(mi)
2466 func (me *Client) DHT() *dht.Server {
2470 func (me *Client) AddDHTNodes(nodes []string) {
2471 for _, n := range nodes {
2472 hmp := missinggo.SplitHostMaybePort(n)
2473 ip := net.ParseIP(hmp.Host)
2475 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
2479 Addr: dht.NewAddr(&net.UDPAddr{
2484 me.DHT().AddNode(ni)