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