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() string {
94 return string(cl.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,
240 halfOpenLimit: defaultHalfOpenConnsPerTorrent,
242 dopplegangerAddrs: make(map[string]struct{}),
243 torrents: make(map[metainfo.Hash]*Torrent),
251 if cfg.UploadRateLimiter == nil {
252 cl.uploadLimit = rate.NewLimiter(rate.Inf, 0)
254 cl.uploadLimit = cfg.UploadRateLimiter
256 if cfg.DownloadRateLimiter == nil {
257 cl.downloadLimit = rate.NewLimiter(rate.Inf, 0)
259 cl.downloadLimit = cfg.DownloadRateLimiter
261 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
263 storageImpl := cfg.DefaultStorage
264 if storageImpl == nil {
265 // We'd use mmap but HFS+ doesn't support sparse files.
266 storageImpl = storage.NewFile(cfg.DataDir)
267 cl.onClose = append(cl.onClose, func() {
268 if err := storageImpl.Close(); err != nil {
269 log.Printf("error closing default storage: %s", err)
273 cl.defaultStorage = storage.NewClient(storageImpl)
274 if cfg.IPBlocklist != nil {
275 cl.ipBlockList = cfg.IPBlocklist
278 if cfg.PeerID != "" {
279 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
281 o := copy(cl.peerID[:], bep20)
282 _, err = rand.Read(cl.peerID[o:])
284 panic("error generating peer id")
288 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
289 !cl.config.DisableTCP,
290 !cl.config.DisableUTP,
292 if cl.config.DisableIPv6 {
298 cl.config.ListenAddr)
302 if cl.tcpListener != nil {
303 go cl.acceptConnections(cl.tcpListener, false)
305 if cl.utpSock != nil {
306 go cl.acceptConnections(cl.utpSock, true)
309 dhtCfg := cfg.DHTConfig
310 if dhtCfg.IPBlocklist == nil {
311 dhtCfg.IPBlocklist = cl.ipBlockList
313 if dhtCfg.Conn == nil {
314 if cl.utpSock != nil {
315 dhtCfg.Conn = cl.utpSock
317 dhtCfg.Conn, err = net.ListenPacket("udp", firstNonEmptyString(cl.listenAddr, cl.config.ListenAddr))
323 if dhtCfg.OnAnnouncePeer == nil {
324 dhtCfg.OnAnnouncePeer = cl.onDHTAnnouncePeer
326 cl.dHT, err = dht.NewServer(&dhtCfg)
331 if _, err := cl.dHT.Bootstrap(); err != nil {
332 log.Printf("error bootstrapping dht: %s", err)
340 func firstNonEmptyString(ss ...string) string {
341 for _, s := range ss {
349 // Stops the client. All connections to peers are closed and all activity will
351 func (cl *Client) Close() {
358 if cl.utpSock != nil {
361 if cl.tcpListener != nil {
362 cl.tcpListener.Close()
364 for _, t := range cl.torrents {
367 for _, f := range cl.onClose {
373 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
375 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
376 if cl.ipBlockList == nil {
380 // If blocklists are enabled, then block non-IPv4 addresses, because
381 // blocklists do not yet support IPv6.
383 if missinggo.CryHeard() {
384 log.Printf("blocking non-IPv4 address: %s", ip)
390 return cl.ipBlockList.Lookup(ip4)
393 func (cl *Client) waitAccept() {
395 for _, t := range cl.torrents {
400 if cl.closed.IsSet() {
407 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
413 conn, err := l.Accept()
414 conn = pproffd.WrapNetConn(conn)
416 if cl.closed.IsSet() {
424 // I think something harsher should happen here? Our accept
425 // routine just fucked off.
434 log.Printf("accepted connection from %s", conn.RemoteAddr())
436 reject := cl.badPeerIPPort(
437 missinggo.AddrIP(conn.RemoteAddr()),
438 missinggo.AddrPort(conn.RemoteAddr()))
441 log.Printf("rejecting connection from %s", conn.RemoteAddr())
447 go cl.incomingConnection(conn, utp)
451 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
453 if tc, ok := nc.(*net.TCPConn); ok {
456 c := cl.newConnection(nc)
457 c.Discovery = peerSourceIncoming
459 cl.runReceivedConn(c)
462 // Returns a handle to the given torrent, if it's present in the client.
463 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
466 t, ok = cl.torrents[ih]
470 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
471 return cl.torrents[ih]
474 type dialResult struct {
479 func countDialResult(err error) {
481 successfulDials.Add(1)
483 unsuccessfulDials.Add(1)
487 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
488 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
489 if ret < minDialTimeout {
495 // Returns whether an address is known to connect to a client with our own ID.
496 func (cl *Client) dopplegangerAddr(addr string) bool {
497 _, ok := cl.dopplegangerAddrs[addr]
501 // Start the process of connecting to the given peer for the given torrent if
503 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
504 if peer.Id == cl.peerID {
507 if cl.badPeerIPPort(peer.IP, peer.Port) {
510 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
511 if t.addrActive(addr) {
514 t.halfOpen[addr] = peer
515 go cl.outgoingConnection(t, addr, peer.Source)
518 func (cl *Client) dialTCP(ctx context.Context, addr string) (c net.Conn, err error) {
520 // LocalAddr: cl.tcpListener.Addr(),
522 c, err = d.DialContext(ctx, "tcp", addr)
525 c.(*net.TCPConn).SetLinger(0)
527 c = pproffd.WrapNetConn(c)
531 func (cl *Client) dialUTP(ctx context.Context, addr string) (c net.Conn, err error) {
532 c, err = cl.utpSock.DialContext(ctx, addr)
538 dialledFirstUtp = expvar.NewInt("dialledFirstUtp")
539 dialledFirstNotUtp = expvar.NewInt("dialledFirstNotUtp")
542 // Returns a connection over UTP or TCP, whichever is first to connect.
543 func (cl *Client) dialFirst(ctx context.Context, addr string) (conn net.Conn, utp bool) {
544 ctx, cancel := context.WithCancel(ctx)
545 // As soon as we return one connection, cancel the others.
548 resCh := make(chan dialResult, left)
549 if !cl.config.DisableUTP {
552 c, _ := cl.dialUTP(ctx, addr)
553 resCh <- dialResult{c, true}
556 if !cl.config.DisableTCP {
559 c, _ := cl.dialTCP(ctx, addr)
560 resCh <- dialResult{c, false}
564 // Wait for a successful connection.
565 for ; left > 0 && res.Conn == nil; left-- {
569 // There are still incompleted dials.
571 for ; left > 0; left-- {
572 conn := (<-resCh).Conn
583 dialledFirstUtp.Add(1)
585 dialledFirstNotUtp.Add(1)
591 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
592 if _, ok := t.halfOpen[addr]; !ok {
593 panic("invariant broken")
595 delete(t.halfOpen, addr)
599 // Performs initiator handshakes and returns a connection. Returns nil
600 // *connection if no connection for valid reasons.
601 func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader, utp bool) (c *connection, err error) {
602 c = cl.newConnection(nc)
603 c.headerEncrypted = encryptHeader
605 ctx, cancel := context.WithTimeout(ctx, handshakesTimeout)
607 dl, ok := ctx.Deadline()
611 err = nc.SetDeadline(dl)
615 ok, err = cl.initiateHandshakes(c, t)
623 initiatedConnWithPreferredHeaderEncryption = expvar.NewInt("initiatedConnWithPreferredHeaderEncryption")
624 initiatedConnWithFallbackHeaderEncryption = expvar.NewInt("initiatedConnWithFallbackHeaderEncryption")
627 // Returns nil connection and nil error if no connection could be established
628 // for valid reasons.
629 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
630 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
632 nc, utp := cl.dialFirst(ctx, addr)
636 obfuscatedHeaderFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
637 c, err = cl.handshakesConnection(ctx, nc, t, obfuscatedHeaderFirst, utp)
639 // log.Printf("error initiating connection handshakes: %s", err)
643 initiatedConnWithPreferredHeaderEncryption.Add(1)
647 if cl.config.ForceEncryption {
648 // We should have just tried with an obfuscated header. A plaintext
649 // header can't result in an encrypted connection, so we're done.
650 if !obfuscatedHeaderFirst {
651 panic(cl.config.EncryptionPolicy)
655 // Try again with encryption if we didn't earlier, or without if we did,
656 // using whichever protocol type worked last time.
658 nc, err = cl.dialUTP(ctx, addr)
660 nc, err = cl.dialTCP(ctx, addr)
663 err = fmt.Errorf("error dialing for header encryption fallback: %s", err)
666 c, err = cl.handshakesConnection(ctx, nc, t, !obfuscatedHeaderFirst, utp)
667 if err != nil || c == nil {
670 if err == nil && c != nil {
671 initiatedConnWithFallbackHeaderEncryption.Add(1)
676 // Called to dial out and run a connection. The addr we're given is already
677 // considered half-open.
678 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
679 c, err := cl.establishOutgoingConn(t, addr)
682 // Don't release lock between here and addConnection, unless it's for
684 cl.noLongerHalfOpen(t, addr)
687 log.Printf("error establishing outgoing connection: %s", err)
696 cl.runInitiatedHandshookConn(c, t)
699 // The port number for incoming peer connections. 0 if the client isn't
701 func (cl *Client) incomingPeerPort() int {
702 if cl.listenAddr == "" {
705 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
712 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
713 if c.headerEncrypted {
715 rw, err = mse.InitiateHandshake(
724 case cl.config.ForceEncryption:
725 return mse.CryptoMethodRC4
726 case cl.config.DisableEncryption:
727 return mse.CryptoMethodPlaintext
729 return mse.AllSupportedCrypto
738 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
739 if ih != t.infoHash {
745 // Calls f with any secret keys.
746 func (cl *Client) forSkeys(f func([]byte) bool) {
749 for ih := range cl.torrents {
756 // Do encryption and bittorrent handshakes as receiver.
757 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
759 rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy)
762 if err == mse.ErrNoSecretKeyMatch {
767 if cl.config.ForceEncryption && !c.headerEncrypted {
768 err = errors.New("connection not encrypted")
771 ih, ok, err := cl.connBTHandshake(c, nil)
773 err = fmt.Errorf("error during bt handshake: %s", err)
785 // Returns !ok if handshake failed for valid reasons.
786 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
787 res, ok, err := handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
788 if err != nil || !ok {
792 c.PeerExtensionBytes = res.peerExtensionBytes
793 c.PeerID = res.peerID
794 c.completedHandshake = time.Now()
798 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
799 if c.PeerID == cl.peerID {
801 addr := c.conn.RemoteAddr().String()
802 cl.dopplegangerAddrs[addr] = struct{}{}
805 cl.runHandshookConn(c, t, true)
808 func (cl *Client) runReceivedConn(c *connection) {
809 err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
813 t, err := cl.receiveHandshakes(c)
816 log.Printf("error receiving handshakes: %s", err)
825 if c.PeerID == cl.peerID {
826 // Because the remote address is not necessarily the same as its
827 // client's torrent listen address, we won't record the remote address
828 // as a doppleganger. Instead, the initiator can record *us* as the
832 cl.runHandshookConn(c, t, false)
835 func (cl *Client) runHandshookConn(c *connection, t *Torrent, outgoing bool) {
836 c.conn.SetWriteDeadline(time.Time{})
837 c.r = deadlineReader{c.conn, c.r}
838 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
839 if !t.addConnection(c, outgoing) {
842 defer t.dropConnection(c)
843 go c.writer(time.Minute)
844 cl.sendInitialMessages(c, t)
845 err := c.mainReadLoop()
846 if err != nil && cl.config.Debug {
847 log.Printf("error during connection loop: %s", err)
851 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
852 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
853 conn.Post(pp.Message{
855 ExtendedID: pp.HandshakeExtendedID,
856 ExtendedPayload: func() []byte {
857 d := map[string]interface{}{
858 "m": func() (ret map[string]int) {
859 ret = make(map[string]int, 2)
860 ret["ut_metadata"] = metadataExtendedId
861 if !cl.config.DisablePEX {
862 ret["ut_pex"] = pexExtendedId
866 "v": extendedHandshakeClientVersion,
867 // No upload queue is implemented yet.
870 if !cl.config.DisableEncryption {
873 if torrent.metadataSizeKnown() {
874 d["metadata_size"] = torrent.metadataSize()
876 if p := cl.incomingPeerPort(); p != 0 {
879 yourip, err := addrCompactIP(conn.remoteAddr())
881 log.Printf("error calculating yourip field value in extension handshake: %s", err)
885 // log.Printf("sending %v", d)
886 b, err := bencode.Marshal(d)
894 if torrent.haveAnyPieces() {
895 conn.Bitfield(torrent.bitfield())
896 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
897 conn.Post(pp.Message{
901 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
902 conn.Post(pp.Message{
904 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
909 // Process incoming ut_metadata message.
910 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
912 err := bencode.Unmarshal(payload, &d)
914 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
916 msgType, ok := d["msg_type"]
918 return errors.New("missing msg_type field")
922 case pp.DataMetadataExtensionMsgType:
923 if !c.requestedMetadataPiece(piece) {
924 return fmt.Errorf("got unexpected piece %d", piece)
926 c.metadataRequests[piece] = false
927 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
928 if begin < 0 || begin >= len(payload) {
929 return fmt.Errorf("data has bad offset in payload: %d", begin)
931 t.saveMetadataPiece(piece, payload[begin:])
932 c.UsefulChunksReceived++
933 c.lastUsefulChunkReceived = time.Now()
934 return t.maybeCompleteMetadata()
935 case pp.RequestMetadataExtensionMsgType:
936 if !t.haveMetadataPiece(piece) {
937 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
940 start := (1 << 14) * piece
941 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
943 case pp.RejectMetadataExtensionMsgType:
946 return errors.New("unknown msg_type value")
950 func (cl *Client) sendChunk(t *Torrent, c *connection, r request, msg func(pp.Message) bool) (more bool, err error) {
951 // Count the chunk being sent, even if it isn't.
952 b := make([]byte, r.Length)
953 p := t.info.Piece(int(r.Index))
954 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
957 panic("expected error")
960 } else if err == io.EOF {
963 more = msg(pp.Message{
970 uploadChunksPosted.Add(1)
971 c.lastChunkSent = time.Now()
975 func (cl *Client) openNewConns(t *Torrent) {
976 defer t.updateWantPeersEvent()
977 for len(t.peers) != 0 {
981 if len(t.halfOpen) >= cl.halfOpenLimit {
988 for k, p = range t.peers {
992 cl.initiateConn(p, t)
996 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1000 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1003 if _, ok := cl.ipBlockRange(ip); ok {
1006 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1012 // Return a Torrent ready for insertion into a Client.
1013 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1014 // use provided storage, if provided
1015 storageClient := cl.defaultStorage
1016 if specStorage != nil {
1017 storageClient = storage.NewClient(specStorage)
1023 peers: make(map[peersKey]Peer),
1024 conns: make(map[*connection]struct{}, 2*defaultEstablishedConnsPerTorrent),
1026 halfOpen: make(map[string]Peer),
1027 pieceStateChanges: pubsub.NewPubSub(),
1029 storageOpener: storageClient,
1030 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1032 networkingEnabled: true,
1035 t.setChunkSize(defaultChunkSize)
1039 // A file-like handle to some torrent data resource.
1040 type Handle interface {
1047 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1048 return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1051 // Adds a torrent by InfoHash with a custom Storage implementation.
1052 // If the torrent already exists then this Storage is ignored and the
1053 // existing torrent returned with `new` set to `false`
1054 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1056 defer cl.mu.Unlock()
1057 t, ok := cl.torrents[infoHash]
1062 t = cl.newTorrent(infoHash, specStorage)
1066 cl.torrents[infoHash] = t
1067 t.updateWantPeersEvent()
1068 // Tickle Client.waitAccept, new torrent may want conns.
1069 cl.event.Broadcast()
1073 // Add or merge a torrent spec. If the torrent is already present, the
1074 // trackers will be merged with the existing ones. If the Info isn't yet
1075 // known, it will be set. The display name is replaced if the new spec
1076 // provides one. Returns new if the torrent wasn't already in the client.
1077 // Note that any `Storage` defined on the spec will be ignored if the
1078 // torrent is already present (i.e. `new` return value is `true`)
1079 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1080 t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1081 if spec.DisplayName != "" {
1082 t.SetDisplayName(spec.DisplayName)
1084 if spec.InfoBytes != nil {
1085 err = t.SetInfoBytes(spec.InfoBytes)
1091 defer cl.mu.Unlock()
1092 if spec.ChunkSize != 0 {
1093 t.setChunkSize(pp.Integer(spec.ChunkSize))
1095 t.addTrackers(spec.Trackers)
1100 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1101 t, ok := cl.torrents[infoHash]
1103 err = fmt.Errorf("no such torrent")
1110 delete(cl.torrents, infoHash)
1114 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1115 _url, err := url.Parse(announceURL)
1119 hmp := missinggo.SplitHostMaybePort(_url.Host)
1124 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1129 _, blocked = cl.ipBlockRange(addr.IP)
1132 hmp.Host = addr.String()
1133 _url.Host = hmp.String()
1134 urlToUse = _url.String()
1138 func (cl *Client) allTorrentsCompleted() bool {
1139 for _, t := range cl.torrents {
1143 if t.numPiecesCompleted() != t.numPieces() {
1150 // Returns true when all torrents are completely downloaded and false if the
1151 // client is stopped before that.
1152 func (cl *Client) WaitAll() bool {
1154 defer cl.mu.Unlock()
1155 for !cl.allTorrentsCompleted() {
1156 if cl.closed.IsSet() {
1164 // Returns handles to all the torrents loaded in the Client.
1165 func (cl *Client) Torrents() []*Torrent {
1167 defer cl.mu.Unlock()
1168 return cl.torrentsAsSlice()
1171 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1172 for _, t := range cl.torrents {
1173 ret = append(ret, t)
1178 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1179 spec, err := TorrentSpecFromMagnetURI(uri)
1183 T, _, err = cl.AddTorrentSpec(spec)
1187 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1188 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1190 slices.MakeInto(&ss, mi.Nodes)
1195 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1196 mi, err := metainfo.LoadFromFile(filename)
1200 return cl.AddTorrent(mi)
1203 func (cl *Client) DHT() *dht.Server {
1207 func (cl *Client) AddDHTNodes(nodes []string) {
1208 if cl.DHT() == nil {
1211 for _, n := range nodes {
1212 hmp := missinggo.SplitHostMaybePort(n)
1213 ip := net.ParseIP(hmp.Host)
1215 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1218 ni := krpc.NodeInfo{
1224 cl.DHT().AddNode(ni)
1228 func (cl *Client) banPeerIP(ip net.IP) {
1229 if cl.badPeerIPs == nil {
1230 cl.badPeerIPs = make(map[string]struct{})
1232 cl.badPeerIPs[ip.String()] = struct{}{}
1235 func (cl *Client) newConnection(nc net.Conn) (c *connection) {
1241 PeerMaxRequests: 250,
1243 c.writerCond.L = &cl.mu
1244 c.setRW(connStatsReadWriter{nc, &cl.mu, c})
1245 c.r = rateLimitedReader{cl.downloadLimit, c.r}
1249 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1251 defer cl.mu.Unlock()
1259 Source: peerSourceDHTAnnouncePeer,