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