]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
PEX: add periodic deltas
[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 (cl *Client) incomingConnection(nc net.Conn) {
465         defer nc.Close()
466         if tc, ok := nc.(*net.TCPConn); ok {
467                 tc.SetLinger(0)
468         }
469         c := cl.newConnection(nc, false, nc.RemoteAddr(), nc.RemoteAddr().Network())
470         c.Discovery = PeerSourceIncoming
471         cl.runReceivedConn(c)
472 }
473
474 // Returns a handle to the given torrent, if it's present in the client.
475 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
476         cl.lock()
477         defer cl.unlock()
478         t, ok = cl.torrents[ih]
479         return
480 }
481
482 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
483         return cl.torrents[ih]
484 }
485
486 type dialResult struct {
487         Conn    net.Conn
488         Network string
489 }
490
491 func countDialResult(err error) {
492         if err == nil {
493                 torrent.Add("successful dials", 1)
494         } else {
495                 torrent.Add("unsuccessful dials", 1)
496         }
497 }
498
499 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
500         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
501         if ret < minDialTimeout {
502                 ret = minDialTimeout
503         }
504         return
505 }
506
507 // Returns whether an address is known to connect to a client with our own ID.
508 func (cl *Client) dopplegangerAddr(addr string) bool {
509         _, ok := cl.dopplegangerAddrs[addr]
510         return ok
511 }
512
513 // Returns a connection over UTP or TCP, whichever is first to connect.
514 func (cl *Client) dialFirst(ctx context.Context, addr string) (res dialResult) {
515         {
516                 t := perf.NewTimer(perf.CallerName(0))
517                 defer func() {
518                         if res.Conn == nil {
519                                 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
520                         } else {
521                                 t.Mark("returned conn over " + res.Network)
522                         }
523                 }()
524         }
525         ctx, cancel := context.WithCancel(ctx)
526         // As soon as we return one connection, cancel the others.
527         defer cancel()
528         left := 0
529         resCh := make(chan dialResult, left)
530         func() {
531                 cl.lock()
532                 defer cl.unlock()
533                 cl.eachDialer(func(s Dialer) bool {
534                         func() {
535                                 left++
536                                 //cl.logger.Printf("dialing %s on %s/%s", addr, s.Addr().Network(), s.Addr())
537                                 go func() {
538                                         resCh <- dialResult{
539                                                 cl.dialFromSocket(ctx, s, addr),
540                                                 s.LocalAddr().Network(),
541                                         }
542                                 }()
543                         }()
544                         return true
545                 })
546         }()
547         // Wait for a successful connection.
548         func() {
549                 defer perf.ScopeTimer()()
550                 for ; left > 0 && res.Conn == nil; left-- {
551                         res = <-resCh
552                 }
553         }()
554         // There are still incompleted dials.
555         go func() {
556                 for ; left > 0; left-- {
557                         conn := (<-resCh).Conn
558                         if conn != nil {
559                                 conn.Close()
560                         }
561                 }
562         }()
563         if res.Conn != nil {
564                 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
565         }
566         //if res.Conn != nil {
567         //      cl.logger.Printf("first connection for %s from %s/%s", addr, res.Conn.LocalAddr().Network(), res.Conn.LocalAddr().String())
568         //} else {
569         //      cl.logger.Printf("failed to dial %s", addr)
570         //}
571         return res
572 }
573
574 func (cl *Client) dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
575         network := s.LocalAddr().Network()
576         cte := cl.config.ConnTracker.Wait(
577                 ctx,
578                 conntrack.Entry{network, s.LocalAddr().String(), addr},
579                 "dial torrent client",
580                 0,
581         )
582         // Try to avoid committing to a dial if the context is complete as it's difficult to determine
583         // which dial errors allow us to forget the connection tracking entry handle.
584         if ctx.Err() != nil {
585                 if cte != nil {
586                         cte.Forget()
587                 }
588                 return nil
589         }
590         c, err := s.Dial(ctx, addr)
591         // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
592         // it now in case we close the connection forthwith.
593         if tc, ok := c.(*net.TCPConn); ok {
594                 tc.SetLinger(0)
595         }
596         countDialResult(err)
597         if c == nil {
598                 if err != nil && forgettableDialError(err) {
599                         cte.Forget()
600                 } else {
601                         cte.Done()
602                 }
603                 return nil
604         }
605         return closeWrapper{c, func() error {
606                 err := c.Close()
607                 cte.Done()
608                 return err
609         }}
610 }
611
612 func forgettableDialError(err error) bool {
613         return strings.Contains(err.Error(), "no suitable address found")
614 }
615
616 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
617         if _, ok := t.halfOpen[addr]; !ok {
618                 panic("invariant broken")
619         }
620         delete(t.halfOpen, addr)
621         t.openNewConns()
622 }
623
624 // Performs initiator handshakes and returns a connection. Returns nil
625 // *connection if no connection for valid reasons.
626 func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader bool, remoteAddr net.Addr, network string) (c *PeerConn, err error) {
627         c = cl.newConnection(nc, true, remoteAddr, network)
628         c.headerEncrypted = encryptHeader
629         ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
630         defer cancel()
631         dl, ok := ctx.Deadline()
632         if !ok {
633                 panic(ctx)
634         }
635         err = nc.SetDeadline(dl)
636         if err != nil {
637                 panic(err)
638         }
639         err = cl.initiateHandshakes(c, t)
640         return
641 }
642
643 // Returns nil connection and nil error if no connection could be established
644 // for valid reasons.
645 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr net.Addr, obfuscatedHeader bool) (*PeerConn, error) {
646         dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
647                 cl.rLock()
648                 defer cl.rUnlock()
649                 return t.dialTimeout()
650         }())
651         defer cancel()
652         dr := cl.dialFirst(dialCtx, addr.String())
653         nc := dr.Conn
654         if nc == nil {
655                 if dialCtx.Err() != nil {
656                         return nil, xerrors.Errorf("dialing: %w", dialCtx.Err())
657                 }
658                 return nil, errors.New("dial failed")
659         }
660         c, err := cl.handshakesConnection(context.Background(), nc, t, obfuscatedHeader, addr, dr.Network)
661         if err != nil {
662                 nc.Close()
663         }
664         return c, err
665 }
666
667 // Returns nil connection and nil error if no connection could be established
668 // for valid reasons.
669 func (cl *Client) establishOutgoingConn(t *Torrent, addr net.Addr) (c *PeerConn, err error) {
670         torrent.Add("establish outgoing connection", 1)
671         obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
672         c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
673         if err == nil {
674                 torrent.Add("initiated conn with preferred header obfuscation", 1)
675                 return
676         }
677         //cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
678         if cl.config.HeaderObfuscationPolicy.RequirePreferred {
679                 // We should have just tried with the preferred header obfuscation. If it was required,
680                 // there's nothing else to try.
681                 return
682         }
683         // Try again with encryption if we didn't earlier, or without if we did.
684         c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
685         if err == nil {
686                 torrent.Add("initiated conn with fallback header obfuscation", 1)
687         }
688         //cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
689         return
690 }
691
692 // Called to dial out and run a connection. The addr we're given is already
693 // considered half-open.
694 func (cl *Client) outgoingConnection(t *Torrent, addr net.Addr, ps PeerSource, trusted bool) {
695         cl.dialRateLimiter.Wait(context.Background())
696         c, err := cl.establishOutgoingConn(t, addr)
697         cl.lock()
698         defer cl.unlock()
699         // Don't release lock between here and addConnection, unless it's for
700         // failure.
701         cl.noLongerHalfOpen(t, addr.String())
702         if err != nil {
703                 if cl.config.Debug {
704                         cl.logger.Printf("error establishing outgoing connection to %v: %v", addr, err)
705                 }
706                 return
707         }
708         defer c.close()
709         c.Discovery = ps
710         c.trusted = trusted
711         cl.runHandshookConn(c, t)
712 }
713
714 // The port number for incoming peer connections. 0 if the client isn't listening.
715 func (cl *Client) incomingPeerPort() int {
716         return cl.LocalPort()
717 }
718
719 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
720         if c.headerEncrypted {
721                 var rw io.ReadWriter
722                 var err error
723                 rw, c.cryptoMethod, err = mse.InitiateHandshake(
724                         struct {
725                                 io.Reader
726                                 io.Writer
727                         }{c.r, c.w},
728                         t.infoHash[:],
729                         nil,
730                         cl.config.CryptoProvides,
731                 )
732                 c.setRW(rw)
733                 if err != nil {
734                         return xerrors.Errorf("header obfuscation handshake: %w", err)
735                 }
736         }
737         ih, err := cl.connBtHandshake(c, &t.infoHash)
738         if err != nil {
739                 return xerrors.Errorf("bittorrent protocol handshake: %w", err)
740         }
741         if ih != t.infoHash {
742                 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
743         }
744         return nil
745 }
746
747 // Calls f with any secret keys.
748 func (cl *Client) forSkeys(f func([]byte) bool) {
749         cl.lock()
750         defer cl.unlock()
751         if false { // Emulate the bug from #114
752                 var firstIh InfoHash
753                 for ih := range cl.torrents {
754                         firstIh = ih
755                         break
756                 }
757                 for range cl.torrents {
758                         if !f(firstIh[:]) {
759                                 break
760                         }
761                 }
762                 return
763         }
764         for ih := range cl.torrents {
765                 if !f(ih[:]) {
766                         break
767                 }
768         }
769 }
770
771 // Do encryption and bittorrent handshakes as receiver.
772 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
773         defer perf.ScopeTimerErr(&err)()
774         var rw io.ReadWriter
775         rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
776         c.setRW(rw)
777         if err == nil || err == mse.ErrNoSecretKeyMatch {
778                 if c.headerEncrypted {
779                         torrent.Add("handshakes received encrypted", 1)
780                 } else {
781                         torrent.Add("handshakes received unencrypted", 1)
782                 }
783         } else {
784                 torrent.Add("handshakes received with error while handling encryption", 1)
785         }
786         if err != nil {
787                 if err == mse.ErrNoSecretKeyMatch {
788                         err = nil
789                 }
790                 return
791         }
792         if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
793                 err = errors.New("connection not have required header obfuscation")
794                 return
795         }
796         ih, err := cl.connBtHandshake(c, nil)
797         if err != nil {
798                 err = xerrors.Errorf("during bt handshake: %w", err)
799                 return
800         }
801         cl.lock()
802         t = cl.torrents[ih]
803         cl.unlock()
804         return
805 }
806
807 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
808         res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
809         if err != nil {
810                 return
811         }
812         ret = res.Hash
813         c.PeerExtensionBytes = res.PeerExtensionBits
814         c.PeerID = res.PeerID
815         c.completedHandshake = time.Now()
816         return
817 }
818
819 func (cl *Client) runReceivedConn(c *PeerConn) {
820         err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
821         if err != nil {
822                 panic(err)
823         }
824         t, err := cl.receiveHandshakes(c)
825         if err != nil {
826                 log.Fmsg(
827                         "error receiving handshakes on %v: %s", c, err,
828                 ).AddValue(
829                         debugLogValue,
830                 ).Add(
831                         "network", c.network,
832                 ).Log(cl.logger)
833                 torrent.Add("error receiving handshake", 1)
834                 cl.lock()
835                 cl.onBadAccept(c.remoteAddr)
836                 cl.unlock()
837                 return
838         }
839         if t == nil {
840                 torrent.Add("received handshake for unloaded torrent", 1)
841                 log.Fmsg("received handshake for unloaded torrent").AddValue(debugLogValue).Log(cl.logger)
842                 cl.lock()
843                 cl.onBadAccept(c.remoteAddr)
844                 cl.unlock()
845                 return
846         }
847         torrent.Add("received handshake for loaded torrent", 1)
848         cl.lock()
849         defer cl.unlock()
850         cl.runHandshookConn(c, t)
851 }
852
853 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) {
854         c.setTorrent(t)
855         if c.PeerID == cl.peerID {
856                 if c.outgoing {
857                         connsToSelf.Add(1)
858                         addr := c.conn.RemoteAddr().String()
859                         cl.dopplegangerAddrs[addr] = struct{}{}
860                 } else {
861                         // Because the remote address is not necessarily the same as its client's torrent listen
862                         // address, we won't record the remote address as a doppleganger. Instead, the initiator
863                         // can record *us* as the doppleganger.
864                 }
865                 return
866         }
867         c.conn.SetWriteDeadline(time.Time{})
868         c.r = deadlineReader{c.conn, c.r}
869         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
870         if connIsIpv6(c.conn) {
871                 torrent.Add("completed handshake over ipv6", 1)
872         }
873         if err := t.addConnection(c); err != nil {
874                 log.Fmsg("error adding connection: %s", err).AddValues(c, debugLogValue).Log(t.logger)
875                 return
876         }
877         defer t.dropConnection(c)
878         go c.writer(time.Minute)
879         cl.sendInitialMessages(c, t)
880         err := c.mainReadLoop()
881         if err != nil && cl.config.Debug {
882                 cl.logger.Printf("error during connection main read loop: %s", err)
883         }
884 }
885
886 // See the order given in Transmission's tr_peerMsgsNew.
887 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
888         if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
889                 conn.post(pp.Message{
890                         Type:       pp.Extended,
891                         ExtendedID: pp.HandshakeExtendedID,
892                         ExtendedPayload: func() []byte {
893                                 msg := pp.ExtendedHandshakeMessage{
894                                         M: map[pp.ExtensionName]pp.ExtensionNumber{
895                                                 pp.ExtensionNameMetadata: metadataExtendedId,
896                                         },
897                                         V:            cl.config.ExtendedHandshakeClientVersion,
898                                         Reqq:         64, // TODO: Really?
899                                         YourIp:       pp.CompactIp(addrIpOrNil(conn.remoteAddr)),
900                                         Encryption:   cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
901                                         Port:         cl.incomingPeerPort(),
902                                         MetadataSize: torrent.metadataSize(),
903                                         // TODO: We can figured these out specific to the socket
904                                         // used.
905                                         Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
906                                         Ipv6: cl.config.PublicIp6.To16(),
907                                 }
908                                 if !cl.config.DisablePEX {
909                                         msg.M[pp.ExtensionNamePex] = pexExtendedId
910                                 }
911                                 return bencode.MustMarshal(msg)
912                         }(),
913                 })
914         }
915         func() {
916                 if conn.fastEnabled() {
917                         if torrent.haveAllPieces() {
918                                 conn.post(pp.Message{Type: pp.HaveAll})
919                                 conn.sentHaves.AddRange(0, bitmap.BitIndex(conn.t.NumPieces()))
920                                 return
921                         } else if !torrent.haveAnyPieces() {
922                                 conn.post(pp.Message{Type: pp.HaveNone})
923                                 conn.sentHaves.Clear()
924                                 return
925                         }
926                 }
927                 conn.postBitfield()
928         }()
929         if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.haveDhtServer() {
930                 conn.post(pp.Message{
931                         Type: pp.Port,
932                         Port: cl.dhtPort(),
933                 })
934         }
935 }
936
937 func (cl *Client) dhtPort() (ret uint16) {
938         cl.eachDhtServer(func(s DhtServer) {
939                 ret = uint16(missinggo.AddrPort(s.Addr()))
940         })
941         return
942 }
943
944 func (cl *Client) haveDhtServer() (ret bool) {
945         cl.eachDhtServer(func(_ DhtServer) {
946                 ret = true
947         })
948         return
949 }
950
951 // Process incoming ut_metadata message.
952 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
953         var d map[string]int
954         err := bencode.Unmarshal(payload, &d)
955         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
956         } else if err != nil {
957                 return fmt.Errorf("error unmarshalling bencode: %s", err)
958         }
959         msgType, ok := d["msg_type"]
960         if !ok {
961                 return errors.New("missing msg_type field")
962         }
963         piece := d["piece"]
964         switch msgType {
965         case pp.DataMetadataExtensionMsgType:
966                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
967                 if !c.requestedMetadataPiece(piece) {
968                         return fmt.Errorf("got unexpected piece %d", piece)
969                 }
970                 c.metadataRequests[piece] = false
971                 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
972                 if begin < 0 || begin >= len(payload) {
973                         return fmt.Errorf("data has bad offset in payload: %d", begin)
974                 }
975                 t.saveMetadataPiece(piece, payload[begin:])
976                 c.lastUsefulChunkReceived = time.Now()
977                 return t.maybeCompleteMetadata()
978         case pp.RequestMetadataExtensionMsgType:
979                 if !t.haveMetadataPiece(piece) {
980                         c.post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
981                         return nil
982                 }
983                 start := (1 << 14) * piece
984                 c.logger.Printf("sending metadata piece %d", piece)
985                 c.post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
986                 return nil
987         case pp.RejectMetadataExtensionMsgType:
988                 return nil
989         default:
990                 return errors.New("unknown msg_type value")
991         }
992 }
993
994 func (cl *Client) badPeerAddr(addr net.Addr) bool {
995         if ipa, ok := tryIpPortFromNetAddr(addr); ok {
996                 return cl.badPeerIPPort(ipa.IP, ipa.Port)
997         }
998         return false
999 }
1000
1001 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1002         if port == 0 {
1003                 return true
1004         }
1005         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1006                 return true
1007         }
1008         if _, ok := cl.ipBlockRange(ip); ok {
1009                 return true
1010         }
1011         if _, ok := cl.badPeerIPs[ip.String()]; ok {
1012                 return true
1013         }
1014         return false
1015 }
1016
1017 // Return a Torrent ready for insertion into a Client.
1018 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1019         // use provided storage, if provided
1020         storageClient := cl.defaultStorage
1021         if specStorage != nil {
1022                 storageClient = storage.NewClient(specStorage)
1023         }
1024
1025         t = &Torrent{
1026                 cl:       cl,
1027                 infoHash: ih,
1028                 peers: prioritizedPeers{
1029                         om: btree.New(32),
1030                         getPrio: func(p Peer) peerPriority {
1031                                 return bep40PriorityIgnoreError(cl.publicAddr(addrIpOrNil(p.Addr)), p.addr())
1032                         },
1033                 },
1034                 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1035
1036                 halfOpen:          make(map[string]Peer),
1037                 pieceStateChanges: pubsub.NewPubSub(),
1038
1039                 storageOpener:       storageClient,
1040                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1041
1042                 networkingEnabled: true,
1043                 metadataChanged: sync.Cond{
1044                         L: cl.locker(),
1045                 },
1046         }
1047         t._pendingPieces.NewSet = priorityBitmapStableNewSet
1048         t.requestStrategy = cl.config.DefaultRequestStrategy(t.requestStrategyCallbacks(), &cl._mu)
1049         t.logger = cl.logger.WithValues(t).WithText(func(m log.Msg) string {
1050                 return fmt.Sprintf("%v: %s", t, m.Text())
1051         })
1052         t.setChunkSize(defaultChunkSize)
1053         return
1054 }
1055
1056 // A file-like handle to some torrent data resource.
1057 type Handle interface {
1058         io.Reader
1059         io.Seeker
1060         io.Closer
1061         io.ReaderAt
1062 }
1063
1064 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1065         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1066 }
1067
1068 // Adds a torrent by InfoHash with a custom Storage implementation.
1069 // If the torrent already exists then this Storage is ignored and the
1070 // existing torrent returned with `new` set to `false`
1071 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1072         cl.lock()
1073         defer cl.unlock()
1074         t, ok := cl.torrents[infoHash]
1075         if ok {
1076                 return
1077         }
1078         new = true
1079
1080         t = cl.newTorrent(infoHash, specStorage)
1081         cl.eachDhtServer(func(s DhtServer) {
1082                 go t.dhtAnnouncer(s)
1083         })
1084         cl.torrents[infoHash] = t
1085         cl.clearAcceptLimits()
1086         t.updateWantPeersEvent()
1087         // Tickle Client.waitAccept, new torrent may want conns.
1088         cl.event.Broadcast()
1089         return
1090 }
1091
1092 // Add or merge a torrent spec. If the torrent is already present, the
1093 // trackers will be merged with the existing ones. If the Info isn't yet
1094 // known, it will be set. The display name is replaced if the new spec
1095 // provides one. Returns new if the torrent wasn't already in the client.
1096 // Note that any `Storage` defined on the spec will be ignored if the
1097 // torrent is already present (i.e. `new` return value is `true`)
1098 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1099         t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1100         if spec.DisplayName != "" {
1101                 t.SetDisplayName(spec.DisplayName)
1102         }
1103         if spec.InfoBytes != nil {
1104                 err = t.SetInfoBytes(spec.InfoBytes)
1105                 if err != nil {
1106                         return
1107                 }
1108         }
1109         cl.lock()
1110         defer cl.unlock()
1111         if spec.ChunkSize != 0 {
1112                 t.setChunkSize(pp.Integer(spec.ChunkSize))
1113         }
1114         t.addTrackers(spec.Trackers)
1115         t.maybeNewConns()
1116         return
1117 }
1118
1119 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1120         t, ok := cl.torrents[infoHash]
1121         if !ok {
1122                 err = fmt.Errorf("no such torrent")
1123                 return
1124         }
1125         err = t.close()
1126         if err != nil {
1127                 panic(err)
1128         }
1129         delete(cl.torrents, infoHash)
1130         return
1131 }
1132
1133 func (cl *Client) allTorrentsCompleted() bool {
1134         for _, t := range cl.torrents {
1135                 if !t.haveInfo() {
1136                         return false
1137                 }
1138                 if !t.haveAllPieces() {
1139                         return false
1140                 }
1141         }
1142         return true
1143 }
1144
1145 // Returns true when all torrents are completely downloaded and false if the
1146 // client is stopped before that.
1147 func (cl *Client) WaitAll() bool {
1148         cl.lock()
1149         defer cl.unlock()
1150         for !cl.allTorrentsCompleted() {
1151                 if cl.closed.IsSet() {
1152                         return false
1153                 }
1154                 cl.event.Wait()
1155         }
1156         return true
1157 }
1158
1159 // Returns handles to all the torrents loaded in the Client.
1160 func (cl *Client) Torrents() []*Torrent {
1161         cl.lock()
1162         defer cl.unlock()
1163         return cl.torrentsAsSlice()
1164 }
1165
1166 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1167         for _, t := range cl.torrents {
1168                 ret = append(ret, t)
1169         }
1170         return
1171 }
1172
1173 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1174         spec, err := TorrentSpecFromMagnetURI(uri)
1175         if err != nil {
1176                 return
1177         }
1178         T, _, err = cl.AddTorrentSpec(spec)
1179         return
1180 }
1181
1182 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1183         T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1184         var ss []string
1185         slices.MakeInto(&ss, mi.Nodes)
1186         cl.AddDHTNodes(ss)
1187         return
1188 }
1189
1190 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1191         mi, err := metainfo.LoadFromFile(filename)
1192         if err != nil {
1193                 return
1194         }
1195         return cl.AddTorrent(mi)
1196 }
1197
1198 func (cl *Client) DhtServers() []DhtServer {
1199         return cl.dhtServers
1200 }
1201
1202 func (cl *Client) AddDHTNodes(nodes []string) {
1203         for _, n := range nodes {
1204                 hmp := missinggo.SplitHostMaybePort(n)
1205                 ip := net.ParseIP(hmp.Host)
1206                 if ip == nil {
1207                         cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1208                         continue
1209                 }
1210                 ni := krpc.NodeInfo{
1211                         Addr: krpc.NodeAddr{
1212                                 IP:   ip,
1213                                 Port: hmp.Port,
1214                         },
1215                 }
1216                 cl.eachDhtServer(func(s DhtServer) {
1217                         s.AddNode(ni)
1218                 })
1219         }
1220 }
1221
1222 func (cl *Client) banPeerIP(ip net.IP) {
1223         cl.logger.Printf("banning ip %v", ip)
1224         if cl.badPeerIPs == nil {
1225                 cl.badPeerIPs = make(map[string]struct{})
1226         }
1227         cl.badPeerIPs[ip.String()] = struct{}{}
1228 }
1229
1230 func (cl *Client) newConnection(nc net.Conn, outgoing bool, remoteAddr net.Addr, network string) (c *PeerConn) {
1231         c = &PeerConn{
1232                 conn:            nc,
1233                 outgoing:        outgoing,
1234                 choking:         true,
1235                 peerChoking:     true,
1236                 PeerMaxRequests: 250,
1237                 writeBuffer:     new(bytes.Buffer),
1238                 remoteAddr:      remoteAddr,
1239                 network:         network,
1240         }
1241         c.logger = cl.logger.WithValues(c,
1242                 log.Debug, // I want messages to default to debug, and can set it here as it's only used by new code
1243         ).WithText(func(m log.Msg) string {
1244                 return fmt.Sprintf("%v: %s", c, m.Text())
1245         })
1246         c.writerCond.L = cl.locker()
1247         c.setRW(connStatsReadWriter{nc, c})
1248         c.r = &rateLimitedReader{
1249                 l: cl.config.DownloadRateLimiter,
1250                 r: c.r,
1251         }
1252         c.logger.Printf("initialized with remote %v over network %v (outgoing=%t)", remoteAddr, network, outgoing)
1253         return
1254 }
1255
1256 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1257         cl.lock()
1258         defer cl.unlock()
1259         t := cl.torrent(ih)
1260         if t == nil {
1261                 return
1262         }
1263         t.addPeers([]Peer{{
1264                 Addr:   ipPortAddr{ip, port},
1265                 Source: PeerSourceDhtAnnouncePeer,
1266         }})
1267 }
1268
1269 func firstNotNil(ips ...net.IP) net.IP {
1270         for _, ip := range ips {
1271                 if ip != nil {
1272                         return ip
1273                 }
1274         }
1275         return nil
1276 }
1277
1278 func (cl *Client) eachDialer(f func(Dialer) bool) {
1279         for _, s := range cl.dialers {
1280                 if !f(s) {
1281                         break
1282                 }
1283         }
1284 }
1285
1286 func (cl *Client) eachListener(f func(Listener) bool) {
1287         for _, s := range cl.listeners {
1288                 if !f(s) {
1289                         break
1290                 }
1291         }
1292 }
1293
1294 func (cl *Client) findListener(f func(net.Listener) bool) (ret net.Listener) {
1295         cl.eachListener(func(l Listener) bool {
1296                 ret = l
1297                 return !f(l)
1298         })
1299         return
1300 }
1301
1302 func (cl *Client) publicIp(peer net.IP) net.IP {
1303         // TODO: Use BEP 10 to determine how peers are seeing us.
1304         if peer.To4() != nil {
1305                 return firstNotNil(
1306                         cl.config.PublicIp4,
1307                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1308                 )
1309         }
1310
1311         return firstNotNil(
1312                 cl.config.PublicIp6,
1313                 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1314         )
1315 }
1316
1317 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1318         return addrIpOrNil(
1319                 cl.findListener(
1320                         func(l net.Listener) bool {
1321                                 return f(addrIpOrNil(l.Addr()))
1322                         },
1323                 ).Addr(),
1324         )
1325 }
1326
1327 // Our IP as a peer should see it.
1328 func (cl *Client) publicAddr(peer net.IP) IpPort {
1329         return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1330 }
1331
1332 // ListenAddrs addresses currently being listened to.
1333 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1334         cl.lock()
1335         defer cl.unlock()
1336         cl.eachListener(func(l Listener) bool {
1337                 ret = append(ret, l.Addr())
1338                 return true
1339         })
1340         return
1341 }
1342
1343 func (cl *Client) onBadAccept(addr net.Addr) {
1344         ipa, ok := tryIpPortFromNetAddr(addr)
1345         if !ok {
1346                 return
1347         }
1348         ip := maskIpForAcceptLimiting(ipa.IP)
1349         if cl.acceptLimiter == nil {
1350                 cl.acceptLimiter = make(map[ipStr]int)
1351         }
1352         cl.acceptLimiter[ipStr(ip.String())]++
1353 }
1354
1355 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1356         if ip4 := ip.To4(); ip4 != nil {
1357                 return ip4.Mask(net.CIDRMask(24, 32))
1358         }
1359         return ip
1360 }
1361
1362 func (cl *Client) clearAcceptLimits() {
1363         cl.acceptLimiter = nil
1364 }
1365
1366 func (cl *Client) acceptLimitClearer() {
1367         for {
1368                 select {
1369                 case <-cl.closed.LockedChan(cl.locker()):
1370                         return
1371                 case <-time.After(15 * time.Minute):
1372                         cl.lock()
1373                         cl.clearAcceptLimits()
1374                         cl.unlock()
1375                 }
1376         }
1377 }
1378
1379 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1380         if cl.config.DisableAcceptRateLimiting {
1381                 return false
1382         }
1383         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1384 }
1385
1386 func (cl *Client) rLock() {
1387         cl._mu.RLock()
1388 }
1389
1390 func (cl *Client) rUnlock() {
1391         cl._mu.RUnlock()
1392 }
1393
1394 func (cl *Client) lock() {
1395         cl._mu.Lock()
1396 }
1397
1398 func (cl *Client) unlock() {
1399         cl._mu.Unlock()
1400 }
1401
1402 func (cl *Client) locker() *lockWithDeferreds {
1403         return &cl._mu
1404 }
1405
1406 func (cl *Client) String() string {
1407         return fmt.Sprintf("<%[1]T %[1]p>", cl)
1408 }