]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
Update dht logging
[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         logger := cl.logger.WithNames("dht", conn.LocalAddr().String())
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:        logger,
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                                 logger.Levelf(log.Warning, "error bootstrapping dht: %s", err)
407                         }
408                         logger.Levelf(log.Debug, "completed bootstrap: %+v", ts)
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
1181                 storageOpener:       storageClient,
1182                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1183
1184                 metadataChanged: sync.Cond{
1185                         L: cl.locker(),
1186                 },
1187                 webSeeds:     make(map[string]*Peer),
1188                 gotMetainfoC: make(chan struct{}),
1189         }
1190         t.networkingEnabled.Set()
1191         t.logger = cl.logger.WithContextValue(t).WithNames("torrent", t.infoHash.HexString())
1192         t.sourcesLogger = t.logger.WithNames("sources")
1193         if opts.ChunkSize == 0 {
1194                 opts.ChunkSize = defaultChunkSize
1195         }
1196         t.setChunkSize(opts.ChunkSize)
1197         return
1198 }
1199
1200 // A file-like handle to some torrent data resource.
1201 type Handle interface {
1202         io.Reader
1203         io.Seeker
1204         io.Closer
1205         io.ReaderAt
1206 }
1207
1208 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1209         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1210 }
1211
1212 // Adds a torrent by InfoHash with a custom Storage implementation.
1213 // If the torrent already exists then this Storage is ignored and the
1214 // existing torrent returned with `new` set to `false`
1215 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1216         cl.lock()
1217         defer cl.unlock()
1218         t, ok := cl.torrents[infoHash]
1219         if ok {
1220                 return
1221         }
1222         new = true
1223
1224         t = cl.newTorrent(infoHash, specStorage)
1225         cl.eachDhtServer(func(s DhtServer) {
1226                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1227                         go t.dhtAnnouncer(s)
1228                 }
1229         })
1230         cl.torrents[infoHash] = t
1231         cl.clearAcceptLimits()
1232         t.updateWantPeersEvent()
1233         // Tickle Client.waitAccept, new torrent may want conns.
1234         cl.event.Broadcast()
1235         return
1236 }
1237
1238 // Adds a torrent by InfoHash with a custom Storage implementation.
1239 // If the torrent already exists then this Storage is ignored and the
1240 // existing torrent returned with `new` set to `false`
1241 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1242         infoHash := opts.InfoHash
1243         cl.lock()
1244         defer cl.unlock()
1245         t, ok := cl.torrents[infoHash]
1246         if ok {
1247                 return
1248         }
1249         new = true
1250
1251         t = cl.newTorrentOpt(opts)
1252         cl.eachDhtServer(func(s DhtServer) {
1253                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1254                         go t.dhtAnnouncer(s)
1255                 }
1256         })
1257         cl.torrents[infoHash] = t
1258         cl.clearAcceptLimits()
1259         t.updateWantPeersEvent()
1260         // Tickle Client.waitAccept, new torrent may want conns.
1261         cl.event.Broadcast()
1262         return
1263 }
1264
1265 type AddTorrentOpts struct {
1266         InfoHash  InfoHash
1267         Storage   storage.ClientImpl
1268         ChunkSize pp.Integer
1269 }
1270
1271 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1272 // Torrent.MergeSpec.
1273 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1274         t, new = cl.AddTorrentOpt(AddTorrentOpts{
1275                 InfoHash:  spec.InfoHash,
1276                 Storage:   spec.Storage,
1277                 ChunkSize: spec.ChunkSize,
1278         })
1279         modSpec := *spec
1280         if new {
1281                 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1282                 // it.
1283                 modSpec.ChunkSize = 0
1284         }
1285         err = t.MergeSpec(&modSpec)
1286         if err != nil && new {
1287                 t.Drop()
1288         }
1289         return
1290 }
1291
1292 type stringAddr string
1293
1294 var _ net.Addr = stringAddr("")
1295
1296 func (stringAddr) Network() string   { return "" }
1297 func (me stringAddr) String() string { return string(me) }
1298
1299 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1300 // spec.DisallowDataDownload/Upload will be read and applied
1301 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1302 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1303         if spec.DisplayName != "" {
1304                 t.SetDisplayName(spec.DisplayName)
1305         }
1306         if spec.InfoBytes != nil {
1307                 err := t.SetInfoBytes(spec.InfoBytes)
1308                 if err != nil {
1309                         return err
1310                 }
1311         }
1312         cl := t.cl
1313         cl.AddDhtNodes(spec.DhtNodes)
1314         t.UseSources(spec.Sources)
1315         cl.lock()
1316         defer cl.unlock()
1317         t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1318         for _, url := range spec.Webseeds {
1319                 t.addWebSeed(url)
1320         }
1321         for _, peerAddr := range spec.PeerAddrs {
1322                 t.addPeer(PeerInfo{
1323                         Addr:    stringAddr(peerAddr),
1324                         Source:  PeerSourceDirect,
1325                         Trusted: true,
1326                 })
1327         }
1328         if spec.ChunkSize != 0 {
1329                 panic("chunk size cannot be changed for existing Torrent")
1330         }
1331         t.addTrackers(spec.Trackers)
1332         t.maybeNewConns()
1333         t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1334         t.dataUploadDisallowed = spec.DisallowDataUpload
1335         return nil
1336 }
1337
1338 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1339         t, ok := cl.torrents[infoHash]
1340         if !ok {
1341                 err = fmt.Errorf("no such torrent")
1342                 return
1343         }
1344         err = t.close(wg)
1345         if err != nil {
1346                 panic(err)
1347         }
1348         delete(cl.torrents, infoHash)
1349         return
1350 }
1351
1352 func (cl *Client) allTorrentsCompleted() bool {
1353         for _, t := range cl.torrents {
1354                 if !t.haveInfo() {
1355                         return false
1356                 }
1357                 if !t.haveAllPieces() {
1358                         return false
1359                 }
1360         }
1361         return true
1362 }
1363
1364 // Returns true when all torrents are completely downloaded and false if the
1365 // client is stopped before that.
1366 func (cl *Client) WaitAll() bool {
1367         cl.lock()
1368         defer cl.unlock()
1369         for !cl.allTorrentsCompleted() {
1370                 if cl.closed.IsSet() {
1371                         return false
1372                 }
1373                 cl.event.Wait()
1374         }
1375         return true
1376 }
1377
1378 // Returns handles to all the torrents loaded in the Client.
1379 func (cl *Client) Torrents() []*Torrent {
1380         cl.lock()
1381         defer cl.unlock()
1382         return cl.torrentsAsSlice()
1383 }
1384
1385 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1386         for _, t := range cl.torrents {
1387                 ret = append(ret, t)
1388         }
1389         return
1390 }
1391
1392 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1393         spec, err := TorrentSpecFromMagnetUri(uri)
1394         if err != nil {
1395                 return
1396         }
1397         T, _, err = cl.AddTorrentSpec(spec)
1398         return
1399 }
1400
1401 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1402         ts, err := TorrentSpecFromMetaInfoErr(mi)
1403         if err != nil {
1404                 return
1405         }
1406         T, _, err = cl.AddTorrentSpec(ts)
1407         return
1408 }
1409
1410 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1411         mi, err := metainfo.LoadFromFile(filename)
1412         if err != nil {
1413                 return
1414         }
1415         return cl.AddTorrent(mi)
1416 }
1417
1418 func (cl *Client) DhtServers() []DhtServer {
1419         return cl.dhtServers
1420 }
1421
1422 func (cl *Client) AddDhtNodes(nodes []string) {
1423         for _, n := range nodes {
1424                 hmp := missinggo.SplitHostMaybePort(n)
1425                 ip := net.ParseIP(hmp.Host)
1426                 if ip == nil {
1427                         cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1428                         continue
1429                 }
1430                 ni := krpc.NodeInfo{
1431                         Addr: krpc.NodeAddr{
1432                                 IP:   ip,
1433                                 Port: hmp.Port,
1434                         },
1435                 }
1436                 cl.eachDhtServer(func(s DhtServer) {
1437                         s.AddNode(ni)
1438                 })
1439         }
1440 }
1441
1442 func (cl *Client) banPeerIP(ip net.IP) {
1443         cl.logger.Printf("banning ip %v", ip)
1444         if cl.badPeerIPs == nil {
1445                 cl.badPeerIPs = make(map[string]struct{})
1446         }
1447         cl.badPeerIPs[ip.String()] = struct{}{}
1448         for _, t := range cl.torrents {
1449                 t.iterPeers(func(p *Peer) {
1450                         if p.remoteIp().Equal(ip) {
1451                                 t.logger.Levelf(log.Warning, "dropping peer %v with banned ip %v", p, ip)
1452                                 // Should this be a close?
1453                                 p.drop()
1454                         }
1455                 })
1456         }
1457 }
1458
1459 func (cl *Client) newConnection(nc net.Conn, outgoing bool, remoteAddr PeerRemoteAddr, network, connString string) (c *PeerConn) {
1460         if network == "" {
1461                 panic(remoteAddr)
1462         }
1463         c = &PeerConn{
1464                 Peer: Peer{
1465                         outgoing:        outgoing,
1466                         choking:         true,
1467                         peerChoking:     true,
1468                         PeerMaxRequests: 250,
1469
1470                         RemoteAddr: remoteAddr,
1471                         Network:    network,
1472                         callbacks:  &cl.config.Callbacks,
1473                 },
1474                 connString: connString,
1475                 conn:       nc,
1476         }
1477         c.peerImpl = c
1478         c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1479         c.setRW(connStatsReadWriter{nc, c})
1480         c.r = &rateLimitedReader{
1481                 l: cl.config.DownloadRateLimiter,
1482                 r: c.r,
1483         }
1484         c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", remoteAddr, network, outgoing)
1485         for _, f := range cl.config.Callbacks.NewPeer {
1486                 f(&c.Peer)
1487         }
1488         return
1489 }
1490
1491 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1492         cl.lock()
1493         defer cl.unlock()
1494         t := cl.torrent(ih)
1495         if t == nil {
1496                 return
1497         }
1498         t.addPeers([]PeerInfo{{
1499                 Addr:   ipPortAddr{ip, port},
1500                 Source: PeerSourceDhtAnnouncePeer,
1501         }})
1502 }
1503
1504 func firstNotNil(ips ...net.IP) net.IP {
1505         for _, ip := range ips {
1506                 if ip != nil {
1507                         return ip
1508                 }
1509         }
1510         return nil
1511 }
1512
1513 func (cl *Client) eachListener(f func(Listener) bool) {
1514         for _, s := range cl.listeners {
1515                 if !f(s) {
1516                         break
1517                 }
1518         }
1519 }
1520
1521 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1522         for i := 0; i < len(cl.listeners); i += 1 {
1523                 if ret = cl.listeners[i]; f(ret) {
1524                         return
1525                 }
1526         }
1527         return nil
1528 }
1529
1530 func (cl *Client) publicIp(peer net.IP) net.IP {
1531         // TODO: Use BEP 10 to determine how peers are seeing us.
1532         if peer.To4() != nil {
1533                 return firstNotNil(
1534                         cl.config.PublicIp4,
1535                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1536                 )
1537         }
1538
1539         return firstNotNil(
1540                 cl.config.PublicIp6,
1541                 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1542         )
1543 }
1544
1545 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1546         l := cl.findListener(
1547                 func(l Listener) bool {
1548                         return f(addrIpOrNil(l.Addr()))
1549                 },
1550         )
1551         if l == nil {
1552                 return nil
1553         }
1554         return addrIpOrNil(l.Addr())
1555 }
1556
1557 // Our IP as a peer should see it.
1558 func (cl *Client) publicAddr(peer net.IP) IpPort {
1559         return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1560 }
1561
1562 // ListenAddrs addresses currently being listened to.
1563 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1564         cl.lock()
1565         ret = make([]net.Addr, len(cl.listeners))
1566         for i := 0; i < len(cl.listeners); i += 1 {
1567                 ret[i] = cl.listeners[i].Addr()
1568         }
1569         cl.unlock()
1570         return
1571 }
1572
1573 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1574         ipa, ok := tryIpPortFromNetAddr(addr)
1575         if !ok {
1576                 return
1577         }
1578         ip := maskIpForAcceptLimiting(ipa.IP)
1579         if cl.acceptLimiter == nil {
1580                 cl.acceptLimiter = make(map[ipStr]int)
1581         }
1582         cl.acceptLimiter[ipStr(ip.String())]++
1583 }
1584
1585 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1586         if ip4 := ip.To4(); ip4 != nil {
1587                 return ip4.Mask(net.CIDRMask(24, 32))
1588         }
1589         return ip
1590 }
1591
1592 func (cl *Client) clearAcceptLimits() {
1593         cl.acceptLimiter = nil
1594 }
1595
1596 func (cl *Client) acceptLimitClearer() {
1597         for {
1598                 select {
1599                 case <-cl.closed.Done():
1600                         return
1601                 case <-time.After(15 * time.Minute):
1602                         cl.lock()
1603                         cl.clearAcceptLimits()
1604                         cl.unlock()
1605                 }
1606         }
1607 }
1608
1609 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1610         if cl.config.DisableAcceptRateLimiting {
1611                 return false
1612         }
1613         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1614 }
1615
1616 func (cl *Client) rLock() {
1617         cl._mu.RLock()
1618 }
1619
1620 func (cl *Client) rUnlock() {
1621         cl._mu.RUnlock()
1622 }
1623
1624 func (cl *Client) lock() {
1625         cl._mu.Lock()
1626 }
1627
1628 func (cl *Client) unlock() {
1629         cl._mu.Unlock()
1630 }
1631
1632 func (cl *Client) locker() *lockWithDeferreds {
1633         return &cl._mu
1634 }
1635
1636 func (cl *Client) String() string {
1637         return fmt.Sprintf("<%[1]T %[1]p>", cl)
1638 }
1639
1640 // Returns connection-level aggregate stats at the Client level. See the comment on
1641 // TorrentStats.ConnStats.
1642 func (cl *Client) ConnStats() ConnStats {
1643         return cl.stats.Copy()
1644 }