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