]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
Merge branch 'bargle'
[btrtrc.git] / client.go
1 package torrent
2
3 import (
4         "bufio"
5         "context"
6         "crypto/rand"
7         "crypto/sha1"
8         "encoding/binary"
9         "errors"
10         "expvar"
11         "fmt"
12         "io"
13         "math"
14         "net"
15         "net/http"
16         "net/netip"
17         "sort"
18         "strconv"
19         "strings"
20         "time"
21
22         "github.com/davecgh/go-spew/spew"
23         "github.com/dustin/go-humanize"
24         gbtree "github.com/google/btree"
25         "github.com/pion/datachannel"
26         "golang.org/x/time/rate"
27
28         "github.com/anacrolix/chansync"
29         "github.com/anacrolix/chansync/events"
30         "github.com/anacrolix/dht/v2"
31         "github.com/anacrolix/dht/v2/krpc"
32         "github.com/anacrolix/generics"
33         . "github.com/anacrolix/generics"
34         "github.com/anacrolix/log"
35         "github.com/anacrolix/missinggo/perf"
36         "github.com/anacrolix/missinggo/v2"
37         "github.com/anacrolix/missinggo/v2/bitmap"
38         "github.com/anacrolix/missinggo/v2/pproffd"
39         "github.com/anacrolix/sync"
40
41         "github.com/anacrolix/torrent/bencode"
42         "github.com/anacrolix/torrent/internal/limiter"
43         "github.com/anacrolix/torrent/iplist"
44         "github.com/anacrolix/torrent/metainfo"
45         "github.com/anacrolix/torrent/mse"
46         pp "github.com/anacrolix/torrent/peer_protocol"
47         request_strategy "github.com/anacrolix/torrent/request-strategy"
48         "github.com/anacrolix/torrent/storage"
49         "github.com/anacrolix/torrent/tracker"
50         "github.com/anacrolix/torrent/webtorrent"
51 )
52
53 // Clients contain zero or more Torrents. A Client manages a blocklist, the
54 // TCP/UDP protocol ports, and DHT as desired.
55 type Client struct {
56         // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
57         // fields. See #262.
58         stats ConnStats
59
60         _mu    lockWithDeferreds
61         event  sync.Cond
62         closed chansync.SetOnce
63
64         config *ClientConfig
65         logger log.Logger
66
67         peerID         PeerID
68         defaultStorage *storage.Client
69         onClose        []func()
70         dialers        []Dialer
71         listeners      []Listener
72         dhtServers     []DhtServer
73         ipBlockList    iplist.Ranger
74
75         // Set of addresses that have our client ID. This intentionally will
76         // include ourselves if we end up trying to connect to our own address
77         // through legitimate channels.
78         dopplegangerAddrs map[string]struct{}
79         badPeerIPs        map[netip.Addr]struct{}
80         torrents          map[InfoHash]*Torrent
81         pieceRequestOrder map[interface{}]*request_strategy.PieceRequestOrder
82
83         acceptLimiter   map[ipStr]int
84         dialRateLimiter *rate.Limiter
85         numHalfOpen     int
86
87         websocketTrackers websocketTrackers
88
89         activeAnnounceLimiter limiter.Instance
90         httpClient            *http.Client
91 }
92
93 type ipStr string
94
95 func (cl *Client) BadPeerIPs() (ips []string) {
96         cl.rLock()
97         ips = cl.badPeerIPsLocked()
98         cl.rUnlock()
99         return
100 }
101
102 func (cl *Client) badPeerIPsLocked() (ips []string) {
103         ips = make([]string, len(cl.badPeerIPs))
104         i := 0
105         for k := range cl.badPeerIPs {
106                 ips[i] = k.String()
107                 i += 1
108         }
109         return
110 }
111
112 func (cl *Client) PeerID() PeerID {
113         return cl.peerID
114 }
115
116 // Returns the port number for the first listener that has one. No longer assumes that all port
117 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
118 // found.
119 func (cl *Client) LocalPort() (port int) {
120         for i := 0; i < len(cl.listeners); i += 1 {
121                 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
122                         return
123                 }
124         }
125         return
126 }
127
128 func writeDhtServerStatus(w io.Writer, s DhtServer) {
129         dhtStats := s.Stats()
130         fmt.Fprintf(w, " ID: %x\n", s.ID())
131         spew.Fdump(w, dhtStats)
132 }
133
134 // Writes out a human readable status of the client, such as for writing to a
135 // HTTP status page.
136 func (cl *Client) WriteStatus(_w io.Writer) {
137         cl.rLock()
138         defer cl.rUnlock()
139         w := bufio.NewWriter(_w)
140         defer w.Flush()
141         fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
142         fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
143         fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
144         fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
145         fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
146         cl.eachDhtServer(func(s DhtServer) {
147                 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
148                 writeDhtServerStatus(w, s)
149         })
150         spew.Fdump(w, &cl.stats)
151         torrentsSlice := cl.torrentsAsSlice()
152         fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
153         fmt.Fprintln(w)
154         sort.Slice(torrentsSlice, func(l, r int) bool {
155                 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
156         })
157         for _, t := range torrentsSlice {
158                 if t.name() == "" {
159                         fmt.Fprint(w, "<unknown name>")
160                 } else {
161                         fmt.Fprint(w, t.name())
162                 }
163                 fmt.Fprint(w, "\n")
164                 if t.info != nil {
165                         fmt.Fprintf(
166                                 w,
167                                 "%f%% of %d bytes (%s)",
168                                 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
169                                 t.length(),
170                                 humanize.Bytes(uint64(t.length())))
171                 } else {
172                         w.WriteString("<missing metainfo>")
173                 }
174                 fmt.Fprint(w, "\n")
175                 t.writeStatus(w)
176                 fmt.Fprintln(w)
177         }
178 }
179
180 func (cl *Client) initLogger() {
181         logger := cl.config.Logger
182         if logger.IsZero() {
183                 logger = log.Default
184         }
185         if cl.config.Debug {
186                 logger = logger.FilterLevel(log.Debug)
187         }
188         cl.logger = logger.WithValues(cl)
189 }
190
191 func (cl *Client) announceKey() int32 {
192         return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
193 }
194
195 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
196 func (cl *Client) init(cfg *ClientConfig) {
197         cl.config = cfg
198         generics.MakeMap(&cl.dopplegangerAddrs)
199         cl.torrents = make(map[metainfo.Hash]*Torrent)
200         cl.dialRateLimiter = rate.NewLimiter(10, 10)
201         cl.activeAnnounceLimiter.SlotsPerKey = 2
202         cl.event.L = cl.locker()
203         cl.ipBlockList = cfg.IPBlocklist
204         cl.httpClient = &http.Client{
205                 Transport: &http.Transport{
206                         Proxy: cfg.HTTPProxy,
207                         // I think this value was observed from some webseeds. It seems reasonable to extend it
208                         // to other uses of HTTP from the client.
209                         MaxConnsPerHost: 10,
210                 },
211         }
212 }
213
214 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
215         if cfg == nil {
216                 cfg = NewDefaultClientConfig()
217                 cfg.ListenPort = 0
218         }
219         var client Client
220         client.init(cfg)
221         cl = &client
222         go cl.acceptLimitClearer()
223         cl.initLogger()
224         defer func() {
225                 if err != nil {
226                         cl.Close()
227                         cl = nil
228                 }
229         }()
230
231         storageImpl := cfg.DefaultStorage
232         if storageImpl == nil {
233                 // We'd use mmap by default but HFS+ doesn't support sparse files.
234                 storageImplCloser := storage.NewFile(cfg.DataDir)
235                 cl.onClose = append(cl.onClose, func() {
236                         if err := storageImplCloser.Close(); err != nil {
237                                 cl.logger.Printf("error closing default storage: %s", err)
238                         }
239                 })
240                 storageImpl = storageImplCloser
241         }
242         cl.defaultStorage = storage.NewClient(storageImpl)
243
244         if cfg.PeerID != "" {
245                 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
246         } else {
247                 o := copy(cl.peerID[:], cfg.Bep20)
248                 _, err = rand.Read(cl.peerID[o:])
249                 if err != nil {
250                         panic("error generating peer id")
251                 }
252         }
253
254         sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback, cl.logger)
255         if err != nil {
256                 return
257         }
258
259         // Check for panics.
260         cl.LocalPort()
261
262         for _, _s := range sockets {
263                 s := _s // Go is fucking retarded.
264                 cl.onClose = append(cl.onClose, func() { go s.Close() })
265                 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
266                         cl.dialers = append(cl.dialers, s)
267                         cl.listeners = append(cl.listeners, s)
268                         if cl.config.AcceptPeerConnections {
269                                 go cl.acceptConnections(s)
270                         }
271                 }
272         }
273
274         go cl.forwardPort()
275         if !cfg.NoDHT {
276                 for _, s := range sockets {
277                         if pc, ok := s.(net.PacketConn); ok {
278                                 ds, err := cl.NewAnacrolixDhtServer(pc)
279                                 if err != nil {
280                                         panic(err)
281                                 }
282                                 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
283                                 cl.onClose = append(cl.onClose, func() { ds.Close() })
284                         }
285                 }
286         }
287
288         cl.websocketTrackers = websocketTrackers{
289                 PeerId: cl.peerID,
290                 Logger: cl.logger,
291                 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
292                         cl.lock()
293                         defer cl.unlock()
294                         t, ok := cl.torrents[infoHash]
295                         if !ok {
296                                 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
297                         }
298                         return t.announceRequest(event), nil
299                 },
300                 Proxy: cl.config.HTTPProxy,
301                 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
302                         cl.lock()
303                         defer cl.unlock()
304                         t, ok := cl.torrents[dcc.InfoHash]
305                         if !ok {
306                                 cl.logger.WithDefaultLevel(log.Warning).Printf(
307                                         "got webrtc conn for unloaded torrent with infohash %x",
308                                         dcc.InfoHash,
309                                 )
310                                 dc.Close()
311                                 return
312                         }
313                         go t.onWebRtcConn(dc, dcc)
314                 },
315         }
316
317         return
318 }
319
320 func (cl *Client) AddDhtServer(d DhtServer) {
321         cl.dhtServers = append(cl.dhtServers, d)
322 }
323
324 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
325 // given address for any Torrent.
326 func (cl *Client) AddDialer(d Dialer) {
327         cl.lock()
328         defer cl.unlock()
329         cl.dialers = append(cl.dialers, d)
330         for _, t := range cl.torrents {
331                 t.openNewConns()
332         }
333 }
334
335 func (cl *Client) Listeners() []Listener {
336         return cl.listeners
337 }
338
339 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
340 // yourself.
341 func (cl *Client) AddListener(l Listener) {
342         cl.listeners = append(cl.listeners, l)
343         if cl.config.AcceptPeerConnections {
344                 go cl.acceptConnections(l)
345         }
346 }
347
348 func (cl *Client) firewallCallback(net.Addr) bool {
349         cl.rLock()
350         block := !cl.wantConns() || !cl.config.AcceptPeerConnections
351         cl.rUnlock()
352         if block {
353                 torrent.Add("connections firewalled", 1)
354         } else {
355                 torrent.Add("connections not firewalled", 1)
356         }
357         return block
358 }
359
360 func (cl *Client) listenOnNetwork(n network) bool {
361         if n.Ipv4 && cl.config.DisableIPv4 {
362                 return false
363         }
364         if n.Ipv6 && cl.config.DisableIPv6 {
365                 return false
366         }
367         if n.Tcp && cl.config.DisableTCP {
368                 return false
369         }
370         if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
371                 return false
372         }
373         return true
374 }
375
376 func (cl *Client) listenNetworks() (ns []network) {
377         for _, n := range allPeerNetworks {
378                 if cl.listenOnNetwork(n) {
379                         ns = append(ns, n)
380                 }
381         }
382         return
383 }
384
385 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
386 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
387         logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
388         cfg := dht.ServerConfig{
389                 IPBlocklist:    cl.ipBlockList,
390                 Conn:           conn,
391                 OnAnnouncePeer: cl.onDHTAnnouncePeer,
392                 PublicIP: func() net.IP {
393                         if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
394                                 return cl.config.PublicIp6
395                         }
396                         return cl.config.PublicIp4
397                 }(),
398                 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
399                 OnQuery:       cl.config.DHTOnQuery,
400                 Logger:        logger,
401         }
402         if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
403                 f(&cfg)
404         }
405         s, err = dht.NewServer(&cfg)
406         if err == nil {
407                 go func() {
408                         ts, err := s.Bootstrap()
409                         if err != nil {
410                                 logger.Levelf(log.Warning, "error bootstrapping dht: %s", err)
411                         }
412                         logger.Levelf(log.Debug, "completed bootstrap: %+v", ts)
413                 }()
414         }
415         return
416 }
417
418 func (cl *Client) Closed() events.Done {
419         return cl.closed.Done()
420 }
421
422 func (cl *Client) eachDhtServer(f func(DhtServer)) {
423         for _, ds := range cl.dhtServers {
424                 f(ds)
425         }
426 }
427
428 // Stops the client. All connections to peers are closed and all activity will come to a halt.
429 func (cl *Client) Close() (errs []error) {
430         var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
431         cl.lock()
432         for _, t := range cl.torrents {
433                 err := t.close(&closeGroup)
434                 if err != nil {
435                         errs = append(errs, err)
436                 }
437         }
438         for i := range cl.onClose {
439                 cl.onClose[len(cl.onClose)-1-i]()
440         }
441         cl.closed.Set()
442         cl.unlock()
443         cl.event.Broadcast()
444         closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
445         return
446 }
447
448 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
449         if cl.ipBlockList == nil {
450                 return
451         }
452         return cl.ipBlockList.Lookup(ip)
453 }
454
455 func (cl *Client) ipIsBlocked(ip net.IP) bool {
456         _, blocked := cl.ipBlockRange(ip)
457         return blocked
458 }
459
460 func (cl *Client) wantConns() bool {
461         if cl.config.AlwaysWantConns {
462                 return true
463         }
464         for _, t := range cl.torrents {
465                 if t.wantConns() {
466                         return true
467                 }
468         }
469         return false
470 }
471
472 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
473 func (cl *Client) rejectAccepted(conn net.Conn) error {
474         if !cl.wantConns() {
475                 return errors.New("don't want conns right now")
476         }
477         ra := conn.RemoteAddr()
478         if rip := addrIpOrNil(ra); rip != nil {
479                 if cl.config.DisableIPv4Peers && rip.To4() != nil {
480                         return errors.New("ipv4 peers disabled")
481                 }
482                 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
483                         return errors.New("ipv4 disabled")
484                 }
485                 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
486                         return errors.New("ipv6 disabled")
487                 }
488                 if cl.rateLimitAccept(rip) {
489                         return errors.New("source IP accepted rate limited")
490                 }
491                 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
492                         return errors.New("bad source addr")
493                 }
494         }
495         return nil
496 }
497
498 func (cl *Client) acceptConnections(l Listener) {
499         for {
500                 conn, err := l.Accept()
501                 torrent.Add("client listener accepts", 1)
502                 conn = pproffd.WrapNetConn(conn)
503                 cl.rLock()
504                 closed := cl.closed.IsSet()
505                 var reject error
506                 if !closed && conn != nil {
507                         reject = cl.rejectAccepted(conn)
508                 }
509                 cl.rUnlock()
510                 if closed {
511                         if conn != nil {
512                                 conn.Close()
513                         }
514                         return
515                 }
516                 if err != nil {
517                         log.Fmsg("error accepting connection: %s", err).LogLevel(log.Debug, cl.logger)
518                         continue
519                 }
520                 go func() {
521                         if reject != nil {
522                                 torrent.Add("rejected accepted connections", 1)
523                                 cl.logger.LazyLog(log.Debug, func() log.Msg {
524                                         return log.Fmsg("rejecting accepted conn: %v", reject)
525                                 })
526                                 conn.Close()
527                         } else {
528                                 go cl.incomingConnection(conn)
529                         }
530                         cl.logger.LazyLog(log.Debug, func() log.Msg {
531                                 return log.Fmsg("accepted %q connection at %q from %q",
532                                         l.Addr().Network(),
533                                         conn.LocalAddr(),
534                                         conn.RemoteAddr(),
535                                 )
536                         })
537                         torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
538                         torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
539                         torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
540                 }()
541         }
542 }
543
544 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
545 func regularNetConnPeerConnConnString(nc net.Conn) string {
546         return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
547 }
548
549 func (cl *Client) incomingConnection(nc net.Conn) {
550         defer nc.Close()
551         if tc, ok := nc.(*net.TCPConn); ok {
552                 tc.SetLinger(0)
553         }
554         remoteAddr, _ := tryIpPortFromNetAddr(nc.RemoteAddr())
555         c := cl.newConnection(
556                 nc,
557                 newConnectionOpts{
558                         outgoing:        false,
559                         remoteAddr:      nc.RemoteAddr(),
560                         localPublicAddr: cl.publicAddr(remoteAddr.IP),
561                         network:         nc.RemoteAddr().Network(),
562                         connString:      regularNetConnPeerConnConnString(nc),
563                 })
564         defer func() {
565                 cl.lock()
566                 defer cl.unlock()
567                 c.close()
568         }()
569         c.Discovery = PeerSourceIncoming
570         cl.runReceivedConn(c)
571 }
572
573 // Returns a handle to the given torrent, if it's present in the client.
574 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
575         cl.rLock()
576         defer cl.rUnlock()
577         t, ok = cl.torrents[ih]
578         return
579 }
580
581 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
582         return cl.torrents[ih]
583 }
584
585 type DialResult struct {
586         Conn   net.Conn
587         Dialer Dialer
588 }
589
590 func countDialResult(err error) {
591         if err == nil {
592                 torrent.Add("successful dials", 1)
593         } else {
594                 torrent.Add("unsuccessful dials", 1)
595         }
596 }
597
598 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit, pendingPeers int) (ret time.Duration) {
599         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
600         if ret < minDialTimeout {
601                 ret = minDialTimeout
602         }
603         return
604 }
605
606 // Returns whether an address is known to connect to a client with our own ID.
607 func (cl *Client) dopplegangerAddr(addr string) bool {
608         _, ok := cl.dopplegangerAddrs[addr]
609         return ok
610 }
611
612 // Returns a connection over UTP or TCP, whichever is first to connect.
613 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
614         return DialFirst(ctx, addr, cl.dialers)
615 }
616
617 // Returns a connection over UTP or TCP, whichever is first to connect.
618 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
619         {
620                 t := perf.NewTimer(perf.CallerName(0))
621                 defer func() {
622                         if res.Conn == nil {
623                                 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
624                         } else {
625                                 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
626                         }
627                 }()
628         }
629         ctx, cancel := context.WithCancel(ctx)
630         // As soon as we return one connection, cancel the others.
631         defer cancel()
632         left := 0
633         resCh := make(chan DialResult, left)
634         for _, _s := range dialers {
635                 left++
636                 s := _s
637                 go func() {
638                         resCh <- DialResult{
639                                 dialFromSocket(ctx, s, addr),
640                                 s,
641                         }
642                 }()
643         }
644         // Wait for a successful connection.
645         func() {
646                 defer perf.ScopeTimer()()
647                 for ; left > 0 && res.Conn == nil; left-- {
648                         res = <-resCh
649                 }
650         }()
651         // There are still incompleted dials.
652         go func() {
653                 for ; left > 0; left-- {
654                         conn := (<-resCh).Conn
655                         if conn != nil {
656                                 conn.Close()
657                         }
658                 }
659         }()
660         if res.Conn != nil {
661                 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
662         }
663         return res
664 }
665
666 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
667         c, err := s.Dial(ctx, addr)
668         // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
669         // it now in case we close the connection forthwith.
670         if tc, ok := c.(*net.TCPConn); ok {
671                 tc.SetLinger(0)
672         }
673         countDialResult(err)
674         return c
675 }
676
677 func forgettableDialError(err error) bool {
678         return strings.Contains(err.Error(), "no suitable address found")
679 }
680
681 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
682         if _, ok := t.halfOpen[addr]; !ok {
683                 panic("invariant broken")
684         }
685         delete(t.halfOpen, addr)
686         cl.numHalfOpen--
687         for _, t := range cl.torrents {
688                 t.openNewConns()
689         }
690 }
691
692 // Performs initiator handshakes and returns a connection. Returns nil *connection if no connection
693 // for valid reasons.
694 func (cl *Client) initiateProtocolHandshakes(
695         ctx context.Context,
696         nc net.Conn,
697         t *Torrent,
698         encryptHeader bool,
699         newConnOpts newConnectionOpts,
700 ) (
701         c *PeerConn, err error,
702 ) {
703         c = cl.newConnection(nc, newConnOpts)
704         c.headerEncrypted = encryptHeader
705         ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
706         defer cancel()
707         dl, ok := ctx.Deadline()
708         if !ok {
709                 panic(ctx)
710         }
711         err = nc.SetDeadline(dl)
712         if err != nil {
713                 panic(err)
714         }
715         err = cl.initiateHandshakes(c, t)
716         return
717 }
718
719 // Returns nil connection and nil error if no connection could be established for valid reasons.
720 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
721         dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
722                 cl.rLock()
723                 defer cl.rUnlock()
724                 return t.dialTimeout()
725         }())
726         defer cancel()
727         dr := cl.dialFirst(dialCtx, addr.String())
728         nc := dr.Conn
729         if nc == nil {
730                 if dialCtx.Err() != nil {
731                         return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
732                 }
733                 return nil, errors.New("dial failed")
734         }
735         addrIpPort, _ := tryIpPortFromNetAddr(addr)
736         c, err := cl.initiateProtocolHandshakes(context.Background(), nc, t, obfuscatedHeader, newConnectionOpts{
737                 outgoing:   true,
738                 remoteAddr: addr,
739                 // It would be possible to retrieve a public IP from the dialer used here?
740                 localPublicAddr: cl.publicAddr(addrIpPort.IP),
741                 network:         dr.Dialer.DialerNetwork(),
742                 connString:      regularNetConnPeerConnConnString(nc),
743         })
744         if err != nil {
745                 nc.Close()
746         }
747         return c, err
748 }
749
750 // Returns nil connection and nil error if no connection could be established
751 // for valid reasons.
752 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
753         torrent.Add("establish outgoing connection", 1)
754         obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
755         c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
756         if err == nil {
757                 torrent.Add("initiated conn with preferred header obfuscation", 1)
758                 return
759         }
760         // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
761         if cl.config.HeaderObfuscationPolicy.RequirePreferred {
762                 // We should have just tried with the preferred header obfuscation. If it was required,
763                 // there's nothing else to try.
764                 return
765         }
766         // Try again with encryption if we didn't earlier, or without if we did.
767         c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
768         if err == nil {
769                 torrent.Add("initiated conn with fallback header obfuscation", 1)
770         }
771         // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
772         return
773 }
774
775 // Called to dial out and run a connection. The addr we're given is already
776 // considered half-open.
777 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
778         cl.dialRateLimiter.Wait(context.Background())
779         c, err := cl.establishOutgoingConn(t, addr)
780         if err == nil {
781                 c.conn.SetWriteDeadline(time.Time{})
782         }
783         cl.lock()
784         defer cl.unlock()
785         // Don't release lock between here and addPeerConn, unless it's for
786         // failure.
787         cl.noLongerHalfOpen(t, addr.String())
788         if err != nil {
789                 if cl.config.Debug {
790                         cl.logger.Levelf(log.Debug, "error establishing outgoing connection to %v: %v", addr, err)
791                 }
792                 return
793         }
794         defer c.close()
795         c.Discovery = ps
796         c.trusted = trusted
797         t.runHandshookConnLoggingErr(c)
798 }
799
800 // The port number for incoming peer connections. 0 if the client isn't listening.
801 func (cl *Client) incomingPeerPort() int {
802         return cl.LocalPort()
803 }
804
805 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
806         if c.headerEncrypted {
807                 var rw io.ReadWriter
808                 var err error
809                 rw, c.cryptoMethod, err = mse.InitiateHandshake(
810                         struct {
811                                 io.Reader
812                                 io.Writer
813                         }{c.r, c.w},
814                         t.infoHash[:],
815                         nil,
816                         cl.config.CryptoProvides,
817                 )
818                 c.setRW(rw)
819                 if err != nil {
820                         return fmt.Errorf("header obfuscation handshake: %w", err)
821                 }
822         }
823         ih, err := cl.connBtHandshake(c, &t.infoHash)
824         if err != nil {
825                 return fmt.Errorf("bittorrent protocol handshake: %w", err)
826         }
827         if ih != t.infoHash {
828                 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
829         }
830         return nil
831 }
832
833 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
834 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
835 func (cl *Client) forSkeys(f func([]byte) bool) {
836         cl.rLock()
837         defer cl.rUnlock()
838         if false { // Emulate the bug from #114
839                 var firstIh InfoHash
840                 for ih := range cl.torrents {
841                         firstIh = ih
842                         break
843                 }
844                 for range cl.torrents {
845                         if !f(firstIh[:]) {
846                                 break
847                         }
848                 }
849                 return
850         }
851         for ih := range cl.torrents {
852                 if !f(ih[:]) {
853                         break
854                 }
855         }
856 }
857
858 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
859         if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
860                 return ret
861         }
862         return cl.forSkeys
863 }
864
865 // Do encryption and bittorrent handshakes as receiver.
866 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
867         defer perf.ScopeTimerErr(&err)()
868         var rw io.ReadWriter
869         rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
870         c.setRW(rw)
871         if err == nil || err == mse.ErrNoSecretKeyMatch {
872                 if c.headerEncrypted {
873                         torrent.Add("handshakes received encrypted", 1)
874                 } else {
875                         torrent.Add("handshakes received unencrypted", 1)
876                 }
877         } else {
878                 torrent.Add("handshakes received with error while handling encryption", 1)
879         }
880         if err != nil {
881                 if err == mse.ErrNoSecretKeyMatch {
882                         err = nil
883                 }
884                 return
885         }
886         if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
887                 err = errors.New("connection does not have required header obfuscation")
888                 return
889         }
890         ih, err := cl.connBtHandshake(c, nil)
891         if err != nil {
892                 return nil, fmt.Errorf("during bt handshake: %w", err)
893         }
894         cl.lock()
895         t = cl.torrents[ih]
896         cl.unlock()
897         return
898 }
899
900 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
901
902 func init() {
903         torrent.Set(
904                 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
905                 &successfulPeerWireProtocolHandshakePeerReservedBytes)
906 }
907
908 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
909         res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
910         if err != nil {
911                 return
912         }
913         successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
914         ret = res.Hash
915         c.PeerExtensionBytes = res.PeerExtensionBits
916         c.PeerID = res.PeerID
917         c.completedHandshake = time.Now()
918         if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
919                 cb(c, res.Hash)
920         }
921         return
922 }
923
924 func (cl *Client) runReceivedConn(c *PeerConn) {
925         err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
926         if err != nil {
927                 panic(err)
928         }
929         t, err := cl.receiveHandshakes(c)
930         if err != nil {
931                 cl.logger.LazyLog(log.Debug, func() log.Msg {
932                         return log.Fmsg(
933                                 "error receiving handshakes on %v: %s", c, err,
934                         ).Add(
935                                 "network", c.Network,
936                         )
937                 })
938                 torrent.Add("error receiving handshake", 1)
939                 cl.lock()
940                 cl.onBadAccept(c.RemoteAddr)
941                 cl.unlock()
942                 return
943         }
944         if t == nil {
945                 torrent.Add("received handshake for unloaded torrent", 1)
946                 cl.logger.LazyLog(log.Debug, func() log.Msg {
947                         return log.Fmsg("received handshake for unloaded torrent")
948                 })
949                 cl.lock()
950                 cl.onBadAccept(c.RemoteAddr)
951                 cl.unlock()
952                 return
953         }
954         torrent.Add("received handshake for loaded torrent", 1)
955         c.conn.SetWriteDeadline(time.Time{})
956         cl.lock()
957         defer cl.unlock()
958         t.runHandshookConnLoggingErr(c)
959 }
960
961 // Client lock must be held before entering this.
962 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
963         c.setTorrent(t)
964         for i, b := range cl.config.MinPeerExtensions {
965                 if c.PeerExtensionBytes[i]&b != b {
966                         return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes[:])
967                 }
968         }
969         if c.PeerID == cl.peerID {
970                 if c.outgoing {
971                         connsToSelf.Add(1)
972                         addr := c.RemoteAddr.String()
973                         cl.dopplegangerAddrs[addr] = struct{}{}
974                 } /* else {
975                         // Because the remote address is not necessarily the same as its client's torrent listen
976                         // address, we won't record the remote address as a doppleganger. Instead, the initiator
977                         // can record *us* as the doppleganger.
978                 } */
979                 t.logger.Levelf(log.Debug, "local and remote peer ids are the same")
980                 return nil
981         }
982         c.r = deadlineReader{c.conn, c.r}
983         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
984         if connIsIpv6(c.conn) {
985                 torrent.Add("completed handshake over ipv6", 1)
986         }
987         if err := t.addPeerConn(c); err != nil {
988                 return fmt.Errorf("adding connection: %w", err)
989         }
990         defer t.dropConnection(c)
991         c.startMessageWriter()
992         cl.sendInitialMessages(c, t)
993         c.initUpdateRequestsTimer()
994         err := c.mainReadLoop()
995         if err != nil {
996                 return fmt.Errorf("main read loop: %w", err)
997         }
998         return nil
999 }
1000
1001 const check = false
1002
1003 func (p *Peer) initUpdateRequestsTimer() {
1004         if check {
1005                 if p.updateRequestsTimer != nil {
1006                         panic(p.updateRequestsTimer)
1007                 }
1008         }
1009         if enableUpdateRequestsTimer {
1010                 p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
1011         }
1012 }
1013
1014 const peerUpdateRequestsTimerReason = "updateRequestsTimer"
1015
1016 func (c *Peer) updateRequestsTimerFunc() {
1017         c.locker().Lock()
1018         defer c.locker().Unlock()
1019         if c.closed.IsSet() {
1020                 return
1021         }
1022         if c.isLowOnRequests() {
1023                 // If there are no outstanding requests, then a request update should have already run.
1024                 return
1025         }
1026         if d := time.Since(c.lastRequestUpdate); d < updateRequestsTimerDuration {
1027                 // These should be benign, Timer.Stop doesn't guarantee that its function won't run if it's
1028                 // already been fired.
1029                 torrent.Add("spurious timer requests updates", 1)
1030                 return
1031         }
1032         c.updateRequests(peerUpdateRequestsTimerReason)
1033 }
1034
1035 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1036 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1037 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1038 const localClientReqq = 1024
1039
1040 // See the order given in Transmission's tr_peerMsgsNew.
1041 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1042         if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1043                 conn.write(pp.Message{
1044                         Type:       pp.Extended,
1045                         ExtendedID: pp.HandshakeExtendedID,
1046                         ExtendedPayload: func() []byte {
1047                                 msg := pp.ExtendedHandshakeMessage{
1048                                         M: map[pp.ExtensionName]pp.ExtensionNumber{
1049                                                 pp.ExtensionNameMetadata: metadataExtendedId,
1050                                         },
1051                                         V:            cl.config.ExtendedHandshakeClientVersion,
1052                                         Reqq:         localClientReqq,
1053                                         YourIp:       pp.CompactIp(conn.remoteIp()),
1054                                         Encryption:   cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1055                                         Port:         cl.incomingPeerPort(),
1056                                         MetadataSize: torrent.metadataSize(),
1057                                         // TODO: We can figured these out specific to the socket
1058                                         // used.
1059                                         Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1060                                         Ipv6: cl.config.PublicIp6.To16(),
1061                                 }
1062                                 if !cl.config.DisablePEX {
1063                                         msg.M[pp.ExtensionNamePex] = pexExtendedId
1064                                 }
1065                                 return bencode.MustMarshal(msg)
1066                         }(),
1067                 })
1068         }
1069         func() {
1070                 if conn.fastEnabled() {
1071                         if torrent.haveAllPieces() {
1072                                 conn.write(pp.Message{Type: pp.HaveAll})
1073                                 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1074                                 return
1075                         } else if !torrent.haveAnyPieces() {
1076                                 conn.write(pp.Message{Type: pp.HaveNone})
1077                                 conn.sentHaves.Clear()
1078                                 return
1079                         }
1080                 }
1081                 conn.postBitfield()
1082         }()
1083         if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1084                 conn.write(pp.Message{
1085                         Type: pp.Port,
1086                         Port: cl.dhtPort(),
1087                 })
1088         }
1089 }
1090
1091 func (cl *Client) dhtPort() (ret uint16) {
1092         if len(cl.dhtServers) == 0 {
1093                 return
1094         }
1095         return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1096 }
1097
1098 func (cl *Client) haveDhtServer() bool {
1099         return len(cl.dhtServers) > 0
1100 }
1101
1102 // Process incoming ut_metadata message.
1103 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1104         var d pp.ExtendedMetadataRequestMsg
1105         err := bencode.Unmarshal(payload, &d)
1106         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1107         } else if err != nil {
1108                 return fmt.Errorf("error unmarshalling bencode: %s", err)
1109         }
1110         piece := d.Piece
1111         switch d.Type {
1112         case pp.DataMetadataExtensionMsgType:
1113                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1114                 if !c.requestedMetadataPiece(piece) {
1115                         return fmt.Errorf("got unexpected piece %d", piece)
1116                 }
1117                 c.metadataRequests[piece] = false
1118                 begin := len(payload) - d.PieceSize()
1119                 if begin < 0 || begin >= len(payload) {
1120                         return fmt.Errorf("data has bad offset in payload: %d", begin)
1121                 }
1122                 t.saveMetadataPiece(piece, payload[begin:])
1123                 c.lastUsefulChunkReceived = time.Now()
1124                 err = t.maybeCompleteMetadata()
1125                 if err != nil {
1126                         // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1127                         // don't know who to blame. TODO: Also errors can be returned here that aren't related
1128                         // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1129                         // log consumers can filter for this message.
1130                         t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1131                 }
1132                 return err
1133         case pp.RequestMetadataExtensionMsgType:
1134                 if !t.haveMetadataPiece(piece) {
1135                         c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1136                         return nil
1137                 }
1138                 start := (1 << 14) * piece
1139                 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1140                 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1141                 return nil
1142         case pp.RejectMetadataExtensionMsgType:
1143                 return nil
1144         default:
1145                 return errors.New("unknown msg_type value")
1146         }
1147 }
1148
1149 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1150         if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1151                 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1152         }
1153         return false
1154 }
1155
1156 // Returns whether the IP address and port are considered "bad".
1157 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1158         if port == 0 || ip == nil {
1159                 return true
1160         }
1161         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1162                 return true
1163         }
1164         if _, ok := cl.ipBlockRange(ip); ok {
1165                 return true
1166         }
1167         ipAddr, ok := netip.AddrFromSlice(ip)
1168         if !ok {
1169                 panic(ip)
1170         }
1171         if _, ok := cl.badPeerIPs[ipAddr]; ok {
1172                 return true
1173         }
1174         return false
1175 }
1176
1177 // Return a Torrent ready for insertion into a Client.
1178 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1179         return cl.newTorrentOpt(AddTorrentOpts{
1180                 InfoHash: ih,
1181                 Storage:  specStorage,
1182         })
1183 }
1184
1185 // Return a Torrent ready for insertion into a Client.
1186 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1187         // use provided storage, if provided
1188         storageClient := cl.defaultStorage
1189         if opts.Storage != nil {
1190                 storageClient = storage.NewClient(opts.Storage)
1191         }
1192
1193         t = &Torrent{
1194                 cl:       cl,
1195                 infoHash: opts.InfoHash,
1196                 peers: prioritizedPeers{
1197                         om: gbtree.New(32),
1198                         getPrio: func(p PeerInfo) peerPriority {
1199                                 ipPort := p.addr()
1200                                 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1201                         },
1202                 },
1203                 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1204
1205                 halfOpen: make(map[string]PeerInfo),
1206
1207                 storageOpener:       storageClient,
1208                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1209
1210                 metadataChanged: sync.Cond{
1211                         L: cl.locker(),
1212                 },
1213                 webSeeds:     make(map[string]*Peer),
1214                 gotMetainfoC: make(chan struct{}),
1215         }
1216         t.smartBanCache.Hash = sha1.Sum
1217         t.smartBanCache.Init()
1218         t.networkingEnabled.Set()
1219         t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString())
1220         t.sourcesLogger = t.logger.WithNames("sources")
1221         if opts.ChunkSize == 0 {
1222                 opts.ChunkSize = defaultChunkSize
1223         }
1224         t.setChunkSize(opts.ChunkSize)
1225         return
1226 }
1227
1228 // A file-like handle to some torrent data resource.
1229 type Handle interface {
1230         io.Reader
1231         io.Seeker
1232         io.Closer
1233         io.ReaderAt
1234 }
1235
1236 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1237         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1238 }
1239
1240 // Adds a torrent by InfoHash with a custom Storage implementation.
1241 // If the torrent already exists then this Storage is ignored and the
1242 // existing torrent returned with `new` set to `false`
1243 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1244         cl.lock()
1245         defer cl.unlock()
1246         t, ok := cl.torrents[infoHash]
1247         if ok {
1248                 return
1249         }
1250         new = true
1251
1252         t = cl.newTorrent(infoHash, specStorage)
1253         cl.eachDhtServer(func(s DhtServer) {
1254                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1255                         go t.dhtAnnouncer(s)
1256                 }
1257         })
1258         cl.torrents[infoHash] = t
1259         cl.clearAcceptLimits()
1260         t.updateWantPeersEvent()
1261         // Tickle Client.waitAccept, new torrent may want conns.
1262         cl.event.Broadcast()
1263         return
1264 }
1265
1266 // Adds a torrent by InfoHash with a custom Storage implementation.
1267 // If the torrent already exists then this Storage is ignored and the
1268 // existing torrent returned with `new` set to `false`
1269 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1270         infoHash := opts.InfoHash
1271         cl.lock()
1272         defer cl.unlock()
1273         t, ok := cl.torrents[infoHash]
1274         if ok {
1275                 return
1276         }
1277         new = true
1278
1279         t = cl.newTorrentOpt(opts)
1280         cl.eachDhtServer(func(s DhtServer) {
1281                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1282                         go t.dhtAnnouncer(s)
1283                 }
1284         })
1285         cl.torrents[infoHash] = t
1286         cl.clearAcceptLimits()
1287         t.updateWantPeersEvent()
1288         // Tickle Client.waitAccept, new torrent may want conns.
1289         cl.event.Broadcast()
1290         return
1291 }
1292
1293 type AddTorrentOpts struct {
1294         InfoHash  InfoHash
1295         Storage   storage.ClientImpl
1296         ChunkSize pp.Integer
1297 }
1298
1299 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1300 // Torrent.MergeSpec.
1301 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1302         t, new = cl.AddTorrentOpt(AddTorrentOpts{
1303                 InfoHash:  spec.InfoHash,
1304                 Storage:   spec.Storage,
1305                 ChunkSize: spec.ChunkSize,
1306         })
1307         modSpec := *spec
1308         if new {
1309                 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1310                 // it.
1311                 modSpec.ChunkSize = 0
1312         }
1313         err = t.MergeSpec(&modSpec)
1314         if err != nil && new {
1315                 t.Drop()
1316         }
1317         return
1318 }
1319
1320 type stringAddr string
1321
1322 var _ net.Addr = stringAddr("")
1323
1324 func (stringAddr) Network() string   { return "" }
1325 func (me stringAddr) String() string { return string(me) }
1326
1327 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1328 // spec.DisallowDataDownload/Upload will be read and applied
1329 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1330 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1331         if spec.DisplayName != "" {
1332                 t.SetDisplayName(spec.DisplayName)
1333         }
1334         if spec.InfoBytes != nil {
1335                 err := t.SetInfoBytes(spec.InfoBytes)
1336                 if err != nil {
1337                         return err
1338                 }
1339         }
1340         cl := t.cl
1341         cl.AddDhtNodes(spec.DhtNodes)
1342         t.UseSources(spec.Sources)
1343         cl.lock()
1344         defer cl.unlock()
1345         t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1346         for _, url := range spec.Webseeds {
1347                 t.addWebSeed(url)
1348         }
1349         for _, peerAddr := range spec.PeerAddrs {
1350                 t.addPeer(PeerInfo{
1351                         Addr:    stringAddr(peerAddr),
1352                         Source:  PeerSourceDirect,
1353                         Trusted: true,
1354                 })
1355         }
1356         if spec.ChunkSize != 0 {
1357                 panic("chunk size cannot be changed for existing Torrent")
1358         }
1359         t.addTrackers(spec.Trackers)
1360         t.maybeNewConns()
1361         t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1362         t.dataUploadDisallowed = spec.DisallowDataUpload
1363         return nil
1364 }
1365
1366 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1367         t, ok := cl.torrents[infoHash]
1368         if !ok {
1369                 err = fmt.Errorf("no such torrent")
1370                 return
1371         }
1372         err = t.close(wg)
1373         delete(cl.torrents, infoHash)
1374         return
1375 }
1376
1377 func (cl *Client) allTorrentsCompleted() bool {
1378         for _, t := range cl.torrents {
1379                 if !t.haveInfo() {
1380                         return false
1381                 }
1382                 if !t.haveAllPieces() {
1383                         return false
1384                 }
1385         }
1386         return true
1387 }
1388
1389 // Returns true when all torrents are completely downloaded and false if the
1390 // client is stopped before that.
1391 func (cl *Client) WaitAll() bool {
1392         cl.lock()
1393         defer cl.unlock()
1394         for !cl.allTorrentsCompleted() {
1395                 if cl.closed.IsSet() {
1396                         return false
1397                 }
1398                 cl.event.Wait()
1399         }
1400         return true
1401 }
1402
1403 // Returns handles to all the torrents loaded in the Client.
1404 func (cl *Client) Torrents() []*Torrent {
1405         cl.rLock()
1406         defer cl.rUnlock()
1407         return cl.torrentsAsSlice()
1408 }
1409
1410 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1411         for _, t := range cl.torrents {
1412                 ret = append(ret, t)
1413         }
1414         return
1415 }
1416
1417 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1418         spec, err := TorrentSpecFromMagnetUri(uri)
1419         if err != nil {
1420                 return
1421         }
1422         T, _, err = cl.AddTorrentSpec(spec)
1423         return
1424 }
1425
1426 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1427         ts, err := TorrentSpecFromMetaInfoErr(mi)
1428         if err != nil {
1429                 return
1430         }
1431         T, _, err = cl.AddTorrentSpec(ts)
1432         return
1433 }
1434
1435 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1436         mi, err := metainfo.LoadFromFile(filename)
1437         if err != nil {
1438                 return
1439         }
1440         return cl.AddTorrent(mi)
1441 }
1442
1443 func (cl *Client) DhtServers() []DhtServer {
1444         return cl.dhtServers
1445 }
1446
1447 func (cl *Client) AddDhtNodes(nodes []string) {
1448         for _, n := range nodes {
1449                 hmp := missinggo.SplitHostMaybePort(n)
1450                 ip := net.ParseIP(hmp.Host)
1451                 if ip == nil {
1452                         cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1453                         continue
1454                 }
1455                 ni := krpc.NodeInfo{
1456                         Addr: krpc.NodeAddr{
1457                                 IP:   ip,
1458                                 Port: hmp.Port,
1459                         },
1460                 }
1461                 cl.eachDhtServer(func(s DhtServer) {
1462                         s.AddNode(ni)
1463                 })
1464         }
1465 }
1466
1467 func (cl *Client) banPeerIP(ip net.IP) {
1468         // We can't take this from string, because it will lose netip's v4on6. net.ParseIP parses v4
1469         // addresses directly to v4on6, which doesn't compare equal with v4.
1470         ipAddr, ok := netip.AddrFromSlice(ip)
1471         if !ok {
1472                 panic(ip)
1473         }
1474         generics.MakeMapIfNilAndSet(&cl.badPeerIPs, ipAddr, struct{}{})
1475         for _, t := range cl.torrents {
1476                 t.iterPeers(func(p *Peer) {
1477                         if p.remoteIp().Equal(ip) {
1478                                 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1479                                 // Should this be a close?
1480                                 p.drop()
1481                         }
1482                 })
1483         }
1484 }
1485
1486 type newConnectionOpts struct {
1487         outgoing        bool
1488         remoteAddr      PeerRemoteAddr
1489         localPublicAddr peerLocalPublicAddr
1490         network         string
1491         connString      string
1492 }
1493
1494 func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerConn) {
1495         if opts.network == "" {
1496                 panic(opts.remoteAddr)
1497         }
1498         c = &PeerConn{
1499                 Peer: Peer{
1500                         outgoing:        opts.outgoing,
1501                         choking:         true,
1502                         peerChoking:     true,
1503                         PeerMaxRequests: 250,
1504
1505                         RemoteAddr:      opts.remoteAddr,
1506                         localPublicAddr: opts.localPublicAddr,
1507                         Network:         opts.network,
1508                         callbacks:       &cl.config.Callbacks,
1509                 },
1510                 connString: opts.connString,
1511                 conn:       nc,
1512         }
1513         c.initRequestState()
1514         // TODO: Need to be much more explicit about this, including allowing non-IP bannable addresses.
1515         if opts.remoteAddr != nil {
1516                 netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
1517                 if err == nil {
1518                         c.bannableAddr = Some(netipAddrPort.Addr())
1519                 }
1520         }
1521         c.peerImpl = c
1522         c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1523         c.setRW(connStatsReadWriter{nc, c})
1524         c.r = &rateLimitedReader{
1525                 l: cl.config.DownloadRateLimiter,
1526                 r: c.r,
1527         }
1528         c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", opts.remoteAddr, opts.network, opts.outgoing)
1529         for _, f := range cl.config.Callbacks.NewPeer {
1530                 f(&c.Peer)
1531         }
1532         return
1533 }
1534
1535 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1536         cl.lock()
1537         defer cl.unlock()
1538         t := cl.torrent(ih)
1539         if t == nil {
1540                 return
1541         }
1542         t.addPeers([]PeerInfo{{
1543                 Addr:   ipPortAddr{ip, port},
1544                 Source: PeerSourceDhtAnnouncePeer,
1545         }})
1546 }
1547
1548 func firstNotNil(ips ...net.IP) net.IP {
1549         for _, ip := range ips {
1550                 if ip != nil {
1551                         return ip
1552                 }
1553         }
1554         return nil
1555 }
1556
1557 func (cl *Client) eachListener(f func(Listener) bool) {
1558         for _, s := range cl.listeners {
1559                 if !f(s) {
1560                         break
1561                 }
1562         }
1563 }
1564
1565 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1566         for i := 0; i < len(cl.listeners); i += 1 {
1567                 if ret = cl.listeners[i]; f(ret) {
1568                         return
1569                 }
1570         }
1571         return nil
1572 }
1573
1574 func (cl *Client) publicIp(peer net.IP) net.IP {
1575         // TODO: Use BEP 10 to determine how peers are seeing us.
1576         if peer.To4() != nil {
1577                 return firstNotNil(
1578                         cl.config.PublicIp4,
1579                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1580                 )
1581         }
1582
1583         return firstNotNil(
1584                 cl.config.PublicIp6,
1585                 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1586         )
1587 }
1588
1589 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1590         l := cl.findListener(
1591                 func(l Listener) bool {
1592                         return f(addrIpOrNil(l.Addr()))
1593                 },
1594         )
1595         if l == nil {
1596                 return nil
1597         }
1598         return addrIpOrNil(l.Addr())
1599 }
1600
1601 // Our IP as a peer should see it.
1602 func (cl *Client) publicAddr(peer net.IP) IpPort {
1603         return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1604 }
1605
1606 // ListenAddrs addresses currently being listened to.
1607 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1608         cl.lock()
1609         ret = make([]net.Addr, len(cl.listeners))
1610         for i := 0; i < len(cl.listeners); i += 1 {
1611                 ret[i] = cl.listeners[i].Addr()
1612         }
1613         cl.unlock()
1614         return
1615 }
1616
1617 func (cl *Client) PublicIPs() (ips []net.IP) {
1618         if ip := cl.config.PublicIp4; ip != nil {
1619                 ips = append(ips, ip)
1620         }
1621         if ip := cl.config.PublicIp6; ip != nil {
1622                 ips = append(ips, ip)
1623         }
1624         return
1625 }
1626
1627 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1628         ipa, ok := tryIpPortFromNetAddr(addr)
1629         if !ok {
1630                 return
1631         }
1632         ip := maskIpForAcceptLimiting(ipa.IP)
1633         if cl.acceptLimiter == nil {
1634                 cl.acceptLimiter = make(map[ipStr]int)
1635         }
1636         cl.acceptLimiter[ipStr(ip.String())]++
1637 }
1638
1639 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1640         if ip4 := ip.To4(); ip4 != nil {
1641                 return ip4.Mask(net.CIDRMask(24, 32))
1642         }
1643         return ip
1644 }
1645
1646 func (cl *Client) clearAcceptLimits() {
1647         cl.acceptLimiter = nil
1648 }
1649
1650 func (cl *Client) acceptLimitClearer() {
1651         for {
1652                 select {
1653                 case <-cl.closed.Done():
1654                         return
1655                 case <-time.After(15 * time.Minute):
1656                         cl.lock()
1657                         cl.clearAcceptLimits()
1658                         cl.unlock()
1659                 }
1660         }
1661 }
1662
1663 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1664         if cl.config.DisableAcceptRateLimiting {
1665                 return false
1666         }
1667         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1668 }
1669
1670 func (cl *Client) rLock() {
1671         cl._mu.RLock()
1672 }
1673
1674 func (cl *Client) rUnlock() {
1675         cl._mu.RUnlock()
1676 }
1677
1678 func (cl *Client) lock() {
1679         cl._mu.Lock()
1680 }
1681
1682 func (cl *Client) unlock() {
1683         cl._mu.Unlock()
1684 }
1685
1686 func (cl *Client) locker() *lockWithDeferreds {
1687         return &cl._mu
1688 }
1689
1690 func (cl *Client) String() string {
1691         return fmt.Sprintf("<%[1]T %[1]p>", cl)
1692 }
1693
1694 // Returns connection-level aggregate stats at the Client level. See the comment on
1695 // TorrentStats.ConnStats.
1696 func (cl *Client) ConnStats() ConnStats {
1697         return cl.stats.Copy()
1698 }