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