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