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