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