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