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