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