]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
Add initial connection tracking
[btrtrc.git] / client.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "crypto/rand"
8         "encoding/binary"
9         "errors"
10         "fmt"
11         "io"
12         "net"
13         "net/http"
14         "net/url"
15         "strconv"
16         "strings"
17         "time"
18
19         "github.com/anacrolix/dht"
20         "github.com/anacrolix/dht/krpc"
21         "github.com/anacrolix/log"
22         "github.com/anacrolix/missinggo"
23         "github.com/anacrolix/missinggo/bitmap"
24         "github.com/anacrolix/missinggo/conntrack"
25         "github.com/anacrolix/missinggo/perf"
26         "github.com/anacrolix/missinggo/pproffd"
27         "github.com/anacrolix/missinggo/pubsub"
28         "github.com/anacrolix/missinggo/slices"
29         "github.com/anacrolix/sync"
30         "github.com/anacrolix/torrent/bencode"
31         "github.com/anacrolix/torrent/iplist"
32         "github.com/anacrolix/torrent/metainfo"
33         "github.com/anacrolix/torrent/mse"
34         pp "github.com/anacrolix/torrent/peer_protocol"
35         "github.com/anacrolix/torrent/storage"
36         "github.com/davecgh/go-spew/spew"
37         "github.com/dustin/go-humanize"
38         "github.com/google/btree"
39         "golang.org/x/time/rate"
40 )
41
42 // Clients contain zero or more Torrents. A Client manages a blocklist, the
43 // TCP/UDP protocol ports, and DHT as desired.
44 type Client struct {
45         // An aggregate of stats over all connections. First in struct to ensure
46         // 64-bit alignment of fields. See #262.
47         stats ConnStats
48
49         _mu    sync.RWMutex
50         event  sync.Cond
51         closed missinggo.Event
52
53         config *ClientConfig
54         logger *log.Logger
55
56         peerID         PeerID
57         defaultStorage *storage.Client
58         onClose        []func()
59         conns          []socket
60         dhtServers     []*dht.Server
61         ipBlockList    iplist.Ranger
62         // Our BitTorrent protocol extension bytes, sent in our BT handshakes.
63         extensionBytes pp.PeerExtensionBits
64
65         // Set of addresses that have our client ID. This intentionally will
66         // include ourselves if we end up trying to connect to our own address
67         // through legitimate channels.
68         dopplegangerAddrs map[string]struct{}
69         badPeerIPs        map[string]struct{}
70         torrents          map[InfoHash]*Torrent
71
72         acceptLimiter   map[ipStr]int
73         dialRateLimiter *rate.Limiter
74 }
75
76 type ipStr string
77
78 func (cl *Client) BadPeerIPs() []string {
79         cl.rLock()
80         defer cl.rUnlock()
81         return cl.badPeerIPsLocked()
82 }
83
84 func (cl *Client) badPeerIPsLocked() []string {
85         return slices.FromMapKeys(cl.badPeerIPs).([]string)
86 }
87
88 func (cl *Client) PeerID() PeerID {
89         return cl.peerID
90 }
91
92 type torrentAddr string
93
94 func (torrentAddr) Network() string { return "" }
95
96 func (me torrentAddr) String() string { return string(me) }
97
98 func (cl *Client) LocalPort() (port int) {
99         cl.eachListener(func(l socket) bool {
100                 _port := missinggo.AddrPort(l.Addr())
101                 if _port == 0 {
102                         panic(l)
103                 }
104                 if port == 0 {
105                         port = _port
106                 } else if port != _port {
107                         panic("mismatched ports")
108                 }
109                 return true
110         })
111         return
112 }
113
114 func writeDhtServerStatus(w io.Writer, s *dht.Server) {
115         dhtStats := s.Stats()
116         fmt.Fprintf(w, "\t# Nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
117         fmt.Fprintf(w, "\tServer ID: %x\n", s.ID())
118         fmt.Fprintf(w, "\tAnnounces: %d\n", dhtStats.SuccessfulOutboundAnnouncePeerQueries)
119         fmt.Fprintf(w, "\tOutstanding transactions: %d\n", dhtStats.OutstandingTransactions)
120 }
121
122 // Writes out a human readable status of the client, such as for writing to a
123 // HTTP status page.
124 func (cl *Client) WriteStatus(_w io.Writer) {
125         cl.rLock()
126         defer cl.rUnlock()
127         w := bufio.NewWriter(_w)
128         defer w.Flush()
129         fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
130         fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
131         fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
132         fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
133         cl.eachDhtServer(func(s *dht.Server) {
134                 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
135                 writeDhtServerStatus(w, s)
136         })
137         spew.Fdump(w, cl.stats)
138         fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
139         fmt.Fprintln(w)
140         for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
141                 return l.InfoHash().AsString() < r.InfoHash().AsString()
142         }).([]*Torrent) {
143                 if t.name() == "" {
144                         fmt.Fprint(w, "<unknown name>")
145                 } else {
146                         fmt.Fprint(w, t.name())
147                 }
148                 fmt.Fprint(w, "\n")
149                 if t.info != nil {
150                         fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())), t.length, humanize.Bytes(uint64(t.info.TotalLength())))
151                 } else {
152                         w.WriteString("<missing metainfo>")
153                 }
154                 fmt.Fprint(w, "\n")
155                 t.writeStatus(w)
156                 fmt.Fprintln(w)
157         }
158 }
159
160 const debugLogValue = "debug"
161
162 func (cl *Client) debugLogFilter(m *log.Msg) bool {
163         if !cl.config.Debug {
164                 _, ok := m.Values()[debugLogValue]
165                 return !ok
166         }
167         return true
168 }
169
170 func (cl *Client) initLogger() {
171         cl.logger = log.Default.Clone().AddValue(cl).AddFilter(log.NewFilter(cl.debugLogFilter))
172 }
173
174 func (cl *Client) announceKey() int32 {
175         return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
176 }
177
178 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
179         if cfg == nil {
180                 cfg = NewDefaultClientConfig()
181         }
182         defer func() {
183                 if err != nil {
184                         cl = nil
185                 }
186         }()
187         cl = &Client{
188                 config:            cfg,
189                 dopplegangerAddrs: make(map[string]struct{}),
190                 torrents:          make(map[metainfo.Hash]*Torrent),
191                 dialRateLimiter:   rate.NewLimiter(10, 10),
192         }
193         go cl.acceptLimitClearer()
194         cl.initLogger()
195         defer func() {
196                 if err == nil {
197                         return
198                 }
199                 cl.Close()
200         }()
201         cl.extensionBytes = defaultPeerExtensionBytes()
202         cl.event.L = cl.locker()
203         storageImpl := cfg.DefaultStorage
204         if storageImpl == nil {
205                 // We'd use mmap but HFS+ doesn't support sparse files.
206                 storageImpl = storage.NewFile(cfg.DataDir)
207                 cl.onClose = append(cl.onClose, func() {
208                         if err := storageImpl.Close(); err != nil {
209                                 log.Printf("error closing default storage: %s", err)
210                         }
211                 })
212         }
213         cl.defaultStorage = storage.NewClient(storageImpl)
214         if cfg.IPBlocklist != nil {
215                 cl.ipBlockList = cfg.IPBlocklist
216         }
217
218         if cfg.PeerID != "" {
219                 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
220         } else {
221                 o := copy(cl.peerID[:], cfg.Bep20)
222                 _, err = rand.Read(cl.peerID[o:])
223                 if err != nil {
224                         panic("error generating peer id")
225                 }
226         }
227
228         if cl.config.HTTPProxy == nil && cl.config.ProxyURL != "" {
229                 if fixedURL, err := url.Parse(cl.config.ProxyURL); err == nil {
230                         cl.config.HTTPProxy = http.ProxyURL(fixedURL)
231                 }
232         }
233
234         cl.conns, err = listenAll(allPeerNetworks, cl.config.ListenHost, cl.config.ListenPort, cl.config.ProxyURL, cl.firewallCallback)
235         if err != nil {
236                 return
237         }
238         // Check for panics.
239         cl.LocalPort()
240
241         for _, s := range cl.conns {
242                 if peerNetworkEnabled(s.Addr().Network(), cl.config) {
243                         go cl.acceptConnections(s)
244                 }
245         }
246
247         go cl.forwardPort()
248         if !cfg.NoDHT {
249                 for _, s := range cl.conns {
250                         if pc, ok := s.(net.PacketConn); ok {
251                                 ds, err := cl.newDhtServer(pc)
252                                 if err != nil {
253                                         panic(err)
254                                 }
255                                 cl.dhtServers = append(cl.dhtServers, ds)
256                         }
257                 }
258         }
259
260         return
261 }
262
263 func (cl *Client) firewallCallback(net.Addr) bool {
264         cl.rLock()
265         block := !cl.wantConns()
266         cl.rUnlock()
267         if block {
268                 torrent.Add("connections firewalled", 1)
269         } else {
270                 torrent.Add("connections not firewalled", 1)
271         }
272         return block
273 }
274
275 func (cl *Client) enabledPeerNetworks() (ns []string) {
276         for _, n := range allPeerNetworks {
277                 if peerNetworkEnabled(n, cl.config) {
278                         ns = append(ns, n)
279                 }
280         }
281         return
282 }
283
284 func (cl *Client) newDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
285         cfg := dht.ServerConfig{
286                 IPBlocklist:    cl.ipBlockList,
287                 Conn:           conn,
288                 OnAnnouncePeer: cl.onDHTAnnouncePeer,
289                 PublicIP: func() net.IP {
290                         if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
291                                 return cl.config.PublicIp6
292                         }
293                         return cl.config.PublicIp4
294                 }(),
295                 StartingNodes:      cl.config.DhtStartingNodes,
296                 ConnectionTracking: cl.config.ConnTracker,
297         }
298         s, err = dht.NewServer(&cfg)
299         if err == nil {
300                 go func() {
301                         if _, err := s.Bootstrap(); err != nil {
302                                 log.Printf("error bootstrapping dht: %s", err)
303                         }
304                 }()
305         }
306         return
307 }
308
309 func firstNonEmptyString(ss ...string) string {
310         for _, s := range ss {
311                 if s != "" {
312                         return s
313                 }
314         }
315         return ""
316 }
317
318 func (cl *Client) Closed() <-chan struct{} {
319         cl.lock()
320         defer cl.unlock()
321         return cl.closed.C()
322 }
323
324 func (cl *Client) eachDhtServer(f func(*dht.Server)) {
325         for _, ds := range cl.dhtServers {
326                 f(ds)
327         }
328 }
329
330 func (cl *Client) closeSockets() {
331         cl.eachListener(func(l socket) bool {
332                 l.Close()
333                 return true
334         })
335         cl.conns = nil
336 }
337
338 // Stops the client. All connections to peers are closed and all activity will
339 // come to a halt.
340 func (cl *Client) Close() {
341         cl.lock()
342         defer cl.unlock()
343         cl.closed.Set()
344         cl.eachDhtServer(func(s *dht.Server) { s.Close() })
345         cl.closeSockets()
346         for _, t := range cl.torrents {
347                 t.close()
348         }
349         for _, f := range cl.onClose {
350                 f()
351         }
352         cl.event.Broadcast()
353 }
354
355 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
356         if cl.ipBlockList == nil {
357                 return
358         }
359         return cl.ipBlockList.Lookup(ip)
360 }
361
362 func (cl *Client) ipIsBlocked(ip net.IP) bool {
363         _, blocked := cl.ipBlockRange(ip)
364         return blocked
365 }
366
367 func (cl *Client) wantConns() bool {
368         for _, t := range cl.torrents {
369                 if t.wantConns() {
370                         return true
371                 }
372         }
373         return false
374 }
375
376 func (cl *Client) waitAccept() {
377         for {
378                 if cl.closed.IsSet() {
379                         return
380                 }
381                 if cl.wantConns() {
382                         return
383                 }
384                 cl.event.Wait()
385         }
386 }
387
388 func (cl *Client) rejectAccepted(conn net.Conn) bool {
389         ra := conn.RemoteAddr()
390         rip := missinggo.AddrIP(ra)
391         if cl.config.DisableIPv4Peers && rip.To4() != nil {
392                 return true
393         }
394         if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
395                 return true
396         }
397         if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
398                 return true
399         }
400         if cl.rateLimitAccept(rip) {
401                 return true
402         }
403         return cl.badPeerIPPort(rip, missinggo.AddrPort(ra))
404 }
405
406 func (cl *Client) acceptConnections(l net.Listener) {
407         for {
408                 conn, err := l.Accept()
409                 conn = pproffd.WrapNetConn(conn)
410                 cl.rLock()
411                 closed := cl.closed.IsSet()
412                 reject := false
413                 if conn != nil {
414                         reject = cl.rejectAccepted(conn)
415                 }
416                 cl.rUnlock()
417                 if closed {
418                         if conn != nil {
419                                 conn.Close()
420                         }
421                         return
422                 }
423                 if err != nil {
424                         log.Printf("error accepting connection: %s", err)
425                         continue
426                 }
427                 go func() {
428                         if reject {
429                                 torrent.Add("rejected accepted connections", 1)
430                                 conn.Close()
431                         } else {
432                                 go cl.incomingConnection(conn)
433                         }
434                         log.Fmsg("accepted %s connection from %s", conn.RemoteAddr().Network(), conn.RemoteAddr()).AddValue(debugLogValue).Log(cl.logger)
435                         torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(missinggo.AddrIP(conn.RemoteAddr()))), 1)
436                         torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
437                         torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
438                 }()
439         }
440 }
441
442 func (cl *Client) incomingConnection(nc net.Conn) {
443         defer nc.Close()
444         if tc, ok := nc.(*net.TCPConn); ok {
445                 tc.SetLinger(0)
446         }
447         c := cl.newConnection(nc, false, missinggo.IpPortFromNetAddr(nc.RemoteAddr()), nc.RemoteAddr().Network())
448         c.Discovery = peerSourceIncoming
449         cl.runReceivedConn(c)
450 }
451
452 // Returns a handle to the given torrent, if it's present in the client.
453 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
454         cl.lock()
455         defer cl.unlock()
456         t, ok = cl.torrents[ih]
457         return
458 }
459
460 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
461         return cl.torrents[ih]
462 }
463
464 type dialResult struct {
465         Conn    net.Conn
466         Network string
467 }
468
469 func countDialResult(err error) {
470         if err == nil {
471                 torrent.Add("successful dials", 1)
472         } else {
473                 torrent.Add("unsuccessful dials", 1)
474         }
475 }
476
477 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
478         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
479         if ret < minDialTimeout {
480                 ret = minDialTimeout
481         }
482         return
483 }
484
485 // Returns whether an address is known to connect to a client with our own ID.
486 func (cl *Client) dopplegangerAddr(addr string) bool {
487         _, ok := cl.dopplegangerAddrs[addr]
488         return ok
489 }
490
491 func ipNetworkSuffix(allowIpv4, allowIpv6 bool) string {
492         switch {
493         case allowIpv4 && allowIpv6:
494                 return ""
495         case allowIpv4 && !allowIpv6:
496                 return "4"
497         case !allowIpv4 && allowIpv6:
498                 return "6"
499         default:
500                 panic("unhandled ip network combination")
501         }
502 }
503
504 func dialUTP(ctx context.Context, addr string, sock utpSocket) (c net.Conn, err error) {
505         return sock.DialContext(ctx, "", addr)
506 }
507
508 var allPeerNetworks = []string{"tcp4", "tcp6", "udp4", "udp6"}
509
510 func peerNetworkEnabled(network string, cfg *ClientConfig) bool {
511         c := func(s string) bool {
512                 return strings.Contains(network, s)
513         }
514         if cfg.DisableUTP {
515                 if c("udp") || c("utp") {
516                         return false
517                 }
518         }
519         if cfg.DisableTCP && c("tcp") {
520                 return false
521         }
522         if cfg.DisableIPv6 && c("6") {
523                 return false
524         }
525         return true
526 }
527
528 // Returns a connection over UTP or TCP, whichever is first to connect.
529 func (cl *Client) dialFirst(ctx context.Context, addr string) dialResult {
530         ctx, cancel := context.WithCancel(ctx)
531         // As soon as we return one connection, cancel the others.
532         defer cancel()
533         left := 0
534         resCh := make(chan dialResult, left)
535         func() {
536                 cl.lock()
537                 defer cl.unlock()
538                 cl.eachListener(func(s socket) bool {
539                         network := s.Addr().Network()
540                         if peerNetworkEnabled(network, cl.config) {
541                                 left++
542                                 go func() {
543                                         cte := cl.config.ConnTracker.Wait(
544                                                 conntrack.Entry{network, s.Addr().String(), addr},
545                                                 "dial torrent client")
546                                         c, err := s.dial(ctx, addr)
547                                         // This is a bit optimistic, but it looks non-trivial to thread
548                                         // this through the proxy code. Set it now in case we close the
549                                         // connection forthwith.
550                                         if tc, ok := c.(*net.TCPConn); ok {
551                                                 tc.SetLinger(0)
552                                         }
553                                         countDialResult(err)
554                                         dr := dialResult{c, network}
555                                         if c == nil {
556                                                 cte.Done()
557                                         } else {
558                                                 dr.Conn = closeWrapper{c, func() error {
559                                                         err := c.Close()
560                                                         cte.Done()
561                                                         return err
562                                                 }}
563                                         }
564                                         resCh <- dr
565                                 }()
566                         }
567                         return true
568                 })
569         }()
570         var res dialResult
571         // Wait for a successful connection.
572         func() {
573                 defer perf.ScopeTimer()()
574                 for ; left > 0 && res.Conn == nil; left-- {
575                         res = <-resCh
576                 }
577         }()
578         // There are still incompleted dials.
579         go func() {
580                 for ; left > 0; left-- {
581                         conn := (<-resCh).Conn
582                         if conn != nil {
583                                 conn.Close()
584                         }
585                 }
586         }()
587         if res.Conn != nil {
588                 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
589         }
590         return res
591 }
592
593 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
594         if _, ok := t.halfOpen[addr]; !ok {
595                 panic("invariant broken")
596         }
597         delete(t.halfOpen, addr)
598         t.openNewConns()
599 }
600
601 // Performs initiator handshakes and returns a connection. Returns nil
602 // *connection if no connection for valid reasons.
603 func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader bool, remoteAddr IpPort, network string) (c *connection, err error) {
604         c = cl.newConnection(nc, true, remoteAddr, network)
605         c.headerEncrypted = encryptHeader
606         ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
607         defer cancel()
608         dl, ok := ctx.Deadline()
609         if !ok {
610                 panic(ctx)
611         }
612         err = nc.SetDeadline(dl)
613         if err != nil {
614                 panic(err)
615         }
616         ok, err = cl.initiateHandshakes(c, t)
617         if !ok {
618                 c = nil
619         }
620         return
621 }
622
623 // Returns nil connection and nil error if no connection could be established
624 // for valid reasons.
625 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr IpPort, ctx context.Context, obfuscatedHeader bool) (c *connection, err error) {
626         dr := cl.dialFirst(ctx, addr.String())
627         nc := dr.Conn
628         if nc == nil {
629                 return
630         }
631         defer func() {
632                 if c == nil || err != nil {
633                         nc.Close()
634                 }
635         }()
636         return cl.handshakesConnection(ctx, nc, t, obfuscatedHeader, addr, dr.Network)
637 }
638
639 // Returns nil connection and nil error if no connection could be established
640 // for valid reasons.
641 func (cl *Client) establishOutgoingConn(t *Torrent, addr IpPort) (c *connection, err error) {
642         torrent.Add("establish outgoing connection", 1)
643         ctx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
644                 cl.rLock()
645                 defer cl.rUnlock()
646                 return t.dialTimeout()
647         }())
648         defer cancel()
649         obfuscatedHeaderFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
650         c, err = cl.establishOutgoingConnEx(t, addr, ctx, obfuscatedHeaderFirst)
651         if err != nil {
652                 return
653         }
654         if c != nil {
655                 torrent.Add("initiated conn with preferred header obfuscation", 1)
656                 return
657         }
658         if cl.config.ForceEncryption {
659                 // We should have just tried with an obfuscated header. A plaintext
660                 // header can't result in an encrypted connection, so we're done.
661                 if !obfuscatedHeaderFirst {
662                         panic(cl.config.EncryptionPolicy)
663                 }
664                 return
665         }
666         // Try again with encryption if we didn't earlier, or without if we did.
667         c, err = cl.establishOutgoingConnEx(t, addr, ctx, !obfuscatedHeaderFirst)
668         if c != nil {
669                 torrent.Add("initiated conn with fallback header obfuscation", 1)
670         }
671         return
672 }
673
674 // Called to dial out and run a connection. The addr we're given is already
675 // considered half-open.
676 func (cl *Client) outgoingConnection(t *Torrent, addr IpPort, ps peerSource) {
677         cl.dialRateLimiter.Wait(context.Background())
678         c, err := cl.establishOutgoingConn(t, addr)
679         cl.lock()
680         defer cl.unlock()
681         // Don't release lock between here and addConnection, unless it's for
682         // failure.
683         cl.noLongerHalfOpen(t, addr.String())
684         if err != nil {
685                 if cl.config.Debug {
686                         log.Printf("error establishing outgoing connection: %s", err)
687                 }
688                 return
689         }
690         if c == nil {
691                 return
692         }
693         defer c.Close()
694         c.Discovery = ps
695         cl.runHandshookConn(c, t)
696 }
697
698 // The port number for incoming peer connections. 0 if the client isn't
699 // listening.
700 func (cl *Client) incomingPeerPort() int {
701         return cl.LocalPort()
702 }
703
704 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
705         if c.headerEncrypted {
706                 var rw io.ReadWriter
707                 rw, c.cryptoMethod, err = mse.InitiateHandshake(
708                         struct {
709                                 io.Reader
710                                 io.Writer
711                         }{c.r, c.w},
712                         t.infoHash[:],
713                         nil,
714                         func() mse.CryptoMethod {
715                                 switch {
716                                 case cl.config.ForceEncryption:
717                                         return mse.CryptoMethodRC4
718                                 case cl.config.DisableEncryption:
719                                         return mse.CryptoMethodPlaintext
720                                 default:
721                                         return mse.AllSupportedCrypto
722                                 }
723                         }(),
724                 )
725                 c.setRW(rw)
726                 if err != nil {
727                         return
728                 }
729         }
730         ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
731         if ih != t.infoHash {
732                 ok = false
733         }
734         return
735 }
736
737 // Calls f with any secret keys.
738 func (cl *Client) forSkeys(f func([]byte) bool) {
739         cl.lock()
740         defer cl.unlock()
741         for ih := range cl.torrents {
742                 if !f(ih[:]) {
743                         break
744                 }
745         }
746 }
747
748 // Do encryption and bittorrent handshakes as receiver.
749 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
750         defer perf.ScopeTimerErr(&err)()
751         var rw io.ReadWriter
752         rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy)
753         c.setRW(rw)
754         if err == nil || err == mse.ErrNoSecretKeyMatch {
755                 if c.headerEncrypted {
756                         torrent.Add("handshakes received encrypted", 1)
757                 } else {
758                         torrent.Add("handshakes received unencrypted", 1)
759                 }
760         } else {
761                 torrent.Add("handshakes received with error while handling encryption", 1)
762         }
763         if err != nil {
764                 if err == mse.ErrNoSecretKeyMatch {
765                         err = nil
766                 }
767                 return
768         }
769         if cl.config.ForceEncryption && !c.headerEncrypted {
770                 err = errors.New("connection not encrypted")
771                 return
772         }
773         ih, ok, err := cl.connBTHandshake(c, nil)
774         if err != nil {
775                 err = fmt.Errorf("error during bt handshake: %s", err)
776                 return
777         }
778         if !ok {
779                 return
780         }
781         cl.lock()
782         t = cl.torrents[ih]
783         cl.unlock()
784         return
785 }
786
787 // Returns !ok if handshake failed for valid reasons.
788 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
789         res, ok, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
790         if err != nil || !ok {
791                 return
792         }
793         ret = res.Hash
794         c.PeerExtensionBytes = res.PeerExtensionBits
795         c.PeerID = res.PeerID
796         c.completedHandshake = time.Now()
797         return
798 }
799
800 func (cl *Client) runReceivedConn(c *connection) {
801         err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
802         if err != nil {
803                 panic(err)
804         }
805         t, err := cl.receiveHandshakes(c)
806         if err != nil {
807                 log.Fmsg(
808                         "error receiving handshakes: %s", err,
809                 ).AddValue(
810                         debugLogValue,
811                 ).Add(
812                         "network", c.network,
813                 ).Log(cl.logger)
814                 torrent.Add("error receiving handshake", 1)
815                 cl.lock()
816                 cl.onBadAccept(c.remoteAddr)
817                 cl.unlock()
818                 return
819         }
820         if t == nil {
821                 torrent.Add("received handshake for unloaded torrent", 1)
822                 cl.lock()
823                 cl.onBadAccept(c.remoteAddr)
824                 cl.unlock()
825                 return
826         }
827         torrent.Add("received handshake for loaded torrent", 1)
828         cl.lock()
829         defer cl.unlock()
830         cl.runHandshookConn(c, t)
831 }
832
833 func (cl *Client) runHandshookConn(c *connection, t *Torrent) {
834         c.setTorrent(t)
835         if c.PeerID == cl.peerID {
836                 if c.outgoing {
837                         connsToSelf.Add(1)
838                         addr := c.conn.RemoteAddr().String()
839                         cl.dopplegangerAddrs[addr] = struct{}{}
840                 } else {
841                         // Because the remote address is not necessarily the same as its
842                         // client's torrent listen address, we won't record the remote address
843                         // as a doppleganger. Instead, the initiator can record *us* as the
844                         // doppleganger.
845                 }
846                 return
847         }
848         c.conn.SetWriteDeadline(time.Time{})
849         c.r = deadlineReader{c.conn, c.r}
850         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
851         if connIsIpv6(c.conn) {
852                 torrent.Add("completed handshake over ipv6", 1)
853         }
854         if err := t.addConnection(c); err != nil {
855                 log.Fmsg("error adding connection: %s", err).AddValues(c, debugLogValue).Log(t.logger)
856                 return
857         }
858         defer t.dropConnection(c)
859         go c.writer(time.Minute)
860         cl.sendInitialMessages(c, t)
861         err := c.mainReadLoop()
862         if err != nil && cl.config.Debug {
863                 log.Printf("error during connection main read loop: %s", err)
864         }
865 }
866
867 // See the order given in Transmission's tr_peerMsgsNew.
868 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
869         if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
870                 conn.Post(pp.Message{
871                         Type:       pp.Extended,
872                         ExtendedID: pp.HandshakeExtendedID,
873                         ExtendedPayload: func() []byte {
874                                 msg := pp.ExtendedHandshakeMessage{
875                                         M: map[pp.ExtensionName]pp.ExtensionNumber{
876                                                 pp.ExtensionNameMetadata: metadataExtendedId,
877                                         },
878                                         V:            cl.config.ExtendedHandshakeClientVersion,
879                                         Reqq:         64, // TODO: Really?
880                                         YourIp:       pp.CompactIp(conn.remoteAddr.IP),
881                                         Encryption:   !cl.config.DisableEncryption,
882                                         Port:         cl.incomingPeerPort(),
883                                         MetadataSize: torrent.metadataSize(),
884                                         // TODO: We can figured these out specific to the socket
885                                         // used.
886                                         Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
887                                         Ipv6: cl.config.PublicIp6.To16(),
888                                 }
889                                 if !cl.config.DisablePEX {
890                                         msg.M[pp.ExtensionNamePex] = pexExtendedId
891                                 }
892                                 return bencode.MustMarshal(msg)
893                         }(),
894                 })
895         }
896         func() {
897                 if conn.fastEnabled() {
898                         if torrent.haveAllPieces() {
899                                 conn.Post(pp.Message{Type: pp.HaveAll})
900                                 conn.sentHaves.AddRange(0, bitmap.BitIndex(conn.t.NumPieces()))
901                                 return
902                         } else if !torrent.haveAnyPieces() {
903                                 conn.Post(pp.Message{Type: pp.HaveNone})
904                                 conn.sentHaves.Clear()
905                                 return
906                         }
907                 }
908                 conn.PostBitfield()
909         }()
910         if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.haveDhtServer() {
911                 conn.Post(pp.Message{
912                         Type: pp.Port,
913                         Port: cl.dhtPort(),
914                 })
915         }
916 }
917
918 func (cl *Client) dhtPort() (ret uint16) {
919         cl.eachDhtServer(func(s *dht.Server) {
920                 ret = uint16(missinggo.AddrPort(s.Addr()))
921         })
922         return
923 }
924
925 func (cl *Client) haveDhtServer() (ret bool) {
926         cl.eachDhtServer(func(_ *dht.Server) {
927                 ret = true
928         })
929         return
930 }
931
932 // Process incoming ut_metadata message.
933 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
934         var d map[string]int
935         err := bencode.Unmarshal(payload, &d)
936         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
937         } else if err != nil {
938                 return fmt.Errorf("error unmarshalling bencode: %s", err)
939         }
940         msgType, ok := d["msg_type"]
941         if !ok {
942                 return errors.New("missing msg_type field")
943         }
944         piece := d["piece"]
945         switch msgType {
946         case pp.DataMetadataExtensionMsgType:
947                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
948                 if !c.requestedMetadataPiece(piece) {
949                         return fmt.Errorf("got unexpected piece %d", piece)
950                 }
951                 c.metadataRequests[piece] = false
952                 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
953                 if begin < 0 || begin >= len(payload) {
954                         return fmt.Errorf("data has bad offset in payload: %d", begin)
955                 }
956                 t.saveMetadataPiece(piece, payload[begin:])
957                 c.lastUsefulChunkReceived = time.Now()
958                 return t.maybeCompleteMetadata()
959         case pp.RequestMetadataExtensionMsgType:
960                 if !t.haveMetadataPiece(piece) {
961                         c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
962                         return nil
963                 }
964                 start := (1 << 14) * piece
965                 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
966                 return nil
967         case pp.RejectMetadataExtensionMsgType:
968                 return nil
969         default:
970                 return errors.New("unknown msg_type value")
971         }
972 }
973
974 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
975         if port == 0 {
976                 return true
977         }
978         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
979                 return true
980         }
981         if _, ok := cl.ipBlockRange(ip); ok {
982                 return true
983         }
984         if _, ok := cl.badPeerIPs[ip.String()]; ok {
985                 return true
986         }
987         return false
988 }
989
990 // Return a Torrent ready for insertion into a Client.
991 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
992         // use provided storage, if provided
993         storageClient := cl.defaultStorage
994         if specStorage != nil {
995                 storageClient = storage.NewClient(specStorage)
996         }
997
998         t = &Torrent{
999                 cl:       cl,
1000                 infoHash: ih,
1001                 peers: prioritizedPeers{
1002                         om: btree.New(32),
1003                         getPrio: func(p Peer) peerPriority {
1004                                 return bep40PriorityIgnoreError(cl.publicAddr(p.IP), p.addr())
1005                         },
1006                 },
1007                 conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1008
1009                 halfOpen:          make(map[string]Peer),
1010                 pieceStateChanges: pubsub.NewPubSub(),
1011
1012                 storageOpener:       storageClient,
1013                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1014
1015                 networkingEnabled: true,
1016                 requestStrategy:   2,
1017                 metadataChanged: sync.Cond{
1018                         L: cl.locker(),
1019                 },
1020                 duplicateRequestTimeout: 1 * time.Second,
1021         }
1022         t.logger = cl.logger.Clone().AddValue(t)
1023         t.setChunkSize(defaultChunkSize)
1024         return
1025 }
1026
1027 // A file-like handle to some torrent data resource.
1028 type Handle interface {
1029         io.Reader
1030         io.Seeker
1031         io.Closer
1032         io.ReaderAt
1033 }
1034
1035 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1036         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1037 }
1038
1039 // Adds a torrent by InfoHash with a custom Storage implementation.
1040 // If the torrent already exists then this Storage is ignored and the
1041 // existing torrent returned with `new` set to `false`
1042 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1043         cl.lock()
1044         defer cl.unlock()
1045         t, ok := cl.torrents[infoHash]
1046         if ok {
1047                 return
1048         }
1049         new = true
1050
1051         t = cl.newTorrent(infoHash, specStorage)
1052         cl.eachDhtServer(func(s *dht.Server) {
1053                 go t.dhtAnnouncer(s)
1054         })
1055         cl.torrents[infoHash] = t
1056         cl.clearAcceptLimits()
1057         t.updateWantPeersEvent()
1058         // Tickle Client.waitAccept, new torrent may want conns.
1059         cl.event.Broadcast()
1060         return
1061 }
1062
1063 // Add or merge a torrent spec. If the torrent is already present, the
1064 // trackers will be merged with the existing ones. If the Info isn't yet
1065 // known, it will be set. The display name is replaced if the new spec
1066 // provides one. Returns new if the torrent wasn't already in the client.
1067 // Note that any `Storage` defined on the spec will be ignored if the
1068 // torrent is already present (i.e. `new` return value is `true`)
1069 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1070         t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1071         if spec.DisplayName != "" {
1072                 t.SetDisplayName(spec.DisplayName)
1073         }
1074         if spec.InfoBytes != nil {
1075                 err = t.SetInfoBytes(spec.InfoBytes)
1076                 if err != nil {
1077                         return
1078                 }
1079         }
1080         cl.lock()
1081         defer cl.unlock()
1082         if spec.ChunkSize != 0 {
1083                 t.setChunkSize(pp.Integer(spec.ChunkSize))
1084         }
1085         t.addTrackers(spec.Trackers)
1086         t.maybeNewConns()
1087         return
1088 }
1089
1090 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1091         t, ok := cl.torrents[infoHash]
1092         if !ok {
1093                 err = fmt.Errorf("no such torrent")
1094                 return
1095         }
1096         err = t.close()
1097         if err != nil {
1098                 panic(err)
1099         }
1100         delete(cl.torrents, infoHash)
1101         return
1102 }
1103
1104 func (cl *Client) allTorrentsCompleted() bool {
1105         for _, t := range cl.torrents {
1106                 if !t.haveInfo() {
1107                         return false
1108                 }
1109                 if !t.haveAllPieces() {
1110                         return false
1111                 }
1112         }
1113         return true
1114 }
1115
1116 // Returns true when all torrents are completely downloaded and false if the
1117 // client is stopped before that.
1118 func (cl *Client) WaitAll() bool {
1119         cl.lock()
1120         defer cl.unlock()
1121         for !cl.allTorrentsCompleted() {
1122                 if cl.closed.IsSet() {
1123                         return false
1124                 }
1125                 cl.event.Wait()
1126         }
1127         return true
1128 }
1129
1130 // Returns handles to all the torrents loaded in the Client.
1131 func (cl *Client) Torrents() []*Torrent {
1132         cl.lock()
1133         defer cl.unlock()
1134         return cl.torrentsAsSlice()
1135 }
1136
1137 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1138         for _, t := range cl.torrents {
1139                 ret = append(ret, t)
1140         }
1141         return
1142 }
1143
1144 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1145         spec, err := TorrentSpecFromMagnetURI(uri)
1146         if err != nil {
1147                 return
1148         }
1149         T, _, err = cl.AddTorrentSpec(spec)
1150         return
1151 }
1152
1153 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1154         T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1155         var ss []string
1156         slices.MakeInto(&ss, mi.Nodes)
1157         cl.AddDHTNodes(ss)
1158         return
1159 }
1160
1161 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1162         mi, err := metainfo.LoadFromFile(filename)
1163         if err != nil {
1164                 return
1165         }
1166         return cl.AddTorrent(mi)
1167 }
1168
1169 func (cl *Client) DhtServers() []*dht.Server {
1170         return cl.dhtServers
1171 }
1172
1173 func (cl *Client) AddDHTNodes(nodes []string) {
1174         for _, n := range nodes {
1175                 hmp := missinggo.SplitHostMaybePort(n)
1176                 ip := net.ParseIP(hmp.Host)
1177                 if ip == nil {
1178                         log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1179                         continue
1180                 }
1181                 ni := krpc.NodeInfo{
1182                         Addr: krpc.NodeAddr{
1183                                 IP:   ip,
1184                                 Port: hmp.Port,
1185                         },
1186                 }
1187                 cl.eachDhtServer(func(s *dht.Server) {
1188                         s.AddNode(ni)
1189                 })
1190         }
1191 }
1192
1193 func (cl *Client) banPeerIP(ip net.IP) {
1194         if cl.badPeerIPs == nil {
1195                 cl.badPeerIPs = make(map[string]struct{})
1196         }
1197         cl.badPeerIPs[ip.String()] = struct{}{}
1198 }
1199
1200 func (cl *Client) newConnection(nc net.Conn, outgoing bool, remoteAddr IpPort, network string) (c *connection) {
1201         c = &connection{
1202                 conn:            nc,
1203                 outgoing:        outgoing,
1204                 Choked:          true,
1205                 PeerChoked:      true,
1206                 PeerMaxRequests: 250,
1207                 writeBuffer:     new(bytes.Buffer),
1208                 remoteAddr:      remoteAddr,
1209                 network:         network,
1210         }
1211         c.writerCond.L = cl.locker()
1212         c.setRW(connStatsReadWriter{nc, c})
1213         c.r = &rateLimitedReader{
1214                 l: cl.config.DownloadRateLimiter,
1215                 r: c.r,
1216         }
1217         return
1218 }
1219
1220 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1221         cl.lock()
1222         defer cl.unlock()
1223         t := cl.torrent(ih)
1224         if t == nil {
1225                 return
1226         }
1227         t.addPeers([]Peer{{
1228                 IP:     p.IP,
1229                 Port:   p.Port,
1230                 Source: peerSourceDHTAnnouncePeer,
1231         }})
1232 }
1233
1234 func firstNotNil(ips ...net.IP) net.IP {
1235         for _, ip := range ips {
1236                 if ip != nil {
1237                         return ip
1238                 }
1239         }
1240         return nil
1241 }
1242
1243 func (cl *Client) eachListener(f func(socket) bool) {
1244         for _, s := range cl.conns {
1245                 if !f(s) {
1246                         break
1247                 }
1248         }
1249 }
1250
1251 func (cl *Client) findListener(f func(net.Listener) bool) (ret net.Listener) {
1252         cl.eachListener(func(l socket) bool {
1253                 ret = l
1254                 return !f(l)
1255         })
1256         return
1257 }
1258
1259 func (cl *Client) publicIp(peer net.IP) net.IP {
1260         // TODO: Use BEP 10 to determine how peers are seeing us.
1261         if peer.To4() != nil {
1262                 return firstNotNil(
1263                         cl.config.PublicIp4,
1264                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1265                 )
1266         } else {
1267                 return firstNotNil(
1268                         cl.config.PublicIp6,
1269                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1270                 )
1271         }
1272 }
1273
1274 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1275         return missinggo.AddrIP(cl.findListener(func(l net.Listener) bool {
1276                 return f(missinggo.AddrIP(l.Addr()))
1277         }).Addr())
1278 }
1279
1280 // Our IP as a peer should see it.
1281 func (cl *Client) publicAddr(peer net.IP) IpPort {
1282         return IpPort{cl.publicIp(peer), uint16(cl.incomingPeerPort())}
1283 }
1284
1285 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1286         cl.lock()
1287         defer cl.unlock()
1288         cl.eachListener(func(l socket) bool {
1289                 ret = append(ret, l.Addr())
1290                 return true
1291         })
1292         return
1293 }
1294
1295 func (cl *Client) onBadAccept(addr IpPort) {
1296         ip := maskIpForAcceptLimiting(addr.IP)
1297         if cl.acceptLimiter == nil {
1298                 cl.acceptLimiter = make(map[ipStr]int)
1299         }
1300         cl.acceptLimiter[ipStr(ip.String())]++
1301 }
1302
1303 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1304         if ip4 := ip.To4(); ip4 != nil {
1305                 return ip4.Mask(net.CIDRMask(24, 32))
1306         }
1307         return ip
1308 }
1309
1310 func (cl *Client) clearAcceptLimits() {
1311         cl.acceptLimiter = nil
1312 }
1313
1314 func (cl *Client) acceptLimitClearer() {
1315         for {
1316                 select {
1317                 case <-cl.closed.LockedChan(cl.locker()):
1318                         return
1319                 case <-time.After(15 * time.Minute):
1320                         cl.lock()
1321                         cl.clearAcceptLimits()
1322                         cl.unlock()
1323                 }
1324         }
1325 }
1326
1327 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1328         if cl.config.DisableAcceptRateLimiting {
1329                 return false
1330         }
1331         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1332 }
1333
1334 func (cl *Client) rLock() {
1335         cl._mu.RLock()
1336 }
1337
1338 func (cl *Client) rUnlock() {
1339         cl._mu.RUnlock()
1340 }
1341
1342 func (cl *Client) lock() {
1343         cl._mu.Lock()
1344 }
1345
1346 func (cl *Client) unlock() {
1347         cl._mu.Unlock()
1348 }
1349
1350 func (cl *Client) locker() sync.Locker {
1351         return clientLocker{cl}
1352 }
1353
1354 type clientLocker struct {
1355         *Client
1356 }
1357
1358 func (cl clientLocker) Lock() {
1359         cl.lock()
1360 }
1361
1362 func (cl clientLocker) Unlock() {
1363         cl.unlock()
1364 }