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