]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
2daff28265c416fb5cf8360e635c052cfbfe5bfd
[btrtrc.git] / client.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "crypto/rand"
7         "crypto/sha1"
8         "encoding/hex"
9         "errors"
10         "expvar"
11         "fmt"
12         "io"
13         "log"
14         "math/big"
15         mathRand "math/rand"
16         "net"
17         "net/url"
18         "os"
19         "path/filepath"
20         "sort"
21         "strconv"
22         "strings"
23         "time"
24
25         "github.com/anacrolix/missinggo"
26         . "github.com/anacrolix/missinggo"
27         "github.com/anacrolix/missinggo/pubsub"
28         "github.com/anacrolix/sync"
29         "github.com/anacrolix/utp"
30         "github.com/bradfitz/iter"
31         "github.com/edsrzf/mmap-go"
32
33         "github.com/anacrolix/torrent/bencode"
34         filePkg "github.com/anacrolix/torrent/data/file"
35         "github.com/anacrolix/torrent/dht"
36         "github.com/anacrolix/torrent/iplist"
37         "github.com/anacrolix/torrent/metainfo"
38         "github.com/anacrolix/torrent/mse"
39         pp "github.com/anacrolix/torrent/peer_protocol"
40         "github.com/anacrolix/torrent/tracker"
41 )
42
43 var (
44         unwantedChunksReceived   = expvar.NewInt("chunksReceivedUnwanted")
45         unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
46         chunksReceived           = expvar.NewInt("chunksReceived")
47
48         peersAddedBySource = expvar.NewMap("peersAddedBySource")
49
50         uploadChunksPosted    = expvar.NewInt("uploadChunksPosted")
51         unexpectedCancels     = expvar.NewInt("unexpectedCancels")
52         postedCancels         = expvar.NewInt("postedCancels")
53         duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
54
55         pieceHashedCorrect    = expvar.NewInt("pieceHashedCorrect")
56         pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
57
58         unsuccessfulDials = expvar.NewInt("dialSuccessful")
59         successfulDials   = expvar.NewInt("dialUnsuccessful")
60
61         acceptUTP    = expvar.NewInt("acceptUTP")
62         acceptTCP    = expvar.NewInt("acceptTCP")
63         acceptReject = expvar.NewInt("acceptReject")
64
65         peerExtensions                    = expvar.NewMap("peerExtensions")
66         completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
67         // Count of connections to peer with same client ID.
68         connsToSelf = expvar.NewInt("connsToSelf")
69         // Number of completed connections to a client we're already connected with.
70         duplicateClientConns       = expvar.NewInt("duplicateClientConns")
71         receivedMessageTypes       = expvar.NewMap("receivedMessageTypes")
72         supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
73 )
74
75 const (
76         // Justification for set bits follows.
77         //
78         // Extension protocol ([5]|=0x10):
79         // http://www.bittorrent.org/beps/bep_0010.html
80         //
81         // Fast Extension ([7]|=0x04):
82         // http://bittorrent.org/beps/bep_0006.html.
83         // Disabled until AllowedFast is implemented.
84         //
85         // DHT ([7]|=1):
86         // http://www.bittorrent.org/beps/bep_0005.html
87         defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
88
89         socketsPerTorrent     = 80
90         torrentPeersHighWater = 200
91         torrentPeersLowWater  = 50
92
93         // Limit how long handshake can take. This is to reduce the lingering
94         // impact of a few bad apples. 4s loses 1% of successful handshakes that
95         // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
96         btHandshakeTimeout = 4 * time.Second
97         handshakesTimeout  = 20 * time.Second
98
99         // These are our extended message IDs.
100         metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
101         pexExtendedId
102
103         // Updated occasionally to when there's been some changes to client
104         // behaviour in case other clients are assuming anything of us. See also
105         // `bep20`.
106         extendedHandshakeClientVersion = "go.torrent dev 20150624"
107 )
108
109 // Currently doesn't really queue, but should in the future.
110 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
111         piece := &t.Pieces[pieceIndex]
112         if piece.QueuedForHash {
113                 return
114         }
115         piece.QueuedForHash = true
116         t.publishPieceChange(int(pieceIndex))
117         go cl.verifyPiece(t, int(pieceIndex))
118 }
119
120 // Queue a piece check if one isn't already queued, and the piece has never
121 // been checked before.
122 func (cl *Client) queueFirstHash(t *torrent, piece int) {
123         p := &t.Pieces[piece]
124         if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
125                 return
126         }
127         cl.queuePieceCheck(t, piece)
128 }
129
130 // Clients contain zero or more Torrents. A client manages a blocklist, the
131 // TCP/UDP protocol ports, and DHT as desired.
132 type Client struct {
133         halfOpenLimit  int
134         peerID         [20]byte
135         listeners      []net.Listener
136         utpSock        *utp.Socket
137         dHT            *dht.Server
138         ipBlockList    iplist.Ranger
139         bannedTorrents map[InfoHash]struct{}
140         config         Config
141         pruneTimer     *time.Timer
142         extensionBytes peerExtensionBytes
143         // Set of addresses that have our client ID. This intentionally will
144         // include ourselves if we end up trying to connect to our own address
145         // through legitimate channels.
146         dopplegangerAddrs map[string]struct{}
147
148         torrentDataOpener TorrentDataOpener
149
150         mu    sync.RWMutex
151         event sync.Cond
152         quit  chan struct{}
153
154         torrents map[InfoHash]*torrent
155 }
156
157 func (me *Client) IPBlockList() iplist.Ranger {
158         me.mu.Lock()
159         defer me.mu.Unlock()
160         return me.ipBlockList
161 }
162
163 func (me *Client) SetIPBlockList(list iplist.Ranger) {
164         me.mu.Lock()
165         defer me.mu.Unlock()
166         me.ipBlockList = list
167         if me.dHT != nil {
168                 me.dHT.SetIPBlockList(list)
169         }
170 }
171
172 func (me *Client) PeerID() string {
173         return string(me.peerID[:])
174 }
175
176 func (me *Client) ListenAddr() (addr net.Addr) {
177         for _, l := range me.listeners {
178                 addr = l.Addr()
179                 break
180         }
181         return
182 }
183
184 type hashSorter struct {
185         Hashes []InfoHash
186 }
187
188 func (me hashSorter) Len() int {
189         return len(me.Hashes)
190 }
191
192 func (me hashSorter) Less(a, b int) bool {
193         return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
194 }
195
196 func (me hashSorter) Swap(a, b int) {
197         me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
198 }
199
200 func (cl *Client) sortedTorrents() (ret []*torrent) {
201         var hs hashSorter
202         for ih := range cl.torrents {
203                 hs.Hashes = append(hs.Hashes, ih)
204         }
205         sort.Sort(hs)
206         for _, ih := range hs.Hashes {
207                 ret = append(ret, cl.torrent(ih))
208         }
209         return
210 }
211
212 // Writes out a human readable status of the client, such as for writing to a
213 // HTTP status page.
214 func (cl *Client) WriteStatus(_w io.Writer) {
215         cl.mu.RLock()
216         defer cl.mu.RUnlock()
217         w := bufio.NewWriter(_w)
218         defer w.Flush()
219         if addr := cl.ListenAddr(); addr != nil {
220                 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
221         } else {
222                 fmt.Fprintln(w, "Not listening!")
223         }
224         fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
225         if cl.dHT != nil {
226                 dhtStats := cl.dHT.Stats()
227                 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
228                 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
229                 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
230                 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
231                 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
232         }
233         fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
234         fmt.Fprintln(w)
235         for _, t := range cl.sortedTorrents() {
236                 if t.Name() == "" {
237                         fmt.Fprint(w, "<unknown name>")
238                 } else {
239                         fmt.Fprint(w, t.Name())
240                 }
241                 fmt.Fprint(w, "\n")
242                 if t.haveInfo() {
243                         fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.length)), t.length)
244                 } else {
245                         w.WriteString("<missing metainfo>")
246                 }
247                 fmt.Fprint(w, "\n")
248                 t.writeStatus(w, cl)
249                 fmt.Fprintln(w)
250         }
251 }
252
253 // TODO: Make this non-blocking Read on Torrent.
254 func dataReadAt(d Data, b []byte, off int64) (n int, err error) {
255         // defer func() {
256         //      if err == io.ErrUnexpectedEOF && n != 0 {
257         //              err = nil
258         //      }
259         // }()
260         // log.Println("data read at", len(b), off)
261         return d.ReadAt(b, off)
262 }
263
264 // Calculates the number of pieces to set to Readahead priority, after the
265 // Now, and Next pieces.
266 func readaheadPieces(readahead, pieceLength int64) (ret int) {
267         // Expand the readahead to fit any partial pieces. Subtract 1 for the
268         // "next" piece that is assigned.
269         ret = int((readahead+pieceLength-1)/pieceLength - 1)
270         // Lengthen the "readahead tail" to smooth blockiness that occurs when the
271         // piece length is much larger than the readahead.
272         if ret < 2 {
273                 ret++
274         }
275         return
276 }
277
278 func (cl *Client) configDir() string {
279         if cl.config.ConfigDir == "" {
280                 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
281         }
282         return cl.config.ConfigDir
283 }
284
285 // The directory where the Client expects to find and store configuration
286 // data. Defaults to $HOME/.config/torrent.
287 func (cl *Client) ConfigDir() string {
288         return cl.configDir()
289 }
290
291 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
292         f, err := os.Open(filename)
293         if os.IsNotExist(err) {
294                 err = nil
295                 return
296         }
297         if err != nil {
298                 return
299         }
300         defer f.Close()
301         mm, err := mmap.Map(f, mmap.RDONLY, 0)
302         if err != nil {
303                 return
304         }
305         ret = iplist.NewFromPacked(mm)
306         return
307 }
308
309 func (cl *Client) setEnvBlocklist() (err error) {
310         filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
311         defaultBlocklist := filename == ""
312         if defaultBlocklist {
313                 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
314                 if err != nil {
315                         return
316                 }
317                 if cl.ipBlockList != nil {
318                         return
319                 }
320                 filename = filepath.Join(cl.configDir(), "blocklist")
321         }
322         f, err := os.Open(filename)
323         if err != nil {
324                 if defaultBlocklist {
325                         err = nil
326                 }
327                 return
328         }
329         defer f.Close()
330         cl.ipBlockList, err = iplist.NewFromReader(f)
331         return
332 }
333
334 func (cl *Client) initBannedTorrents() error {
335         f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
336         if err != nil {
337                 if os.IsNotExist(err) {
338                         return nil
339                 }
340                 return fmt.Errorf("error opening banned infohashes file: %s", err)
341         }
342         defer f.Close()
343         scanner := bufio.NewScanner(f)
344         cl.bannedTorrents = make(map[InfoHash]struct{})
345         for scanner.Scan() {
346                 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
347                         continue
348                 }
349                 var ihs string
350                 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
351                 if err != nil {
352                         return fmt.Errorf("error reading infohash: %s", err)
353                 }
354                 if n != 1 {
355                         continue
356                 }
357                 if len(ihs) != 20 {
358                         return errors.New("bad infohash")
359                 }
360                 var ih InfoHash
361                 CopyExact(&ih, ihs)
362                 cl.bannedTorrents[ih] = struct{}{}
363         }
364         if err := scanner.Err(); err != nil {
365                 return fmt.Errorf("error scanning file: %s", err)
366         }
367         return nil
368 }
369
370 // Creates a new client.
371 func NewClient(cfg *Config) (cl *Client, err error) {
372         if cfg == nil {
373                 cfg = &Config{}
374         }
375
376         defer func() {
377                 if err != nil {
378                         cl = nil
379                 }
380         }()
381         cl = &Client{
382                 halfOpenLimit: socketsPerTorrent,
383                 config:        *cfg,
384                 torrentDataOpener: func(md *metainfo.Info) Data {
385                         return filePkg.TorrentData(md, cfg.DataDir)
386                 },
387                 dopplegangerAddrs: make(map[string]struct{}),
388
389                 quit:     make(chan struct{}),
390                 torrents: make(map[InfoHash]*torrent),
391         }
392         CopyExact(&cl.extensionBytes, defaultExtensionBytes)
393         cl.event.L = &cl.mu
394         if cfg.TorrentDataOpener != nil {
395                 cl.torrentDataOpener = cfg.TorrentDataOpener
396         }
397
398         if cfg.IPBlocklist != nil {
399                 cl.ipBlockList = cfg.IPBlocklist
400         } else if !cfg.NoDefaultBlocklist {
401                 err = cl.setEnvBlocklist()
402                 if err != nil {
403                         return
404                 }
405         }
406
407         if err = cl.initBannedTorrents(); err != nil {
408                 err = fmt.Errorf("error initing banned torrents: %s", err)
409                 return
410         }
411
412         if cfg.PeerID != "" {
413                 CopyExact(&cl.peerID, cfg.PeerID)
414         } else {
415                 o := copy(cl.peerID[:], bep20)
416                 _, err = rand.Read(cl.peerID[o:])
417                 if err != nil {
418                         panic("error generating peer id")
419                 }
420         }
421
422         // Returns the laddr string to listen on for the next Listen call.
423         listenAddr := func() string {
424                 if addr := cl.ListenAddr(); addr != nil {
425                         return addr.String()
426                 }
427                 if cfg.ListenAddr == "" {
428                         return ":50007"
429                 }
430                 return cfg.ListenAddr
431         }
432         if !cl.config.DisableTCP {
433                 var l net.Listener
434                 l, err = net.Listen(func() string {
435                         if cl.config.DisableIPv6 {
436                                 return "tcp4"
437                         } else {
438                                 return "tcp"
439                         }
440                 }(), listenAddr())
441                 if err != nil {
442                         return
443                 }
444                 cl.listeners = append(cl.listeners, l)
445                 go cl.acceptConnections(l, false)
446         }
447         if !cl.config.DisableUTP {
448                 cl.utpSock, err = utp.NewSocket(func() string {
449                         if cl.config.DisableIPv6 {
450                                 return "udp4"
451                         } else {
452                                 return "udp"
453                         }
454                 }(), listenAddr())
455                 if err != nil {
456                         return
457                 }
458                 cl.listeners = append(cl.listeners, cl.utpSock)
459                 go cl.acceptConnections(cl.utpSock, true)
460         }
461         if !cfg.NoDHT {
462                 dhtCfg := cfg.DHTConfig
463                 if dhtCfg.IPBlocklist == nil {
464                         dhtCfg.IPBlocklist = cl.ipBlockList
465                 }
466                 if dhtCfg.Addr == "" {
467                         dhtCfg.Addr = listenAddr()
468                 }
469                 if dhtCfg.Conn == nil && cl.utpSock != nil {
470                         dhtCfg.Conn = cl.utpSock
471                 }
472                 cl.dHT, err = dht.NewServer(&dhtCfg)
473                 if err != nil {
474                         return
475                 }
476         }
477
478         return
479 }
480
481 func (cl *Client) stopped() bool {
482         select {
483         case <-cl.quit:
484                 return true
485         default:
486                 return false
487         }
488 }
489
490 // Stops the client. All connections to peers are closed and all activity will
491 // come to a halt.
492 func (me *Client) Close() {
493         me.mu.Lock()
494         defer me.mu.Unlock()
495         select {
496         case <-me.quit:
497                 return
498         default:
499         }
500         close(me.quit)
501         if me.dHT != nil {
502                 me.dHT.Close()
503         }
504         for _, l := range me.listeners {
505                 l.Close()
506         }
507         for _, t := range me.torrents {
508                 t.close()
509         }
510         me.event.Broadcast()
511 }
512
513 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
514
515 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
516         if cl.ipBlockList == nil {
517                 return
518         }
519         ip4 := ip.To4()
520         // If blocklists are enabled, then block non-IPv4 addresses, because
521         // blocklists do not yet support IPv6.
522         if ip4 == nil {
523                 if missinggo.CryHeard() {
524                         log.Printf("blocking non-IPv4 address: %s", ip)
525                 }
526                 r = ipv6BlockRange
527                 blocked = true
528                 return
529         }
530         return cl.ipBlockList.Lookup(ip4)
531 }
532
533 func (cl *Client) waitAccept() {
534         cl.mu.Lock()
535         defer cl.mu.Unlock()
536         for {
537                 for _, t := range cl.torrents {
538                         if cl.wantConns(t) {
539                                 return
540                         }
541                 }
542                 select {
543                 case <-cl.quit:
544                         return
545                 default:
546                 }
547                 cl.event.Wait()
548         }
549 }
550
551 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
552         for {
553                 cl.waitAccept()
554                 // We accept all connections immediately, because we don't know what
555                 // torrent they're for.
556                 conn, err := l.Accept()
557                 select {
558                 case <-cl.quit:
559                         if conn != nil {
560                                 conn.Close()
561                         }
562                         return
563                 default:
564                 }
565                 if err != nil {
566                         log.Print(err)
567                         return
568                 }
569                 if utp {
570                         acceptUTP.Add(1)
571                 } else {
572                         acceptTCP.Add(1)
573                 }
574                 cl.mu.RLock()
575                 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
576                 _, blocked := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
577                 cl.mu.RUnlock()
578                 if blocked || doppleganger {
579                         acceptReject.Add(1)
580                         // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
581                         conn.Close()
582                         continue
583                 }
584                 go cl.incomingConnection(conn, utp)
585         }
586 }
587
588 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
589         defer nc.Close()
590         if tc, ok := nc.(*net.TCPConn); ok {
591                 tc.SetLinger(0)
592         }
593         c := newConnection()
594         c.conn = nc
595         c.rw = nc
596         c.Discovery = peerSourceIncoming
597         c.uTP = utp
598         err := cl.runReceivedConn(c)
599         if err != nil {
600                 // log.Print(err)
601         }
602 }
603
604 // Returns a handle to the given torrent, if it's present in the client.
605 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
606         cl.mu.Lock()
607         defer cl.mu.Unlock()
608         t, ok := cl.torrents[ih]
609         if !ok {
610                 return
611         }
612         T = Torrent{cl, t}
613         return
614 }
615
616 func (me *Client) torrent(ih InfoHash) *torrent {
617         return me.torrents[ih]
618 }
619
620 type dialResult struct {
621         Conn net.Conn
622         UTP  bool
623 }
624
625 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
626         conn, err := dial(addr, t)
627         if err != nil {
628                 if conn != nil {
629                         conn.Close()
630                 }
631                 conn = nil // Pedantic
632         }
633         ch <- dialResult{conn, utp}
634         if err == nil {
635                 successfulDials.Add(1)
636                 return
637         }
638         unsuccessfulDials.Add(1)
639 }
640
641 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
642         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
643         if ret < minDialTimeout {
644                 ret = minDialTimeout
645         }
646         return
647 }
648
649 // Returns whether an address is known to connect to a client with our own ID.
650 func (me *Client) dopplegangerAddr(addr string) bool {
651         _, ok := me.dopplegangerAddrs[addr]
652         return ok
653 }
654
655 // Start the process of connecting to the given peer for the given torrent if
656 // appropriate.
657 func (me *Client) initiateConn(peer Peer, t *torrent) {
658         if peer.Id == me.peerID {
659                 return
660         }
661         addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
662         if me.dopplegangerAddr(addr) || t.addrActive(addr) {
663                 duplicateConnsAvoided.Add(1)
664                 return
665         }
666         if r, ok := me.ipBlockRange(peer.IP); ok {
667                 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
668                 return
669         }
670         t.HalfOpen[addr] = struct{}{}
671         go me.outgoingConnection(t, addr, peer.Source)
672 }
673
674 func (me *Client) dialTimeout(t *torrent) time.Duration {
675         me.mu.Lock()
676         pendingPeers := len(t.Peers)
677         me.mu.Unlock()
678         return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
679 }
680
681 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
682         c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
683         if err == nil {
684                 c.(*net.TCPConn).SetLinger(0)
685         }
686         return
687 }
688
689 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
690         return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
691 }
692
693 // Returns a connection over UTP or TCP, whichever is first to connect.
694 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
695         // Initiate connections via TCP and UTP simultaneously. Use the first one
696         // that succeeds.
697         left := 0
698         if !me.config.DisableUTP {
699                 left++
700         }
701         if !me.config.DisableTCP {
702                 left++
703         }
704         resCh := make(chan dialResult, left)
705         if !me.config.DisableUTP {
706                 go doDial(me.dialUTP, resCh, true, addr, t)
707         }
708         if !me.config.DisableTCP {
709                 go doDial(me.dialTCP, resCh, false, addr, t)
710         }
711         var res dialResult
712         // Wait for a successful connection.
713         for ; left > 0 && res.Conn == nil; left-- {
714                 res = <-resCh
715         }
716         if left > 0 {
717                 // There are still incompleted dials.
718                 go func() {
719                         for ; left > 0; left-- {
720                                 conn := (<-resCh).Conn
721                                 if conn != nil {
722                                         conn.Close()
723                                 }
724                         }
725                 }()
726         }
727         conn = res.Conn
728         utp = res.UTP
729         return
730 }
731
732 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
733         if _, ok := t.HalfOpen[addr]; !ok {
734                 panic("invariant broken")
735         }
736         delete(t.HalfOpen, addr)
737         me.openNewConns(t)
738 }
739
740 // Performs initiator handshakes and returns a connection.
741 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
742         c = newConnection()
743         c.conn = nc
744         c.rw = nc
745         c.encrypted = encrypted
746         c.uTP = utp
747         err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
748         if err != nil {
749                 return
750         }
751         ok, err := me.initiateHandshakes(c, t)
752         if !ok {
753                 c = nil
754         }
755         return
756 }
757
758 // Returns nil connection and nil error if no connection could be established
759 // for valid reasons.
760 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
761         nc, utp := me.dialFirst(addr, t)
762         if nc == nil {
763                 return
764         }
765         c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
766         if err != nil {
767                 nc.Close()
768                 return
769         } else if c != nil {
770                 return
771         }
772         nc.Close()
773         if me.config.DisableEncryption {
774                 // We already tried without encryption.
775                 return
776         }
777         // Try again without encryption, using whichever protocol type worked last
778         // time.
779         if utp {
780                 nc, err = me.dialUTP(addr, t)
781         } else {
782                 nc, err = me.dialTCP(addr, t)
783         }
784         if err != nil {
785                 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
786                 return
787         }
788         c, err = me.handshakesConnection(nc, t, false, utp)
789         if err != nil {
790                 nc.Close()
791         }
792         return
793 }
794
795 // Called to dial out and run a connection. The addr we're given is already
796 // considered half-open.
797 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
798         c, err := me.establishOutgoingConn(t, addr)
799         me.mu.Lock()
800         defer me.mu.Unlock()
801         // Don't release lock between here and addConnection, unless it's for
802         // failure.
803         me.noLongerHalfOpen(t, addr)
804         if err != nil {
805                 return
806         }
807         if c == nil {
808                 return
809         }
810         defer c.Close()
811         c.Discovery = ps
812         err = me.runInitiatedHandshookConn(c, t)
813         if err != nil {
814                 // log.Print(err)
815         }
816 }
817
818 // The port number for incoming peer connections. 0 if the client isn't
819 // listening.
820 func (cl *Client) incomingPeerPort() int {
821         listenAddr := cl.ListenAddr()
822         if listenAddr == nil {
823                 return 0
824         }
825         return addrPort(listenAddr)
826 }
827
828 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
829 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
830 func addrCompactIP(addr net.Addr) (string, error) {
831         host, _, err := net.SplitHostPort(addr.String())
832         if err != nil {
833                 return "", err
834         }
835         ip := net.ParseIP(host)
836         if v4 := ip.To4(); v4 != nil {
837                 if len(v4) != 4 {
838                         panic(v4)
839                 }
840                 return string(v4), nil
841         }
842         return string(ip.To16()), nil
843 }
844
845 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
846         var err error
847         for b := range bb {
848                 _, err = w.Write(b)
849                 if err != nil {
850                         break
851                 }
852         }
853         done <- err
854 }
855
856 type (
857         peerExtensionBytes [8]byte
858         peerID             [20]byte
859 )
860
861 func (me *peerExtensionBytes) SupportsExtended() bool {
862         return me[5]&0x10 != 0
863 }
864
865 func (me *peerExtensionBytes) SupportsDHT() bool {
866         return me[7]&0x01 != 0
867 }
868
869 func (me *peerExtensionBytes) SupportsFast() bool {
870         return me[7]&0x04 != 0
871 }
872
873 type handshakeResult struct {
874         peerExtensionBytes
875         peerID
876         InfoHash
877 }
878
879 // ih is nil if we expect the peer to declare the InfoHash, such as when the
880 // peer initiated the connection. Returns ok if the handshake was successful,
881 // and err if there was an unexpected condition other than the peer simply
882 // abandoning the handshake.
883 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
884         // Bytes to be sent to the peer. Should never block the sender.
885         postCh := make(chan []byte, 4)
886         // A single error value sent when the writer completes.
887         writeDone := make(chan error, 1)
888         // Performs writes to the socket and ensures posts don't block.
889         go handshakeWriter(sock, postCh, writeDone)
890
891         defer func() {
892                 close(postCh) // Done writing.
893                 if !ok {
894                         return
895                 }
896                 if err != nil {
897                         panic(err)
898                 }
899                 // Wait until writes complete before returning from handshake.
900                 err = <-writeDone
901                 if err != nil {
902                         err = fmt.Errorf("error writing: %s", err)
903                 }
904         }()
905
906         post := func(bb []byte) {
907                 select {
908                 case postCh <- bb:
909                 default:
910                         panic("mustn't block while posting")
911                 }
912         }
913
914         post([]byte(pp.Protocol))
915         post(extensions[:])
916         if ih != nil { // We already know what we want.
917                 post(ih[:])
918                 post(peerID[:])
919         }
920         var b [68]byte
921         _, err = io.ReadFull(sock, b[:68])
922         if err != nil {
923                 err = nil
924                 return
925         }
926         if string(b[:20]) != pp.Protocol {
927                 return
928         }
929         CopyExact(&res.peerExtensionBytes, b[20:28])
930         CopyExact(&res.InfoHash, b[28:48])
931         CopyExact(&res.peerID, b[48:68])
932         peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
933
934         // TODO: Maybe we can just drop peers here if we're not interested. This
935         // could prevent them trying to reconnect, falsely believing there was
936         // just a problem.
937         if ih == nil { // We were waiting for the peer to tell us what they wanted.
938                 post(res.InfoHash[:])
939                 post(peerID[:])
940         }
941
942         ok = true
943         return
944 }
945
946 // Wraps a raw connection and provides the interface we want for using the
947 // connection in the message loop.
948 type deadlineReader struct {
949         nc net.Conn
950         r  io.Reader
951 }
952
953 func (me deadlineReader) Read(b []byte) (n int, err error) {
954         // Keep-alives should be received every 2 mins. Give a bit of gracetime.
955         err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
956         if err != nil {
957                 err = fmt.Errorf("error setting read deadline: %s", err)
958         }
959         n, err = me.r.Read(b)
960         // Convert common errors into io.EOF.
961         // if err != nil {
962         //      if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
963         //              err = io.EOF
964         //      } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
965         //              if n != 0 {
966         //                      panic(n)
967         //              }
968         //              err = io.EOF
969         //      }
970         // }
971         return
972 }
973
974 type readWriter struct {
975         io.Reader
976         io.Writer
977 }
978
979 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
980         var protocol [len(pp.Protocol)]byte
981         _, err = io.ReadFull(rw, protocol[:])
982         if err != nil {
983                 return
984         }
985         ret = readWriter{
986                 io.MultiReader(bytes.NewReader(protocol[:]), rw),
987                 rw,
988         }
989         if string(protocol[:]) == pp.Protocol {
990                 return
991         }
992         encrypted = true
993         ret, err = mse.ReceiveHandshake(ret, skeys)
994         return
995 }
996
997 func (cl *Client) receiveSkeys() (ret [][]byte) {
998         for ih := range cl.torrents {
999                 ret = append(ret, ih[:])
1000         }
1001         return
1002 }
1003
1004 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1005         if c.encrypted {
1006                 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1007                 if err != nil {
1008                         return
1009                 }
1010         }
1011         ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1012         if ih != t.InfoHash {
1013                 ok = false
1014         }
1015         return
1016 }
1017
1018 // Do encryption and bittorrent handshakes as receiver.
1019 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1020         cl.mu.Lock()
1021         skeys := cl.receiveSkeys()
1022         cl.mu.Unlock()
1023         if !cl.config.DisableEncryption {
1024                 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1025                 if err != nil {
1026                         if err == mse.ErrNoSecretKeyMatch {
1027                                 err = nil
1028                         }
1029                         return
1030                 }
1031         }
1032         ih, ok, err := cl.connBTHandshake(c, nil)
1033         if err != nil {
1034                 err = fmt.Errorf("error during bt handshake: %s", err)
1035                 return
1036         }
1037         if !ok {
1038                 return
1039         }
1040         cl.mu.Lock()
1041         t = cl.torrents[ih]
1042         cl.mu.Unlock()
1043         return
1044 }
1045
1046 // Returns !ok if handshake failed for valid reasons.
1047 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1048         res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1049         if err != nil || !ok {
1050                 return
1051         }
1052         ret = res.InfoHash
1053         c.PeerExtensionBytes = res.peerExtensionBytes
1054         c.PeerID = res.peerID
1055         c.completedHandshake = time.Now()
1056         return
1057 }
1058
1059 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1060         if c.PeerID == cl.peerID {
1061                 // Only if we initiated the connection is the remote address a
1062                 // listen addr for a doppleganger.
1063                 connsToSelf.Add(1)
1064                 addr := c.conn.RemoteAddr().String()
1065                 cl.dopplegangerAddrs[addr] = struct{}{}
1066                 return
1067         }
1068         return cl.runHandshookConn(c, t)
1069 }
1070
1071 func (cl *Client) runReceivedConn(c *connection) (err error) {
1072         err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1073         if err != nil {
1074                 return
1075         }
1076         t, err := cl.receiveHandshakes(c)
1077         if err != nil {
1078                 err = fmt.Errorf("error receiving handshakes: %s", err)
1079                 return
1080         }
1081         if t == nil {
1082                 return
1083         }
1084         cl.mu.Lock()
1085         defer cl.mu.Unlock()
1086         if c.PeerID == cl.peerID {
1087                 return
1088         }
1089         return cl.runHandshookConn(c, t)
1090 }
1091
1092 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1093         c.conn.SetWriteDeadline(time.Time{})
1094         c.rw = readWriter{
1095                 deadlineReader{c.conn, c.rw},
1096                 c.rw,
1097         }
1098         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1099         if !cl.addConnection(t, c) {
1100                 return
1101         }
1102         defer cl.dropConnection(t, c)
1103         go c.writer()
1104         go c.writeOptimizer(time.Minute)
1105         cl.sendInitialMessages(c, t)
1106         err = cl.connectionLoop(t, c)
1107         if err != nil {
1108                 err = fmt.Errorf("error during connection loop: %s", err)
1109         }
1110         return
1111 }
1112
1113 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1114         if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1115                 conn.Post(pp.Message{
1116                         Type:       pp.Extended,
1117                         ExtendedID: pp.HandshakeExtendedID,
1118                         ExtendedPayload: func() []byte {
1119                                 d := map[string]interface{}{
1120                                         "m": func() (ret map[string]int) {
1121                                                 ret = make(map[string]int, 2)
1122                                                 ret["ut_metadata"] = metadataExtendedId
1123                                                 if !me.config.DisablePEX {
1124                                                         ret["ut_pex"] = pexExtendedId
1125                                                 }
1126                                                 return
1127                                         }(),
1128                                         "v": extendedHandshakeClientVersion,
1129                                         // No upload queue is implemented yet.
1130                                         "reqq": 64,
1131                                 }
1132                                 if !me.config.DisableEncryption {
1133                                         d["e"] = 1
1134                                 }
1135                                 if torrent.metadataSizeKnown() {
1136                                         d["metadata_size"] = torrent.metadataSize()
1137                                 }
1138                                 if p := me.incomingPeerPort(); p != 0 {
1139                                         d["p"] = p
1140                                 }
1141                                 yourip, err := addrCompactIP(conn.remoteAddr())
1142                                 if err != nil {
1143                                         log.Printf("error calculating yourip field value in extension handshake: %s", err)
1144                                 } else {
1145                                         d["yourip"] = yourip
1146                                 }
1147                                 // log.Printf("sending %v", d)
1148                                 b, err := bencode.Marshal(d)
1149                                 if err != nil {
1150                                         panic(err)
1151                                 }
1152                                 return b
1153                         }(),
1154                 })
1155         }
1156         if torrent.haveAnyPieces() {
1157                 conn.Bitfield(torrent.bitfield())
1158         } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1159                 conn.Post(pp.Message{
1160                         Type: pp.HaveNone,
1161                 })
1162         }
1163         if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1164                 conn.Post(pp.Message{
1165                         Type: pp.Port,
1166                         Port: uint16(AddrPort(me.dHT.Addr())),
1167                 })
1168         }
1169 }
1170
1171 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) error {
1172         if !c.peerHasAll {
1173                 if t.haveInfo() {
1174                         if c.PeerPieces == nil {
1175                                 c.PeerPieces = make([]bool, t.numPieces())
1176                         }
1177                 } else {
1178                         for piece >= len(c.PeerPieces) {
1179                                 c.PeerPieces = append(c.PeerPieces, false)
1180                         }
1181                 }
1182                 if piece >= len(c.PeerPieces) {
1183                         return errors.New("peer got out of range piece index")
1184                 }
1185                 c.PeerPieces[piece] = true
1186         }
1187         if t.wantPiece(piece) {
1188                 c.updateRequests()
1189         }
1190         return nil
1191 }
1192
1193 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1194         conn.updateRequests()
1195 }
1196
1197 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1198         ok = cn.Cancel(r)
1199         if ok {
1200                 postedCancels.Add(1)
1201         }
1202         return
1203 }
1204
1205 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1206         if !cn.RequestPending(r) {
1207                 return false
1208         }
1209         delete(cn.Requests, r)
1210         return true
1211 }
1212
1213 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1214         if t.haveInfo() {
1215                 return
1216         }
1217         if c.PeerExtensionIDs["ut_metadata"] == 0 {
1218                 // Peer doesn't support this.
1219                 return
1220         }
1221         // Request metadata pieces that we don't have in a random order.
1222         var pending []int
1223         for index := 0; index < t.metadataPieceCount(); index++ {
1224                 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1225                         pending = append(pending, index)
1226                 }
1227         }
1228         for _, i := range mathRand.Perm(len(pending)) {
1229                 c.requestMetadataPiece(pending[i])
1230         }
1231 }
1232
1233 func (cl *Client) completedMetadata(t *torrent) {
1234         h := sha1.New()
1235         h.Write(t.MetaData)
1236         var ih InfoHash
1237         CopyExact(&ih, h.Sum(nil))
1238         if ih != t.InfoHash {
1239                 log.Print("bad metadata")
1240                 t.invalidateMetadata()
1241                 return
1242         }
1243         var info metainfo.Info
1244         err := bencode.Unmarshal(t.MetaData, &info)
1245         if err != nil {
1246                 log.Printf("error unmarshalling metadata: %s", err)
1247                 t.invalidateMetadata()
1248                 return
1249         }
1250         // TODO(anacrolix): If this fails, I think something harsher should be
1251         // done.
1252         err = cl.setMetaData(t, &info, t.MetaData)
1253         if err != nil {
1254                 log.Printf("error setting metadata: %s", err)
1255                 t.invalidateMetadata()
1256                 return
1257         }
1258         if cl.config.Debug {
1259                 log.Printf("%s: got metadata from peers", t)
1260         }
1261 }
1262
1263 // Process incoming ut_metadata message.
1264 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1265         var d map[string]int
1266         err = bencode.Unmarshal(payload, &d)
1267         if err != nil {
1268                 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1269                 return
1270         }
1271         msgType, ok := d["msg_type"]
1272         if !ok {
1273                 err = errors.New("missing msg_type field")
1274                 return
1275         }
1276         piece := d["piece"]
1277         switch msgType {
1278         case pp.DataMetadataExtensionMsgType:
1279                 if t.haveInfo() {
1280                         break
1281                 }
1282                 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1283                 if begin < 0 || begin >= len(payload) {
1284                         log.Printf("got bad metadata piece")
1285                         break
1286                 }
1287                 if !c.requestedMetadataPiece(piece) {
1288                         log.Printf("got unexpected metadata piece %d", piece)
1289                         break
1290                 }
1291                 c.metadataRequests[piece] = false
1292                 t.saveMetadataPiece(piece, payload[begin:])
1293                 c.UsefulChunksReceived++
1294                 c.lastUsefulChunkReceived = time.Now()
1295                 if !t.haveAllMetadataPieces() {
1296                         break
1297                 }
1298                 cl.completedMetadata(t)
1299         case pp.RequestMetadataExtensionMsgType:
1300                 if !t.haveMetadataPiece(piece) {
1301                         c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1302                         break
1303                 }
1304                 start := (1 << 14) * piece
1305                 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1306         case pp.RejectMetadataExtensionMsgType:
1307         default:
1308                 err = errors.New("unknown msg_type value")
1309         }
1310         return
1311 }
1312
1313 // Extracts the port as an integer from an address string.
1314 func addrPort(addr net.Addr) int {
1315         return AddrPort(addr)
1316 }
1317
1318 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1319         cn.peerHasAll = true
1320         cn.PeerPieces = nil
1321         if t.haveInfo() {
1322                 for i := 0; i < t.numPieces(); i++ {
1323                         cl.peerGotPiece(t, cn, i)
1324                 }
1325         }
1326 }
1327
1328 func (me *Client) upload(t *torrent, c *connection) {
1329         if me.config.NoUpload {
1330                 return
1331         }
1332         if !c.PeerInterested {
1333                 return
1334         }
1335         seeding := me.seeding(t)
1336         if !seeding && !t.connHasWantedPieces(c) {
1337                 return
1338         }
1339 another:
1340         for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1341                 c.Unchoke()
1342                 for r := range c.PeerRequests {
1343                         err := me.sendChunk(t, c, r)
1344                         if err != nil {
1345                                 log.Printf("error sending chunk %+v to peer: %s", r, err)
1346                         }
1347                         delete(c.PeerRequests, r)
1348                         goto another
1349                 }
1350                 return
1351         }
1352         c.Choke()
1353 }
1354
1355 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1356         // Count the chunk being sent, even if it isn't.
1357         c.chunksSent++
1358         b := make([]byte, r.Length)
1359         tp := &t.Pieces[r.Index]
1360         tp.waitNoPendingWrites()
1361         p := t.Info.Piece(int(r.Index))
1362         n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1363         if err != nil {
1364                 return err
1365         }
1366         if n != len(b) {
1367                 log.Fatal(b)
1368         }
1369         c.Post(pp.Message{
1370                 Type:  pp.Piece,
1371                 Index: r.Index,
1372                 Begin: r.Begin,
1373                 Piece: b,
1374         })
1375         uploadChunksPosted.Add(1)
1376         c.lastChunkSent = time.Now()
1377         return nil
1378 }
1379
1380 // Processes incoming bittorrent messages. The client lock is held upon entry
1381 // and exit.
1382 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1383         decoder := pp.Decoder{
1384                 R:         bufio.NewReader(c.rw),
1385                 MaxLength: 256 * 1024,
1386         }
1387         for {
1388                 me.mu.Unlock()
1389                 var msg pp.Message
1390                 err := decoder.Decode(&msg)
1391                 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1392                 me.mu.Lock()
1393                 c.lastMessageReceived = time.Now()
1394                 if c.closed.IsSet() {
1395                         return nil
1396                 }
1397                 if err != nil {
1398                         if me.stopped() || err == io.EOF {
1399                                 return nil
1400                         }
1401                         return err
1402                 }
1403                 if msg.Keepalive {
1404                         continue
1405                 }
1406                 switch msg.Type {
1407                 case pp.Choke:
1408                         c.PeerChoked = true
1409                         for r := range c.Requests {
1410                                 me.connDeleteRequest(t, c, r)
1411                         }
1412                         // We can then reset our interest.
1413                         c.updateRequests()
1414                 case pp.Reject:
1415                         me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1416                         c.updateRequests()
1417                 case pp.Unchoke:
1418                         c.PeerChoked = false
1419                         me.peerUnchoked(t, c)
1420                 case pp.Interested:
1421                         c.PeerInterested = true
1422                         me.upload(t, c)
1423                 case pp.NotInterested:
1424                         c.PeerInterested = false
1425                         c.Choke()
1426                 case pp.Have:
1427                         me.peerGotPiece(t, c, int(msg.Index))
1428                 case pp.Request:
1429                         if c.Choked {
1430                                 break
1431                         }
1432                         if !c.PeerInterested {
1433                                 err = errors.New("peer sent request but isn't interested")
1434                                 break
1435                         }
1436                         if c.PeerRequests == nil {
1437                                 c.PeerRequests = make(map[request]struct{}, maxRequests)
1438                         }
1439                         c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1440                         me.upload(t, c)
1441                 case pp.Cancel:
1442                         req := newRequest(msg.Index, msg.Begin, msg.Length)
1443                         if !c.PeerCancel(req) {
1444                                 unexpectedCancels.Add(1)
1445                         }
1446                 case pp.Bitfield:
1447                         if c.PeerPieces != nil || c.peerHasAll {
1448                                 err = errors.New("received unexpected bitfield")
1449                                 break
1450                         }
1451                         if t.haveInfo() {
1452                                 if len(msg.Bitfield) < t.numPieces() {
1453                                         err = errors.New("received invalid bitfield")
1454                                         break
1455                                 }
1456                                 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1457                         }
1458                         c.PeerPieces = msg.Bitfield
1459                         for index, has := range c.PeerPieces {
1460                                 if has {
1461                                         me.peerGotPiece(t, c, index)
1462                                 }
1463                         }
1464                 case pp.HaveAll:
1465                         if c.PeerPieces != nil || c.peerHasAll {
1466                                 err = errors.New("unexpected have-all")
1467                                 break
1468                         }
1469                         me.peerHasAll(t, c)
1470                 case pp.HaveNone:
1471                         if c.peerHasAll || c.PeerPieces != nil {
1472                                 err = errors.New("unexpected have-none")
1473                                 break
1474                         }
1475                         c.PeerPieces = make([]bool, func() int {
1476                                 if t.haveInfo() {
1477                                         return t.numPieces()
1478                                 } else {
1479                                         return 0
1480                                 }
1481                         }())
1482                 case pp.Piece:
1483                         me.downloadedChunk(t, c, &msg)
1484                 case pp.Extended:
1485                         switch msg.ExtendedID {
1486                         case pp.HandshakeExtendedID:
1487                                 // TODO: Create a bencode struct for this.
1488                                 var d map[string]interface{}
1489                                 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1490                                 if err != nil {
1491                                         err = fmt.Errorf("error decoding extended message payload: %s", err)
1492                                         break
1493                                 }
1494                                 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1495                                 if reqq, ok := d["reqq"]; ok {
1496                                         if i, ok := reqq.(int64); ok {
1497                                                 c.PeerMaxRequests = int(i)
1498                                         }
1499                                 }
1500                                 if v, ok := d["v"]; ok {
1501                                         c.PeerClientName = v.(string)
1502                                 }
1503                                 m, ok := d["m"]
1504                                 if !ok {
1505                                         err = errors.New("handshake missing m item")
1506                                         break
1507                                 }
1508                                 mTyped, ok := m.(map[string]interface{})
1509                                 if !ok {
1510                                         err = errors.New("handshake m value is not dict")
1511                                         break
1512                                 }
1513                                 if c.PeerExtensionIDs == nil {
1514                                         c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1515                                 }
1516                                 for name, v := range mTyped {
1517                                         id, ok := v.(int64)
1518                                         if !ok {
1519                                                 log.Printf("bad handshake m item extension ID type: %T", v)
1520                                                 continue
1521                                         }
1522                                         if id == 0 {
1523                                                 delete(c.PeerExtensionIDs, name)
1524                                         } else {
1525                                                 if c.PeerExtensionIDs[name] == 0 {
1526                                                         supportedExtensionMessages.Add(name, 1)
1527                                                 }
1528                                                 c.PeerExtensionIDs[name] = byte(id)
1529                                         }
1530                                 }
1531                                 metadata_sizeUntyped, ok := d["metadata_size"]
1532                                 if ok {
1533                                         metadata_size, ok := metadata_sizeUntyped.(int64)
1534                                         if !ok {
1535                                                 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1536                                         } else {
1537                                                 t.setMetadataSize(metadata_size, me)
1538                                         }
1539                                 }
1540                                 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1541                                         me.requestPendingMetadata(t, c)
1542                                 }
1543                         case metadataExtendedId:
1544                                 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1545                                 if err != nil {
1546                                         err = fmt.Errorf("error handling metadata extension message: %s", err)
1547                                 }
1548                         case pexExtendedId:
1549                                 if me.config.DisablePEX {
1550                                         break
1551                                 }
1552                                 var pexMsg peerExchangeMessage
1553                                 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1554                                 if err != nil {
1555                                         err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1556                                         break
1557                                 }
1558                                 go func() {
1559                                         me.mu.Lock()
1560                                         me.addPeers(t, func() (ret []Peer) {
1561                                                 for i, cp := range pexMsg.Added {
1562                                                         p := Peer{
1563                                                                 IP:     make([]byte, 4),
1564                                                                 Port:   int(cp.Port),
1565                                                                 Source: peerSourcePEX,
1566                                                         }
1567                                                         if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1568                                                                 p.SupportsEncryption = true
1569                                                         }
1570                                                         CopyExact(p.IP, cp.IP[:])
1571                                                         ret = append(ret, p)
1572                                                 }
1573                                                 return
1574                                         }())
1575                                         me.mu.Unlock()
1576                                 }()
1577                         default:
1578                                 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1579                         }
1580                         if err != nil {
1581                                 // That client uses its own extension IDs for outgoing message
1582                                 // types, which is incorrect.
1583                                 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1584                                         strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1585                                         return nil
1586                                 }
1587                         }
1588                 case pp.Port:
1589                         if me.dHT == nil {
1590                                 break
1591                         }
1592                         pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1593                         if err != nil {
1594                                 panic(err)
1595                         }
1596                         if msg.Port != 0 {
1597                                 pingAddr.Port = int(msg.Port)
1598                         }
1599                         _, err = me.dHT.Ping(pingAddr)
1600                 default:
1601                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1602                 }
1603                 if err != nil {
1604                         return err
1605                 }
1606         }
1607 }
1608
1609 // Returns true if connection is removed from torrent.Conns.
1610 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1611         for i0, _c := range t.Conns {
1612                 if _c != c {
1613                         continue
1614                 }
1615                 i1 := len(t.Conns) - 1
1616                 if i0 != i1 {
1617                         t.Conns[i0] = t.Conns[i1]
1618                 }
1619                 t.Conns = t.Conns[:i1]
1620                 return true
1621         }
1622         return false
1623 }
1624
1625 func (me *Client) dropConnection(t *torrent, c *connection) {
1626         me.event.Broadcast()
1627         c.Close()
1628         if me.deleteConnection(t, c) {
1629                 me.openNewConns(t)
1630         }
1631 }
1632
1633 // Returns true if the connection is added.
1634 func (me *Client) addConnection(t *torrent, c *connection) bool {
1635         if me.stopped() {
1636                 return false
1637         }
1638         select {
1639         case <-t.ceasingNetworking:
1640                 return false
1641         default:
1642         }
1643         if !me.wantConns(t) {
1644                 return false
1645         }
1646         for _, c0 := range t.Conns {
1647                 if c.PeerID == c0.PeerID {
1648                         // Already connected to a client with that ID.
1649                         duplicateClientConns.Add(1)
1650                         return false
1651                 }
1652         }
1653         if len(t.Conns) >= socketsPerTorrent {
1654                 c := t.worstBadConn(me)
1655                 if c == nil {
1656                         return false
1657                 }
1658                 if me.config.Debug && missinggo.CryHeard() {
1659                         log.Printf("%s: dropping connection to make room for new one:\n    %s", t, c)
1660                 }
1661                 c.Close()
1662                 me.deleteConnection(t, c)
1663         }
1664         if len(t.Conns) >= socketsPerTorrent {
1665                 panic(len(t.Conns))
1666         }
1667         t.Conns = append(t.Conns, c)
1668         c.t = t
1669         return true
1670 }
1671
1672 func (t *torrent) needData() bool {
1673         if !t.haveInfo() {
1674                 return true
1675         }
1676         for i := t.pendingPieces.Iter(); i.Next(); {
1677                 if t.wantPiece(i.Value()) {
1678                         return true
1679                 }
1680         }
1681         return !t.forReaderOffsetPieces(func(begin, end int) (again bool) {
1682                 for i := begin; i < end; i++ {
1683                         if !t.pieceComplete(i) {
1684                                 return false
1685                         }
1686                 }
1687                 return true
1688         })
1689 }
1690
1691 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1692         if c.closed.IsSet() {
1693                 return false
1694         }
1695         if !t.haveInfo() {
1696                 return c.supportsExtension("ut_metadata")
1697         }
1698         if cl.seeding(t) {
1699                 return c.PeerInterested
1700         }
1701         return t.connHasWantedPieces(c)
1702 }
1703
1704 func (me *Client) wantConns(t *torrent) bool {
1705         if !me.seeding(t) && !t.needData() {
1706                 return false
1707         }
1708         if len(t.Conns) < socketsPerTorrent {
1709                 return true
1710         }
1711         return t.worstBadConn(me) != nil
1712 }
1713
1714 func (me *Client) openNewConns(t *torrent) {
1715         select {
1716         case <-t.ceasingNetworking:
1717                 return
1718         default:
1719         }
1720         for len(t.Peers) != 0 {
1721                 if !me.wantConns(t) {
1722                         return
1723                 }
1724                 if len(t.HalfOpen) >= me.halfOpenLimit {
1725                         return
1726                 }
1727                 var (
1728                         k peersKey
1729                         p Peer
1730                 )
1731                 for k, p = range t.Peers {
1732                         break
1733                 }
1734                 delete(t.Peers, k)
1735                 me.initiateConn(p, t)
1736         }
1737         t.wantPeers.Broadcast()
1738 }
1739
1740 func (me *Client) addPeers(t *torrent, peers []Peer) {
1741         for _, p := range peers {
1742                 if me.dopplegangerAddr(net.JoinHostPort(
1743                         p.IP.String(),
1744                         strconv.FormatInt(int64(p.Port), 10),
1745                 )) {
1746                         continue
1747                 }
1748                 if _, ok := me.ipBlockRange(p.IP); ok {
1749                         continue
1750                 }
1751                 if p.Port == 0 {
1752                         // The spec says to scrub these yourselves. Fine.
1753                         continue
1754                 }
1755                 t.addPeer(p, me)
1756         }
1757 }
1758
1759 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1760         return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1761 }
1762
1763 func (cl *Client) saveTorrentFile(t *torrent) error {
1764         path := cl.cachedMetaInfoFilename(t.InfoHash)
1765         os.MkdirAll(filepath.Dir(path), 0777)
1766         f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1767         if err != nil {
1768                 return fmt.Errorf("error opening file: %s", err)
1769         }
1770         defer f.Close()
1771         e := bencode.NewEncoder(f)
1772         err = e.Encode(t.MetaInfo())
1773         if err != nil {
1774                 return fmt.Errorf("error marshalling metainfo: %s", err)
1775         }
1776         mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1777         if err != nil {
1778                 // For example, a script kiddy makes us load too many files, and we're
1779                 // able to save the torrent, but not load it again to check it.
1780                 return nil
1781         }
1782         if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1783                 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1784         }
1785         return nil
1786 }
1787
1788 func (cl *Client) startTorrent(t *torrent) {
1789         if t.Info == nil || t.data == nil {
1790                 panic("nope")
1791         }
1792         // If the client intends to upload, it needs to know what state pieces are
1793         // in.
1794         if !cl.config.NoUpload {
1795                 // Queue all pieces for hashing. This is done sequentially to avoid
1796                 // spamming goroutines.
1797                 for i := range t.Pieces {
1798                         t.Pieces[i].QueuedForHash = true
1799                 }
1800                 go func() {
1801                         for i := range t.Pieces {
1802                                 cl.verifyPiece(t, i)
1803                         }
1804                 }()
1805         }
1806 }
1807
1808 // Storage cannot be changed once it's set.
1809 func (cl *Client) setStorage(t *torrent, td Data) (err error) {
1810         err = t.setStorage(td)
1811         cl.event.Broadcast()
1812         if err != nil {
1813                 return
1814         }
1815         cl.startTorrent(t)
1816         return
1817 }
1818
1819 type TorrentDataOpener func(*metainfo.Info) Data
1820
1821 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1822         err = t.setMetadata(md, bytes)
1823         if err != nil {
1824                 return
1825         }
1826         if !cl.config.DisableMetainfoCache {
1827                 if err := cl.saveTorrentFile(t); err != nil {
1828                         log.Printf("error saving torrent file for %s: %s", t, err)
1829                 }
1830         }
1831         cl.event.Broadcast()
1832         close(t.gotMetainfo)
1833         td := cl.torrentDataOpener(md)
1834         err = cl.setStorage(t, td)
1835         return
1836 }
1837
1838 // Prepare a Torrent without any attachment to a Client. That means we can
1839 // initialize fields all fields that don't require the Client without locking
1840 // it.
1841 func newTorrent(ih InfoHash) (t *torrent) {
1842         t = &torrent{
1843                 InfoHash:  ih,
1844                 chunkSize: defaultChunkSize,
1845                 Peers:     make(map[peersKey]Peer),
1846
1847                 closing:           make(chan struct{}),
1848                 ceasingNetworking: make(chan struct{}),
1849
1850                 gotMetainfo: make(chan struct{}),
1851
1852                 HalfOpen:          make(map[string]struct{}),
1853                 pieceStateChanges: pubsub.NewPubSub(),
1854         }
1855         t.wantPeers.L = &t.stateMu
1856         return
1857 }
1858
1859 func init() {
1860         // For shuffling the tracker tiers.
1861         mathRand.Seed(time.Now().Unix())
1862 }
1863
1864 // The trackers within each tier must be shuffled before use.
1865 // http://stackoverflow.com/a/12267471/149482
1866 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1867 func shuffleTier(tier []tracker.Client) {
1868         for i := range tier {
1869                 j := mathRand.Intn(i + 1)
1870                 tier[i], tier[j] = tier[j], tier[i]
1871         }
1872 }
1873
1874 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1875         for _, tier := range base {
1876                 copy = append(copy, append([]tracker.Client{}, tier...))
1877         }
1878         return
1879 }
1880
1881 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1882 nextURL:
1883         for _, url := range newURLs {
1884                 for _, tr := range tier {
1885                         if tr.URL() == url {
1886                                 continue nextURL
1887                         }
1888                 }
1889                 tr, err := tracker.New(url)
1890                 if err != nil {
1891                         // log.Printf("error creating tracker client for %q: %s", url, err)
1892                         continue
1893                 }
1894                 tier = append(tier, tr)
1895         }
1896         return tier
1897 }
1898
1899 func (t *torrent) addTrackers(announceList [][]string) {
1900         newTrackers := copyTrackers(t.Trackers)
1901         for tierIndex, tier := range announceList {
1902                 if tierIndex < len(newTrackers) {
1903                         newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1904                 } else {
1905                         newTrackers = append(newTrackers, mergeTier(nil, tier))
1906                 }
1907                 shuffleTier(newTrackers[tierIndex])
1908         }
1909         t.Trackers = newTrackers
1910 }
1911
1912 // Don't call this before the info is available.
1913 func (t *torrent) bytesCompleted() int64 {
1914         if !t.haveInfo() {
1915                 return 0
1916         }
1917         return t.Info.TotalLength() - t.bytesLeft()
1918 }
1919
1920 // A file-like handle to some torrent data resource.
1921 type Handle interface {
1922         io.Reader
1923         io.Seeker
1924         io.Closer
1925         io.ReaderAt
1926 }
1927
1928 // Returns handles to the files in the torrent. This requires the metainfo is
1929 // available first.
1930 func (t Torrent) Files() (ret []File) {
1931         t.cl.mu.Lock()
1932         info := t.Info()
1933         t.cl.mu.Unlock()
1934         if info == nil {
1935                 return
1936         }
1937         var offset int64
1938         for _, fi := range info.UpvertedFiles() {
1939                 ret = append(ret, File{
1940                         t,
1941                         strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1942                         offset,
1943                         fi.Length,
1944                         fi,
1945                 })
1946                 offset += fi.Length
1947         }
1948         return
1949 }
1950
1951 func (t Torrent) AddPeers(pp []Peer) error {
1952         cl := t.cl
1953         cl.mu.Lock()
1954         defer cl.mu.Unlock()
1955         cl.addPeers(t.torrent, pp)
1956         return nil
1957 }
1958
1959 // Marks the entire torrent for download. Requires the info first, see
1960 // GotInfo.
1961 func (t Torrent) DownloadAll() {
1962         t.cl.mu.Lock()
1963         defer t.cl.mu.Unlock()
1964         for i := range iter.N(t.torrent.Info.NumPieces()) {
1965                 t.torrent.pendPiece(i, t.cl)
1966         }
1967 }
1968
1969 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1970 // metainfo has the correct infohash.
1971 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1972         if cl.config.DisableMetainfoCache {
1973                 return
1974         }
1975         f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1976         if err != nil {
1977                 if os.IsNotExist(err) {
1978                         err = nil
1979                 }
1980                 return
1981         }
1982         defer f.Close()
1983         dec := bencode.NewDecoder(f)
1984         err = dec.Decode(&mi)
1985         if err != nil {
1986                 return
1987         }
1988         if !bytes.Equal(mi.Info.Hash, ih[:]) {
1989                 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1990                 return
1991         }
1992         return
1993 }
1994
1995 // Specifies a new torrent for adding to a client. There are helpers for
1996 // magnet URIs and torrent metainfo files.
1997 type TorrentSpec struct {
1998         // The tiered tracker URIs.
1999         Trackers [][]string
2000         InfoHash InfoHash
2001         Info     *metainfo.InfoEx
2002         // The name to use if the Name field from the Info isn't available.
2003         DisplayName string
2004         // The chunk size to use for outbound requests. Defaults to 16KiB if not
2005         // set.
2006         ChunkSize int
2007 }
2008
2009 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2010         m, err := ParseMagnetURI(uri)
2011         if err != nil {
2012                 return
2013         }
2014         spec = &TorrentSpec{
2015                 Trackers:    [][]string{m.Trackers},
2016                 DisplayName: m.DisplayName,
2017                 InfoHash:    m.InfoHash,
2018         }
2019         return
2020 }
2021
2022 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2023         spec = &TorrentSpec{
2024                 Trackers:    mi.AnnounceList,
2025                 Info:        &mi.Info,
2026                 DisplayName: mi.Info.Name,
2027         }
2028
2029         if len(spec.Trackers) == 0 {
2030                 spec.Trackers = [][]string{[]string{mi.Announce}}
2031         } else {
2032                 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
2033         }
2034
2035         CopyExact(&spec.InfoHash, &mi.Info.Hash)
2036         return
2037 }
2038
2039 // Add or merge a torrent spec. If the torrent is already present, the
2040 // trackers will be merged with the existing ones. If the Info isn't yet
2041 // known, it will be set. The display name is replaced if the new spec
2042 // provides one. Returns new if the torrent wasn't already in the client.
2043 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2044         T.cl = cl
2045         cl.mu.Lock()
2046         defer cl.mu.Unlock()
2047
2048         t, ok := cl.torrents[spec.InfoHash]
2049         if !ok {
2050                 new = true
2051
2052                 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2053                         err = errors.New("banned torrent")
2054                         return
2055                 }
2056                 // TODO: Tidy this up?
2057                 t = newTorrent(spec.InfoHash)
2058                 if spec.ChunkSize != 0 {
2059                         t.chunkSize = pp.Integer(spec.ChunkSize)
2060                 }
2061         }
2062         if spec.DisplayName != "" {
2063                 t.setDisplayName(spec.DisplayName)
2064         }
2065         // Try to merge in info we have on the torrent. Any err left will
2066         // terminate the function.
2067         if t.Info == nil {
2068                 if spec.Info != nil {
2069                         err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2070                 } else {
2071                         var mi *metainfo.MetaInfo
2072                         mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2073                         if err != nil {
2074                                 log.Printf("error getting cached metainfo: %s", err)
2075                                 err = nil
2076                         } else if mi != nil {
2077                                 t.addTrackers(mi.AnnounceList)
2078                                 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2079                         }
2080                 }
2081         }
2082         if err != nil {
2083                 return
2084         }
2085         t.addTrackers(spec.Trackers)
2086
2087         cl.torrents[spec.InfoHash] = t
2088         T.torrent = t
2089
2090         // From this point onwards, we can consider the torrent a part of the
2091         // client.
2092         if new {
2093                 if !cl.config.DisableTrackers {
2094                         go cl.announceTorrentTrackers(T.torrent)
2095                 }
2096                 if cl.dHT != nil {
2097                         go cl.announceTorrentDHT(T.torrent, true)
2098                 }
2099         }
2100         return
2101 }
2102
2103 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2104         t, ok := me.torrents[infoHash]
2105         if !ok {
2106                 err = fmt.Errorf("no such torrent")
2107                 return
2108         }
2109         err = t.close()
2110         if err != nil {
2111                 panic(err)
2112         }
2113         delete(me.torrents, infoHash)
2114         return
2115 }
2116
2117 // Returns true when peers are required, or false if the torrent is closing.
2118 func (cl *Client) waitWantPeers(t *torrent) bool {
2119         cl.mu.Lock()
2120         defer cl.mu.Unlock()
2121         t.stateMu.Lock()
2122         defer t.stateMu.Unlock()
2123         for {
2124                 select {
2125                 case <-t.ceasingNetworking:
2126                         return false
2127                 default:
2128                 }
2129                 if len(t.Peers) > torrentPeersLowWater {
2130                         goto wait
2131                 }
2132                 if t.needData() || cl.seeding(t) {
2133                         return true
2134                 }
2135         wait:
2136                 cl.mu.Unlock()
2137                 t.wantPeers.Wait()
2138                 t.stateMu.Unlock()
2139                 cl.mu.Lock()
2140                 t.stateMu.Lock()
2141         }
2142 }
2143
2144 // Returns whether the client should make effort to seed the torrent.
2145 func (cl *Client) seeding(t *torrent) bool {
2146         if cl.config.NoUpload {
2147                 return false
2148         }
2149         if !cl.config.Seed {
2150                 return false
2151         }
2152         if t.needData() {
2153                 return false
2154         }
2155         return true
2156 }
2157
2158 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2159         for cl.waitWantPeers(t) {
2160                 // log.Printf("getting peers for %q from DHT", t)
2161                 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2162                 if err != nil {
2163                         log.Printf("error getting peers from dht: %s", err)
2164                         return
2165                 }
2166                 // Count all the unique addresses we got during this announce.
2167                 allAddrs := make(map[string]struct{})
2168         getPeers:
2169                 for {
2170                         select {
2171                         case v, ok := <-ps.Peers:
2172                                 if !ok {
2173                                         break getPeers
2174                                 }
2175                                 addPeers := make([]Peer, 0, len(v.Peers))
2176                                 for _, cp := range v.Peers {
2177                                         if cp.Port == 0 {
2178                                                 // Can't do anything with this.
2179                                                 continue
2180                                         }
2181                                         addPeers = append(addPeers, Peer{
2182                                                 IP:     cp.IP[:],
2183                                                 Port:   int(cp.Port),
2184                                                 Source: peerSourceDHT,
2185                                         })
2186                                         key := (&net.UDPAddr{
2187                                                 IP:   cp.IP[:],
2188                                                 Port: int(cp.Port),
2189                                         }).String()
2190                                         allAddrs[key] = struct{}{}
2191                                 }
2192                                 cl.mu.Lock()
2193                                 cl.addPeers(t, addPeers)
2194                                 numPeers := len(t.Peers)
2195                                 cl.mu.Unlock()
2196                                 if numPeers >= torrentPeersHighWater {
2197                                         break getPeers
2198                                 }
2199                         case <-t.ceasingNetworking:
2200                                 ps.Close()
2201                                 return
2202                         }
2203                 }
2204                 ps.Close()
2205                 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2206         }
2207 }
2208
2209 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2210         url_, err := url.Parse(tr.URL())
2211         if err != nil {
2212                 return
2213         }
2214         host, _, err := net.SplitHostPort(url_.Host)
2215         if err != nil {
2216                 host = url_.Host
2217         }
2218         addr, err := net.ResolveIPAddr("ip", host)
2219         if err != nil {
2220                 return
2221         }
2222         cl.mu.RLock()
2223         _, blocked = cl.ipBlockRange(addr.IP)
2224         cl.mu.RUnlock()
2225         return
2226 }
2227
2228 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2229         blocked, err := cl.trackerBlockedUnlocked(tr)
2230         if err != nil {
2231                 return fmt.Errorf("error determining if tracker blocked: %s", err)
2232         }
2233         if blocked {
2234                 return fmt.Errorf("tracker blocked: %s", tr)
2235         }
2236         if err := tr.Connect(); err != nil {
2237                 return fmt.Errorf("error connecting: %s", err)
2238         }
2239         resp, err := tr.Announce(req)
2240         if err != nil {
2241                 return fmt.Errorf("error announcing: %s", err)
2242         }
2243         var peers []Peer
2244         for _, peer := range resp.Peers {
2245                 peers = append(peers, Peer{
2246                         IP:   peer.IP,
2247                         Port: peer.Port,
2248                 })
2249         }
2250         cl.mu.Lock()
2251         cl.addPeers(t, peers)
2252         cl.mu.Unlock()
2253
2254         // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2255
2256         time.Sleep(time.Second * time.Duration(resp.Interval))
2257         return nil
2258 }
2259
2260 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2261         oks := make(chan bool)
2262         outstanding := 0
2263         for _, tier := range trackers {
2264                 for _, tr := range tier {
2265                         outstanding++
2266                         go func(tr tracker.Client) {
2267                                 err := cl.announceTorrentSingleTracker(tr, req, t)
2268                                 oks <- err == nil
2269                         }(tr)
2270                 }
2271         }
2272         for outstanding > 0 {
2273                 ok := <-oks
2274                 outstanding--
2275                 if ok {
2276                         atLeastOne = true
2277                 }
2278         }
2279         return
2280 }
2281
2282 // Announce torrent to its trackers.
2283 func (cl *Client) announceTorrentTrackers(t *torrent) {
2284         req := tracker.AnnounceRequest{
2285                 Event:    tracker.Started,
2286                 NumWant:  -1,
2287                 Port:     uint16(cl.incomingPeerPort()),
2288                 PeerId:   cl.peerID,
2289                 InfoHash: t.InfoHash,
2290         }
2291         if !cl.waitWantPeers(t) {
2292                 return
2293         }
2294         cl.mu.RLock()
2295         req.Left = uint64(t.bytesLeft())
2296         trackers := t.Trackers
2297         cl.mu.RUnlock()
2298         if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2299                 req.Event = tracker.None
2300         }
2301 newAnnounce:
2302         for cl.waitWantPeers(t) {
2303                 cl.mu.RLock()
2304                 req.Left = uint64(t.bytesLeft())
2305                 trackers = t.Trackers
2306                 cl.mu.RUnlock()
2307                 numTrackersTried := 0
2308                 for _, tier := range trackers {
2309                         for trIndex, tr := range tier {
2310                                 numTrackersTried++
2311                                 err := cl.announceTorrentSingleTracker(tr, &req, t)
2312                                 if err != nil {
2313                                         continue
2314                                 }
2315                                 // Float the successful announce to the top of the tier. If
2316                                 // the trackers list has been changed, we'll be modifying an
2317                                 // old copy so it won't matter.
2318                                 cl.mu.Lock()
2319                                 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2320                                 cl.mu.Unlock()
2321
2322                                 req.Event = tracker.None
2323                                 continue newAnnounce
2324                         }
2325                 }
2326                 if numTrackersTried != 0 {
2327                         log.Printf("%s: all trackers failed", t)
2328                 }
2329                 // TODO: Wait until trackers are added if there are none.
2330                 time.Sleep(10 * time.Second)
2331         }
2332 }
2333
2334 func (cl *Client) allTorrentsCompleted() bool {
2335         for _, t := range cl.torrents {
2336                 if !t.haveInfo() {
2337                         return false
2338                 }
2339                 if t.numPiecesCompleted() != t.numPieces() {
2340                         return false
2341                 }
2342         }
2343         return true
2344 }
2345
2346 // Returns true when all torrents are completely downloaded and false if the
2347 // client is stopped before that.
2348 func (me *Client) WaitAll() bool {
2349         me.mu.Lock()
2350         defer me.mu.Unlock()
2351         for !me.allTorrentsCompleted() {
2352                 if me.stopped() {
2353                         return false
2354                 }
2355                 me.event.Wait()
2356         }
2357         return true
2358 }
2359
2360 // Handle a received chunk from a peer.
2361 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) {
2362         chunksReceived.Add(1)
2363
2364         req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2365
2366         // Request has been satisfied.
2367         if me.connDeleteRequest(t, c, req) {
2368                 defer c.updateRequests()
2369         } else {
2370                 unexpectedChunksReceived.Add(1)
2371         }
2372
2373         index := int(req.Index)
2374         piece := &t.Pieces[index]
2375
2376         // Do we actually want this chunk?
2377         if !t.wantChunk(req) {
2378                 unwantedChunksReceived.Add(1)
2379                 c.UnwantedChunksReceived++
2380                 return
2381         }
2382
2383         c.UsefulChunksReceived++
2384         c.lastUsefulChunkReceived = time.Now()
2385
2386         me.upload(t, c)
2387
2388         // Need to record that it hasn't been written yet, before we attempt to do
2389         // anything with it.
2390         piece.incrementPendingWrites()
2391         // Record that we have the chunk.
2392         piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2393
2394         // Cancel pending requests for this chunk.
2395         for _, c := range t.Conns {
2396                 if me.connCancel(t, c, req) {
2397                         c.updateRequests()
2398                 }
2399         }
2400
2401         me.mu.Unlock()
2402         // Write the chunk out.
2403         err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2404         me.mu.Lock()
2405
2406         piece.decrementPendingWrites()
2407
2408         if err != nil {
2409                 log.Printf("error writing chunk: %s", err)
2410                 t.pendRequest(req)
2411                 return
2412         }
2413
2414         // It's important that the piece is potentially queued before we check if
2415         // the piece is still wanted, because if it is queued, it won't be wanted.
2416         if t.pieceAllDirty(index) {
2417                 me.queuePieceCheck(t, int(req.Index))
2418         }
2419
2420         if c.peerTouchedPieces == nil {
2421                 c.peerTouchedPieces = make(map[int]struct{})
2422         }
2423         c.peerTouchedPieces[index] = struct{}{}
2424
2425         me.event.Broadcast()
2426         t.publishPieceChange(int(req.Index))
2427         return
2428 }
2429
2430 // Return the connections that touched a piece, and clear the entry while
2431 // doing it.
2432 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2433         for _, c := range t.Conns {
2434                 if _, ok := c.peerTouchedPieces[piece]; ok {
2435                         ret = append(ret, c)
2436                         delete(c.peerTouchedPieces, piece)
2437                 }
2438         }
2439         return
2440 }
2441
2442 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2443         p := &t.Pieces[piece]
2444         if p.EverHashed {
2445                 // Don't score the first time a piece is hashed, it could be an
2446                 // initial check.
2447                 if correct {
2448                         pieceHashedCorrect.Add(1)
2449                 } else {
2450                         log.Printf("%s: piece %d failed hash", t, piece)
2451                         pieceHashedNotCorrect.Add(1)
2452                 }
2453         }
2454         p.EverHashed = true
2455         touchers := me.reapPieceTouches(t, int(piece))
2456         if correct {
2457                 err := t.data.PieceCompleted(int(piece))
2458                 if err != nil {
2459                         log.Printf("error completing piece: %s", err)
2460                         correct = false
2461                 }
2462         } else if len(touchers) != 0 {
2463                 log.Printf("dropping %d conns that touched piece", len(touchers))
2464                 for _, c := range touchers {
2465                         me.dropConnection(t, c)
2466                 }
2467         }
2468         me.pieceChanged(t, int(piece))
2469 }
2470
2471 func (me *Client) onCompletedPiece(t *torrent, piece int) {
2472         t.pendingPieces.Remove(piece)
2473         for _, conn := range t.Conns {
2474                 conn.Have(piece)
2475                 for r := range conn.Requests {
2476                         if int(r.Index) == piece {
2477                                 conn.Cancel(r)
2478                         }
2479                 }
2480                 // Could check here if peer doesn't have piece, but due to caching
2481                 // some peers may have said they have a piece but they don't.
2482                 me.upload(t, conn)
2483         }
2484 }
2485
2486 func (me *Client) onFailedPiece(t *torrent, piece int) {
2487         if t.pieceAllDirty(piece) {
2488                 t.pendAllChunkSpecs(piece)
2489         }
2490         if !t.wantPiece(piece) {
2491                 return
2492         }
2493         me.openNewConns(t)
2494         for _, conn := range t.Conns {
2495                 if conn.PeerHasPiece(piece) {
2496                         conn.updateRequests()
2497                 }
2498         }
2499 }
2500
2501 func (me *Client) pieceChanged(t *torrent, piece int) {
2502         correct := t.pieceComplete(piece)
2503         defer t.publishPieceChange(piece)
2504         defer me.event.Broadcast()
2505         if correct {
2506                 me.onCompletedPiece(t, piece)
2507         } else {
2508                 me.onFailedPiece(t, piece)
2509         }
2510 }
2511
2512 func (cl *Client) verifyPiece(t *torrent, piece int) {
2513         cl.mu.Lock()
2514         defer cl.mu.Unlock()
2515         p := &t.Pieces[piece]
2516         for p.Hashing || t.data == nil {
2517                 cl.event.Wait()
2518         }
2519         p.QueuedForHash = false
2520         if t.isClosed() || t.pieceComplete(piece) {
2521                 return
2522         }
2523         p.Hashing = true
2524         cl.mu.Unlock()
2525         sum := t.hashPiece(piece)
2526         cl.mu.Lock()
2527         select {
2528         case <-t.closing:
2529                 return
2530         default:
2531         }
2532         p.Hashing = false
2533         cl.pieceHashed(t, piece, sum == p.Hash)
2534 }
2535
2536 // Returns handles to all the torrents loaded in the Client.
2537 func (me *Client) Torrents() (ret []Torrent) {
2538         me.mu.Lock()
2539         for _, t := range me.torrents {
2540                 ret = append(ret, Torrent{me, t})
2541         }
2542         me.mu.Unlock()
2543         return
2544 }
2545
2546 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2547         spec, err := TorrentSpecFromMagnetURI(uri)
2548         if err != nil {
2549                 return
2550         }
2551         T, _, err = me.AddTorrentSpec(spec)
2552         return
2553 }
2554
2555 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2556         T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2557         return
2558 }
2559
2560 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2561         mi, err := metainfo.LoadFromFile(filename)
2562         if err != nil {
2563                 return
2564         }
2565         T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2566         return
2567 }
2568
2569 func (me *Client) DHT() *dht.Server {
2570         return me.dHT
2571 }