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