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