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