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