25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/pubsub"
28 "github.com/anacrolix/sync"
29 "github.com/anacrolix/utp"
30 "github.com/bradfitz/iter"
31 "github.com/edsrzf/mmap-go"
33 "github.com/anacrolix/torrent/bencode"
34 filePkg "github.com/anacrolix/torrent/data/file"
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/tracker"
44 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
45 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
46 chunksReceived = expvar.NewInt("chunksReceived")
48 peersAddedBySource = expvar.NewMap("peersAddedBySource")
50 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
51 unexpectedCancels = expvar.NewInt("unexpectedCancels")
52 postedCancels = expvar.NewInt("postedCancels")
53 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
55 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
56 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
58 unsuccessfulDials = expvar.NewInt("dialSuccessful")
59 successfulDials = expvar.NewInt("dialUnsuccessful")
61 acceptUTP = expvar.NewInt("acceptUTP")
62 acceptTCP = expvar.NewInt("acceptTCP")
63 acceptReject = expvar.NewInt("acceptReject")
65 peerExtensions = expvar.NewMap("peerExtensions")
66 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
67 // Count of connections to peer with same client ID.
68 connsToSelf = expvar.NewInt("connsToSelf")
69 // Number of completed connections to a client we're already connected with.
70 duplicateClientConns = expvar.NewInt("duplicateClientConns")
71 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
72 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
76 // Justification for set bits follows.
78 // Extension protocol ([5]|=0x10):
79 // http://www.bittorrent.org/beps/bep_0010.html
81 // Fast Extension ([7]|=0x04):
82 // http://bittorrent.org/beps/bep_0006.html.
83 // Disabled until AllowedFast is implemented.
86 // http://www.bittorrent.org/beps/bep_0005.html
87 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
89 socketsPerTorrent = 80
90 torrentPeersHighWater = 200
91 torrentPeersLowWater = 50
93 // Limit how long handshake can take. This is to reduce the lingering
94 // impact of a few bad apples. 4s loses 1% of successful handshakes that
95 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
96 btHandshakeTimeout = 4 * time.Second
97 handshakesTimeout = 20 * time.Second
99 // These are our extended message IDs.
100 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
103 // Updated occasionally to when there's been some changes to client
104 // behaviour in case other clients are assuming anything of us. See also
106 extendedHandshakeClientVersion = "go.torrent dev 20150624"
109 // Currently doesn't really queue, but should in the future.
110 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
111 piece := &t.Pieces[pieceIndex]
112 if piece.QueuedForHash {
115 piece.QueuedForHash = true
116 t.publishPieceChange(int(pieceIndex))
117 go cl.verifyPiece(t, int(pieceIndex))
120 // Queue a piece check if one isn't already queued, and the piece has never
121 // been checked before.
122 func (cl *Client) queueFirstHash(t *torrent, piece int) {
123 p := &t.Pieces[piece]
124 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
127 cl.queuePieceCheck(t, piece)
130 // Clients contain zero or more Torrents. A client manages a blocklist, the
131 // TCP/UDP protocol ports, and DHT as desired.
135 listeners []net.Listener
138 ipBlockList iplist.Ranger
139 bannedTorrents map[InfoHash]struct{}
141 pruneTimer *time.Timer
142 extensionBytes peerExtensionBytes
143 // Set of addresses that have our client ID. This intentionally will
144 // include ourselves if we end up trying to connect to our own address
145 // through legitimate channels.
146 dopplegangerAddrs map[string]struct{}
148 torrentDataOpener TorrentDataOpener
154 torrents map[InfoHash]*torrent
157 func (me *Client) IPBlockList() iplist.Ranger {
160 return me.ipBlockList
163 func (me *Client) SetIPBlockList(list iplist.Ranger) {
166 me.ipBlockList = list
168 me.dHT.SetIPBlockList(list)
172 func (me *Client) PeerID() string {
173 return string(me.peerID[:])
176 func (me *Client) ListenAddr() (addr net.Addr) {
177 for _, l := range me.listeners {
184 type hashSorter struct {
188 func (me hashSorter) Len() int {
189 return len(me.Hashes)
192 func (me hashSorter) Less(a, b int) bool {
193 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
196 func (me hashSorter) Swap(a, b int) {
197 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
200 func (cl *Client) sortedTorrents() (ret []*torrent) {
202 for ih := range cl.torrents {
203 hs.Hashes = append(hs.Hashes, ih)
206 for _, ih := range hs.Hashes {
207 ret = append(ret, cl.torrent(ih))
212 // Writes out a human readable status of the client, such as for writing to a
214 func (cl *Client) WriteStatus(_w io.Writer) {
216 defer cl.mu.RUnlock()
217 w := bufio.NewWriter(_w)
219 if addr := cl.ListenAddr(); addr != nil {
220 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
222 fmt.Fprintln(w, "Not listening!")
224 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
226 dhtStats := cl.dHT.Stats()
227 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
228 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
229 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
230 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
231 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
233 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
235 for _, t := range cl.sortedTorrents() {
237 fmt.Fprint(w, "<unknown name>")
239 fmt.Fprint(w, t.Name())
243 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.length)), t.length)
245 w.WriteString("<missing metainfo>")
253 // TODO: Make this non-blocking Read on Torrent.
254 func dataReadAt(d Data, b []byte, off int64) (n int, err error) {
256 // if err == io.ErrUnexpectedEOF && n != 0 {
260 // log.Println("data read at", len(b), off)
261 return d.ReadAt(b, off)
264 // Calculates the number of pieces to set to Readahead priority, after the
265 // Now, and Next pieces.
266 func readaheadPieces(readahead, pieceLength int64) (ret int) {
267 // Expand the readahead to fit any partial pieces. Subtract 1 for the
268 // "next" piece that is assigned.
269 ret = int((readahead+pieceLength-1)/pieceLength - 1)
270 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
271 // piece length is much larger than the readahead.
278 func (cl *Client) configDir() string {
279 if cl.config.ConfigDir == "" {
280 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
282 return cl.config.ConfigDir
285 // The directory where the Client expects to find and store configuration
286 // data. Defaults to $HOME/.config/torrent.
287 func (cl *Client) ConfigDir() string {
288 return cl.configDir()
291 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
292 f, err := os.Open(filename)
293 if os.IsNotExist(err) {
301 mm, err := mmap.Map(f, mmap.RDONLY, 0)
305 ret = iplist.NewFromPacked(mm)
309 func (cl *Client) setEnvBlocklist() (err error) {
310 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
311 defaultBlocklist := filename == ""
312 if defaultBlocklist {
313 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
317 if cl.ipBlockList != nil {
320 filename = filepath.Join(cl.configDir(), "blocklist")
322 f, err := os.Open(filename)
324 if defaultBlocklist {
330 cl.ipBlockList, err = iplist.NewFromReader(f)
334 func (cl *Client) initBannedTorrents() error {
335 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
337 if os.IsNotExist(err) {
340 return fmt.Errorf("error opening banned infohashes file: %s", err)
343 scanner := bufio.NewScanner(f)
344 cl.bannedTorrents = make(map[InfoHash]struct{})
346 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
350 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
352 return fmt.Errorf("error reading infohash: %s", err)
358 return errors.New("bad infohash")
362 cl.bannedTorrents[ih] = struct{}{}
364 if err := scanner.Err(); err != nil {
365 return fmt.Errorf("error scanning file: %s", err)
370 // Creates a new client.
371 func NewClient(cfg *Config) (cl *Client, err error) {
382 halfOpenLimit: socketsPerTorrent,
384 torrentDataOpener: func(md *metainfo.Info) Data {
385 return filePkg.TorrentData(md, cfg.DataDir)
387 dopplegangerAddrs: make(map[string]struct{}),
389 quit: make(chan struct{}),
390 torrents: make(map[InfoHash]*torrent),
392 CopyExact(&cl.extensionBytes, defaultExtensionBytes)
394 if cfg.TorrentDataOpener != nil {
395 cl.torrentDataOpener = cfg.TorrentDataOpener
398 if cfg.IPBlocklist != nil {
399 cl.ipBlockList = cfg.IPBlocklist
400 } else if !cfg.NoDefaultBlocklist {
401 err = cl.setEnvBlocklist()
407 if err = cl.initBannedTorrents(); err != nil {
408 err = fmt.Errorf("error initing banned torrents: %s", err)
412 if cfg.PeerID != "" {
413 CopyExact(&cl.peerID, cfg.PeerID)
415 o := copy(cl.peerID[:], bep20)
416 _, err = rand.Read(cl.peerID[o:])
418 panic("error generating peer id")
422 // Returns the laddr string to listen on for the next Listen call.
423 listenAddr := func() string {
424 if addr := cl.ListenAddr(); addr != nil {
427 if cfg.ListenAddr == "" {
430 return cfg.ListenAddr
432 if !cl.config.DisableTCP {
434 l, err = net.Listen(func() string {
435 if cl.config.DisableIPv6 {
444 cl.listeners = append(cl.listeners, l)
445 go cl.acceptConnections(l, false)
447 if !cl.config.DisableUTP {
448 cl.utpSock, err = utp.NewSocket(func() string {
449 if cl.config.DisableIPv6 {
458 cl.listeners = append(cl.listeners, cl.utpSock)
459 go cl.acceptConnections(cl.utpSock, true)
462 dhtCfg := cfg.DHTConfig
463 if dhtCfg.IPBlocklist == nil {
464 dhtCfg.IPBlocklist = cl.ipBlockList
466 if dhtCfg.Addr == "" {
467 dhtCfg.Addr = listenAddr()
469 if dhtCfg.Conn == nil && cl.utpSock != nil {
470 dhtCfg.Conn = cl.utpSock
472 cl.dHT, err = dht.NewServer(&dhtCfg)
481 func (cl *Client) stopped() bool {
490 // Stops the client. All connections to peers are closed and all activity will
492 func (me *Client) Close() {
504 for _, l := range me.listeners {
507 for _, t := range me.torrents {
513 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
515 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
516 if cl.ipBlockList == nil {
520 // If blocklists are enabled, then block non-IPv4 addresses, because
521 // blocklists do not yet support IPv6.
523 if missinggo.CryHeard() {
524 log.Printf("blocking non-IPv4 address: %s", ip)
530 return cl.ipBlockList.Lookup(ip4)
533 func (cl *Client) waitAccept() {
537 for _, t := range cl.torrents {
551 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
554 // We accept all connections immediately, because we don't know what
555 // torrent they're for.
556 conn, err := l.Accept()
575 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
576 _, blocked := cl.ipBlockRange(AddrIP(conn.RemoteAddr()))
578 if blocked || doppleganger {
580 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
584 go cl.incomingConnection(conn, utp)
588 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
590 if tc, ok := nc.(*net.TCPConn); ok {
596 c.Discovery = peerSourceIncoming
598 err := cl.runReceivedConn(c)
604 // Returns a handle to the given torrent, if it's present in the client.
605 func (cl *Client) Torrent(ih InfoHash) (T Torrent, ok bool) {
608 t, ok := cl.torrents[ih]
616 func (me *Client) torrent(ih InfoHash) *torrent {
617 return me.torrents[ih]
620 type dialResult struct {
625 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
626 conn, err := dial(addr, t)
631 conn = nil // Pedantic
633 ch <- dialResult{conn, utp}
635 successfulDials.Add(1)
638 unsuccessfulDials.Add(1)
641 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
642 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
643 if ret < minDialTimeout {
649 // Returns whether an address is known to connect to a client with our own ID.
650 func (me *Client) dopplegangerAddr(addr string) bool {
651 _, ok := me.dopplegangerAddrs[addr]
655 // Start the process of connecting to the given peer for the given torrent if
657 func (me *Client) initiateConn(peer Peer, t *torrent) {
658 if peer.Id == me.peerID {
661 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
662 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
663 duplicateConnsAvoided.Add(1)
666 if r, ok := me.ipBlockRange(peer.IP); ok {
667 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
670 t.HalfOpen[addr] = struct{}{}
671 go me.outgoingConnection(t, addr, peer.Source)
674 func (me *Client) dialTimeout(t *torrent) time.Duration {
676 pendingPeers := len(t.Peers)
678 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
681 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
682 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
684 c.(*net.TCPConn).SetLinger(0)
689 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
690 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
693 // Returns a connection over UTP or TCP, whichever is first to connect.
694 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
695 // Initiate connections via TCP and UTP simultaneously. Use the first one
698 if !me.config.DisableUTP {
701 if !me.config.DisableTCP {
704 resCh := make(chan dialResult, left)
705 if !me.config.DisableUTP {
706 go doDial(me.dialUTP, resCh, true, addr, t)
708 if !me.config.DisableTCP {
709 go doDial(me.dialTCP, resCh, false, addr, t)
712 // Wait for a successful connection.
713 for ; left > 0 && res.Conn == nil; left-- {
717 // There are still incompleted dials.
719 for ; left > 0; left-- {
720 conn := (<-resCh).Conn
732 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
733 if _, ok := t.HalfOpen[addr]; !ok {
734 panic("invariant broken")
736 delete(t.HalfOpen, addr)
740 // Performs initiator handshakes and returns a connection.
741 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
745 c.encrypted = encrypted
747 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
751 ok, err := me.initiateHandshakes(c, t)
758 // Returns nil connection and nil error if no connection could be established
759 // for valid reasons.
760 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
761 nc, utp := me.dialFirst(addr, t)
765 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
773 if me.config.DisableEncryption {
774 // We already tried without encryption.
777 // Try again without encryption, using whichever protocol type worked last
780 nc, err = me.dialUTP(addr, t)
782 nc, err = me.dialTCP(addr, t)
785 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
788 c, err = me.handshakesConnection(nc, t, false, utp)
795 // Called to dial out and run a connection. The addr we're given is already
796 // considered half-open.
797 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
798 c, err := me.establishOutgoingConn(t, addr)
801 // Don't release lock between here and addConnection, unless it's for
803 me.noLongerHalfOpen(t, addr)
812 err = me.runInitiatedHandshookConn(c, t)
818 // The port number for incoming peer connections. 0 if the client isn't
820 func (cl *Client) incomingPeerPort() int {
821 listenAddr := cl.ListenAddr()
822 if listenAddr == nil {
825 return addrPort(listenAddr)
828 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
829 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
830 func addrCompactIP(addr net.Addr) (string, error) {
831 host, _, err := net.SplitHostPort(addr.String())
835 ip := net.ParseIP(host)
836 if v4 := ip.To4(); v4 != nil {
840 return string(v4), nil
842 return string(ip.To16()), nil
845 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
857 peerExtensionBytes [8]byte
861 func (me *peerExtensionBytes) SupportsExtended() bool {
862 return me[5]&0x10 != 0
865 func (me *peerExtensionBytes) SupportsDHT() bool {
866 return me[7]&0x01 != 0
869 func (me *peerExtensionBytes) SupportsFast() bool {
870 return me[7]&0x04 != 0
873 type handshakeResult struct {
879 // ih is nil if we expect the peer to declare the InfoHash, such as when the
880 // peer initiated the connection. Returns ok if the handshake was successful,
881 // and err if there was an unexpected condition other than the peer simply
882 // abandoning the handshake.
883 func handshake(sock io.ReadWriter, ih *InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
884 // Bytes to be sent to the peer. Should never block the sender.
885 postCh := make(chan []byte, 4)
886 // A single error value sent when the writer completes.
887 writeDone := make(chan error, 1)
888 // Performs writes to the socket and ensures posts don't block.
889 go handshakeWriter(sock, postCh, writeDone)
892 close(postCh) // Done writing.
899 // Wait until writes complete before returning from handshake.
902 err = fmt.Errorf("error writing: %s", err)
906 post := func(bb []byte) {
910 panic("mustn't block while posting")
914 post([]byte(pp.Protocol))
916 if ih != nil { // We already know what we want.
921 _, err = io.ReadFull(sock, b[:68])
926 if string(b[:20]) != pp.Protocol {
929 CopyExact(&res.peerExtensionBytes, b[20:28])
930 CopyExact(&res.InfoHash, b[28:48])
931 CopyExact(&res.peerID, b[48:68])
932 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
934 // TODO: Maybe we can just drop peers here if we're not interested. This
935 // could prevent them trying to reconnect, falsely believing there was
937 if ih == nil { // We were waiting for the peer to tell us what they wanted.
938 post(res.InfoHash[:])
946 // Wraps a raw connection and provides the interface we want for using the
947 // connection in the message loop.
948 type deadlineReader struct {
953 func (me deadlineReader) Read(b []byte) (n int, err error) {
954 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
955 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
957 err = fmt.Errorf("error setting read deadline: %s", err)
959 n, err = me.r.Read(b)
960 // Convert common errors into io.EOF.
962 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
964 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
974 type readWriter struct {
979 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
980 var protocol [len(pp.Protocol)]byte
981 _, err = io.ReadFull(rw, protocol[:])
986 io.MultiReader(bytes.NewReader(protocol[:]), rw),
989 if string(protocol[:]) == pp.Protocol {
993 ret, err = mse.ReceiveHandshake(ret, skeys)
997 func (cl *Client) receiveSkeys() (ret [][]byte) {
998 for ih := range cl.torrents {
999 ret = append(ret, ih[:])
1004 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
1006 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
1011 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
1012 if ih != t.InfoHash {
1018 // Do encryption and bittorrent handshakes as receiver.
1019 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1021 skeys := cl.receiveSkeys()
1023 if !cl.config.DisableEncryption {
1024 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1026 if err == mse.ErrNoSecretKeyMatch {
1032 ih, ok, err := cl.connBTHandshake(c, nil)
1034 err = fmt.Errorf("error during bt handshake: %s", err)
1046 // Returns !ok if handshake failed for valid reasons.
1047 func (cl *Client) connBTHandshake(c *connection, ih *InfoHash) (ret InfoHash, ok bool, err error) {
1048 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1049 if err != nil || !ok {
1053 c.PeerExtensionBytes = res.peerExtensionBytes
1054 c.PeerID = res.peerID
1055 c.completedHandshake = time.Now()
1059 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1060 if c.PeerID == cl.peerID {
1061 // Only if we initiated the connection is the remote address a
1062 // listen addr for a doppleganger.
1064 addr := c.conn.RemoteAddr().String()
1065 cl.dopplegangerAddrs[addr] = struct{}{}
1068 return cl.runHandshookConn(c, t)
1071 func (cl *Client) runReceivedConn(c *connection) (err error) {
1072 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1076 t, err := cl.receiveHandshakes(c)
1078 err = fmt.Errorf("error receiving handshakes: %s", err)
1085 defer cl.mu.Unlock()
1086 if c.PeerID == cl.peerID {
1089 return cl.runHandshookConn(c, t)
1092 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1093 c.conn.SetWriteDeadline(time.Time{})
1095 deadlineReader{c.conn, c.rw},
1098 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1099 if !cl.addConnection(t, c) {
1102 defer cl.dropConnection(t, c)
1104 go c.writeOptimizer(time.Minute)
1105 cl.sendInitialMessages(c, t)
1106 err = cl.connectionLoop(t, c)
1108 err = fmt.Errorf("error during connection loop: %s", err)
1113 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1114 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1115 conn.Post(pp.Message{
1117 ExtendedID: pp.HandshakeExtendedID,
1118 ExtendedPayload: func() []byte {
1119 d := map[string]interface{}{
1120 "m": func() (ret map[string]int) {
1121 ret = make(map[string]int, 2)
1122 ret["ut_metadata"] = metadataExtendedId
1123 if !me.config.DisablePEX {
1124 ret["ut_pex"] = pexExtendedId
1128 "v": extendedHandshakeClientVersion,
1129 // No upload queue is implemented yet.
1132 if !me.config.DisableEncryption {
1135 if torrent.metadataSizeKnown() {
1136 d["metadata_size"] = torrent.metadataSize()
1138 if p := me.incomingPeerPort(); p != 0 {
1141 yourip, err := addrCompactIP(conn.remoteAddr())
1143 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1145 d["yourip"] = yourip
1147 // log.Printf("sending %v", d)
1148 b, err := bencode.Marshal(d)
1156 if torrent.haveAnyPieces() {
1157 conn.Bitfield(torrent.bitfield())
1158 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1159 conn.Post(pp.Message{
1163 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1164 conn.Post(pp.Message{
1166 Port: uint16(AddrPort(me.dHT.Addr())),
1171 func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) error {
1174 if c.PeerPieces == nil {
1175 c.PeerPieces = make([]bool, t.numPieces())
1178 for piece >= len(c.PeerPieces) {
1179 c.PeerPieces = append(c.PeerPieces, false)
1182 if piece >= len(c.PeerPieces) {
1183 return errors.New("peer got out of range piece index")
1185 c.PeerPieces[piece] = true
1187 if t.wantPiece(piece) {
1193 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1194 conn.updateRequests()
1197 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1200 postedCancels.Add(1)
1205 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1206 if !cn.RequestPending(r) {
1209 delete(cn.Requests, r)
1213 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1217 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1218 // Peer doesn't support this.
1221 // Request metadata pieces that we don't have in a random order.
1223 for index := 0; index < t.metadataPieceCount(); index++ {
1224 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1225 pending = append(pending, index)
1228 for _, i := range mathRand.Perm(len(pending)) {
1229 c.requestMetadataPiece(pending[i])
1233 func (cl *Client) completedMetadata(t *torrent) {
1237 CopyExact(&ih, h.Sum(nil))
1238 if ih != t.InfoHash {
1239 log.Print("bad metadata")
1240 t.invalidateMetadata()
1243 var info metainfo.Info
1244 err := bencode.Unmarshal(t.MetaData, &info)
1246 log.Printf("error unmarshalling metadata: %s", err)
1247 t.invalidateMetadata()
1250 // TODO(anacrolix): If this fails, I think something harsher should be
1252 err = cl.setMetaData(t, &info, t.MetaData)
1254 log.Printf("error setting metadata: %s", err)
1255 t.invalidateMetadata()
1258 if cl.config.Debug {
1259 log.Printf("%s: got metadata from peers", t)
1263 // Process incoming ut_metadata message.
1264 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1265 var d map[string]int
1266 err = bencode.Unmarshal(payload, &d)
1268 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1271 msgType, ok := d["msg_type"]
1273 err = errors.New("missing msg_type field")
1278 case pp.DataMetadataExtensionMsgType:
1282 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1283 if begin < 0 || begin >= len(payload) {
1284 log.Printf("got bad metadata piece")
1287 if !c.requestedMetadataPiece(piece) {
1288 log.Printf("got unexpected metadata piece %d", piece)
1291 c.metadataRequests[piece] = false
1292 t.saveMetadataPiece(piece, payload[begin:])
1293 c.UsefulChunksReceived++
1294 c.lastUsefulChunkReceived = time.Now()
1295 if !t.haveAllMetadataPieces() {
1298 cl.completedMetadata(t)
1299 case pp.RequestMetadataExtensionMsgType:
1300 if !t.haveMetadataPiece(piece) {
1301 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1304 start := (1 << 14) * piece
1305 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.MetaData[start:start+t.metadataPieceSize(piece)]))
1306 case pp.RejectMetadataExtensionMsgType:
1308 err = errors.New("unknown msg_type value")
1313 // Extracts the port as an integer from an address string.
1314 func addrPort(addr net.Addr) int {
1315 return AddrPort(addr)
1318 func (cl *Client) peerHasAll(t *torrent, cn *connection) {
1319 cn.peerHasAll = true
1322 for i := 0; i < t.numPieces(); i++ {
1323 cl.peerGotPiece(t, cn, i)
1328 func (me *Client) upload(t *torrent, c *connection) {
1329 if me.config.NoUpload {
1332 if !c.PeerInterested {
1335 seeding := me.seeding(t)
1336 if !seeding && !t.connHasWantedPieces(c) {
1340 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1342 for r := range c.PeerRequests {
1343 err := me.sendChunk(t, c, r)
1345 log.Printf("error sending chunk %+v to peer: %s", r, err)
1347 delete(c.PeerRequests, r)
1355 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1356 // Count the chunk being sent, even if it isn't.
1358 b := make([]byte, r.Length)
1359 tp := &t.Pieces[r.Index]
1360 tp.waitNoPendingWrites()
1361 p := t.Info.Piece(int(r.Index))
1362 n, err := dataReadAt(t.data, b, p.Offset()+int64(r.Begin))
1375 uploadChunksPosted.Add(1)
1376 c.lastChunkSent = time.Now()
1380 // Processes incoming bittorrent messages. The client lock is held upon entry
1382 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1383 decoder := pp.Decoder{
1384 R: bufio.NewReader(c.rw),
1385 MaxLength: 256 * 1024,
1390 err := decoder.Decode(&msg)
1391 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1393 c.lastMessageReceived = time.Now()
1394 if c.closed.IsSet() {
1398 if me.stopped() || err == io.EOF {
1409 for r := range c.Requests {
1410 me.connDeleteRequest(t, c, r)
1412 // We can then reset our interest.
1415 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1418 c.PeerChoked = false
1419 me.peerUnchoked(t, c)
1421 c.PeerInterested = true
1423 case pp.NotInterested:
1424 c.PeerInterested = false
1427 me.peerGotPiece(t, c, int(msg.Index))
1432 if !c.PeerInterested {
1433 err = errors.New("peer sent request but isn't interested")
1436 if c.PeerRequests == nil {
1437 c.PeerRequests = make(map[request]struct{}, maxRequests)
1439 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1442 req := newRequest(msg.Index, msg.Begin, msg.Length)
1443 if !c.PeerCancel(req) {
1444 unexpectedCancels.Add(1)
1447 if c.PeerPieces != nil || c.peerHasAll {
1448 err = errors.New("received unexpected bitfield")
1452 if len(msg.Bitfield) < t.numPieces() {
1453 err = errors.New("received invalid bitfield")
1456 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1458 c.PeerPieces = msg.Bitfield
1459 for index, has := range c.PeerPieces {
1461 me.peerGotPiece(t, c, index)
1465 if c.PeerPieces != nil || c.peerHasAll {
1466 err = errors.New("unexpected have-all")
1471 if c.peerHasAll || c.PeerPieces != nil {
1472 err = errors.New("unexpected have-none")
1475 c.PeerPieces = make([]bool, func() int {
1477 return t.numPieces()
1483 me.downloadedChunk(t, c, &msg)
1485 switch msg.ExtendedID {
1486 case pp.HandshakeExtendedID:
1487 // TODO: Create a bencode struct for this.
1488 var d map[string]interface{}
1489 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1491 err = fmt.Errorf("error decoding extended message payload: %s", err)
1494 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1495 if reqq, ok := d["reqq"]; ok {
1496 if i, ok := reqq.(int64); ok {
1497 c.PeerMaxRequests = int(i)
1500 if v, ok := d["v"]; ok {
1501 c.PeerClientName = v.(string)
1505 err = errors.New("handshake missing m item")
1508 mTyped, ok := m.(map[string]interface{})
1510 err = errors.New("handshake m value is not dict")
1513 if c.PeerExtensionIDs == nil {
1514 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1516 for name, v := range mTyped {
1519 log.Printf("bad handshake m item extension ID type: %T", v)
1523 delete(c.PeerExtensionIDs, name)
1525 if c.PeerExtensionIDs[name] == 0 {
1526 supportedExtensionMessages.Add(name, 1)
1528 c.PeerExtensionIDs[name] = byte(id)
1531 metadata_sizeUntyped, ok := d["metadata_size"]
1533 metadata_size, ok := metadata_sizeUntyped.(int64)
1535 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1537 t.setMetadataSize(metadata_size, me)
1540 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1541 me.requestPendingMetadata(t, c)
1543 case metadataExtendedId:
1544 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1546 err = fmt.Errorf("error handling metadata extension message: %s", err)
1549 if me.config.DisablePEX {
1552 var pexMsg peerExchangeMessage
1553 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1555 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1560 me.addPeers(t, func() (ret []Peer) {
1561 for i, cp := range pexMsg.Added {
1563 IP: make([]byte, 4),
1565 Source: peerSourcePEX,
1567 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1568 p.SupportsEncryption = true
1570 CopyExact(p.IP, cp.IP[:])
1571 ret = append(ret, p)
1578 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1581 // That client uses its own extension IDs for outgoing message
1582 // types, which is incorrect.
1583 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1584 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1592 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1597 pingAddr.Port = int(msg.Port)
1599 _, err = me.dHT.Ping(pingAddr)
1601 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1609 // Returns true if connection is removed from torrent.Conns.
1610 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1611 for i0, _c := range t.Conns {
1615 i1 := len(t.Conns) - 1
1617 t.Conns[i0] = t.Conns[i1]
1619 t.Conns = t.Conns[:i1]
1625 func (me *Client) dropConnection(t *torrent, c *connection) {
1626 me.event.Broadcast()
1628 if me.deleteConnection(t, c) {
1633 // Returns true if the connection is added.
1634 func (me *Client) addConnection(t *torrent, c *connection) bool {
1639 case <-t.ceasingNetworking:
1643 if !me.wantConns(t) {
1646 for _, c0 := range t.Conns {
1647 if c.PeerID == c0.PeerID {
1648 // Already connected to a client with that ID.
1649 duplicateClientConns.Add(1)
1653 if len(t.Conns) >= socketsPerTorrent {
1654 c := t.worstBadConn(me)
1658 if me.config.Debug && missinggo.CryHeard() {
1659 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1662 me.deleteConnection(t, c)
1664 if len(t.Conns) >= socketsPerTorrent {
1667 t.Conns = append(t.Conns, c)
1672 func (t *torrent) needData() bool {
1676 for i := t.pendingPieces.Iter(); i.Next(); {
1677 if t.wantPiece(i.Value()) {
1681 return !t.forReaderOffsetPieces(func(begin, end int) (again bool) {
1682 for i := begin; i < end; i++ {
1683 if !t.pieceComplete(i) {
1691 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1692 if c.closed.IsSet() {
1696 return c.supportsExtension("ut_metadata")
1699 return c.PeerInterested
1701 return t.connHasWantedPieces(c)
1704 func (me *Client) wantConns(t *torrent) bool {
1705 if !me.seeding(t) && !t.needData() {
1708 if len(t.Conns) < socketsPerTorrent {
1711 return t.worstBadConn(me) != nil
1714 func (me *Client) openNewConns(t *torrent) {
1716 case <-t.ceasingNetworking:
1720 for len(t.Peers) != 0 {
1721 if !me.wantConns(t) {
1724 if len(t.HalfOpen) >= me.halfOpenLimit {
1731 for k, p = range t.Peers {
1735 me.initiateConn(p, t)
1737 t.wantPeers.Broadcast()
1740 func (me *Client) addPeers(t *torrent, peers []Peer) {
1741 for _, p := range peers {
1742 if me.dopplegangerAddr(net.JoinHostPort(
1744 strconv.FormatInt(int64(p.Port), 10),
1748 if _, ok := me.ipBlockRange(p.IP); ok {
1752 // The spec says to scrub these yourselves. Fine.
1759 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1760 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1763 func (cl *Client) saveTorrentFile(t *torrent) error {
1764 path := cl.cachedMetaInfoFilename(t.InfoHash)
1765 os.MkdirAll(filepath.Dir(path), 0777)
1766 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1768 return fmt.Errorf("error opening file: %s", err)
1771 e := bencode.NewEncoder(f)
1772 err = e.Encode(t.MetaInfo())
1774 return fmt.Errorf("error marshalling metainfo: %s", err)
1776 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1778 // For example, a script kiddy makes us load too many files, and we're
1779 // able to save the torrent, but not load it again to check it.
1782 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1783 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1788 func (cl *Client) startTorrent(t *torrent) {
1789 if t.Info == nil || t.data == nil {
1792 // If the client intends to upload, it needs to know what state pieces are
1794 if !cl.config.NoUpload {
1795 // Queue all pieces for hashing. This is done sequentially to avoid
1796 // spamming goroutines.
1797 for i := range t.Pieces {
1798 t.Pieces[i].QueuedForHash = true
1801 for i := range t.Pieces {
1802 cl.verifyPiece(t, i)
1808 // Storage cannot be changed once it's set.
1809 func (cl *Client) setStorage(t *torrent, td Data) (err error) {
1810 err = t.setStorage(td)
1811 cl.event.Broadcast()
1819 type TorrentDataOpener func(*metainfo.Info) Data
1821 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1822 err = t.setMetadata(md, bytes)
1826 if !cl.config.DisableMetainfoCache {
1827 if err := cl.saveTorrentFile(t); err != nil {
1828 log.Printf("error saving torrent file for %s: %s", t, err)
1831 cl.event.Broadcast()
1832 close(t.gotMetainfo)
1833 td := cl.torrentDataOpener(md)
1834 err = cl.setStorage(t, td)
1838 // Prepare a Torrent without any attachment to a Client. That means we can
1839 // initialize fields all fields that don't require the Client without locking
1841 func newTorrent(ih InfoHash) (t *torrent) {
1844 chunkSize: defaultChunkSize,
1845 Peers: make(map[peersKey]Peer),
1847 closing: make(chan struct{}),
1848 ceasingNetworking: make(chan struct{}),
1850 gotMetainfo: make(chan struct{}),
1852 HalfOpen: make(map[string]struct{}),
1853 pieceStateChanges: pubsub.NewPubSub(),
1855 t.wantPeers.L = &t.stateMu
1860 // For shuffling the tracker tiers.
1861 mathRand.Seed(time.Now().Unix())
1864 // The trackers within each tier must be shuffled before use.
1865 // http://stackoverflow.com/a/12267471/149482
1866 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1867 func shuffleTier(tier []tracker.Client) {
1868 for i := range tier {
1869 j := mathRand.Intn(i + 1)
1870 tier[i], tier[j] = tier[j], tier[i]
1874 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1875 for _, tier := range base {
1876 copy = append(copy, append([]tracker.Client{}, tier...))
1881 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1883 for _, url := range newURLs {
1884 for _, tr := range tier {
1885 if tr.URL() == url {
1889 tr, err := tracker.New(url)
1891 // log.Printf("error creating tracker client for %q: %s", url, err)
1894 tier = append(tier, tr)
1899 func (t *torrent) addTrackers(announceList [][]string) {
1900 newTrackers := copyTrackers(t.Trackers)
1901 for tierIndex, tier := range announceList {
1902 if tierIndex < len(newTrackers) {
1903 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1905 newTrackers = append(newTrackers, mergeTier(nil, tier))
1907 shuffleTier(newTrackers[tierIndex])
1909 t.Trackers = newTrackers
1912 // Don't call this before the info is available.
1913 func (t *torrent) bytesCompleted() int64 {
1917 return t.Info.TotalLength() - t.bytesLeft()
1920 // A file-like handle to some torrent data resource.
1921 type Handle interface {
1928 // Returns handles to the files in the torrent. This requires the metainfo is
1930 func (t Torrent) Files() (ret []File) {
1938 for _, fi := range info.UpvertedFiles() {
1939 ret = append(ret, File{
1941 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1951 func (t Torrent) AddPeers(pp []Peer) error {
1954 defer cl.mu.Unlock()
1955 cl.addPeers(t.torrent, pp)
1959 // Marks the entire torrent for download. Requires the info first, see
1961 func (t Torrent) DownloadAll() {
1963 defer t.cl.mu.Unlock()
1964 for i := range iter.N(t.torrent.Info.NumPieces()) {
1965 t.torrent.pendPiece(i, t.cl)
1969 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1970 // metainfo has the correct infohash.
1971 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1972 if cl.config.DisableMetainfoCache {
1975 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1977 if os.IsNotExist(err) {
1983 dec := bencode.NewDecoder(f)
1984 err = dec.Decode(&mi)
1988 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1989 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1995 // Specifies a new torrent for adding to a client. There are helpers for
1996 // magnet URIs and torrent metainfo files.
1997 type TorrentSpec struct {
1998 // The tiered tracker URIs.
2001 Info *metainfo.InfoEx
2002 // The name to use if the Name field from the Info isn't available.
2004 // The chunk size to use for outbound requests. Defaults to 16KiB if not
2009 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2010 m, err := ParseMagnetURI(uri)
2014 spec = &TorrentSpec{
2015 Trackers: [][]string{m.Trackers},
2016 DisplayName: m.DisplayName,
2017 InfoHash: m.InfoHash,
2022 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2023 spec = &TorrentSpec{
2024 Trackers: mi.AnnounceList,
2026 DisplayName: mi.Info.Name,
2029 if len(spec.Trackers) == 0 {
2030 spec.Trackers = [][]string{[]string{mi.Announce}}
2032 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
2035 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2039 // Add or merge a torrent spec. If the torrent is already present, the
2040 // trackers will be merged with the existing ones. If the Info isn't yet
2041 // known, it will be set. The display name is replaced if the new spec
2042 // provides one. Returns new if the torrent wasn't already in the client.
2043 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2046 defer cl.mu.Unlock()
2048 t, ok := cl.torrents[spec.InfoHash]
2052 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2053 err = errors.New("banned torrent")
2056 // TODO: Tidy this up?
2057 t = newTorrent(spec.InfoHash)
2058 if spec.ChunkSize != 0 {
2059 t.chunkSize = pp.Integer(spec.ChunkSize)
2062 if spec.DisplayName != "" {
2063 t.setDisplayName(spec.DisplayName)
2065 // Try to merge in info we have on the torrent. Any err left will
2066 // terminate the function.
2068 if spec.Info != nil {
2069 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2071 var mi *metainfo.MetaInfo
2072 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2074 log.Printf("error getting cached metainfo: %s", err)
2076 } else if mi != nil {
2077 t.addTrackers(mi.AnnounceList)
2078 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2085 t.addTrackers(spec.Trackers)
2087 cl.torrents[spec.InfoHash] = t
2090 // From this point onwards, we can consider the torrent a part of the
2093 if !cl.config.DisableTrackers {
2094 go cl.announceTorrentTrackers(T.torrent)
2097 go cl.announceTorrentDHT(T.torrent, true)
2103 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2104 t, ok := me.torrents[infoHash]
2106 err = fmt.Errorf("no such torrent")
2113 delete(me.torrents, infoHash)
2117 // Returns true when peers are required, or false if the torrent is closing.
2118 func (cl *Client) waitWantPeers(t *torrent) bool {
2120 defer cl.mu.Unlock()
2122 defer t.stateMu.Unlock()
2125 case <-t.ceasingNetworking:
2129 if len(t.Peers) > torrentPeersLowWater {
2132 if t.needData() || cl.seeding(t) {
2144 // Returns whether the client should make effort to seed the torrent.
2145 func (cl *Client) seeding(t *torrent) bool {
2146 if cl.config.NoUpload {
2149 if !cl.config.Seed {
2158 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2159 for cl.waitWantPeers(t) {
2160 // log.Printf("getting peers for %q from DHT", t)
2161 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2163 log.Printf("error getting peers from dht: %s", err)
2166 // Count all the unique addresses we got during this announce.
2167 allAddrs := make(map[string]struct{})
2171 case v, ok := <-ps.Peers:
2175 addPeers := make([]Peer, 0, len(v.Peers))
2176 for _, cp := range v.Peers {
2178 // Can't do anything with this.
2181 addPeers = append(addPeers, Peer{
2184 Source: peerSourceDHT,
2186 key := (&net.UDPAddr{
2190 allAddrs[key] = struct{}{}
2193 cl.addPeers(t, addPeers)
2194 numPeers := len(t.Peers)
2196 if numPeers >= torrentPeersHighWater {
2199 case <-t.ceasingNetworking:
2205 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2209 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2210 url_, err := url.Parse(tr.URL())
2214 host, _, err := net.SplitHostPort(url_.Host)
2218 addr, err := net.ResolveIPAddr("ip", host)
2223 _, blocked = cl.ipBlockRange(addr.IP)
2228 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2229 blocked, err := cl.trackerBlockedUnlocked(tr)
2231 return fmt.Errorf("error determining if tracker blocked: %s", err)
2234 return fmt.Errorf("tracker blocked: %s", tr)
2236 if err := tr.Connect(); err != nil {
2237 return fmt.Errorf("error connecting: %s", err)
2239 resp, err := tr.Announce(req)
2241 return fmt.Errorf("error announcing: %s", err)
2244 for _, peer := range resp.Peers {
2245 peers = append(peers, Peer{
2251 cl.addPeers(t, peers)
2254 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2256 time.Sleep(time.Second * time.Duration(resp.Interval))
2260 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2261 oks := make(chan bool)
2263 for _, tier := range trackers {
2264 for _, tr := range tier {
2266 go func(tr tracker.Client) {
2267 err := cl.announceTorrentSingleTracker(tr, req, t)
2272 for outstanding > 0 {
2282 // Announce torrent to its trackers.
2283 func (cl *Client) announceTorrentTrackers(t *torrent) {
2284 req := tracker.AnnounceRequest{
2285 Event: tracker.Started,
2287 Port: uint16(cl.incomingPeerPort()),
2289 InfoHash: t.InfoHash,
2291 if !cl.waitWantPeers(t) {
2295 req.Left = uint64(t.bytesLeft())
2296 trackers := t.Trackers
2298 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2299 req.Event = tracker.None
2302 for cl.waitWantPeers(t) {
2304 req.Left = uint64(t.bytesLeft())
2305 trackers = t.Trackers
2307 numTrackersTried := 0
2308 for _, tier := range trackers {
2309 for trIndex, tr := range tier {
2311 err := cl.announceTorrentSingleTracker(tr, &req, t)
2315 // Float the successful announce to the top of the tier. If
2316 // the trackers list has been changed, we'll be modifying an
2317 // old copy so it won't matter.
2319 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2322 req.Event = tracker.None
2323 continue newAnnounce
2326 if numTrackersTried != 0 {
2327 log.Printf("%s: all trackers failed", t)
2329 // TODO: Wait until trackers are added if there are none.
2330 time.Sleep(10 * time.Second)
2334 func (cl *Client) allTorrentsCompleted() bool {
2335 for _, t := range cl.torrents {
2339 if t.numPiecesCompleted() != t.numPieces() {
2346 // Returns true when all torrents are completely downloaded and false if the
2347 // client is stopped before that.
2348 func (me *Client) WaitAll() bool {
2350 defer me.mu.Unlock()
2351 for !me.allTorrentsCompleted() {
2360 // Handle a received chunk from a peer.
2361 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) {
2362 chunksReceived.Add(1)
2364 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2366 // Request has been satisfied.
2367 if me.connDeleteRequest(t, c, req) {
2368 defer c.updateRequests()
2370 unexpectedChunksReceived.Add(1)
2373 index := int(req.Index)
2374 piece := &t.Pieces[index]
2376 // Do we actually want this chunk?
2377 if !t.wantChunk(req) {
2378 unwantedChunksReceived.Add(1)
2379 c.UnwantedChunksReceived++
2383 c.UsefulChunksReceived++
2384 c.lastUsefulChunkReceived = time.Now()
2388 // Need to record that it hasn't been written yet, before we attempt to do
2389 // anything with it.
2390 piece.incrementPendingWrites()
2391 // Record that we have the chunk.
2392 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2394 // Cancel pending requests for this chunk.
2395 for _, c := range t.Conns {
2396 if me.connCancel(t, c, req) {
2402 // Write the chunk out.
2403 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2406 piece.decrementPendingWrites()
2409 log.Printf("error writing chunk: %s", err)
2414 // It's important that the piece is potentially queued before we check if
2415 // the piece is still wanted, because if it is queued, it won't be wanted.
2416 if t.pieceAllDirty(index) {
2417 me.queuePieceCheck(t, int(req.Index))
2420 if c.peerTouchedPieces == nil {
2421 c.peerTouchedPieces = make(map[int]struct{})
2423 c.peerTouchedPieces[index] = struct{}{}
2425 me.event.Broadcast()
2426 t.publishPieceChange(int(req.Index))
2430 // Return the connections that touched a piece, and clear the entry while
2432 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2433 for _, c := range t.Conns {
2434 if _, ok := c.peerTouchedPieces[piece]; ok {
2435 ret = append(ret, c)
2436 delete(c.peerTouchedPieces, piece)
2442 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2443 p := &t.Pieces[piece]
2445 // Don't score the first time a piece is hashed, it could be an
2448 pieceHashedCorrect.Add(1)
2450 log.Printf("%s: piece %d failed hash", t, piece)
2451 pieceHashedNotCorrect.Add(1)
2455 touchers := me.reapPieceTouches(t, int(piece))
2457 err := t.data.PieceCompleted(int(piece))
2459 log.Printf("error completing piece: %s", err)
2462 } else if len(touchers) != 0 {
2463 log.Printf("dropping %d conns that touched piece", len(touchers))
2464 for _, c := range touchers {
2465 me.dropConnection(t, c)
2468 me.pieceChanged(t, int(piece))
2471 func (me *Client) onCompletedPiece(t *torrent, piece int) {
2472 t.pendingPieces.Remove(piece)
2473 for _, conn := range t.Conns {
2475 for r := range conn.Requests {
2476 if int(r.Index) == piece {
2480 // Could check here if peer doesn't have piece, but due to caching
2481 // some peers may have said they have a piece but they don't.
2486 func (me *Client) onFailedPiece(t *torrent, piece int) {
2487 if t.pieceAllDirty(piece) {
2488 t.pendAllChunkSpecs(piece)
2490 if !t.wantPiece(piece) {
2494 for _, conn := range t.Conns {
2495 if conn.PeerHasPiece(piece) {
2496 conn.updateRequests()
2501 func (me *Client) pieceChanged(t *torrent, piece int) {
2502 correct := t.pieceComplete(piece)
2503 defer t.publishPieceChange(piece)
2504 defer me.event.Broadcast()
2506 me.onCompletedPiece(t, piece)
2508 me.onFailedPiece(t, piece)
2512 func (cl *Client) verifyPiece(t *torrent, piece int) {
2514 defer cl.mu.Unlock()
2515 p := &t.Pieces[piece]
2516 for p.Hashing || t.data == nil {
2519 p.QueuedForHash = false
2520 if t.isClosed() || t.pieceComplete(piece) {
2525 sum := t.hashPiece(piece)
2533 cl.pieceHashed(t, piece, sum == p.Hash)
2536 // Returns handles to all the torrents loaded in the Client.
2537 func (me *Client) Torrents() (ret []Torrent) {
2539 for _, t := range me.torrents {
2540 ret = append(ret, Torrent{me, t})
2546 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2547 spec, err := TorrentSpecFromMagnetURI(uri)
2551 T, _, err = me.AddTorrentSpec(spec)
2555 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2556 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2560 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2561 mi, err := metainfo.LoadFromFile(filename)
2565 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2569 func (me *Client) DHT() *dht.Server {