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