18 "github.com/anacrolix/dht"
19 "github.com/anacrolix/dht/krpc"
20 "github.com/anacrolix/missinggo"
21 "github.com/anacrolix/missinggo/pproffd"
22 "github.com/anacrolix/missinggo/pubsub"
23 "github.com/anacrolix/missinggo/slices"
24 "github.com/anacrolix/sync"
25 "github.com/dustin/go-humanize"
26 "golang.org/x/time/rate"
28 "github.com/anacrolix/torrent/bencode"
29 "github.com/anacrolix/torrent/iplist"
30 "github.com/anacrolix/torrent/metainfo"
31 "github.com/anacrolix/torrent/mse"
32 pp "github.com/anacrolix/torrent/peer_protocol"
33 "github.com/anacrolix/torrent/storage"
36 // Clients contain zero or more Torrents. A Client manages a blocklist, the
37 // TCP/UDP protocol ports, and DHT as desired.
41 closed missinggo.Event
47 defaultStorage *storage.Client
49 tcpListener net.Listener
52 ipBlockList iplist.Ranger
53 // Our BitTorrent protocol extension bytes, sent in our BT handshakes.
54 extensionBytes peerExtensionBytes
55 // The net.Addr.String part that should be common to all active listeners.
57 uploadLimit *rate.Limiter
58 downloadLimit *rate.Limiter
60 // Set of addresses that have our client ID. This intentionally will
61 // include ourselves if we end up trying to connect to our own address
62 // through legitimate channels.
63 dopplegangerAddrs map[string]struct{}
64 badPeerIPs map[string]struct{}
65 torrents map[metainfo.Hash]*Torrent
68 func (cl *Client) BadPeerIPs() []string {
71 return cl.badPeerIPsLocked()
74 func (cl *Client) badPeerIPsLocked() []string {
75 return slices.FromMapKeys(cl.badPeerIPs).([]string)
78 func (cl *Client) IPBlockList() iplist.Ranger {
84 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
89 cl.dHT.SetIPBlockList(list)
93 func (cl *Client) PeerID() PeerID {
97 type torrentAddr string
99 func (torrentAddr) Network() string { return "" }
101 func (me torrentAddr) String() string { return string(me) }
103 func (cl *Client) ListenAddr() net.Addr {
104 if cl.listenAddr == "" {
107 return torrentAddr(cl.listenAddr)
110 // Writes out a human readable status of the client, such as for writing to a
112 func (cl *Client) WriteStatus(_w io.Writer) {
115 w := bufio.NewWriter(_w)
117 if addr := cl.ListenAddr(); addr != nil {
118 fmt.Fprintf(w, "Listening on %s\n", addr)
120 fmt.Fprintln(w, "Not listening!")
122 fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
123 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
124 if dht := cl.DHT(); dht != nil {
125 dhtStats := dht.Stats()
126 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
127 fmt.Fprintf(w, "DHT Server ID: %x\n", dht.ID())
128 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(dht.Addr()))
129 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
130 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
132 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
134 for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
135 return l.InfoHash().AsString() < r.InfoHash().AsString()
138 fmt.Fprint(w, "<unknown name>")
140 fmt.Fprint(w, t.name())
144 fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())), t.length, humanize.Bytes(uint64(t.info.TotalLength())))
146 w.WriteString("<missing metainfo>")
154 func listenUTP(networkSuffix, addr string) (utpSocket, error) {
155 return NewUtpSocket("udp"+networkSuffix, addr)
158 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
159 return net.Listen("tcp"+networkSuffix, addr)
162 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
164 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
168 listenedAddr = tcpL.Addr().String()
169 utpSock, err = listenUTP(networkSuffix, listenedAddr)
174 if !strings.Contains(err.Error(), "address already in use") {
180 // Listen to enabled protocols, ensuring ports match.
181 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
188 host, port, err = missinggo.ParseHostPort(addr)
193 // If both protocols are active, they need to have the same port.
194 return listenBothSameDynamicPort(networkSuffix, host)
203 tcpL, err = listenTCP(networkSuffix, addr)
212 listenedAddr = tcpL.Addr().String()
215 utpSock, err = listenUTP(networkSuffix, addr)
219 listenedAddr = utpSock.Addr().String()
224 // Creates a new client.
225 func NewClient(cfg *Config) (cl *Client, err error) {
228 DHTConfig: dht.ServerConfig{
229 StartingNodes: dht.GlobalBootstrapAddrs,
244 halfOpenLimit: cfg.HalfOpenConnsPerTorrent,
246 dopplegangerAddrs: make(map[string]struct{}),
247 torrents: make(map[metainfo.Hash]*Torrent),
255 if cfg.UploadRateLimiter == nil {
256 cl.uploadLimit = rate.NewLimiter(rate.Inf, 0)
258 cl.uploadLimit = cfg.UploadRateLimiter
260 if cfg.DownloadRateLimiter == nil {
261 cl.downloadLimit = rate.NewLimiter(rate.Inf, 0)
263 cl.downloadLimit = cfg.DownloadRateLimiter
265 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
267 storageImpl := cfg.DefaultStorage
268 if storageImpl == nil {
269 // We'd use mmap but HFS+ doesn't support sparse files.
270 storageImpl = storage.NewFile(cfg.DataDir)
271 cl.onClose = append(cl.onClose, func() {
272 if err := storageImpl.Close(); err != nil {
273 log.Printf("error closing default storage: %s", err)
277 cl.defaultStorage = storage.NewClient(storageImpl)
278 if cfg.IPBlocklist != nil {
279 cl.ipBlockList = cfg.IPBlocklist
282 if cfg.PeerID != "" {
283 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
285 o := copy(cl.peerID[:], cfg.Bep20)
286 _, err = rand.Read(cl.peerID[o:])
288 panic("error generating peer id")
292 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
293 !cl.config.DisableTCP,
294 !cl.config.DisableUTP,
296 if cl.config.DisableIPv6 {
302 cl.config.ListenAddr)
306 if cl.tcpListener != nil {
307 go cl.acceptConnections(cl.tcpListener, false)
309 if cl.utpSock != nil {
310 go cl.acceptConnections(cl.utpSock, true)
313 dhtCfg := cfg.DHTConfig
314 if dhtCfg.IPBlocklist == nil {
315 dhtCfg.IPBlocklist = cl.ipBlockList
317 if dhtCfg.Conn == nil {
318 if cl.utpSock != nil {
319 dhtCfg.Conn = cl.utpSock
321 dhtCfg.Conn, err = net.ListenPacket("udp", firstNonEmptyString(cl.listenAddr, cl.config.ListenAddr))
327 if dhtCfg.OnAnnouncePeer == nil {
328 dhtCfg.OnAnnouncePeer = cl.onDHTAnnouncePeer
330 cl.dHT, err = dht.NewServer(&dhtCfg)
335 if _, err := cl.dHT.Bootstrap(); err != nil {
336 log.Printf("error bootstrapping dht: %s", err)
344 func firstNonEmptyString(ss ...string) string {
345 for _, s := range ss {
353 // Stops the client. All connections to peers are closed and all activity will
355 func (cl *Client) Close() {
362 if cl.utpSock != nil {
365 if cl.tcpListener != nil {
366 cl.tcpListener.Close()
368 for _, t := range cl.torrents {
371 for _, f := range cl.onClose {
377 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
379 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
380 if cl.ipBlockList == nil {
384 // If blocklists are enabled, then block non-IPv4 addresses, because
385 // blocklists do not yet support IPv6.
387 if missinggo.CryHeard() {
388 log.Printf("blocking non-IPv4 address: %s", ip)
394 return cl.ipBlockList.Lookup(ip4)
397 func (cl *Client) waitAccept() {
399 for _, t := range cl.torrents {
404 if cl.closed.IsSet() {
411 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
417 conn, err := l.Accept()
418 conn = pproffd.WrapNetConn(conn)
420 if cl.closed.IsSet() {
428 // I think something harsher should happen here? Our accept
429 // routine just fucked off.
438 log.Printf("accepted connection from %s", conn.RemoteAddr())
440 reject := cl.badPeerIPPort(
441 missinggo.AddrIP(conn.RemoteAddr()),
442 missinggo.AddrPort(conn.RemoteAddr()))
445 log.Printf("rejecting connection from %s", conn.RemoteAddr())
451 go cl.incomingConnection(conn, utp)
455 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
457 if tc, ok := nc.(*net.TCPConn); ok {
460 c := cl.newConnection(nc)
461 c.Discovery = peerSourceIncoming
463 cl.runReceivedConn(c)
466 // Returns a handle to the given torrent, if it's present in the client.
467 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
470 t, ok = cl.torrents[ih]
474 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
475 return cl.torrents[ih]
478 type dialResult struct {
483 func countDialResult(err error) {
485 successfulDials.Add(1)
487 unsuccessfulDials.Add(1)
491 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
492 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
493 if ret < minDialTimeout {
499 // Returns whether an address is known to connect to a client with our own ID.
500 func (cl *Client) dopplegangerAddr(addr string) bool {
501 _, ok := cl.dopplegangerAddrs[addr]
505 // Start the process of connecting to the given peer for the given torrent if
507 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
508 if peer.Id == cl.peerID {
511 if cl.badPeerIPPort(peer.IP, peer.Port) {
514 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
515 if t.addrActive(addr) {
518 t.halfOpen[addr] = peer
519 go cl.outgoingConnection(t, addr, peer.Source)
522 func (cl *Client) dialTCP(ctx context.Context, addr string) (c net.Conn, err error) {
524 // LocalAddr: cl.tcpListener.Addr(),
526 c, err = d.DialContext(ctx, "tcp", addr)
529 c.(*net.TCPConn).SetLinger(0)
531 c = pproffd.WrapNetConn(c)
535 func (cl *Client) dialUTP(ctx context.Context, addr string) (c net.Conn, err error) {
536 c, err = cl.utpSock.DialContext(ctx, addr)
542 dialledFirstUtp = expvar.NewInt("dialledFirstUtp")
543 dialledFirstNotUtp = expvar.NewInt("dialledFirstNotUtp")
546 // Returns a connection over UTP or TCP, whichever is first to connect.
547 func (cl *Client) dialFirst(ctx context.Context, addr string) (conn net.Conn, utp bool) {
548 ctx, cancel := context.WithCancel(ctx)
549 // As soon as we return one connection, cancel the others.
552 resCh := make(chan dialResult, left)
553 if !cl.config.DisableUTP {
556 c, _ := cl.dialUTP(ctx, addr)
557 resCh <- dialResult{c, true}
560 if !cl.config.DisableTCP {
563 c, _ := cl.dialTCP(ctx, addr)
564 resCh <- dialResult{c, false}
568 // Wait for a successful connection.
569 for ; left > 0 && res.Conn == nil; left-- {
573 // There are still incompleted dials.
575 for ; left > 0; left-- {
576 conn := (<-resCh).Conn
587 dialledFirstUtp.Add(1)
589 dialledFirstNotUtp.Add(1)
595 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
596 if _, ok := t.halfOpen[addr]; !ok {
597 panic("invariant broken")
599 delete(t.halfOpen, addr)
603 // Performs initiator handshakes and returns a connection. Returns nil
604 // *connection if no connection for valid reasons.
605 func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader, utp bool) (c *connection, err error) {
606 c = cl.newConnection(nc)
607 c.headerEncrypted = encryptHeader
609 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
611 dl, ok := ctx.Deadline()
615 err = nc.SetDeadline(dl)
619 ok, err = cl.initiateHandshakes(c, t)
627 initiatedConnWithPreferredHeaderEncryption = expvar.NewInt("initiatedConnWithPreferredHeaderEncryption")
628 initiatedConnWithFallbackHeaderEncryption = expvar.NewInt("initiatedConnWithFallbackHeaderEncryption")
631 // Returns nil connection and nil error if no connection could be established
632 // for valid reasons.
633 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
634 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
636 nc, utp := cl.dialFirst(ctx, addr)
640 obfuscatedHeaderFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
641 c, err = cl.handshakesConnection(ctx, nc, t, obfuscatedHeaderFirst, utp)
643 // log.Printf("error initiating connection handshakes: %s", err)
647 initiatedConnWithPreferredHeaderEncryption.Add(1)
651 if cl.config.ForceEncryption {
652 // We should have just tried with an obfuscated header. A plaintext
653 // header can't result in an encrypted connection, so we're done.
654 if !obfuscatedHeaderFirst {
655 panic(cl.config.EncryptionPolicy)
659 // Try again with encryption if we didn't earlier, or without if we did,
660 // using whichever protocol type worked last time.
662 nc, err = cl.dialUTP(ctx, addr)
664 nc, err = cl.dialTCP(ctx, addr)
667 err = fmt.Errorf("error dialing for header encryption fallback: %s", err)
670 c, err = cl.handshakesConnection(ctx, nc, t, !obfuscatedHeaderFirst, utp)
671 if err != nil || c == nil {
674 if err == nil && c != nil {
675 initiatedConnWithFallbackHeaderEncryption.Add(1)
680 // Called to dial out and run a connection. The addr we're given is already
681 // considered half-open.
682 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
683 c, err := cl.establishOutgoingConn(t, addr)
686 // Don't release lock between here and addConnection, unless it's for
688 cl.noLongerHalfOpen(t, addr)
691 log.Printf("error establishing outgoing connection: %s", err)
700 cl.runInitiatedHandshookConn(c, t)
703 // The port number for incoming peer connections. 0 if the client isn't
705 func (cl *Client) incomingPeerPort() int {
706 if cl.listenAddr == "" {
709 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
716 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
717 if c.headerEncrypted {
719 rw, err = mse.InitiateHandshake(
728 case cl.config.ForceEncryption:
729 return mse.CryptoMethodRC4
730 case cl.config.DisableEncryption:
731 return mse.CryptoMethodPlaintext
733 return mse.AllSupportedCrypto
742 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
743 if ih != t.infoHash {
749 // Calls f with any secret keys.
750 func (cl *Client) forSkeys(f func([]byte) bool) {
753 for ih := range cl.torrents {
760 // Do encryption and bittorrent handshakes as receiver.
761 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
763 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy)
766 if err == mse.ErrNoSecretKeyMatch {
771 if cl.config.ForceEncryption && !c.headerEncrypted {
772 err = errors.New("connection not encrypted")
775 ih, ok, err := cl.connBTHandshake(c, nil)
777 err = fmt.Errorf("error during bt handshake: %s", err)
789 // Returns !ok if handshake failed for valid reasons.
790 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
791 res, ok, err := handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
792 if err != nil || !ok {
796 c.PeerExtensionBytes = res.peerExtensionBytes
797 c.PeerID = res.PeerID
798 c.completedHandshake = time.Now()
802 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
803 if c.PeerID == cl.peerID {
805 addr := c.conn.RemoteAddr().String()
806 cl.dopplegangerAddrs[addr] = struct{}{}
809 cl.runHandshookConn(c, t, true)
812 func (cl *Client) runReceivedConn(c *connection) {
813 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
817 t, err := cl.receiveHandshakes(c)
820 log.Printf("error receiving handshakes: %s", err)
829 if c.PeerID == cl.peerID {
830 // Because the remote address is not necessarily the same as its
831 // client's torrent listen address, we won't record the remote address
832 // as a doppleganger. Instead, the initiator can record *us* as the
836 cl.runHandshookConn(c, t, false)
839 func (cl *Client) runHandshookConn(c *connection, t *Torrent, outgoing bool) {
840 c.conn.SetWriteDeadline(time.Time{})
841 c.r = deadlineReader{c.conn, c.r}
842 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
843 if !t.addConnection(c, outgoing) {
846 defer t.dropConnection(c)
847 go c.writer(time.Minute)
848 cl.sendInitialMessages(c, t)
849 err := c.mainReadLoop()
850 if err != nil && cl.config.Debug {
851 log.Printf("error during connection loop: %s", err)
855 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
856 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
857 conn.Post(pp.Message{
859 ExtendedID: pp.HandshakeExtendedID,
860 ExtendedPayload: func() []byte {
861 d := map[string]interface{}{
862 "m": func() (ret map[string]int) {
863 ret = make(map[string]int, 2)
864 ret["ut_metadata"] = metadataExtendedId
865 if !cl.config.DisablePEX {
866 ret["ut_pex"] = pexExtendedId
870 "v": cl.config.ExtendedHandshakeClientVersion,
871 // No upload queue is implemented yet.
874 if !cl.config.DisableEncryption {
877 if torrent.metadataSizeKnown() {
878 d["metadata_size"] = torrent.metadataSize()
880 if p := cl.incomingPeerPort(); p != 0 {
883 yourip, err := addrCompactIP(conn.remoteAddr())
885 log.Printf("error calculating yourip field value in extension handshake: %s", err)
889 // log.Printf("sending %v", d)
890 b, err := bencode.Marshal(d)
898 if torrent.haveAnyPieces() {
899 conn.Bitfield(torrent.bitfield())
900 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
901 conn.Post(pp.Message{
905 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
906 conn.Post(pp.Message{
908 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
913 // Process incoming ut_metadata message.
914 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
916 err := bencode.Unmarshal(payload, &d)
918 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
920 msgType, ok := d["msg_type"]
922 return errors.New("missing msg_type field")
926 case pp.DataMetadataExtensionMsgType:
927 if !c.requestedMetadataPiece(piece) {
928 return fmt.Errorf("got unexpected piece %d", piece)
930 c.metadataRequests[piece] = false
931 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
932 if begin < 0 || begin >= len(payload) {
933 return fmt.Errorf("data has bad offset in payload: %d", begin)
935 t.saveMetadataPiece(piece, payload[begin:])
936 c.UsefulChunksReceived++
937 c.lastUsefulChunkReceived = time.Now()
938 return t.maybeCompleteMetadata()
939 case pp.RequestMetadataExtensionMsgType:
940 if !t.haveMetadataPiece(piece) {
941 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
944 start := (1 << 14) * piece
945 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
947 case pp.RejectMetadataExtensionMsgType:
950 return errors.New("unknown msg_type value")
954 func (cl *Client) sendChunk(t *Torrent, c *connection, r request, msg func(pp.Message) bool) (more bool, err error) {
955 // Count the chunk being sent, even if it isn't.
956 b := make([]byte, r.Length)
957 p := t.info.Piece(int(r.Index))
958 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
961 panic("expected error")
964 } else if err == io.EOF {
967 more = msg(pp.Message{
974 uploadChunksPosted.Add(1)
975 c.lastChunkSent = time.Now()
979 func (cl *Client) openNewConns(t *Torrent) {
980 defer t.updateWantPeersEvent()
981 for len(t.peers) != 0 {
985 if len(t.halfOpen) >= cl.halfOpenLimit {
992 for k, p = range t.peers {
996 cl.initiateConn(p, t)
1000 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1004 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1007 if _, ok := cl.ipBlockRange(ip); ok {
1010 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1016 // Return a Torrent ready for insertion into a Client.
1017 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1018 // use provided storage, if provided
1019 storageClient := cl.defaultStorage
1020 if specStorage != nil {
1021 storageClient = storage.NewClient(specStorage)
1027 peers: make(map[peersKey]Peer),
1028 conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1030 halfOpen: make(map[string]Peer),
1031 pieceStateChanges: pubsub.NewPubSub(),
1033 storageOpener: storageClient,
1034 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1036 networkingEnabled: true,
1038 metadataChanged: sync.Cond{
1042 t.setChunkSize(defaultChunkSize)
1046 // A file-like handle to some torrent data resource.
1047 type Handle interface {
1054 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1055 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1058 // Adds a torrent by InfoHash with a custom Storage implementation.
1059 // If the torrent already exists then this Storage is ignored and the
1060 // existing torrent returned with `new` set to `false`
1061 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1063 defer cl.mu.Unlock()
1064 t, ok := cl.torrents[infoHash]
1069 t = cl.newTorrent(infoHash, specStorage)
1073 cl.torrents[infoHash] = t
1074 t.updateWantPeersEvent()
1075 // Tickle Client.waitAccept, new torrent may want conns.
1076 cl.event.Broadcast()
1080 // Add or merge a torrent spec. If the torrent is already present, the
1081 // trackers will be merged with the existing ones. If the Info isn't yet
1082 // known, it will be set. The display name is replaced if the new spec
1083 // provides one. Returns new if the torrent wasn't already in the client.
1084 // Note that any `Storage` defined on the spec will be ignored if the
1085 // torrent is already present (i.e. `new` return value is `true`)
1086 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1087 t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1088 if spec.DisplayName != "" {
1089 t.SetDisplayName(spec.DisplayName)
1091 if spec.InfoBytes != nil {
1092 err = t.SetInfoBytes(spec.InfoBytes)
1098 defer cl.mu.Unlock()
1099 if spec.ChunkSize != 0 {
1100 t.setChunkSize(pp.Integer(spec.ChunkSize))
1102 t.addTrackers(spec.Trackers)
1107 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1108 t, ok := cl.torrents[infoHash]
1110 err = fmt.Errorf("no such torrent")
1117 delete(cl.torrents, infoHash)
1121 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1122 _url, err := url.Parse(announceURL)
1126 hmp := missinggo.SplitHostMaybePort(_url.Host)
1131 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1136 _, blocked = cl.ipBlockRange(addr.IP)
1139 hmp.Host = addr.String()
1140 _url.Host = hmp.String()
1141 urlToUse = _url.String()
1145 func (cl *Client) allTorrentsCompleted() bool {
1146 for _, t := range cl.torrents {
1150 if t.numPiecesCompleted() != t.numPieces() {
1157 // Returns true when all torrents are completely downloaded and false if the
1158 // client is stopped before that.
1159 func (cl *Client) WaitAll() bool {
1161 defer cl.mu.Unlock()
1162 for !cl.allTorrentsCompleted() {
1163 if cl.closed.IsSet() {
1171 // Returns handles to all the torrents loaded in the Client.
1172 func (cl *Client) Torrents() []*Torrent {
1174 defer cl.mu.Unlock()
1175 return cl.torrentsAsSlice()
1178 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1179 for _, t := range cl.torrents {
1180 ret = append(ret, t)
1185 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1186 spec, err := TorrentSpecFromMagnetURI(uri)
1190 T, _, err = cl.AddTorrentSpec(spec)
1194 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1195 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1197 slices.MakeInto(&ss, mi.Nodes)
1202 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1203 mi, err := metainfo.LoadFromFile(filename)
1207 return cl.AddTorrent(mi)
1210 func (cl *Client) DHT() *dht.Server {
1214 func (cl *Client) AddDHTNodes(nodes []string) {
1215 if cl.DHT() == nil {
1218 for _, n := range nodes {
1219 hmp := missinggo.SplitHostMaybePort(n)
1220 ip := net.ParseIP(hmp.Host)
1222 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1225 ni := krpc.NodeInfo{
1231 cl.DHT().AddNode(ni)
1235 func (cl *Client) banPeerIP(ip net.IP) {
1236 if cl.badPeerIPs == nil {
1237 cl.badPeerIPs = make(map[string]struct{})
1239 cl.badPeerIPs[ip.String()] = struct{}{}
1242 func (cl *Client) newConnection(nc net.Conn) (c *connection) {
1248 PeerMaxRequests: 250,
1250 c.writerCond.L = &cl.mu
1251 c.setRW(connStatsReadWriter{nc, &cl.mu, c})
1252 c.r = rateLimitedReader{cl.downloadLimit, c.r}
1256 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1258 defer cl.mu.Unlock()
1266 Source: peerSourceDHTAnnouncePeer,