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