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