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