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