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