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