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