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