]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
5d2c4e02abd4d1f98cc4ead3ddbe66b54240b948
[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         mathRand "math/rand"
13         "net"
14         "net/url"
15         "strconv"
16         "strings"
17         "time"
18
19         "github.com/anacrolix/missinggo"
20         "github.com/anacrolix/missinggo/pproffd"
21         "github.com/anacrolix/missinggo/pubsub"
22         "github.com/anacrolix/missinggo/slices"
23         "github.com/anacrolix/sync"
24         "github.com/anacrolix/utp"
25         "github.com/dustin/go-humanize"
26
27         "github.com/anacrolix/torrent/bencode"
28         "github.com/anacrolix/torrent/dht"
29         "github.com/anacrolix/torrent/dht/krpc"
30         "github.com/anacrolix/torrent/iplist"
31         "github.com/anacrolix/torrent/metainfo"
32         "github.com/anacrolix/torrent/mse"
33         pp "github.com/anacrolix/torrent/peer_protocol"
34         "github.com/anacrolix/torrent/storage"
35 )
36
37 // Currently doesn't really queue, but should in the future.
38 func (cl *Client) queuePieceCheck(t *Torrent, pieceIndex int) {
39         piece := &t.pieces[pieceIndex]
40         if piece.QueuedForHash {
41                 return
42         }
43         piece.QueuedForHash = true
44         t.publishPieceChange(pieceIndex)
45         go cl.verifyPiece(t, pieceIndex)
46 }
47
48 // Queue a piece check if one isn't already queued, and the piece has never
49 // been checked before.
50 func (cl *Client) queueFirstHash(t *Torrent, piece int) {
51         p := &t.pieces[piece]
52         if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
53                 return
54         }
55         cl.queuePieceCheck(t, piece)
56 }
57
58 // Clients contain zero or more Torrents. A Client manages a blocklist, the
59 // TCP/UDP protocol ports, and DHT as desired.
60 type Client struct {
61         halfOpenLimit int
62         peerID        [20]byte
63         // The net.Addr.String part that should be common to all active listeners.
64         listenAddr     string
65         tcpListener    net.Listener
66         utpSock        *utp.Socket
67         dHT            *dht.Server
68         ipBlockList    iplist.Ranger
69         config         Config
70         extensionBytes peerExtensionBytes
71         // Set of addresses that have our client ID. This intentionally will
72         // include ourselves if we end up trying to connect to our own address
73         // through legitimate channels.
74         dopplegangerAddrs map[string]struct{}
75         badPeerIPs        map[string]struct{}
76
77         defaultStorage storage.Client
78
79         mu     sync.RWMutex
80         event  sync.Cond
81         closed missinggo.Event
82
83         torrents map[metainfo.Hash]*Torrent
84 }
85
86 func (cl *Client) BadPeerIPs() []string {
87         cl.mu.RLock()
88         defer cl.mu.RUnlock()
89         return slices.FromMapKeys(cl.badPeerIPs).([]string)
90 }
91
92 func (cl *Client) IPBlockList() iplist.Ranger {
93         cl.mu.Lock()
94         defer cl.mu.Unlock()
95         return cl.ipBlockList
96 }
97
98 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
99         cl.mu.Lock()
100         defer cl.mu.Unlock()
101         cl.ipBlockList = list
102         if cl.dHT != nil {
103                 cl.dHT.SetIPBlockList(list)
104         }
105 }
106
107 func (cl *Client) PeerID() string {
108         return string(cl.peerID[:])
109 }
110
111 type torrentAddr string
112
113 func (me torrentAddr) Network() string { return "" }
114
115 func (me torrentAddr) String() string { return string(me) }
116
117 func (cl *Client) ListenAddr() net.Addr {
118         if cl.listenAddr == "" {
119                 return nil
120         }
121         return torrentAddr(cl.listenAddr)
122 }
123
124 func (cl *Client) sortedTorrents() (ret []*Torrent) {
125         return slices.Sort(slices.FromMapElems(cl.torrents), func(l, r metainfo.Hash) bool {
126                 return l.AsString() < r.AsString()
127         }).([]*Torrent)
128 }
129
130 // Writes out a human readable status of the client, such as for writing to a
131 // HTTP status page.
132 func (cl *Client) WriteStatus(_w io.Writer) {
133         w := bufio.NewWriter(_w)
134         defer w.Flush()
135         if addr := cl.ListenAddr(); addr != nil {
136                 fmt.Fprintf(w, "Listening on %s\n", addr)
137         } else {
138                 fmt.Fprintln(w, "Not listening!")
139         }
140         fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
141         fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.BadPeerIPs()))
142         if dht := cl.DHT(); dht != nil {
143                 dhtStats := dht.Stats()
144                 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
145                 fmt.Fprintf(w, "DHT Server ID: %x\n", dht.ID())
146                 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(dht.Addr()))
147                 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
148                 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
149         }
150         fmt.Fprintf(w, "# Torrents: %d\n", len(cl.Torrents()))
151         fmt.Fprintln(w)
152         for _, t := range slices.Sort(append([]*Torrent(nil), cl.Torrents()...), func(l, r *Torrent) bool {
153                 return l.InfoHash().AsString() < r.InfoHash().AsString()
154         }).([]*Torrent) {
155                 if t.Name() == "" {
156                         fmt.Fprint(w, "<unknown name>")
157                 } else {
158                         fmt.Fprint(w, t.Name())
159                 }
160                 fmt.Fprint(w, "\n")
161                 if t.Info() != nil {
162                         fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.BytesMissing())/float64(t.Info().TotalLength())), t.length, humanize.Bytes(uint64(t.Info().TotalLength())))
163                 } else {
164                         w.WriteString("<missing metainfo>")
165                 }
166                 fmt.Fprint(w, "\n")
167                 t.writeStatus(w)
168                 fmt.Fprintln(w)
169         }
170 }
171
172 func listenUTP(networkSuffix, addr string) (*utp.Socket, error) {
173         return utp.NewSocket("udp"+networkSuffix, addr)
174 }
175
176 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
177         return net.Listen("tcp"+networkSuffix, addr)
178 }
179
180 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock *utp.Socket, listenedAddr string, err error) {
181         for {
182                 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
183                 if err != nil {
184                         return
185                 }
186                 listenedAddr = tcpL.Addr().String()
187                 utpSock, err = listenUTP(networkSuffix, listenedAddr)
188                 if err == nil {
189                         return
190                 }
191                 tcpL.Close()
192                 if !strings.Contains(err.Error(), "address already in use") {
193                         return
194                 }
195         }
196 }
197
198 // Listen to enabled protocols, ensuring ports match.
199 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock *utp.Socket, listenedAddr string, err error) {
200         if addr == "" {
201                 addr = ":50007"
202         }
203         host, port, err := missinggo.ParseHostPort(addr)
204         if err != nil {
205                 return
206         }
207         if tcp && utp && port == 0 {
208                 // If both protocols are active, they need to have the same port.
209                 return listenBothSameDynamicPort(networkSuffix, host)
210         }
211         defer func() {
212                 if err != nil {
213                         listenedAddr = ""
214                 }
215         }()
216         if tcp {
217                 tcpL, err = listenTCP(networkSuffix, addr)
218                 if err != nil {
219                         return
220                 }
221                 defer func() {
222                         if err != nil {
223                                 tcpL.Close()
224                         }
225                 }()
226                 listenedAddr = tcpL.Addr().String()
227         }
228         if utp {
229                 utpSock, err = listenUTP(networkSuffix, addr)
230                 if err != nil {
231                         return
232                 }
233                 listenedAddr = utpSock.Addr().String()
234         }
235         return
236 }
237
238 // Creates a new client.
239 func NewClient(cfg *Config) (cl *Client, err error) {
240         if cfg == nil {
241                 cfg = &Config{}
242         }
243
244         defer func() {
245                 if err != nil {
246                         cl = nil
247                 }
248         }()
249         cl = &Client{
250                 halfOpenLimit:     defaultHalfOpenConnsPerTorrent,
251                 config:            *cfg,
252                 defaultStorage:    cfg.DefaultStorage,
253                 dopplegangerAddrs: make(map[string]struct{}),
254                 torrents:          make(map[metainfo.Hash]*Torrent),
255         }
256         missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
257         cl.event.L = &cl.mu
258         if cl.defaultStorage == nil {
259                 cl.defaultStorage = storage.NewFile(cfg.DataDir)
260         }
261         if cfg.IPBlocklist != nil {
262                 cl.ipBlockList = cfg.IPBlocklist
263         }
264
265         if cfg.PeerID != "" {
266                 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
267         } else {
268                 o := copy(cl.peerID[:], bep20)
269                 _, err = rand.Read(cl.peerID[o:])
270                 if err != nil {
271                         panic("error generating peer id")
272                 }
273         }
274
275         cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
276                 !cl.config.DisableTCP,
277                 !cl.config.DisableUTP,
278                 func() string {
279                         if cl.config.DisableIPv6 {
280                                 return "4"
281                         } else {
282                                 return ""
283                         }
284                 }(),
285                 cl.config.ListenAddr)
286         if err != nil {
287                 return
288         }
289         if cl.tcpListener != nil {
290                 go cl.acceptConnections(cl.tcpListener, false)
291         }
292         if cl.utpSock != nil {
293                 go cl.acceptConnections(cl.utpSock, true)
294         }
295         if !cfg.NoDHT {
296                 dhtCfg := cfg.DHTConfig
297                 if dhtCfg.IPBlocklist == nil {
298                         dhtCfg.IPBlocklist = cl.ipBlockList
299                 }
300                 dhtCfg.Addr = firstNonEmptyString(dhtCfg.Addr, cl.listenAddr, cl.config.ListenAddr)
301                 if dhtCfg.Conn == nil && cl.utpSock != nil {
302                         dhtCfg.Conn = cl.utpSock
303                 }
304                 cl.dHT, err = dht.NewServer(&dhtCfg)
305                 if err != nil {
306                         return
307                 }
308         }
309
310         return
311 }
312
313 func firstNonEmptyString(ss ...string) string {
314         for _, s := range ss {
315                 if s != "" {
316                         return s
317                 }
318         }
319         return ""
320 }
321
322 // Stops the client. All connections to peers are closed and all activity will
323 // come to a halt.
324 func (cl *Client) Close() {
325         cl.mu.Lock()
326         defer cl.mu.Unlock()
327         cl.closed.Set()
328         if cl.dHT != nil {
329                 cl.dHT.Close()
330         }
331         if cl.utpSock != nil {
332                 cl.utpSock.CloseNow()
333         }
334         if cl.tcpListener != nil {
335                 cl.tcpListener.Close()
336         }
337         for _, t := range cl.torrents {
338                 t.close()
339         }
340         cl.event.Broadcast()
341 }
342
343 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
344
345 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
346         if cl.ipBlockList == nil {
347                 return
348         }
349         ip4 := ip.To4()
350         // If blocklists are enabled, then block non-IPv4 addresses, because
351         // blocklists do not yet support IPv6.
352         if ip4 == nil {
353                 if missinggo.CryHeard() {
354                         log.Printf("blocking non-IPv4 address: %s", ip)
355                 }
356                 r = ipv6BlockRange
357                 blocked = true
358                 return
359         }
360         return cl.ipBlockList.Lookup(ip4)
361 }
362
363 func (cl *Client) waitAccept() {
364         for {
365                 for _, t := range cl.torrents {
366                         if t.wantConns() {
367                                 return
368                         }
369                 }
370                 if cl.closed.IsSet() {
371                         return
372                 }
373                 cl.event.Wait()
374         }
375 }
376
377 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
378         cl.mu.Lock()
379         defer cl.mu.Unlock()
380         for {
381                 cl.waitAccept()
382                 cl.mu.Unlock()
383                 conn, err := l.Accept()
384                 conn = pproffd.WrapNetConn(conn)
385                 cl.mu.Lock()
386                 if cl.closed.IsSet() {
387                         if conn != nil {
388                                 conn.Close()
389                         }
390                         return
391                 }
392                 if err != nil {
393                         log.Print(err)
394                         // I think something harsher should happen here? Our accept
395                         // routine just fucked off.
396                         return
397                 }
398                 if utp {
399                         acceptUTP.Add(1)
400                 } else {
401                         acceptTCP.Add(1)
402                 }
403                 reject := cl.badPeerIPPort(
404                         missinggo.AddrIP(conn.RemoteAddr()),
405                         missinggo.AddrPort(conn.RemoteAddr()))
406                 if reject {
407                         acceptReject.Add(1)
408                         conn.Close()
409                         continue
410                 }
411                 go cl.incomingConnection(conn, utp)
412         }
413 }
414
415 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
416         defer nc.Close()
417         if tc, ok := nc.(*net.TCPConn); ok {
418                 tc.SetLinger(0)
419         }
420         c := newConnection(nc, &cl.mu)
421         c.Discovery = peerSourceIncoming
422         c.uTP = utp
423         cl.runReceivedConn(c)
424 }
425
426 // Returns a handle to the given torrent, if it's present in the client.
427 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
428         cl.mu.Lock()
429         defer cl.mu.Unlock()
430         t, ok = cl.torrents[ih]
431         return
432 }
433
434 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
435         return cl.torrents[ih]
436 }
437
438 type dialResult struct {
439         Conn net.Conn
440         UTP  bool
441 }
442
443 func doDial(dial func(addr string, t *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
444         conn, err := dial(addr, t)
445         if err != nil {
446                 if conn != nil {
447                         conn.Close()
448                 }
449                 conn = nil // Pedantic
450         }
451         ch <- dialResult{conn, utp}
452         if err == nil {
453                 successfulDials.Add(1)
454                 return
455         }
456         unsuccessfulDials.Add(1)
457 }
458
459 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
460         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
461         if ret < minDialTimeout {
462                 ret = minDialTimeout
463         }
464         return
465 }
466
467 // Returns whether an address is known to connect to a client with our own ID.
468 func (cl *Client) dopplegangerAddr(addr string) bool {
469         _, ok := cl.dopplegangerAddrs[addr]
470         return ok
471 }
472
473 // Start the process of connecting to the given peer for the given torrent if
474 // appropriate.
475 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
476         if peer.Id == cl.peerID {
477                 return
478         }
479         if cl.badPeerIPPort(peer.IP, peer.Port) {
480                 return
481         }
482         addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
483         if t.addrActive(addr) {
484                 return
485         }
486         t.halfOpen[addr] = struct{}{}
487         go cl.outgoingConnection(t, addr, peer.Source)
488 }
489
490 func (cl *Client) dialTimeout(t *Torrent) time.Duration {
491         cl.mu.Lock()
492         pendingPeers := len(t.peers)
493         cl.mu.Unlock()
494         return reducedDialTimeout(nominalDialTimeout, cl.halfOpenLimit, pendingPeers)
495 }
496
497 func (cl *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
498         c, err = net.DialTimeout("tcp", addr, cl.dialTimeout(t))
499         if err == nil {
500                 c.(*net.TCPConn).SetLinger(0)
501         }
502         c = pproffd.WrapNetConn(c)
503         return
504 }
505
506 func (cl *Client) dialUTP(addr string, t *Torrent) (c net.Conn, err error) {
507         return cl.utpSock.DialTimeout(addr, cl.dialTimeout(t))
508 }
509
510 // Returns a connection over UTP or TCP, whichever is first to connect.
511 func (cl *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
512         // Initiate connections via TCP and UTP simultaneously. Use the first one
513         // that succeeds.
514         left := 0
515         if !cl.config.DisableUTP {
516                 left++
517         }
518         if !cl.config.DisableTCP {
519                 left++
520         }
521         resCh := make(chan dialResult, left)
522         if !cl.config.DisableUTP {
523                 go doDial(cl.dialUTP, resCh, true, addr, t)
524         }
525         if !cl.config.DisableTCP {
526                 go doDial(cl.dialTCP, resCh, false, addr, t)
527         }
528         var res dialResult
529         // Wait for a successful connection.
530         for ; left > 0 && res.Conn == nil; left-- {
531                 res = <-resCh
532         }
533         if left > 0 {
534                 // There are still incompleted dials.
535                 go func() {
536                         for ; left > 0; left-- {
537                                 conn := (<-resCh).Conn
538                                 if conn != nil {
539                                         conn.Close()
540                                 }
541                         }
542                 }()
543         }
544         conn = res.Conn
545         utp = res.UTP
546         return
547 }
548
549 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
550         if _, ok := t.halfOpen[addr]; !ok {
551                 panic("invariant broken")
552         }
553         delete(t.halfOpen, addr)
554         cl.openNewConns(t)
555 }
556
557 // Performs initiator handshakes and returns a connection. Returns nil
558 // *connection if no connection for valid reasons.
559 func (cl *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
560         c = newConnection(nc, &cl.mu)
561         c.encrypted = encrypted
562         c.uTP = utp
563         err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
564         if err != nil {
565                 return
566         }
567         ok, err := cl.initiateHandshakes(c, t)
568         if !ok {
569                 c = nil
570         }
571         return
572 }
573
574 // Returns nil connection and nil error if no connection could be established
575 // for valid reasons.
576 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
577         nc, utp := cl.dialFirst(addr, t)
578         if nc == nil {
579                 return
580         }
581         c, err = cl.handshakesConnection(nc, t, !cl.config.DisableEncryption, utp)
582         if err != nil {
583                 nc.Close()
584                 return
585         } else if c != nil {
586                 return
587         }
588         nc.Close()
589         if cl.config.DisableEncryption {
590                 // We already tried without encryption.
591                 return
592         }
593         // Try again without encryption, using whichever protocol type worked last
594         // time.
595         if utp {
596                 nc, err = cl.dialUTP(addr, t)
597         } else {
598                 nc, err = cl.dialTCP(addr, t)
599         }
600         if err != nil {
601                 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
602                 return
603         }
604         c, err = cl.handshakesConnection(nc, t, false, utp)
605         if err != nil || c == nil {
606                 nc.Close()
607         }
608         return
609 }
610
611 // Called to dial out and run a connection. The addr we're given is already
612 // considered half-open.
613 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
614         c, err := cl.establishOutgoingConn(t, addr)
615         cl.mu.Lock()
616         defer cl.mu.Unlock()
617         // Don't release lock between here and addConnection, unless it's for
618         // failure.
619         cl.noLongerHalfOpen(t, addr)
620         if err != nil {
621                 if cl.config.Debug {
622                         log.Printf("error establishing outgoing connection: %s", err)
623                 }
624                 return
625         }
626         if c == nil {
627                 return
628         }
629         defer c.Close()
630         c.Discovery = ps
631         cl.runInitiatedHandshookConn(c, t)
632 }
633
634 // The port number for incoming peer connections. 0 if the client isn't
635 // listening.
636 func (cl *Client) incomingPeerPort() int {
637         if cl.listenAddr == "" {
638                 return 0
639         }
640         _, port, err := missinggo.ParseHostPort(cl.listenAddr)
641         if err != nil {
642                 panic(err)
643         }
644         return port
645 }
646
647 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
648 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
649 func addrCompactIP(addr net.Addr) (string, error) {
650         host, _, err := net.SplitHostPort(addr.String())
651         if err != nil {
652                 return "", err
653         }
654         ip := net.ParseIP(host)
655         if v4 := ip.To4(); v4 != nil {
656                 if len(v4) != 4 {
657                         panic(v4)
658                 }
659                 return string(v4), nil
660         }
661         return string(ip.To16()), nil
662 }
663
664 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
665         var err error
666         for b := range bb {
667                 _, err = w.Write(b)
668                 if err != nil {
669                         break
670                 }
671         }
672         done <- err
673 }
674
675 type (
676         peerExtensionBytes [8]byte
677         peerID             [20]byte
678 )
679
680 func (pex *peerExtensionBytes) SupportsExtended() bool {
681         return pex[5]&0x10 != 0
682 }
683
684 func (pex *peerExtensionBytes) SupportsDHT() bool {
685         return pex[7]&0x01 != 0
686 }
687
688 func (pex *peerExtensionBytes) SupportsFast() bool {
689         return pex[7]&0x04 != 0
690 }
691
692 type handshakeResult struct {
693         peerExtensionBytes
694         peerID
695         metainfo.Hash
696 }
697
698 // ih is nil if we expect the peer to declare the InfoHash, such as when the
699 // peer initiated the connection. Returns ok if the handshake was successful,
700 // and err if there was an unexpected condition other than the peer simply
701 // abandoning the handshake.
702 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
703         // Bytes to be sent to the peer. Should never block the sender.
704         postCh := make(chan []byte, 4)
705         // A single error value sent when the writer completes.
706         writeDone := make(chan error, 1)
707         // Performs writes to the socket and ensures posts don't block.
708         go handshakeWriter(sock, postCh, writeDone)
709
710         defer func() {
711                 close(postCh) // Done writing.
712                 if !ok {
713                         return
714                 }
715                 if err != nil {
716                         panic(err)
717                 }
718                 // Wait until writes complete before returning from handshake.
719                 err = <-writeDone
720                 if err != nil {
721                         err = fmt.Errorf("error writing: %s", err)
722                 }
723         }()
724
725         post := func(bb []byte) {
726                 select {
727                 case postCh <- bb:
728                 default:
729                         panic("mustn't block while posting")
730                 }
731         }
732
733         post([]byte(pp.Protocol))
734         post(extensions[:])
735         if ih != nil { // We already know what we want.
736                 post(ih[:])
737                 post(peerID[:])
738         }
739         var b [68]byte
740         _, err = io.ReadFull(sock, b[:68])
741         if err != nil {
742                 err = nil
743                 return
744         }
745         if string(b[:20]) != pp.Protocol {
746                 return
747         }
748         missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
749         missinggo.CopyExact(&res.Hash, b[28:48])
750         missinggo.CopyExact(&res.peerID, b[48:68])
751         peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
752
753         // TODO: Maybe we can just drop peers here if we're not interested. This
754         // could prevent them trying to reconnect, falsely believing there was
755         // just a problem.
756         if ih == nil { // We were waiting for the peer to tell us what they wanted.
757                 post(res.Hash[:])
758                 post(peerID[:])
759         }
760
761         ok = true
762         return
763 }
764
765 // Wraps a raw connection and provides the interface we want for using the
766 // connection in the message loop.
767 type deadlineReader struct {
768         nc net.Conn
769         r  io.Reader
770 }
771
772 func (r deadlineReader) Read(b []byte) (n int, err error) {
773         // Keep-alives should be received every 2 mins. Give a bit of gracetime.
774         err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
775         if err != nil {
776                 err = fmt.Errorf("error setting read deadline: %s", err)
777         }
778         n, err = r.r.Read(b)
779         // Convert common errors into io.EOF.
780         // if err != nil {
781         //      if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
782         //              err = io.EOF
783         //      } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
784         //              if n != 0 {
785         //                      panic(n)
786         //              }
787         //              err = io.EOF
788         //      }
789         // }
790         return
791 }
792
793 type readWriter struct {
794         io.Reader
795         io.Writer
796 }
797
798 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
799         var protocol [len(pp.Protocol)]byte
800         _, err = io.ReadFull(rw, protocol[:])
801         if err != nil {
802                 return
803         }
804         ret = readWriter{
805                 io.MultiReader(bytes.NewReader(protocol[:]), rw),
806                 rw,
807         }
808         if string(protocol[:]) == pp.Protocol {
809                 return
810         }
811         encrypted = true
812         ret, err = mse.ReceiveHandshake(ret, skeys)
813         return
814 }
815
816 func (cl *Client) receiveSkeys() (ret [][]byte) {
817         for ih := range cl.torrents {
818                 ret = append(ret, ih[:])
819         }
820         return
821 }
822
823 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
824         if c.encrypted {
825                 c.rw, err = mse.InitiateHandshake(c.rw, t.infoHash[:], nil)
826                 if err != nil {
827                         return
828                 }
829         }
830         ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
831         if ih != t.infoHash {
832                 ok = false
833         }
834         return
835 }
836
837 // Do encryption and bittorrent handshakes as receiver.
838 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
839         cl.mu.Lock()
840         skeys := cl.receiveSkeys()
841         cl.mu.Unlock()
842         if !cl.config.DisableEncryption {
843                 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
844                 if err != nil {
845                         if err == mse.ErrNoSecretKeyMatch {
846                                 err = nil
847                         }
848                         return
849                 }
850         }
851         ih, ok, err := cl.connBTHandshake(c, nil)
852         if err != nil {
853                 err = fmt.Errorf("error during bt handshake: %s", err)
854                 return
855         }
856         if !ok {
857                 return
858         }
859         cl.mu.Lock()
860         t = cl.torrents[ih]
861         cl.mu.Unlock()
862         return
863 }
864
865 // Returns !ok if handshake failed for valid reasons.
866 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
867         res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
868         if err != nil || !ok {
869                 return
870         }
871         ret = res.Hash
872         c.PeerExtensionBytes = res.peerExtensionBytes
873         c.PeerID = res.peerID
874         c.completedHandshake = time.Now()
875         return
876 }
877
878 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
879         if c.PeerID == cl.peerID {
880                 connsToSelf.Add(1)
881                 addr := c.conn.RemoteAddr().String()
882                 cl.dopplegangerAddrs[addr] = struct{}{}
883                 return
884         }
885         cl.runHandshookConn(c, t)
886 }
887
888 func (cl *Client) runReceivedConn(c *connection) {
889         err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
890         if err != nil {
891                 panic(err)
892         }
893         t, err := cl.receiveHandshakes(c)
894         if err != nil {
895                 if cl.config.Debug {
896                         log.Printf("error receiving handshakes: %s", err)
897                 }
898                 return
899         }
900         if t == nil {
901                 return
902         }
903         cl.mu.Lock()
904         defer cl.mu.Unlock()
905         if c.PeerID == cl.peerID {
906                 // Because the remote address is not necessarily the same as its
907                 // client's torrent listen address, we won't record the remote address
908                 // as a doppleganger. Instead, the initiator can record *us* as the
909                 // doppleganger.
910                 return
911         }
912         cl.runHandshookConn(c, t)
913 }
914
915 func (cl *Client) runHandshookConn(c *connection, t *Torrent) {
916         c.conn.SetWriteDeadline(time.Time{})
917         c.rw = readWriter{
918                 deadlineReader{c.conn, c.rw},
919                 c.rw,
920         }
921         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
922         if !t.addConnection(c) {
923                 return
924         }
925         defer t.dropConnection(c)
926         go c.writer(time.Minute)
927         cl.sendInitialMessages(c, t)
928         err := cl.connectionLoop(t, c)
929         if err != nil && cl.config.Debug {
930                 log.Printf("error during connection loop: %s", err)
931         }
932 }
933
934 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
935         if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
936                 conn.Post(pp.Message{
937                         Type:       pp.Extended,
938                         ExtendedID: pp.HandshakeExtendedID,
939                         ExtendedPayload: func() []byte {
940                                 d := map[string]interface{}{
941                                         "m": func() (ret map[string]int) {
942                                                 ret = make(map[string]int, 2)
943                                                 ret["ut_metadata"] = metadataExtendedId
944                                                 if !cl.config.DisablePEX {
945                                                         ret["ut_pex"] = pexExtendedId
946                                                 }
947                                                 return
948                                         }(),
949                                         "v": extendedHandshakeClientVersion,
950                                         // No upload queue is implemented yet.
951                                         "reqq": 64,
952                                 }
953                                 if !cl.config.DisableEncryption {
954                                         d["e"] = 1
955                                 }
956                                 if torrent.metadataSizeKnown() {
957                                         d["metadata_size"] = torrent.metadataSize()
958                                 }
959                                 if p := cl.incomingPeerPort(); p != 0 {
960                                         d["p"] = p
961                                 }
962                                 yourip, err := addrCompactIP(conn.remoteAddr())
963                                 if err != nil {
964                                         log.Printf("error calculating yourip field value in extension handshake: %s", err)
965                                 } else {
966                                         d["yourip"] = yourip
967                                 }
968                                 // log.Printf("sending %v", d)
969                                 b, err := bencode.Marshal(d)
970                                 if err != nil {
971                                         panic(err)
972                                 }
973                                 return b
974                         }(),
975                 })
976         }
977         if torrent.haveAnyPieces() {
978                 conn.Bitfield(torrent.bitfield())
979         } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
980                 conn.Post(pp.Message{
981                         Type: pp.HaveNone,
982                 })
983         }
984         if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
985                 conn.Post(pp.Message{
986                         Type: pp.Port,
987                         Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
988                 })
989         }
990 }
991
992 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
993         conn.updateRequests()
994 }
995
996 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
997         ok = cn.Cancel(r)
998         if ok {
999                 postedCancels.Add(1)
1000         }
1001         return
1002 }
1003
1004 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1005         if !cn.RequestPending(r) {
1006                 return false
1007         }
1008         delete(cn.Requests, r)
1009         return true
1010 }
1011
1012 // Process incoming ut_metadata message.
1013 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error {
1014         var d map[string]int
1015         err := bencode.Unmarshal(payload, &d)
1016         if err != nil {
1017                 return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1018         }
1019         msgType, ok := d["msg_type"]
1020         if !ok {
1021                 return errors.New("missing msg_type field")
1022         }
1023         piece := d["piece"]
1024         switch msgType {
1025         case pp.DataMetadataExtensionMsgType:
1026                 if !c.requestedMetadataPiece(piece) {
1027                         return fmt.Errorf("got unexpected piece %d", piece)
1028                 }
1029                 c.metadataRequests[piece] = false
1030                 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1031                 if begin < 0 || begin >= len(payload) {
1032                         return fmt.Errorf("data has bad offset in payload: %d", begin)
1033                 }
1034                 t.saveMetadataPiece(piece, payload[begin:])
1035                 c.UsefulChunksReceived++
1036                 c.lastUsefulChunkReceived = time.Now()
1037                 return t.maybeCompleteMetadata()
1038         case pp.RequestMetadataExtensionMsgType:
1039                 if !t.haveMetadataPiece(piece) {
1040                         c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1041                         return nil
1042                 }
1043                 start := (1 << 14) * piece
1044                 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1045                 return nil
1046         case pp.RejectMetadataExtensionMsgType:
1047                 return nil
1048         default:
1049                 return errors.New("unknown msg_type value")
1050         }
1051 }
1052
1053 func (cl *Client) upload(t *Torrent, c *connection) {
1054         if cl.config.NoUpload {
1055                 return
1056         }
1057         if !c.PeerInterested {
1058                 return
1059         }
1060         seeding := t.seeding()
1061         if !seeding && !t.connHasWantedPieces(c) {
1062                 return
1063         }
1064 another:
1065         for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1066                 c.Unchoke()
1067                 for r := range c.PeerRequests {
1068                         err := cl.sendChunk(t, c, r)
1069                         if err != nil {
1070                                 i := int(r.Index)
1071                                 if t.pieceComplete(i) {
1072                                         t.updatePieceCompletion(i)
1073                                         if !t.pieceComplete(i) {
1074                                                 // We had the piece, but not anymore.
1075                                                 break another
1076                                         }
1077                                 }
1078                                 log.Printf("error sending chunk %+v to peer: %s", r, err)
1079                                 // If we failed to send a chunk, choke the peer to ensure they
1080                                 // flush all their requests. We've probably dropped a piece,
1081                                 // but there's no way to communicate this to the peer. If they
1082                                 // ask for it again, we'll kick them to allow us to send them
1083                                 // an updated bitfield.
1084                                 break another
1085                         }
1086                         delete(c.PeerRequests, r)
1087                         goto another
1088                 }
1089                 return
1090         }
1091         c.Choke()
1092 }
1093
1094 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1095         // Count the chunk being sent, even if it isn't.
1096         b := make([]byte, r.Length)
1097         p := t.info.Piece(int(r.Index))
1098         n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1099         if n != len(b) {
1100                 if err == nil {
1101                         panic("expected error")
1102                 }
1103                 return err
1104         }
1105         c.Post(pp.Message{
1106                 Type:  pp.Piece,
1107                 Index: r.Index,
1108                 Begin: r.Begin,
1109                 Piece: b,
1110         })
1111         c.chunksSent++
1112         uploadChunksPosted.Add(1)
1113         c.lastChunkSent = time.Now()
1114         return nil
1115 }
1116
1117 // Processes incoming bittorrent messages. The client lock is held upon entry
1118 // and exit. Returning will end the connection.
1119 func (cl *Client) connectionLoop(t *Torrent, c *connection) error {
1120         decoder := pp.Decoder{
1121                 R:         bufio.NewReader(c.rw),
1122                 MaxLength: 256 * 1024,
1123         }
1124         for {
1125                 cl.mu.Unlock()
1126                 var msg pp.Message
1127                 err := decoder.Decode(&msg)
1128                 cl.mu.Lock()
1129                 if cl.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1130                         return nil
1131                 }
1132                 if err != nil {
1133                         return err
1134                 }
1135                 c.readMsg(&msg)
1136                 c.lastMessageReceived = time.Now()
1137                 if msg.Keepalive {
1138                         receivedKeepalives.Add(1)
1139                         continue
1140                 }
1141                 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1142                 switch msg.Type {
1143                 case pp.Choke:
1144                         c.PeerChoked = true
1145                         c.Requests = nil
1146                         // We can then reset our interest.
1147                         c.updateRequests()
1148                 case pp.Reject:
1149                         cl.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1150                         c.updateRequests()
1151                 case pp.Unchoke:
1152                         c.PeerChoked = false
1153                         cl.peerUnchoked(t, c)
1154                 case pp.Interested:
1155                         c.PeerInterested = true
1156                         cl.upload(t, c)
1157                 case pp.NotInterested:
1158                         c.PeerInterested = false
1159                         c.Choke()
1160                 case pp.Have:
1161                         err = c.peerSentHave(int(msg.Index))
1162                 case pp.Request:
1163                         if c.Choked {
1164                                 break
1165                         }
1166                         if !c.PeerInterested {
1167                                 err = errors.New("peer sent request but isn't interested")
1168                                 break
1169                         }
1170                         if !t.havePiece(msg.Index.Int()) {
1171                                 // This isn't necessarily them screwing up. We can drop pieces
1172                                 // from our storage, and can't communicate this to peers
1173                                 // except by reconnecting.
1174                                 requestsReceivedForMissingPieces.Add(1)
1175                                 err = errors.New("peer requested piece we don't have")
1176                                 break
1177                         }
1178                         if c.PeerRequests == nil {
1179                                 c.PeerRequests = make(map[request]struct{}, maxRequests)
1180                         }
1181                         c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1182                         cl.upload(t, c)
1183                 case pp.Cancel:
1184                         req := newRequest(msg.Index, msg.Begin, msg.Length)
1185                         if !c.PeerCancel(req) {
1186                                 unexpectedCancels.Add(1)
1187                         }
1188                 case pp.Bitfield:
1189                         err = c.peerSentBitfield(msg.Bitfield)
1190                 case pp.HaveAll:
1191                         err = c.peerSentHaveAll()
1192                 case pp.HaveNone:
1193                         err = c.peerSentHaveNone()
1194                 case pp.Piece:
1195                         cl.downloadedChunk(t, c, &msg)
1196                 case pp.Extended:
1197                         switch msg.ExtendedID {
1198                         case pp.HandshakeExtendedID:
1199                                 // TODO: Create a bencode struct for this.
1200                                 var d map[string]interface{}
1201                                 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1202                                 if err != nil {
1203                                         err = fmt.Errorf("error decoding extended message payload: %s", err)
1204                                         break
1205                                 }
1206                                 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1207                                 if reqq, ok := d["reqq"]; ok {
1208                                         if i, ok := reqq.(int64); ok {
1209                                                 c.PeerMaxRequests = int(i)
1210                                         }
1211                                 }
1212                                 if v, ok := d["v"]; ok {
1213                                         c.PeerClientName = v.(string)
1214                                 }
1215                                 m, ok := d["m"]
1216                                 if !ok {
1217                                         err = errors.New("handshake missing m item")
1218                                         break
1219                                 }
1220                                 mTyped, ok := m.(map[string]interface{})
1221                                 if !ok {
1222                                         err = errors.New("handshake m value is not dict")
1223                                         break
1224                                 }
1225                                 if c.PeerExtensionIDs == nil {
1226                                         c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1227                                 }
1228                                 for name, v := range mTyped {
1229                                         id, ok := v.(int64)
1230                                         if !ok {
1231                                                 log.Printf("bad handshake m item extension ID type: %T", v)
1232                                                 continue
1233                                         }
1234                                         if id == 0 {
1235                                                 delete(c.PeerExtensionIDs, name)
1236                                         } else {
1237                                                 if c.PeerExtensionIDs[name] == 0 {
1238                                                         supportedExtensionMessages.Add(name, 1)
1239                                                 }
1240                                                 c.PeerExtensionIDs[name] = byte(id)
1241                                         }
1242                                 }
1243                                 metadata_sizeUntyped, ok := d["metadata_size"]
1244                                 if ok {
1245                                         metadata_size, ok := metadata_sizeUntyped.(int64)
1246                                         if !ok {
1247                                                 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1248                                         } else {
1249                                                 err = t.setMetadataSize(metadata_size)
1250                                                 if err != nil {
1251                                                         err = fmt.Errorf("error setting metadata size to %d", metadata_size)
1252                                                         break
1253                                                 }
1254                                         }
1255                                 }
1256                                 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1257                                         c.requestPendingMetadata()
1258                                 }
1259                         case metadataExtendedId:
1260                                 err = cl.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1261                                 if err != nil {
1262                                         err = fmt.Errorf("error handling metadata extension message: %s", err)
1263                                 }
1264                         case pexExtendedId:
1265                                 if cl.config.DisablePEX {
1266                                         break
1267                                 }
1268                                 var pexMsg peerExchangeMessage
1269                                 err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1270                                 if err != nil {
1271                                         err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1272                                         break
1273                                 }
1274                                 go func() {
1275                                         cl.mu.Lock()
1276                                         t.addPeers(func() (ret []Peer) {
1277                                                 for i, cp := range pexMsg.Added {
1278                                                         p := Peer{
1279                                                                 IP:     make([]byte, 4),
1280                                                                 Port:   cp.Port,
1281                                                                 Source: peerSourcePEX,
1282                                                         }
1283                                                         if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1284                                                                 p.SupportsEncryption = true
1285                                                         }
1286                                                         missinggo.CopyExact(p.IP, cp.IP[:])
1287                                                         ret = append(ret, p)
1288                                                 }
1289                                                 return
1290                                         }())
1291                                         cl.mu.Unlock()
1292                                 }()
1293                         default:
1294                                 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1295                         }
1296                         if err != nil {
1297                                 // That client uses its own extension IDs for outgoing message
1298                                 // types, which is incorrect.
1299                                 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1300                                         strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1301                                         return nil
1302                                 }
1303                         }
1304                 case pp.Port:
1305                         if cl.dHT == nil {
1306                                 break
1307                         }
1308                         pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1309                         if err != nil {
1310                                 panic(err)
1311                         }
1312                         if msg.Port != 0 {
1313                                 pingAddr.Port = int(msg.Port)
1314                         }
1315                         cl.dHT.Ping(pingAddr)
1316                 default:
1317                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1318                 }
1319                 if err != nil {
1320                         return err
1321                 }
1322         }
1323 }
1324
1325 func (cl *Client) openNewConns(t *Torrent) {
1326         defer t.updateWantPeersEvent()
1327         for len(t.peers) != 0 {
1328                 if !t.wantConns() {
1329                         return
1330                 }
1331                 if len(t.halfOpen) >= cl.halfOpenLimit {
1332                         return
1333                 }
1334                 var (
1335                         k peersKey
1336                         p Peer
1337                 )
1338                 for k, p = range t.peers {
1339                         break
1340                 }
1341                 delete(t.peers, k)
1342                 cl.initiateConn(p, t)
1343         }
1344 }
1345
1346 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1347         if port == 0 {
1348                 return true
1349         }
1350         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1351                 return true
1352         }
1353         if _, ok := cl.ipBlockRange(ip); ok {
1354                 return true
1355         }
1356         if _, ok := cl.badPeerIPs[ip.String()]; ok {
1357                 return true
1358         }
1359         return false
1360 }
1361
1362 // Return a Torrent ready for insertion into a Client.
1363 func (cl *Client) newTorrent(ih metainfo.Hash) (t *Torrent) {
1364         t = &Torrent{
1365                 cl:        cl,
1366                 infoHash:  ih,
1367                 chunkSize: defaultChunkSize,
1368                 peers:     make(map[peersKey]Peer),
1369
1370                 halfOpen:          make(map[string]struct{}),
1371                 pieceStateChanges: pubsub.NewPubSub(),
1372
1373                 storageOpener:       cl.defaultStorage,
1374                 maxEstablishedConns: defaultEstablishedConnsPerTorrent,
1375         }
1376         return
1377 }
1378
1379 func init() {
1380         // For shuffling the tracker tiers.
1381         mathRand.Seed(time.Now().Unix())
1382 }
1383
1384 type trackerTier []string
1385
1386 // The trackers within each tier must be shuffled before use.
1387 // http://stackoverflow.com/a/12267471/149482
1388 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1389 func shuffleTier(tier trackerTier) {
1390         for i := range tier {
1391                 j := mathRand.Intn(i + 1)
1392                 tier[i], tier[j] = tier[j], tier[i]
1393         }
1394 }
1395
1396 // A file-like handle to some torrent data resource.
1397 type Handle interface {
1398         io.Reader
1399         io.Seeker
1400         io.Closer
1401         io.ReaderAt
1402 }
1403
1404 // Specifies a new torrent for adding to a client. There are helpers for
1405 // magnet URIs and torrent metainfo files.
1406 type TorrentSpec struct {
1407         // The tiered tracker URIs.
1408         Trackers [][]string
1409         InfoHash metainfo.Hash
1410         Info     *metainfo.InfoEx
1411         // The name to use if the Name field from the Info isn't available.
1412         DisplayName string
1413         // The chunk size to use for outbound requests. Defaults to 16KiB if not
1414         // set.
1415         ChunkSize int
1416         Storage   storage.Client
1417 }
1418
1419 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1420         m, err := metainfo.ParseMagnetURI(uri)
1421         if err != nil {
1422                 return
1423         }
1424         spec = &TorrentSpec{
1425                 Trackers:    [][]string{m.Trackers},
1426                 DisplayName: m.DisplayName,
1427                 InfoHash:    m.InfoHash,
1428         }
1429         return
1430 }
1431
1432 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1433         spec = &TorrentSpec{
1434                 Trackers:    mi.AnnounceList,
1435                 Info:        &mi.Info,
1436                 DisplayName: mi.Info.Name,
1437                 InfoHash:    mi.Info.Hash(),
1438         }
1439         if spec.Trackers == nil && mi.Announce != "" {
1440                 spec.Trackers = [][]string{{mi.Announce}}
1441         }
1442         return
1443 }
1444
1445 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1446         cl.mu.Lock()
1447         defer cl.mu.Unlock()
1448         t, ok := cl.torrents[infoHash]
1449         if ok {
1450                 return
1451         }
1452         new = true
1453         t = cl.newTorrent(infoHash)
1454         if cl.dHT != nil {
1455                 go t.dhtAnnouncer()
1456         }
1457         cl.torrents[infoHash] = t
1458         t.updateWantPeersEvent()
1459         // Tickle Client.waitAccept, new torrent may want conns.
1460         cl.event.Broadcast()
1461         return
1462 }
1463
1464 // Add or merge a torrent spec. If the torrent is already present, the
1465 // trackers will be merged with the existing ones. If the Info isn't yet
1466 // known, it will be set. The display name is replaced if the new spec
1467 // provides one. Returns new if the torrent wasn't already in the client.
1468 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1469         t, new = cl.AddTorrentInfoHash(spec.InfoHash)
1470         if spec.DisplayName != "" {
1471                 t.SetDisplayName(spec.DisplayName)
1472         }
1473         if spec.Info != nil {
1474                 err = t.SetInfoBytes(spec.Info.Bytes)
1475                 if err != nil {
1476                         return
1477                 }
1478         }
1479         cl.mu.Lock()
1480         defer cl.mu.Unlock()
1481         if spec.ChunkSize != 0 {
1482                 t.chunkSize = pp.Integer(spec.ChunkSize)
1483         }
1484         t.addTrackers(spec.Trackers)
1485         t.maybeNewConns()
1486         return
1487 }
1488
1489 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1490         t, ok := cl.torrents[infoHash]
1491         if !ok {
1492                 err = fmt.Errorf("no such torrent")
1493                 return
1494         }
1495         err = t.close()
1496         if err != nil {
1497                 panic(err)
1498         }
1499         delete(cl.torrents, infoHash)
1500         return
1501 }
1502
1503 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1504         _url, err := url.Parse(announceURL)
1505         if err != nil {
1506                 return
1507         }
1508         hmp := missinggo.SplitHostMaybePort(_url.Host)
1509         if hmp.Err != nil {
1510                 err = hmp.Err
1511                 return
1512         }
1513         addr, err := net.ResolveIPAddr("ip", hmp.Host)
1514         if err != nil {
1515                 return
1516         }
1517         cl.mu.RLock()
1518         _, blocked = cl.ipBlockRange(addr.IP)
1519         cl.mu.RUnlock()
1520         host = _url.Host
1521         hmp.Host = addr.String()
1522         _url.Host = hmp.String()
1523         urlToUse = _url.String()
1524         return
1525 }
1526
1527 func (cl *Client) allTorrentsCompleted() bool {
1528         for _, t := range cl.torrents {
1529                 if !t.haveInfo() {
1530                         return false
1531                 }
1532                 if t.numPiecesCompleted() != t.numPieces() {
1533                         return false
1534                 }
1535         }
1536         return true
1537 }
1538
1539 // Returns true when all torrents are completely downloaded and false if the
1540 // client is stopped before that.
1541 func (cl *Client) WaitAll() bool {
1542         cl.mu.Lock()
1543         defer cl.mu.Unlock()
1544         for !cl.allTorrentsCompleted() {
1545                 if cl.closed.IsSet() {
1546                         return false
1547                 }
1548                 cl.event.Wait()
1549         }
1550         return true
1551 }
1552
1553 // Handle a received chunk from a peer.
1554 func (cl *Client) downloadedChunk(t *Torrent, c *connection, msg *pp.Message) {
1555         chunksReceived.Add(1)
1556
1557         req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1558
1559         // Request has been satisfied.
1560         if cl.connDeleteRequest(t, c, req) {
1561                 defer c.updateRequests()
1562         } else {
1563                 unexpectedChunksReceived.Add(1)
1564         }
1565
1566         index := int(req.Index)
1567         piece := &t.pieces[index]
1568
1569         // Do we actually want this chunk?
1570         if !t.wantPiece(req) {
1571                 unwantedChunksReceived.Add(1)
1572                 c.UnwantedChunksReceived++
1573                 return
1574         }
1575
1576         c.UsefulChunksReceived++
1577         c.lastUsefulChunkReceived = time.Now()
1578
1579         cl.upload(t, c)
1580
1581         // Need to record that it hasn't been written yet, before we attempt to do
1582         // anything with it.
1583         piece.incrementPendingWrites()
1584         // Record that we have the chunk.
1585         piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1586
1587         // Cancel pending requests for this chunk.
1588         for _, c := range t.conns {
1589                 if cl.connCancel(t, c, req) {
1590                         c.updateRequests()
1591                 }
1592         }
1593
1594         cl.mu.Unlock()
1595         // Write the chunk out. Note that the upper bound on chunk writing
1596         // concurrency will be the number of connections.
1597         err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1598         cl.mu.Lock()
1599
1600         piece.decrementPendingWrites()
1601
1602         if err != nil {
1603                 log.Printf("%s: error writing chunk %v: %s", t, req, err)
1604                 t.pendRequest(req)
1605                 t.updatePieceCompletion(int(msg.Index))
1606                 return
1607         }
1608
1609         // It's important that the piece is potentially queued before we check if
1610         // the piece is still wanted, because if it is queued, it won't be wanted.
1611         if t.pieceAllDirty(index) {
1612                 cl.queuePieceCheck(t, int(req.Index))
1613         }
1614
1615         if c.peerTouchedPieces == nil {
1616                 c.peerTouchedPieces = make(map[int]struct{})
1617         }
1618         c.peerTouchedPieces[index] = struct{}{}
1619
1620         cl.event.Broadcast()
1621         t.publishPieceChange(int(req.Index))
1622         return
1623 }
1624
1625 // Return the connections that touched a piece, and clear the entry while
1626 // doing it.
1627 func (cl *Client) reapPieceTouches(t *Torrent, piece int) (ret []*connection) {
1628         for _, c := range t.conns {
1629                 if _, ok := c.peerTouchedPieces[piece]; ok {
1630                         ret = append(ret, c)
1631                         delete(c.peerTouchedPieces, piece)
1632                 }
1633         }
1634         return
1635 }
1636
1637 func (cl *Client) pieceHashed(t *Torrent, piece int, correct bool) {
1638         if t.closed.IsSet() {
1639                 return
1640         }
1641         p := &t.pieces[piece]
1642         if p.EverHashed {
1643                 // Don't score the first time a piece is hashed, it could be an
1644                 // initial check.
1645                 if correct {
1646                         pieceHashedCorrect.Add(1)
1647                 } else {
1648                         log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
1649                         pieceHashedNotCorrect.Add(1)
1650                 }
1651         }
1652         p.EverHashed = true
1653         touchers := cl.reapPieceTouches(t, piece)
1654         if correct {
1655                 for _, c := range touchers {
1656                         c.goodPiecesDirtied++
1657                 }
1658                 err := p.Storage().MarkComplete()
1659                 if err != nil {
1660                         log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
1661                 }
1662                 t.updatePieceCompletion(piece)
1663         } else if len(touchers) != 0 {
1664                 log.Printf("dropping and banning %d conns that touched piece", len(touchers))
1665                 for _, c := range touchers {
1666                         c.badPiecesDirtied++
1667                         t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1668                         t.dropConnection(c)
1669                 }
1670         }
1671         cl.pieceChanged(t, piece)
1672 }
1673
1674 func (cl *Client) onCompletedPiece(t *Torrent, piece int) {
1675         t.pendingPieces.Remove(piece)
1676         t.pendAllChunkSpecs(piece)
1677         for _, conn := range t.conns {
1678                 conn.Have(piece)
1679                 for r := range conn.Requests {
1680                         if int(r.Index) == piece {
1681                                 conn.Cancel(r)
1682                         }
1683                 }
1684                 // Could check here if peer doesn't have piece, but due to caching
1685                 // some peers may have said they have a piece but they don't.
1686                 cl.upload(t, conn)
1687         }
1688 }
1689
1690 func (cl *Client) onFailedPiece(t *Torrent, piece int) {
1691         if t.pieceAllDirty(piece) {
1692                 t.pendAllChunkSpecs(piece)
1693         }
1694         if !t.wantPieceIndex(piece) {
1695                 return
1696         }
1697         cl.openNewConns(t)
1698         for _, conn := range t.conns {
1699                 if conn.PeerHasPiece(piece) {
1700                         conn.updateRequests()
1701                 }
1702         }
1703 }
1704
1705 func (cl *Client) pieceChanged(t *Torrent, piece int) {
1706         correct := t.pieceComplete(piece)
1707         defer cl.event.Broadcast()
1708         if correct {
1709                 cl.onCompletedPiece(t, piece)
1710         } else {
1711                 cl.onFailedPiece(t, piece)
1712         }
1713         if t.updatePiecePriority(piece) {
1714                 t.piecePriorityChanged(piece)
1715         }
1716         t.publishPieceChange(piece)
1717 }
1718
1719 func (cl *Client) verifyPiece(t *Torrent, piece int) {
1720         cl.mu.Lock()
1721         defer cl.mu.Unlock()
1722         p := &t.pieces[piece]
1723         for p.Hashing || t.storage == nil {
1724                 cl.event.Wait()
1725         }
1726         p.QueuedForHash = false
1727         if t.closed.IsSet() || t.pieceComplete(piece) {
1728                 t.updatePiecePriority(piece)
1729                 t.publishPieceChange(piece)
1730                 return
1731         }
1732         p.Hashing = true
1733         t.publishPieceChange(piece)
1734         cl.mu.Unlock()
1735         sum := t.hashPiece(piece)
1736         cl.mu.Lock()
1737         p.Hashing = false
1738         cl.pieceHashed(t, piece, sum == p.Hash)
1739 }
1740
1741 // Returns handles to all the torrents loaded in the Client.
1742 func (cl *Client) Torrents() (ret []*Torrent) {
1743         cl.mu.Lock()
1744         for _, t := range cl.torrents {
1745                 ret = append(ret, t)
1746         }
1747         cl.mu.Unlock()
1748         return
1749 }
1750
1751 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1752         spec, err := TorrentSpecFromMagnetURI(uri)
1753         if err != nil {
1754                 return
1755         }
1756         T, _, err = cl.AddTorrentSpec(spec)
1757         return
1758 }
1759
1760 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1761         T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1762         var ss []string
1763         slices.MakeInto(&ss, mi.Nodes)
1764         cl.AddDHTNodes(ss)
1765         return
1766 }
1767
1768 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1769         mi, err := metainfo.LoadFromFile(filename)
1770         if err != nil {
1771                 return
1772         }
1773         return cl.AddTorrent(mi)
1774 }
1775
1776 func (cl *Client) DHT() *dht.Server {
1777         return cl.dHT
1778 }
1779
1780 func (cl *Client) AddDHTNodes(nodes []string) {
1781         for _, n := range nodes {
1782                 hmp := missinggo.SplitHostMaybePort(n)
1783                 ip := net.ParseIP(hmp.Host)
1784                 if ip == nil {
1785                         log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1786                         continue
1787                 }
1788                 ni := krpc.NodeInfo{
1789                         Addr: &net.UDPAddr{
1790                                 IP:   ip,
1791                                 Port: hmp.Port,
1792                         },
1793                 }
1794                 cl.DHT().AddNode(ni)
1795         }
1796 }
1797
1798 func (cl *Client) banPeerIP(ip net.IP) {
1799         if cl.badPeerIPs == nil {
1800                 cl.badPeerIPs = make(map[string]struct{})
1801         }
1802         cl.badPeerIPs[ip.String()] = struct{}{}
1803 }