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