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