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