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