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