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