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