]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
4e40197a1bb6f81ccd6cd23de2ac75af91ef47db
[btrtrc.git] / client.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "crypto/rand"
7         "encoding/hex"
8         "errors"
9         "fmt"
10         "io"
11         "log"
12         "net"
13         "net/url"
14         "strconv"
15         "strings"
16         "time"
17
18         "github.com/anacrolix/dht"
19         "github.com/anacrolix/dht/krpc"
20         "github.com/anacrolix/missinggo"
21         "github.com/anacrolix/missinggo/pproffd"
22         "github.com/anacrolix/missinggo/pubsub"
23         "github.com/anacrolix/missinggo/slices"
24         "github.com/anacrolix/sync"
25         "github.com/dustin/go-humanize"
26         "golang.org/x/time/rate"
27
28         "github.com/anacrolix/torrent/bencode"
29         "github.com/anacrolix/torrent/iplist"
30         "github.com/anacrolix/torrent/metainfo"
31         "github.com/anacrolix/torrent/mse"
32         pp "github.com/anacrolix/torrent/peer_protocol"
33         "github.com/anacrolix/torrent/storage"
34 )
35
36 // Clients contain zero or more Torrents. A Client manages a blocklist, the
37 // TCP/UDP protocol ports, and DHT as desired.
38 type Client struct {
39         mu     sync.RWMutex
40         event  sync.Cond
41         closed missinggo.Event
42
43         config Config
44
45         halfOpenLimit  int
46         peerID         [20]byte
47         defaultStorage *storage.Client
48         onClose        []func()
49         tcpListener    net.Listener
50         utpSock        utpSocket
51         dHT            *dht.Server
52         ipBlockList    iplist.Ranger
53         // Our BitTorrent protocol extension bytes, sent in our BT handshakes.
54         extensionBytes peerExtensionBytes
55         // The net.Addr.String part that should be common to all active listeners.
56         listenAddr    string
57         uploadLimit   *rate.Limiter
58         downloadLimit *rate.Limiter
59
60         // Set of addresses that have our client ID. This intentionally will
61         // include ourselves if we end up trying to connect to our own address
62         // through legitimate channels.
63         dopplegangerAddrs map[string]struct{}
64         badPeerIPs        map[string]struct{}
65         torrents          map[metainfo.Hash]*Torrent
66 }
67
68 func (cl *Client) BadPeerIPs() []string {
69         cl.mu.RLock()
70         defer cl.mu.RUnlock()
71         return cl.badPeerIPsLocked()
72 }
73
74 func (cl *Client) badPeerIPsLocked() []string {
75         return slices.FromMapKeys(cl.badPeerIPs).([]string)
76 }
77
78 func (cl *Client) IPBlockList() iplist.Ranger {
79         cl.mu.Lock()
80         defer cl.mu.Unlock()
81         return cl.ipBlockList
82 }
83
84 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
85         cl.mu.Lock()
86         defer cl.mu.Unlock()
87         cl.ipBlockList = list
88         if cl.dHT != nil {
89                 cl.dHT.SetIPBlockList(list)
90         }
91 }
92
93 func (cl *Client) PeerID() string {
94         return string(cl.peerID[:])
95 }
96
97 type torrentAddr string
98
99 func (torrentAddr) Network() string { return "" }
100
101 func (me torrentAddr) String() string { return string(me) }
102
103 func (cl *Client) ListenAddr() net.Addr {
104         if cl.listenAddr == "" {
105                 return nil
106         }
107         return torrentAddr(cl.listenAddr)
108 }
109
110 // Writes out a human readable status of the client, such as for writing to a
111 // HTTP status page.
112 func (cl *Client) WriteStatus(_w io.Writer) {
113         cl.mu.Lock()
114         defer cl.mu.Unlock()
115         w := bufio.NewWriter(_w)
116         defer w.Flush()
117         if addr := cl.ListenAddr(); addr != nil {
118                 fmt.Fprintf(w, "Listening on %s\n", addr)
119         } else {
120                 fmt.Fprintln(w, "Not listening!")
121         }
122         fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
123         fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
124         if dht := cl.DHT(); dht != nil {
125                 dhtStats := dht.Stats()
126                 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
127                 fmt.Fprintf(w, "DHT Server ID: %x\n", dht.ID())
128                 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(dht.Addr()))
129                 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
130                 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
131         }
132         fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice()))
133         fmt.Fprintln(w)
134         for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool {
135                 return l.InfoHash().AsString() < r.InfoHash().AsString()
136         }).([]*Torrent) {
137                 if t.name() == "" {
138                         fmt.Fprint(w, "<unknown name>")
139                 } else {
140                         fmt.Fprint(w, t.name())
141                 }
142                 fmt.Fprint(w, "\n")
143                 if t.Info() != nil {
144                         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())))
145                 } else {
146                         w.WriteString("<missing metainfo>")
147                 }
148                 fmt.Fprint(w, "\n")
149                 t.writeStatus(w)
150                 fmt.Fprintln(w)
151         }
152 }
153
154 func listenUTP(networkSuffix, addr string) (utpSocket, error) {
155         return NewUtpSocket("udp"+networkSuffix, addr)
156 }
157
158 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
159         return net.Listen("tcp"+networkSuffix, addr)
160 }
161
162 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
163         for {
164                 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
165                 if err != nil {
166                         return
167                 }
168                 listenedAddr = tcpL.Addr().String()
169                 utpSock, err = listenUTP(networkSuffix, listenedAddr)
170                 if err == nil {
171                         return
172                 }
173                 tcpL.Close()
174                 if !strings.Contains(err.Error(), "address already in use") {
175                         return
176                 }
177         }
178 }
179
180 // Listen to enabled protocols, ensuring ports match.
181 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock utpSocket, listenedAddr string, err error) {
182         if addr == "" {
183                 addr = ":50007"
184         }
185         if tcp && utp {
186                 var host string
187                 var port int
188                 host, port, err = missinggo.ParseHostPort(addr)
189                 if err != nil {
190                         return
191                 }
192                 if port == 0 {
193                         // If both protocols are active, they need to have the same port.
194                         return listenBothSameDynamicPort(networkSuffix, host)
195                 }
196         }
197         defer func() {
198                 if err != nil {
199                         listenedAddr = ""
200                 }
201         }()
202         if tcp {
203                 tcpL, err = listenTCP(networkSuffix, addr)
204                 if err != nil {
205                         return
206                 }
207                 defer func() {
208                         if err != nil {
209                                 tcpL.Close()
210                         }
211                 }()
212                 listenedAddr = tcpL.Addr().String()
213         }
214         if utp {
215                 utpSock, err = listenUTP(networkSuffix, addr)
216                 if err != nil {
217                         return
218                 }
219                 listenedAddr = utpSock.Addr().String()
220         }
221         return
222 }
223
224 // Creates a new client.
225 func NewClient(cfg *Config) (cl *Client, err error) {
226         if cfg == nil {
227                 cfg = &Config{}
228         }
229
230         defer func() {
231                 if err != nil {
232                         cl = nil
233                 }
234         }()
235         cl = &Client{
236                 halfOpenLimit:     defaultHalfOpenConnsPerTorrent,
237                 config:            *cfg,
238                 dopplegangerAddrs: make(map[string]struct{}),
239                 torrents:          make(map[metainfo.Hash]*Torrent),
240         }
241         defer func() {
242                 if err == nil {
243                         return
244                 }
245                 cl.Close()
246         }()
247         if cfg.UploadRateLimiter == nil {
248                 cl.uploadLimit = rate.NewLimiter(rate.Inf, 0)
249         } else {
250                 cl.uploadLimit = cfg.UploadRateLimiter
251         }
252         if cfg.DownloadRateLimiter == nil {
253                 cl.downloadLimit = rate.NewLimiter(rate.Inf, 0)
254         } else {
255                 cl.downloadLimit = cfg.DownloadRateLimiter
256         }
257         missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
258         cl.event.L = &cl.mu
259         storageImpl := cfg.DefaultStorage
260         if storageImpl == nil {
261                 storageImpl = storage.NewFile(cfg.DataDir)
262                 cl.onClose = append(cl.onClose, func() {
263                         if err := storageImpl.Close(); err != nil {
264                                 log.Printf("error closing default storage: %s", err)
265                         }
266                 })
267         }
268         cl.defaultStorage = storage.NewClient(storageImpl)
269         if cfg.IPBlocklist != nil {
270                 cl.ipBlockList = cfg.IPBlocklist
271         }
272
273         if cfg.PeerID != "" {
274                 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
275         } else {
276                 o := copy(cl.peerID[:], bep20)
277                 _, err = rand.Read(cl.peerID[o:])
278                 if err != nil {
279                         panic("error generating peer id")
280                 }
281         }
282
283         cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
284                 !cl.config.DisableTCP,
285                 !cl.config.DisableUTP,
286                 func() string {
287                         if cl.config.DisableIPv6 {
288                                 return "4"
289                         } else {
290                                 return ""
291                         }
292                 }(),
293                 cl.config.ListenAddr)
294         if err != nil {
295                 return
296         }
297         if cl.tcpListener != nil {
298                 go cl.acceptConnections(cl.tcpListener, false)
299         }
300         if cl.utpSock != nil {
301                 go cl.acceptConnections(cl.utpSock, true)
302         }
303         if !cfg.NoDHT {
304                 dhtCfg := cfg.DHTConfig
305                 if dhtCfg.IPBlocklist == nil {
306                         dhtCfg.IPBlocklist = cl.ipBlockList
307                 }
308                 if dhtCfg.Conn == nil {
309                         if cl.utpSock != nil {
310                                 dhtCfg.Conn = cl.utpSock
311                         } else {
312                                 dhtCfg.Conn, err = net.ListenPacket("udp", firstNonEmptyString(cl.listenAddr, cl.config.ListenAddr))
313                                 if err != nil {
314                                         return
315                                 }
316                         }
317                 }
318                 if dhtCfg.OnAnnouncePeer == nil {
319                         dhtCfg.OnAnnouncePeer = cl.onDHTAnnouncePeer
320                 }
321                 cl.dHT, err = dht.NewServer(&dhtCfg)
322                 if err != nil {
323                         return
324                 }
325                 go func() {
326                         if _, err := cl.dHT.Bootstrap(); err != nil {
327                                 log.Printf("error bootstrapping dht: %s", err)
328                         }
329                 }()
330         }
331
332         return
333 }
334
335 func firstNonEmptyString(ss ...string) string {
336         for _, s := range ss {
337                 if s != "" {
338                         return s
339                 }
340         }
341         return ""
342 }
343
344 // Stops the client. All connections to peers are closed and all activity will
345 // come to a halt.
346 func (cl *Client) Close() {
347         cl.mu.Lock()
348         defer cl.mu.Unlock()
349         cl.closed.Set()
350         if cl.dHT != nil {
351                 cl.dHT.Close()
352         }
353         if cl.utpSock != nil {
354                 cl.utpSock.Close()
355         }
356         if cl.tcpListener != nil {
357                 cl.tcpListener.Close()
358         }
359         for _, t := range cl.torrents {
360                 t.close()
361         }
362         for _, f := range cl.onClose {
363                 f()
364         }
365         cl.event.Broadcast()
366 }
367
368 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
369
370 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
371         if cl.ipBlockList == nil {
372                 return
373         }
374         ip4 := ip.To4()
375         // If blocklists are enabled, then block non-IPv4 addresses, because
376         // blocklists do not yet support IPv6.
377         if ip4 == nil {
378                 if missinggo.CryHeard() {
379                         log.Printf("blocking non-IPv4 address: %s", ip)
380                 }
381                 r = ipv6BlockRange
382                 blocked = true
383                 return
384         }
385         return cl.ipBlockList.Lookup(ip4)
386 }
387
388 func (cl *Client) waitAccept() {
389         for {
390                 for _, t := range cl.torrents {
391                         if t.wantConns() {
392                                 return
393                         }
394                 }
395                 if cl.closed.IsSet() {
396                         return
397                 }
398                 cl.event.Wait()
399         }
400 }
401
402 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
403         cl.mu.Lock()
404         defer cl.mu.Unlock()
405         for {
406                 cl.waitAccept()
407                 cl.mu.Unlock()
408                 conn, err := l.Accept()
409                 conn = pproffd.WrapNetConn(conn)
410                 cl.mu.Lock()
411                 if cl.closed.IsSet() {
412                         if conn != nil {
413                                 conn.Close()
414                         }
415                         return
416                 }
417                 if err != nil {
418                         log.Print(err)
419                         // I think something harsher should happen here? Our accept
420                         // routine just fucked off.
421                         return
422                 }
423                 if utp {
424                         acceptUTP.Add(1)
425                 } else {
426                         acceptTCP.Add(1)
427                 }
428                 if cl.config.Debug {
429                         log.Printf("accepted connection from %s", conn.RemoteAddr())
430                 }
431                 reject := cl.badPeerIPPort(
432                         missinggo.AddrIP(conn.RemoteAddr()),
433                         missinggo.AddrPort(conn.RemoteAddr()))
434                 if reject {
435                         if cl.config.Debug {
436                                 log.Printf("rejecting connection from %s", conn.RemoteAddr())
437                         }
438                         acceptReject.Add(1)
439                         conn.Close()
440                         continue
441                 }
442                 go cl.incomingConnection(conn, utp)
443         }
444 }
445
446 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
447         defer nc.Close()
448         if tc, ok := nc.(*net.TCPConn); ok {
449                 tc.SetLinger(0)
450         }
451         c := cl.newConnection(nc)
452         c.Discovery = peerSourceIncoming
453         c.uTP = utp
454         cl.runReceivedConn(c)
455 }
456
457 // Returns a handle to the given torrent, if it's present in the client.
458 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
459         cl.mu.Lock()
460         defer cl.mu.Unlock()
461         t, ok = cl.torrents[ih]
462         return
463 }
464
465 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
466         return cl.torrents[ih]
467 }
468
469 type dialResult struct {
470         Conn net.Conn
471         UTP  bool
472 }
473
474 func doDial(dial func(string, *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
475         conn, err := dial(addr, t)
476         if err != nil {
477                 if conn != nil {
478                         conn.Close()
479                 }
480                 conn = nil // Pedantic
481         }
482         ch <- dialResult{conn, utp}
483         if err == nil {
484                 successfulDials.Add(1)
485                 return
486         }
487         unsuccessfulDials.Add(1)
488 }
489
490 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
491         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
492         if ret < minDialTimeout {
493                 ret = minDialTimeout
494         }
495         return
496 }
497
498 // Returns whether an address is known to connect to a client with our own ID.
499 func (cl *Client) dopplegangerAddr(addr string) bool {
500         _, ok := cl.dopplegangerAddrs[addr]
501         return ok
502 }
503
504 // Start the process of connecting to the given peer for the given torrent if
505 // appropriate.
506 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
507         if peer.Id == cl.peerID {
508                 return
509         }
510         if cl.badPeerIPPort(peer.IP, peer.Port) {
511                 return
512         }
513         addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
514         if t.addrActive(addr) {
515                 return
516         }
517         t.halfOpen[addr] = struct{}{}
518         go cl.outgoingConnection(t, addr, peer.Source)
519 }
520
521 func (cl *Client) dialTimeout(t *Torrent) time.Duration {
522         cl.mu.Lock()
523         pendingPeers := len(t.peers)
524         cl.mu.Unlock()
525         return reducedDialTimeout(nominalDialTimeout, cl.halfOpenLimit, pendingPeers)
526 }
527
528 func (cl *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
529         c, err = net.DialTimeout("tcp", addr, cl.dialTimeout(t))
530         if err == nil {
531                 c.(*net.TCPConn).SetLinger(0)
532         }
533         c = pproffd.WrapNetConn(c)
534         return
535 }
536
537 func (cl *Client) dialUTP(addr string, t *Torrent) (net.Conn, error) {
538         return cl.utpSock.DialTimeout(addr, cl.dialTimeout(t))
539 }
540
541 // Returns a connection over UTP or TCP, whichever is first to connect.
542 func (cl *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
543         // Initiate connections via TCP and UTP simultaneously. Use the first one
544         // that succeeds.
545         left := 0
546         resCh := make(chan dialResult, left)
547         if !cl.config.DisableUTP {
548                 left++
549                 go doDial(cl.dialUTP, resCh, true, addr, t)
550         }
551         if !cl.config.DisableTCP {
552                 left++
553                 go doDial(cl.dialTCP, resCh, false, addr, t)
554         }
555         var res dialResult
556         // Wait for a successful connection.
557         for ; left > 0 && res.Conn == nil; left-- {
558                 res = <-resCh
559         }
560         if left > 0 {
561                 // There are still incompleted dials.
562                 go func() {
563                         for ; left > 0; left-- {
564                                 conn := (<-resCh).Conn
565                                 if conn != nil {
566                                         conn.Close()
567                                 }
568                         }
569                 }()
570         }
571         conn = res.Conn
572         utp = res.UTP
573         return
574 }
575
576 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
577         if _, ok := t.halfOpen[addr]; !ok {
578                 panic("invariant broken")
579         }
580         delete(t.halfOpen, addr)
581         cl.openNewConns(t)
582 }
583
584 // Performs initiator handshakes and returns a connection. Returns nil
585 // *connection if no connection for valid reasons.
586 func (cl *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
587         c = cl.newConnection(nc)
588         c.encrypted = encrypted
589         c.uTP = utp
590         err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
591         if err != nil {
592                 return
593         }
594         ok, err := cl.initiateHandshakes(c, t)
595         if !ok {
596                 c = nil
597         }
598         return
599 }
600
601 // Returns nil connection and nil error if no connection could be established
602 // for valid reasons.
603 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
604         nc, utp := cl.dialFirst(addr, t)
605         if nc == nil {
606                 return
607         }
608         encryptFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
609         c, err = cl.handshakesConnection(nc, t, encryptFirst, utp)
610         if err != nil {
611                 nc.Close()
612                 return
613         } else if c != nil {
614                 return
615         }
616         nc.Close()
617         if cl.config.DisableEncryption || cl.config.ForceEncryption {
618                 // There's no alternate encryption case to try.
619                 return
620         }
621         // Try again with encryption if we didn't earlier, or without if we did,
622         // using whichever protocol type worked last time.
623         if utp {
624                 nc, err = cl.dialUTP(addr, t)
625         } else {
626                 nc, err = cl.dialTCP(addr, t)
627         }
628         if err != nil {
629                 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
630                 return
631         }
632         c, err = cl.handshakesConnection(nc, t, !encryptFirst, utp)
633         if err != nil || c == nil {
634                 nc.Close()
635         }
636         return
637 }
638
639 // Called to dial out and run a connection. The addr we're given is already
640 // considered half-open.
641 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
642         c, err := cl.establishOutgoingConn(t, addr)
643         cl.mu.Lock()
644         defer cl.mu.Unlock()
645         // Don't release lock between here and addConnection, unless it's for
646         // failure.
647         cl.noLongerHalfOpen(t, addr)
648         if err != nil {
649                 if cl.config.Debug {
650                         log.Printf("error establishing outgoing connection: %s", err)
651                 }
652                 return
653         }
654         if c == nil {
655                 return
656         }
657         defer c.Close()
658         c.Discovery = ps
659         cl.runInitiatedHandshookConn(c, t)
660 }
661
662 // The port number for incoming peer connections. 0 if the client isn't
663 // listening.
664 func (cl *Client) incomingPeerPort() int {
665         if cl.listenAddr == "" {
666                 return 0
667         }
668         _, port, err := missinggo.ParseHostPort(cl.listenAddr)
669         if err != nil {
670                 panic(err)
671         }
672         return port
673 }
674
675 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
676 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
677 func addrCompactIP(addr net.Addr) (string, error) {
678         host, _, err := net.SplitHostPort(addr.String())
679         if err != nil {
680                 return "", err
681         }
682         ip := net.ParseIP(host)
683         if v4 := ip.To4(); v4 != nil {
684                 if len(v4) != 4 {
685                         panic(v4)
686                 }
687                 return string(v4), nil
688         }
689         return string(ip.To16()), nil
690 }
691
692 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
693         var err error
694         for b := range bb {
695                 _, err = w.Write(b)
696                 if err != nil {
697                         break
698                 }
699         }
700         done <- err
701 }
702
703 type (
704         peerExtensionBytes [8]byte
705         peerID             [20]byte
706 )
707
708 func (pex *peerExtensionBytes) SupportsExtended() bool {
709         return pex[5]&0x10 != 0
710 }
711
712 func (pex *peerExtensionBytes) SupportsDHT() bool {
713         return pex[7]&0x01 != 0
714 }
715
716 func (pex *peerExtensionBytes) SupportsFast() bool {
717         return pex[7]&0x04 != 0
718 }
719
720 type handshakeResult struct {
721         peerExtensionBytes
722         peerID
723         metainfo.Hash
724 }
725
726 // ih is nil if we expect the peer to declare the InfoHash, such as when the
727 // peer initiated the connection. Returns ok if the handshake was successful,
728 // and err if there was an unexpected condition other than the peer simply
729 // abandoning the handshake.
730 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
731         // Bytes to be sent to the peer. Should never block the sender.
732         postCh := make(chan []byte, 4)
733         // A single error value sent when the writer completes.
734         writeDone := make(chan error, 1)
735         // Performs writes to the socket and ensures posts don't block.
736         go handshakeWriter(sock, postCh, writeDone)
737
738         defer func() {
739                 close(postCh) // Done writing.
740                 if !ok {
741                         return
742                 }
743                 if err != nil {
744                         panic(err)
745                 }
746                 // Wait until writes complete before returning from handshake.
747                 err = <-writeDone
748                 if err != nil {
749                         err = fmt.Errorf("error writing: %s", err)
750                 }
751         }()
752
753         post := func(bb []byte) {
754                 select {
755                 case postCh <- bb:
756                 default:
757                         panic("mustn't block while posting")
758                 }
759         }
760
761         post([]byte(pp.Protocol))
762         post(extensions[:])
763         if ih != nil { // We already know what we want.
764                 post(ih[:])
765                 post(peerID[:])
766         }
767         var b [68]byte
768         _, err = io.ReadFull(sock, b[:68])
769         if err != nil {
770                 err = nil
771                 return
772         }
773         if string(b[:20]) != pp.Protocol {
774                 return
775         }
776         missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
777         missinggo.CopyExact(&res.Hash, b[28:48])
778         missinggo.CopyExact(&res.peerID, b[48:68])
779         peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
780
781         // TODO: Maybe we can just drop peers here if we're not interested. This
782         // could prevent them trying to reconnect, falsely believing there was
783         // just a problem.
784         if ih == nil { // We were waiting for the peer to tell us what they wanted.
785                 post(res.Hash[:])
786                 post(peerID[:])
787         }
788
789         ok = true
790         return
791 }
792
793 // Wraps a raw connection and provides the interface we want for using the
794 // connection in the message loop.
795 type deadlineReader struct {
796         nc net.Conn
797         r  io.Reader
798 }
799
800 func (r deadlineReader) Read(b []byte) (n int, err error) {
801         // Keep-alives should be received every 2 mins. Give a bit of gracetime.
802         err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
803         if err != nil {
804                 err = fmt.Errorf("error setting read deadline: %s", err)
805         }
806         n, err = r.r.Read(b)
807         // Convert common errors into io.EOF.
808         // if err != nil {
809         //      if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
810         //              err = io.EOF
811         //      } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
812         //              if n != 0 {
813         //                      panic(n)
814         //              }
815         //              err = io.EOF
816         //      }
817         // }
818         return
819 }
820
821 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys mse.SecretKeyIter) (ret io.ReadWriter, encrypted bool, err error) {
822         var protocol [len(pp.Protocol)]byte
823         _, err = io.ReadFull(rw, protocol[:])
824         if err != nil {
825                 return
826         }
827         ret = struct {
828                 io.Reader
829                 io.Writer
830         }{
831                 io.MultiReader(bytes.NewReader(protocol[:]), rw),
832                 rw,
833         }
834         if string(protocol[:]) == pp.Protocol {
835                 return
836         }
837         encrypted = true
838         ret, err = mse.ReceiveHandshakeLazy(ret, skeys)
839         return
840 }
841
842 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
843         if c.encrypted {
844                 var rw io.ReadWriter
845                 rw, err = mse.InitiateHandshake(struct {
846                         io.Reader
847                         io.Writer
848                 }{c.r, c.w}, t.infoHash[:], nil)
849                 c.setRW(rw)
850                 if err != nil {
851                         return
852                 }
853         }
854         ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
855         if ih != t.infoHash {
856                 ok = false
857         }
858         return
859 }
860
861 // Calls f with any secret keys.
862 func (cl *Client) forSkeys(f func([]byte) bool) {
863         cl.mu.Lock()
864         defer cl.mu.Unlock()
865         for ih := range cl.torrents {
866                 if !f(ih[:]) {
867                         break
868                 }
869         }
870 }
871
872 // Do encryption and bittorrent handshakes as receiver.
873 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
874         if !cl.config.DisableEncryption {
875                 var rw io.ReadWriter
876                 rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw(), cl.forSkeys)
877                 c.setRW(rw)
878                 if err != nil {
879                         if err == mse.ErrNoSecretKeyMatch {
880                                 err = nil
881                         }
882                         return
883                 }
884         }
885         if cl.config.ForceEncryption && !c.encrypted {
886                 err = errors.New("connection not encrypted")
887                 return
888         }
889         ih, ok, err := cl.connBTHandshake(c, nil)
890         if err != nil {
891                 err = fmt.Errorf("error during bt handshake: %s", err)
892                 return
893         }
894         if !ok {
895                 return
896         }
897         cl.mu.Lock()
898         t = cl.torrents[ih]
899         cl.mu.Unlock()
900         return
901 }
902
903 // Returns !ok if handshake failed for valid reasons.
904 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
905         res, ok, err := handshake(c.rw(), ih, cl.peerID, cl.extensionBytes)
906         if err != nil || !ok {
907                 return
908         }
909         ret = res.Hash
910         c.PeerExtensionBytes = res.peerExtensionBytes
911         c.PeerID = res.peerID
912         c.completedHandshake = time.Now()
913         return
914 }
915
916 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
917         if c.PeerID == cl.peerID {
918                 connsToSelf.Add(1)
919                 addr := c.conn.RemoteAddr().String()
920                 cl.dopplegangerAddrs[addr] = struct{}{}
921                 return
922         }
923         cl.runHandshookConn(c, t, true)
924 }
925
926 func (cl *Client) runReceivedConn(c *connection) {
927         err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
928         if err != nil {
929                 panic(err)
930         }
931         t, err := cl.receiveHandshakes(c)
932         if err != nil {
933                 if cl.config.Debug {
934                         log.Printf("error receiving handshakes: %s", err)
935                 }
936                 return
937         }
938         if t == nil {
939                 return
940         }
941         cl.mu.Lock()
942         defer cl.mu.Unlock()
943         if c.PeerID == cl.peerID {
944                 // Because the remote address is not necessarily the same as its
945                 // client's torrent listen address, we won't record the remote address
946                 // as a doppleganger. Instead, the initiator can record *us* as the
947                 // doppleganger.
948                 return
949         }
950         cl.runHandshookConn(c, t, false)
951 }
952
953 func (cl *Client) runHandshookConn(c *connection, t *Torrent, outgoing bool) {
954         c.conn.SetWriteDeadline(time.Time{})
955         c.r = deadlineReader{c.conn, c.r}
956         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
957         if !t.addConnection(c, outgoing) {
958                 return
959         }
960         defer t.dropConnection(c)
961         go c.writer(time.Minute)
962         cl.sendInitialMessages(c, t)
963         err := c.mainReadLoop()
964         if err != nil && cl.config.Debug {
965                 log.Printf("error during connection loop: %s", err)
966         }
967 }
968
969 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
970         if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
971                 conn.Post(pp.Message{
972                         Type:       pp.Extended,
973                         ExtendedID: pp.HandshakeExtendedID,
974                         ExtendedPayload: func() []byte {
975                                 d := map[string]interface{}{
976                                         "m": func() (ret map[string]int) {
977                                                 ret = make(map[string]int, 2)
978                                                 ret["ut_metadata"] = metadataExtendedId
979                                                 if !cl.config.DisablePEX {
980                                                         ret["ut_pex"] = pexExtendedId
981                                                 }
982                                                 return
983                                         }(),
984                                         "v": extendedHandshakeClientVersion,
985                                         // No upload queue is implemented yet.
986                                         "reqq": 64,
987                                 }
988                                 if !cl.config.DisableEncryption {
989                                         d["e"] = 1
990                                 }
991                                 if torrent.metadataSizeKnown() {
992                                         d["metadata_size"] = torrent.metadataSize()
993                                 }
994                                 if p := cl.incomingPeerPort(); p != 0 {
995                                         d["p"] = p
996                                 }
997                                 yourip, err := addrCompactIP(conn.remoteAddr())
998                                 if err != nil {
999                                         log.Printf("error calculating yourip field value in extension handshake: %s", err)
1000                                 } else {
1001                                         d["yourip"] = yourip
1002                                 }
1003                                 // log.Printf("sending %v", d)
1004                                 b, err := bencode.Marshal(d)
1005                                 if err != nil {
1006                                         panic(err)
1007                                 }
1008                                 return b
1009                         }(),
1010                 })
1011         }
1012         if torrent.haveAnyPieces() {
1013                 conn.Bitfield(torrent.bitfield())
1014         } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1015                 conn.Post(pp.Message{
1016                         Type: pp.HaveNone,
1017                 })
1018         }
1019         if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
1020                 conn.Post(pp.Message{
1021                         Type: pp.Port,
1022                         Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
1023                 })
1024         }
1025 }
1026
1027 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
1028         conn.updateRequests()
1029 }
1030
1031 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
1032         ok = cn.Cancel(r)
1033         if ok {
1034                 postedCancels.Add(1)
1035         }
1036         return
1037 }
1038
1039 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1040         if !cn.RequestPending(r) {
1041                 return false
1042         }
1043         delete(cn.Requests, r)
1044         return true
1045 }
1046
1047 // Process incoming ut_metadata message.
1048 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
1049         var d map[string]int
1050         err := bencode.Unmarshal(payload, &d)
1051         if err != nil {
1052                 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1053         }
1054         msgType, ok := d["msg_type"]
1055         if !ok {
1056                 return errors.New("missing msg_type field")
1057         }
1058         piece := d["piece"]
1059         switch msgType {
1060         case pp.DataMetadataExtensionMsgType:
1061                 if !c.requestedMetadataPiece(piece) {
1062                         return fmt.Errorf("got unexpected piece %d", piece)
1063                 }
1064                 c.metadataRequests[piece] = false
1065                 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1066                 if begin < 0 || begin >= len(payload) {
1067                         return fmt.Errorf("data has bad offset in payload: %d", begin)
1068                 }
1069                 t.saveMetadataPiece(piece, payload[begin:])
1070                 c.UsefulChunksReceived++
1071                 c.lastUsefulChunkReceived = time.Now()
1072                 return t.maybeCompleteMetadata()
1073         case pp.RequestMetadataExtensionMsgType:
1074                 if !t.haveMetadataPiece(piece) {
1075                         c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1076                         return nil
1077                 }
1078                 start := (1 << 14) * piece
1079                 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1080                 return nil
1081         case pp.RejectMetadataExtensionMsgType:
1082                 return nil
1083         default:
1084                 return errors.New("unknown msg_type value")
1085         }
1086 }
1087
1088 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1089         // Count the chunk being sent, even if it isn't.
1090         b := make([]byte, r.Length)
1091         p := t.info.Piece(int(r.Index))
1092         n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1093         if n != len(b) {
1094                 if err == nil {
1095                         panic("expected error")
1096                 }
1097                 return err
1098         }
1099         c.Post(pp.Message{
1100                 Type:  pp.Piece,
1101                 Index: r.Index,
1102                 Begin: r.Begin,
1103                 Piece: b,
1104         })
1105         c.chunksSent++
1106         uploadChunksPosted.Add(1)
1107         c.lastChunkSent = time.Now()
1108         return nil
1109 }
1110
1111 func (cl *Client) openNewConns(t *Torrent) {
1112         defer t.updateWantPeersEvent()
1113         for len(t.peers) != 0 {
1114                 if !t.wantConns() {
1115                         return
1116                 }
1117                 if len(t.halfOpen) >= cl.halfOpenLimit {
1118                         return
1119                 }
1120                 var (
1121                         k peersKey
1122                         p Peer
1123                 )
1124                 for k, p = range t.peers {
1125                         break
1126                 }
1127                 delete(t.peers, k)
1128                 cl.initiateConn(p, t)
1129         }
1130 }
1131
1132 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1133         if port == 0 {
1134                 return true
1135         }
1136         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1137                 return true
1138         }
1139         if _, ok := cl.ipBlockRange(ip); ok {
1140                 return true
1141         }
1142         if _, ok := cl.badPeerIPs[ip.String()]; ok {
1143                 return true
1144         }
1145         return false
1146 }
1147
1148 // Return a Torrent ready for insertion into a Client.
1149 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1150         // use provided storage, if provided
1151         storageClient := cl.defaultStorage
1152         if specStorage != nil {
1153                 storageClient = storage.NewClient(specStorage)
1154         }
1155
1156         t = &Torrent{
1157                 cl:       cl,
1158                 infoHash: ih,
1159                 peers:    make(map[peersKey]Peer),
1160                 conns:    make(map[*connection]struct{}, 2*defaultEstablishedConnsPerTorrent),
1161
1162                 halfOpen:          make(map[string]struct{}),
1163                 pieceStateChanges: pubsub.NewPubSub(),
1164
1165                 storageOpener:       storageClient,
1166                 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1167         }
1168         t.setChunkSize(defaultChunkSize)
1169         return
1170 }
1171
1172 // A file-like handle to some torrent data resource.
1173 type Handle interface {
1174         io.Reader
1175         io.Seeker
1176         io.Closer
1177         io.ReaderAt
1178 }
1179
1180 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1181         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1182 }
1183
1184 // Adds a torrent by InfoHash with a custom Storage implementation.
1185 // If the torrent already exists then this Storage is ignored and the
1186 // existing torrent returned with `new` set to `false`
1187 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1188         cl.mu.Lock()
1189         defer cl.mu.Unlock()
1190         t, ok := cl.torrents[infoHash]
1191         if ok {
1192                 return
1193         }
1194         new = true
1195         t = cl.newTorrent(infoHash, specStorage)
1196         if cl.dHT != nil {
1197                 go t.dhtAnnouncer()
1198         }
1199         cl.torrents[infoHash] = t
1200         t.updateWantPeersEvent()
1201         // Tickle Client.waitAccept, new torrent may want conns.
1202         cl.event.Broadcast()
1203         return
1204 }
1205
1206 // Add or merge a torrent spec. If the torrent is already present, the
1207 // trackers will be merged with the existing ones. If the Info isn't yet
1208 // known, it will be set. The display name is replaced if the new spec
1209 // provides one. Returns new if the torrent wasn't already in the client.
1210 // Note that any `Storage` defined on the spec will be ignored if the
1211 // torrent is already present (i.e. `new` return value is `true`)
1212 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1213         t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1214         if spec.DisplayName != "" {
1215                 t.SetDisplayName(spec.DisplayName)
1216         }
1217         if spec.InfoBytes != nil {
1218                 err = t.SetInfoBytes(spec.InfoBytes)
1219                 if err != nil {
1220                         return
1221                 }
1222         }
1223         cl.mu.Lock()
1224         defer cl.mu.Unlock()
1225         if spec.ChunkSize != 0 {
1226                 t.setChunkSize(pp.Integer(spec.ChunkSize))
1227         }
1228         t.addTrackers(spec.Trackers)
1229         t.maybeNewConns()
1230         return
1231 }
1232
1233 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1234         t, ok := cl.torrents[infoHash]
1235         if !ok {
1236                 err = fmt.Errorf("no such torrent")
1237                 return
1238         }
1239         err = t.close()
1240         if err != nil {
1241                 panic(err)
1242         }
1243         delete(cl.torrents, infoHash)
1244         return
1245 }
1246
1247 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1248         _url, err := url.Parse(announceURL)
1249         if err != nil {
1250                 return
1251         }
1252         hmp := missinggo.SplitHostMaybePort(_url.Host)
1253         if hmp.Err != nil {
1254                 err = hmp.Err
1255                 return
1256         }
1257         addr, err := net.ResolveIPAddr("ip", hmp.Host)
1258         if err != nil {
1259                 return
1260         }
1261         cl.mu.RLock()
1262         _, blocked = cl.ipBlockRange(addr.IP)
1263         cl.mu.RUnlock()
1264         host = _url.Host
1265         hmp.Host = addr.String()
1266         _url.Host = hmp.String()
1267         urlToUse = _url.String()
1268         return
1269 }
1270
1271 func (cl *Client) allTorrentsCompleted() bool {
1272         for _, t := range cl.torrents {
1273                 if !t.haveInfo() {
1274                         return false
1275                 }
1276                 if t.numPiecesCompleted() != t.numPieces() {
1277                         return false
1278                 }
1279         }
1280         return true
1281 }
1282
1283 // Returns true when all torrents are completely downloaded and false if the
1284 // client is stopped before that.
1285 func (cl *Client) WaitAll() bool {
1286         cl.mu.Lock()
1287         defer cl.mu.Unlock()
1288         for !cl.allTorrentsCompleted() {
1289                 if cl.closed.IsSet() {
1290                         return false
1291                 }
1292                 cl.event.Wait()
1293         }
1294         return true
1295 }
1296
1297 // Returns handles to all the torrents loaded in the Client.
1298 func (cl *Client) Torrents() []*Torrent {
1299         cl.mu.Lock()
1300         defer cl.mu.Unlock()
1301         return cl.torrentsAsSlice()
1302 }
1303
1304 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1305         for _, t := range cl.torrents {
1306                 ret = append(ret, t)
1307         }
1308         return
1309 }
1310
1311 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1312         spec, err := TorrentSpecFromMagnetURI(uri)
1313         if err != nil {
1314                 return
1315         }
1316         T, _, err = cl.AddTorrentSpec(spec)
1317         return
1318 }
1319
1320 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1321         T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1322         var ss []string
1323         slices.MakeInto(&ss, mi.Nodes)
1324         cl.AddDHTNodes(ss)
1325         return
1326 }
1327
1328 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1329         mi, err := metainfo.LoadFromFile(filename)
1330         if err != nil {
1331                 return
1332         }
1333         return cl.AddTorrent(mi)
1334 }
1335
1336 func (cl *Client) DHT() *dht.Server {
1337         return cl.dHT
1338 }
1339
1340 func (cl *Client) AddDHTNodes(nodes []string) {
1341         if cl.DHT() == nil {
1342                 return
1343         }
1344         for _, n := range nodes {
1345                 hmp := missinggo.SplitHostMaybePort(n)
1346                 ip := net.ParseIP(hmp.Host)
1347                 if ip == nil {
1348                         log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1349                         continue
1350                 }
1351                 ni := krpc.NodeInfo{
1352                         Addr: &net.UDPAddr{
1353                                 IP:   ip,
1354                                 Port: hmp.Port,
1355                         },
1356                 }
1357                 cl.DHT().AddNode(ni)
1358         }
1359 }
1360
1361 func (cl *Client) banPeerIP(ip net.IP) {
1362         if cl.badPeerIPs == nil {
1363                 cl.badPeerIPs = make(map[string]struct{})
1364         }
1365         cl.badPeerIPs[ip.String()] = struct{}{}
1366 }
1367
1368 func (cl *Client) newConnection(nc net.Conn) (c *connection) {
1369         c = &connection{
1370                 conn: nc,
1371
1372                 Choked:          true,
1373                 PeerChoked:      true,
1374                 PeerMaxRequests: 250,
1375         }
1376         c.setRW(connStatsReadWriter{nc, &cl.mu, c})
1377         c.r = rateLimitedReader{cl.downloadLimit, c.r}
1378         return
1379 }
1380
1381 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, p dht.Peer) {
1382         cl.mu.Lock()
1383         defer cl.mu.Unlock()
1384         t := cl.torrent(ih)
1385         if t == nil {
1386                 return
1387         }
1388         t.addPeers([]Peer{{
1389                 IP:     p.IP,
1390                 Port:   p.Port,
1391                 Source: peerSourceDHTAnnouncePeer,
1392         }})
1393 }