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