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)
307 if cl.tcpListener != nil {
308 go cl.acceptConnections(cl.tcpListener, false)
310 if cl.utpSock != nil {
311 go cl.acceptConnections(cl.utpSock, true)
314 dhtCfg := cfg.DHTConfig
315 if dhtCfg.IPBlocklist == nil {
316 dhtCfg.IPBlocklist = cl.ipBlockList
318 if dhtCfg.Conn == nil {
319 if cl.utpSock != nil {
320 dhtCfg.Conn = cl.utpSock
322 dhtCfg.Conn, err = net.ListenPacket("udp", firstNonEmptyString(cl.listenAddr, cl.config.ListenAddr))
328 if dhtCfg.OnAnnouncePeer == nil {
329 dhtCfg.OnAnnouncePeer = cl.onDHTAnnouncePeer
331 cl.dHT, err = dht.NewServer(&dhtCfg)
336 if _, err := cl.dHT.Bootstrap(); err != nil {
337 log.Printf("error bootstrapping dht: %s", err)
345 func firstNonEmptyString(ss ...string) string {
346 for _, s := range ss {
354 // Stops the client. All connections to peers are closed and all activity will
356 func (cl *Client) Close() {
363 if cl.utpSock != nil {
366 if cl.tcpListener != nil {
367 cl.tcpListener.Close()
369 for _, t := range cl.torrents {
372 for _, f := range cl.onClose {
378 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
380 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
381 if cl.ipBlockList == nil {
385 // If blocklists are enabled, then block non-IPv4 addresses, because
386 // blocklists do not yet support IPv6.
388 if missinggo.CryHeard() {
389 log.Printf("blocking non-IPv4 address: %s", ip)
395 return cl.ipBlockList.Lookup(ip4)
398 func (cl *Client) waitAccept() {
400 for _, t := range cl.torrents {
405 if cl.closed.IsSet() {
412 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
418 conn, err := l.Accept()
419 conn = pproffd.WrapNetConn(conn)
421 if cl.closed.IsSet() {
429 // I think something harsher should happen here? Our accept
430 // routine just fucked off.
439 log.Printf("accepted connection from %s", conn.RemoteAddr())
441 reject := cl.badPeerIPPort(
442 missinggo.AddrIP(conn.RemoteAddr()),
443 missinggo.AddrPort(conn.RemoteAddr()))
446 log.Printf("rejecting connection from %s", conn.RemoteAddr())
452 go cl.incomingConnection(conn, utp)
456 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
458 if tc, ok := nc.(*net.TCPConn); ok {
461 c := cl.newConnection(nc)
462 c.Discovery = peerSourceIncoming
464 cl.runReceivedConn(c)
467 // Returns a handle to the given torrent, if it's present in the client.
468 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
471 t, ok = cl.torrents[ih]
475 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
476 return cl.torrents[ih]
479 type dialResult struct {
484 func countDialResult(err error) {
486 successfulDials.Add(1)
488 unsuccessfulDials.Add(1)
492 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
493 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
494 if ret < minDialTimeout {
500 // Returns whether an address is known to connect to a client with our own ID.
501 func (cl *Client) dopplegangerAddr(addr string) bool {
502 _, ok := cl.dopplegangerAddrs[addr]
506 // Start the process of connecting to the given peer for the given torrent if
508 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
509 if peer.Id == cl.peerID {
512 if cl.badPeerIPPort(peer.IP, peer.Port) {
515 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
516 if t.addrActive(addr) {
519 t.halfOpen[addr] = peer
520 go cl.outgoingConnection(t, addr, peer.Source)
523 func (cl *Client) dialTCP(ctx context.Context, addr string) (c net.Conn, err error) {
525 // LocalAddr: cl.tcpListener.Addr(),
527 c, err = d.DialContext(ctx, "tcp", addr)
530 c.(*net.TCPConn).SetLinger(0)
532 c = pproffd.WrapNetConn(c)
536 func (cl *Client) dialUTP(ctx context.Context, addr string) (c net.Conn, err error) {
537 c, err = cl.utpSock.DialContext(ctx, addr)
543 dialledFirstUtp = expvar.NewInt("dialledFirstUtp")
544 dialledFirstNotUtp = expvar.NewInt("dialledFirstNotUtp")
547 // Returns a connection over UTP or TCP, whichever is first to connect.
548 func (cl *Client) dialFirst(ctx context.Context, addr string) (conn net.Conn, utp bool) {
549 ctx, cancel := context.WithCancel(ctx)
550 // As soon as we return one connection, cancel the others.
553 resCh := make(chan dialResult, left)
554 if !cl.config.DisableUTP {
557 c, _ := cl.dialUTP(ctx, addr)
558 resCh <- dialResult{c, true}
561 if !cl.config.DisableTCP {
564 c, _ := cl.dialTCP(ctx, addr)
565 resCh <- dialResult{c, false}
569 // Wait for a successful connection.
570 for ; left > 0 && res.Conn == nil; left-- {
574 // There are still incompleted dials.
576 for ; left > 0; left-- {
577 conn := (<-resCh).Conn
588 dialledFirstUtp.Add(1)
590 dialledFirstNotUtp.Add(1)
596 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
597 if _, ok := t.halfOpen[addr]; !ok {
598 panic("invariant broken")
600 delete(t.halfOpen, addr)
604 // Performs initiator handshakes and returns a connection. Returns nil
605 // *connection if no connection for valid reasons.
606 func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader, utp bool) (c *connection, err error) {
607 c = cl.newConnection(nc)
608 c.headerEncrypted = encryptHeader
610 ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
612 dl, ok := ctx.Deadline()
616 err = nc.SetDeadline(dl)
620 ok, err = cl.initiateHandshakes(c, t)
628 initiatedConnWithPreferredHeaderEncryption = expvar.NewInt("initiatedConnWithPreferredHeaderEncryption")
629 initiatedConnWithFallbackHeaderEncryption = expvar.NewInt("initiatedConnWithFallbackHeaderEncryption")
632 // Returns nil connection and nil error if no connection could be established
633 // for valid reasons.
634 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
635 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
637 nc, utp := cl.dialFirst(ctx, addr)
641 obfuscatedHeaderFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
642 c, err = cl.handshakesConnection(ctx, nc, t, obfuscatedHeaderFirst, utp)
644 // log.Printf("error initiating connection handshakes: %s", err)
648 initiatedConnWithPreferredHeaderEncryption.Add(1)
652 if cl.config.ForceEncryption {
653 // We should have just tried with an obfuscated header. A plaintext
654 // header can't result in an encrypted connection, so we're done.
655 if !obfuscatedHeaderFirst {
656 panic(cl.config.EncryptionPolicy)
660 // Try again with encryption if we didn't earlier, or without if we did,
661 // using whichever protocol type worked last time.
663 nc, err = cl.dialUTP(ctx, addr)
665 nc, err = cl.dialTCP(ctx, addr)
668 err = fmt.Errorf("error dialing for header encryption fallback: %s", err)
671 c, err = cl.handshakesConnection(ctx, nc, t, !obfuscatedHeaderFirst, utp)
672 if err != nil || c == nil {
675 if err == nil && c != nil {
676 initiatedConnWithFallbackHeaderEncryption.Add(1)
681 // Called to dial out and run a connection. The addr we're given is already
682 // considered half-open.
683 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
684 c, err := cl.establishOutgoingConn(t, addr)
687 // Don't release lock between here and addConnection, unless it's for
689 cl.noLongerHalfOpen(t, addr)
692 log.Printf("error establishing outgoing connection: %s", err)
701 cl.runInitiatedHandshookConn(c, t)
704 // The port number for incoming peer connections. 0 if the client isn't
706 func (cl *Client) incomingPeerPort() int {
707 if cl.listenAddr == "" {
710 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
717 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
718 if c.headerEncrypted {
720 rw, err = mse.InitiateHandshake(
729 case cl.config.ForceEncryption:
730 return mse.CryptoMethodRC4
731 case cl.config.DisableEncryption:
732 return mse.CryptoMethodPlaintext
734 return mse.AllSupportedCrypto
743 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
744 if ih != t.infoHash {
750 // Calls f with any secret keys.
751 func (cl *Client) forSkeys(f func([]byte) bool) {
754 for ih := range cl.torrents {
761 // Do encryption and bittorrent handshakes as receiver.
762 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
764 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy)
767 if err == mse.ErrNoSecretKeyMatch {
772 if cl.config.ForceEncryption && !c.headerEncrypted {
773 err = errors.New("connection not encrypted")
776 ih, ok, err := cl.connBTHandshake(c, nil)
778 err = fmt.Errorf("error during bt handshake: %s", err)
790 // Returns !ok if handshake failed for valid reasons.
791 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
792 res, ok, err := handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
793 if err != nil || !ok {
797 c.PeerExtensionBytes = res.peerExtensionBytes
798 c.PeerID = res.PeerID
799 c.completedHandshake = time.Now()
803 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
804 if c.PeerID == cl.peerID {
806 addr := c.conn.RemoteAddr().String()
807 cl.dopplegangerAddrs[addr] = struct{}{}
810 cl.runHandshookConn(c, t, true)
813 func (cl *Client) runReceivedConn(c *connection) {
814 err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
818 t, err := cl.receiveHandshakes(c)
821 log.Printf("error receiving handshakes: %s", err)
830 if c.PeerID == cl.peerID {
831 // Because the remote address is not necessarily the same as its
832 // client's torrent listen address, we won't record the remote address
833 // as a doppleganger. Instead, the initiator can record *us* as the
837 cl.runHandshookConn(c, t, false)
840 func (cl *Client) runHandshookConn(c *connection, t *Torrent, outgoing bool) {
841 c.conn.SetWriteDeadline(time.Time{})
842 c.r = deadlineReader{c.conn, c.r}
843 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
844 if !t.addConnection(c, outgoing) {
847 defer t.dropConnection(c)
848 go c.writer(time.Minute)
849 cl.sendInitialMessages(c, t)
850 err := c.mainReadLoop()
851 if err != nil && cl.config.Debug {
852 log.Printf("error during connection main read loop: %s", err)
856 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
857 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
858 conn.Post(pp.Message{
860 ExtendedID: pp.HandshakeExtendedID,
861 ExtendedPayload: func() []byte {
862 d := map[string]interface{}{
863 "m": func() (ret map[string]int) {
864 ret = make(map[string]int, 2)
865 ret["ut_metadata"] = metadataExtendedId
866 if !cl.config.DisablePEX {
867 ret["ut_pex"] = pexExtendedId
871 "v": cl.config.ExtendedHandshakeClientVersion,
872 // No upload queue is implemented yet.
875 if !cl.config.DisableEncryption {
878 if torrent.metadataSizeKnown() {
879 d["metadata_size"] = torrent.metadataSize()
881 if p := cl.incomingPeerPort(); p != 0 {
884 yourip, err := addrCompactIP(conn.remoteAddr())
886 log.Printf("error calculating yourip field value in extension handshake: %s", err)
890 // log.Printf("sending %v", d)
891 b, err := bencode.Marshal(d)
899 if torrent.haveAnyPieces() {
900 conn.Bitfield(torrent.bitfield())
901 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
902 conn.Post(pp.Message{
906 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
907 conn.Post(pp.Message{
909 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
914 // Process incoming ut_metadata message.
915 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
917 err := bencode.Unmarshal(payload, &d)
919 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
921 msgType, ok := d["msg_type"]
923 return errors.New("missing msg_type field")
927 case pp.DataMetadataExtensionMsgType:
928 if !c.requestedMetadataPiece(piece) {
929 return fmt.Errorf("got unexpected piece %d", piece)
931 c.metadataRequests[piece] = false
932 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
933 if begin < 0 || begin >= len(payload) {
934 return fmt.Errorf("data has bad offset in payload: %d", begin)
936 t.saveMetadataPiece(piece, payload[begin:])
937 c.UsefulChunksReceived++
938 c.lastUsefulChunkReceived = time.Now()
939 return t.maybeCompleteMetadata()
940 case pp.RequestMetadataExtensionMsgType:
941 if !t.haveMetadataPiece(piece) {
942 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
945 start := (1 << 14) * piece
946 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
948 case pp.RejectMetadataExtensionMsgType:
951 return errors.New("unknown msg_type value")
955 func (cl *Client) sendChunk(t *Torrent, c *connection, r request, msg func(pp.Message) bool) (more bool, err error) {
956 // Count the chunk being sent, even if it isn't.
957 b := make([]byte, r.Length)
958 p := t.info.Piece(int(r.Index))
959 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
962 panic("expected error")
965 } else if err == io.EOF {
968 more = msg(pp.Message{
975 uploadChunksPosted.Add(1)
976 c.lastChunkSent = time.Now()
980 func (cl *Client) openNewConns(t *Torrent) {
981 defer t.updateWantPeersEvent()
982 for len(t.peers) != 0 {
986 if len(t.halfOpen) >= cl.halfOpenLimit {
993 for k, p = range t.peers {
997 cl.initiateConn(p, t)
1001 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1005 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1008 if _, ok := cl.ipBlockRange(ip); ok {
1011 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1017 // Return a Torrent ready for insertion into a Client.
1018 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1019 // use provided storage, if provided
1020 storageClient := cl.defaultStorage
1021 if specStorage != nil {
1022 storageClient = storage.NewClient(specStorage)
1028 peers: make(map[peersKey]Peer),
1029 conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1031 halfOpen: make(map[string]Peer),
1032 pieceStateChanges: pubsub.NewPubSub(),
1034 storageOpener: storageClient,
1035 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1037 networkingEnabled: true,
1039 metadataChanged: sync.Cond{
1043 t.setChunkSize(defaultChunkSize)
1047 // A file-like handle to some torrent data resource.
1048 type Handle interface {
1055 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1056 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1059 // Adds a torrent by InfoHash with a custom Storage implementation.
1060 // If the torrent already exists then this Storage is ignored and the
1061 // existing torrent returned with `new` set to `false`
1062 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1064 defer cl.mu.Unlock()
1065 t, ok := cl.torrents[infoHash]
1070 t = cl.newTorrent(infoHash, specStorage)
1074 cl.torrents[infoHash] = t
1075 t.updateWantPeersEvent()
1076 // Tickle Client.waitAccept, new torrent may want conns.
1077 cl.event.Broadcast()
1081 // Add or merge a torrent spec. If the torrent is already present, the
1082 // trackers will be merged with the existing ones. If the Info isn't yet
1083 // known, it will be set. The display name is replaced if the new spec
1084 // provides one. Returns new if the torrent wasn't already in the client.
1085 // Note that any `Storage` defined on the spec will be ignored if the
1086 // torrent is already present (i.e. `new` return value is `true`)
1087 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1088 t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1089 if spec.DisplayName != "" {
1090 t.SetDisplayName(spec.DisplayName)
1092 if spec.InfoBytes != nil {
1093 err = t.SetInfoBytes(spec.InfoBytes)
1099 defer cl.mu.Unlock()
1100 if spec.ChunkSize != 0 {
1101 t.setChunkSize(pp.Integer(spec.ChunkSize))
1103 t.addTrackers(spec.Trackers)
1108 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1109 t, ok := cl.torrents[infoHash]
1111 err = fmt.Errorf("no such torrent")
1118 delete(cl.torrents, infoHash)
1122 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1123 _url, err := url.Parse(announceURL)
1127 hmp := missinggo.SplitHostMaybePort(_url.Host)
1132 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1137 _, blocked = cl.ipBlockRange(addr.IP)
1140 hmp.Host = addr.String()
1141 _url.Host = hmp.String()
1142 urlToUse = _url.String()
1146 func (cl *Client) allTorrentsCompleted() bool {
1147 for _, t := range cl.torrents {
1151 if t.numPiecesCompleted() != t.numPieces() {
1158 // Returns true when all torrents are completely downloaded and false if the
1159 // client is stopped before that.
1160 func (cl *Client) WaitAll() bool {
1162 defer cl.mu.Unlock()
1163 for !cl.allTorrentsCompleted() {
1164 if cl.closed.IsSet() {
1172 // Returns handles to all the torrents loaded in the Client.
1173 func (cl *Client) Torrents() []*Torrent {
1175 defer cl.mu.Unlock()
1176 return cl.torrentsAsSlice()
1179 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1180 for _, t := range cl.torrents {
1181 ret = append(ret, t)
1186 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1187 spec, err := TorrentSpecFromMagnetURI(uri)
1191 T, _, err = cl.AddTorrentSpec(spec)
1195 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1196 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1198 slices.MakeInto(&ss, mi.Nodes)
1203 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1204 mi, err := metainfo.LoadFromFile(filename)
1208 return cl.AddTorrent(mi)
1211 func (cl *Client) DHT() *dht.Server {
1215 func (cl *Client) AddDHTNodes(nodes []string) {
1216 if cl.DHT() == nil {
1219 for _, n := range nodes {
1220 hmp := missinggo.SplitHostMaybePort(n)
1221 ip := net.ParseIP(hmp.Host)
1223 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1226 ni := krpc.NodeInfo{
1232 cl.DHT().AddNode(ni)
1236 func (cl *Client) banPeerIP(ip net.IP) {
1237 if cl.badPeerIPs == nil {
1238 cl.badPeerIPs = make(map[string]struct{})
1240 cl.badPeerIPs[ip.String()] = struct{}{}
1243 func (cl *Client) newConnection(nc net.Conn) (c *connection) {
1249 PeerMaxRequests: 250,
1251 c.writerCond.L = &cl.mu
1252 c.setRW(connStatsReadWriter{nc, &cl.mu, c})
1253 c.r = rateLimitedReader{cl.downloadLimit, c.r}
1257 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1259 defer cl.mu.Unlock()
1267 Source: peerSourceDHTAnnouncePeer,