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