25 "github.com/anacrolix/missinggo"
26 . "github.com/anacrolix/missinggo"
27 "github.com/anacrolix/missinggo/perf"
28 "github.com/anacrolix/missinggo/pubsub"
29 "github.com/anacrolix/sync"
30 "github.com/anacrolix/utp"
31 "github.com/bradfitz/iter"
32 "github.com/edsrzf/mmap-go"
34 "github.com/anacrolix/torrent/bencode"
35 filePkg "github.com/anacrolix/torrent/data/file"
36 "github.com/anacrolix/torrent/dht"
37 "github.com/anacrolix/torrent/iplist"
38 "github.com/anacrolix/torrent/metainfo"
39 "github.com/anacrolix/torrent/mse"
40 pp "github.com/anacrolix/torrent/peer_protocol"
41 "github.com/anacrolix/torrent/tracker"
45 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
46 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
47 chunksReceived = expvar.NewInt("chunksReceived")
49 peersAddedBySource = expvar.NewMap("peersAddedBySource")
51 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
52 unexpectedCancels = expvar.NewInt("unexpectedCancels")
53 postedCancels = expvar.NewInt("postedCancels")
54 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
56 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
57 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
59 unsuccessfulDials = expvar.NewInt("dialSuccessful")
60 successfulDials = expvar.NewInt("dialUnsuccessful")
62 acceptUTP = expvar.NewInt("acceptUTP")
63 acceptTCP = expvar.NewInt("acceptTCP")
64 acceptReject = expvar.NewInt("acceptReject")
66 peerExtensions = expvar.NewMap("peerExtensions")
67 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
68 // Count of connections to peer with same client ID.
69 connsToSelf = expvar.NewInt("connsToSelf")
70 // Number of completed connections to a client we're already connected with.
71 duplicateClientConns = expvar.NewInt("duplicateClientConns")
72 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
73 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
77 // Justification for set bits follows.
79 // Extension protocol ([5]|=0x10):
80 // http://www.bittorrent.org/beps/bep_0010.html
82 // Fast Extension ([7]|=0x04):
83 // http://bittorrent.org/beps/bep_0006.html.
84 // Disabled until AllowedFast is implemented.
87 // http://www.bittorrent.org/beps/bep_0005.html
88 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
90 socketsPerTorrent = 80
91 torrentPeersHighWater = 200
92 torrentPeersLowWater = 50
94 // Limit how long handshake can take. This is to reduce the lingering
95 // impact of a few bad apples. 4s loses 1% of successful handshakes that
96 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
97 btHandshakeTimeout = 4 * time.Second
98 handshakesTimeout = 20 * time.Second
100 // These are our extended message IDs.
101 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
104 // Updated occasionally to when there's been some changes to client
105 // behaviour in case other clients are assuming anything of us. See also
107 extendedHandshakeClientVersion = "go.torrent dev 20150624"
110 // Currently doesn't really queue, but should in the future.
111 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
112 piece := &t.Pieces[pieceIndex]
113 if piece.QueuedForHash {
116 piece.QueuedForHash = true
117 t.publishPieceChange(int(pieceIndex))
118 go cl.verifyPiece(t, int(pieceIndex))
121 // Queue a piece check if one isn't already queued, and the piece has never
122 // been checked before.
123 func (cl *Client) queueFirstHash(t *torrent, piece int) {
124 p := &t.Pieces[piece]
125 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
128 cl.queuePieceCheck(t, piece)
131 // Clients contain zero or more Torrents. A client manages a blocklist, the
132 // TCP/UDP protocol ports, and DHT as desired.
136 listeners []net.Listener
139 ipBlockList iplist.Ranger
140 bannedTorrents map[InfoHash]struct{}
142 pruneTimer *time.Timer
143 extensionBytes peerExtensionBytes
144 // Set of addresses that have our client ID. This intentionally will
145 // include ourselves if we end up trying to connect to our own address
146 // through legitimate channels.
147 dopplegangerAddrs map[string]struct{}
149 torrentDataOpener TorrentDataOpener
155 torrents map[InfoHash]*torrent
158 func (me *Client) IPBlockList() iplist.Ranger {
161 return me.ipBlockList
164 func (me *Client) SetIPBlockList(list iplist.Ranger) {
167 me.ipBlockList = list
169 me.dHT.SetIPBlockList(list)
173 func (me *Client) PeerID() string {
174 return string(me.peerID[:])
177 func (me *Client) ListenAddr() (addr net.Addr) {
178 for _, l := range me.listeners {
185 type hashSorter struct {
189 func (me hashSorter) Len() int {
190 return len(me.Hashes)
193 func (me hashSorter) Less(a, b int) bool {
194 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
197 func (me hashSorter) Swap(a, b int) {
198 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
201 func (cl *Client) sortedTorrents() (ret []*torrent) {
203 for ih := range cl.torrents {
204 hs.Hashes = append(hs.Hashes, ih)
207 for _, ih := range hs.Hashes {
208 ret = append(ret, cl.torrent(ih))
213 // Writes out a human readable status of the client, such as for writing to a
215 func (cl *Client) WriteStatus(_w io.Writer) {
217 defer cl.mu.RUnlock()
218 w := bufio.NewWriter(_w)
220 if addr := cl.ListenAddr(); addr != nil {
221 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
223 fmt.Fprintln(w, "Not listening!")
225 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
227 dhtStats := cl.dHT.Stats()
228 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
229 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
230 fmt.Fprintf(w, "DHT port: %d\n", addrPort(cl.dHT.Addr()))
231 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
232 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
234 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
236 for _, t := range cl.sortedTorrents() {
238 fmt.Fprint(w, "<unknown name>")
240 fmt.Fprint(w, t.Name())
244 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float32(t.bytesLeft())/float32(t.length)), t.length)
246 w.WriteString("<missing metainfo>")
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()
1400 if me.stopped() || err == io.EOF {
1411 for r := range c.Requests {
1412 me.connDeleteRequest(t, c, r)
1414 // We can then reset our interest.
1417 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1420 c.PeerChoked = false
1421 me.peerUnchoked(t, c)
1423 c.PeerInterested = true
1425 case pp.NotInterested:
1426 c.PeerInterested = false
1429 me.peerGotPiece(t, c, int(msg.Index))
1434 if !c.PeerInterested {
1435 err = errors.New("peer sent request but isn't interested")
1438 if c.PeerRequests == nil {
1439 c.PeerRequests = make(map[request]struct{}, maxRequests)
1441 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1444 req := newRequest(msg.Index, msg.Begin, msg.Length)
1445 if !c.PeerCancel(req) {
1446 unexpectedCancels.Add(1)
1449 if c.PeerPieces != nil || c.peerHasAll {
1450 err = errors.New("received unexpected bitfield")
1454 if len(msg.Bitfield) < t.numPieces() {
1455 err = errors.New("received invalid bitfield")
1458 msg.Bitfield = msg.Bitfield[:t.numPieces()]
1460 c.PeerPieces = msg.Bitfield
1461 for index, has := range c.PeerPieces {
1463 me.peerGotPiece(t, c, index)
1467 if c.PeerPieces != nil || c.peerHasAll {
1468 err = errors.New("unexpected have-all")
1473 if c.peerHasAll || c.PeerPieces != nil {
1474 err = errors.New("unexpected have-none")
1477 c.PeerPieces = make([]bool, func() int {
1479 return t.numPieces()
1485 err = me.downloadedChunk(t, c, &msg)
1487 switch msg.ExtendedID {
1488 case pp.HandshakeExtendedID:
1489 // TODO: Create a bencode struct for this.
1490 var d map[string]interface{}
1491 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1493 err = fmt.Errorf("error decoding extended message payload: %s", err)
1496 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1497 if reqq, ok := d["reqq"]; ok {
1498 if i, ok := reqq.(int64); ok {
1499 c.PeerMaxRequests = int(i)
1502 if v, ok := d["v"]; ok {
1503 c.PeerClientName = v.(string)
1507 err = errors.New("handshake missing m item")
1510 mTyped, ok := m.(map[string]interface{})
1512 err = errors.New("handshake m value is not dict")
1515 if c.PeerExtensionIDs == nil {
1516 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1518 for name, v := range mTyped {
1521 log.Printf("bad handshake m item extension ID type: %T", v)
1525 delete(c.PeerExtensionIDs, name)
1527 if c.PeerExtensionIDs[name] == 0 {
1528 supportedExtensionMessages.Add(name, 1)
1530 c.PeerExtensionIDs[name] = byte(id)
1533 metadata_sizeUntyped, ok := d["metadata_size"]
1535 metadata_size, ok := metadata_sizeUntyped.(int64)
1537 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1539 t.setMetadataSize(metadata_size, me)
1542 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1543 me.requestPendingMetadata(t, c)
1545 case metadataExtendedId:
1546 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1548 err = fmt.Errorf("error handling metadata extension message: %s", err)
1551 if me.config.DisablePEX {
1554 var pexMsg peerExchangeMessage
1555 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1557 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1562 me.addPeers(t, func() (ret []Peer) {
1563 for i, cp := range pexMsg.Added {
1565 IP: make([]byte, 4),
1567 Source: peerSourcePEX,
1569 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1570 p.SupportsEncryption = true
1572 CopyExact(p.IP, cp.IP[:])
1573 ret = append(ret, p)
1580 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1583 // That client uses its own extension IDs for outgoing message
1584 // types, which is incorrect.
1585 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1586 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1594 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1599 pingAddr.Port = int(msg.Port)
1601 _, err = me.dHT.Ping(pingAddr)
1603 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1611 // Returns true if connection is removed from torrent.Conns.
1612 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1613 for i0, _c := range t.Conns {
1617 i1 := len(t.Conns) - 1
1619 t.Conns[i0] = t.Conns[i1]
1621 t.Conns = t.Conns[:i1]
1627 func (me *Client) dropConnection(t *torrent, c *connection) {
1628 me.event.Broadcast()
1630 if me.deleteConnection(t, c) {
1635 // Returns true if the connection is added.
1636 func (me *Client) addConnection(t *torrent, c *connection) bool {
1641 case <-t.ceasingNetworking:
1645 if !me.wantConns(t) {
1648 for _, c0 := range t.Conns {
1649 if c.PeerID == c0.PeerID {
1650 // Already connected to a client with that ID.
1651 duplicateClientConns.Add(1)
1655 if len(t.Conns) >= socketsPerTorrent {
1656 c := t.worstBadConn(me)
1660 if me.config.Debug && missinggo.CryHeard() {
1661 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1664 me.deleteConnection(t, c)
1666 if len(t.Conns) >= socketsPerTorrent {
1669 t.Conns = append(t.Conns, c)
1674 func (t *torrent) needData() bool {
1678 if len(t.pendingPieces) != 0 {
1681 return !t.forReaderWantedRegionPieces(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 {
1698 return c.supportsExtension("ut_metadata")
1701 return c.PeerInterested
1703 return t.connHasWantedPieces(c)
1706 func (me *Client) wantConns(t *torrent) bool {
1707 if !me.seeding(t) && !t.needData() {
1710 if len(t.Conns) < socketsPerTorrent {
1713 return t.worstBadConn(me) != nil
1716 func (me *Client) openNewConns(t *torrent) {
1718 case <-t.ceasingNetworking:
1722 for len(t.Peers) != 0 {
1723 if !me.wantConns(t) {
1726 if len(t.HalfOpen) >= me.halfOpenLimit {
1733 for k, p = range t.Peers {
1737 me.initiateConn(p, t)
1739 t.wantPeers.Broadcast()
1742 func (me *Client) addPeers(t *torrent, peers []Peer) {
1743 for _, p := range peers {
1744 if me.dopplegangerAddr(net.JoinHostPort(
1746 strconv.FormatInt(int64(p.Port), 10),
1750 if _, ok := me.ipBlockRange(p.IP); ok {
1754 // The spec says to scrub these yourselves. Fine.
1761 func (cl *Client) cachedMetaInfoFilename(ih InfoHash) string {
1762 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1765 func (cl *Client) saveTorrentFile(t *torrent) error {
1766 path := cl.cachedMetaInfoFilename(t.InfoHash)
1767 os.MkdirAll(filepath.Dir(path), 0777)
1768 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1770 return fmt.Errorf("error opening file: %s", err)
1773 e := bencode.NewEncoder(f)
1774 err = e.Encode(t.MetaInfo())
1776 return fmt.Errorf("error marshalling metainfo: %s", err)
1778 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1780 // For example, a script kiddy makes us load too many files, and we're
1781 // able to save the torrent, but not load it again to check it.
1784 if !bytes.Equal(mi.Info.Hash, t.InfoHash[:]) {
1785 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1790 func (cl *Client) startTorrent(t *torrent) {
1791 if t.Info == nil || t.data == nil {
1794 // If the client intends to upload, it needs to know what state pieces are
1796 if !cl.config.NoUpload {
1797 // Queue all pieces for hashing. This is done sequentially to avoid
1798 // spamming goroutines.
1799 for i := range t.Pieces {
1800 t.Pieces[i].QueuedForHash = true
1803 for i := range t.Pieces {
1804 cl.verifyPiece(t, i)
1810 // Storage cannot be changed once it's set.
1811 func (cl *Client) setStorage(t *torrent, td Data) (err error) {
1812 err = t.setStorage(td)
1813 cl.event.Broadcast()
1821 type TorrentDataOpener func(*metainfo.Info) Data
1823 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1824 err = t.setMetadata(md, bytes)
1828 if !cl.config.DisableMetainfoCache {
1829 if err := cl.saveTorrentFile(t); err != nil {
1830 log.Printf("error saving torrent file for %s: %s", t, err)
1833 cl.event.Broadcast()
1834 close(t.gotMetainfo)
1835 td := cl.torrentDataOpener(md)
1836 err = cl.setStorage(t, td)
1840 // Prepare a Torrent without any attachment to a Client. That means we can
1841 // initialize fields all fields that don't require the Client without locking
1843 func newTorrent(ih InfoHash) (t *torrent, err error) {
1846 chunkSize: defaultChunkSize,
1847 Peers: make(map[peersKey]Peer),
1849 closing: make(chan struct{}),
1850 ceasingNetworking: make(chan struct{}),
1852 gotMetainfo: make(chan struct{}),
1854 HalfOpen: make(map[string]struct{}),
1855 pieceStateChanges: pubsub.NewPubSub(),
1857 t.wantPeers.L = &t.stateMu
1862 // For shuffling the tracker tiers.
1863 mathRand.Seed(time.Now().Unix())
1866 // The trackers within each tier must be shuffled before use.
1867 // http://stackoverflow.com/a/12267471/149482
1868 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1869 func shuffleTier(tier []tracker.Client) {
1870 for i := range tier {
1871 j := mathRand.Intn(i + 1)
1872 tier[i], tier[j] = tier[j], tier[i]
1876 func copyTrackers(base [][]tracker.Client) (copy [][]tracker.Client) {
1877 for _, tier := range base {
1878 copy = append(copy, append([]tracker.Client{}, tier...))
1883 func mergeTier(tier []tracker.Client, newURLs []string) []tracker.Client {
1885 for _, url := range newURLs {
1886 for _, tr := range tier {
1887 if tr.URL() == url {
1891 tr, err := tracker.New(url)
1893 // log.Printf("error creating tracker client for %q: %s", url, err)
1896 tier = append(tier, tr)
1901 func (t *torrent) addTrackers(announceList [][]string) {
1902 newTrackers := copyTrackers(t.Trackers)
1903 for tierIndex, tier := range announceList {
1904 if tierIndex < len(newTrackers) {
1905 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1907 newTrackers = append(newTrackers, mergeTier(nil, tier))
1909 shuffleTier(newTrackers[tierIndex])
1911 t.Trackers = newTrackers
1914 // Don't call this before the info is available.
1915 func (t *torrent) bytesCompleted() int64 {
1919 return t.Info.TotalLength() - t.bytesLeft()
1922 // A file-like handle to some torrent data resource.
1923 type Handle interface {
1930 // Returns handles to the files in the torrent. This requires the metainfo is
1932 func (t Torrent) Files() (ret []File) {
1940 for _, fi := range info.UpvertedFiles() {
1941 ret = append(ret, File{
1943 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1953 func (t Torrent) AddPeers(pp []Peer) error {
1956 defer cl.mu.Unlock()
1957 cl.addPeers(t.torrent, pp)
1961 // Marks the entire torrent for download. Requires the info first, see
1963 func (t Torrent) DownloadAll() {
1965 defer t.cl.mu.Unlock()
1966 for i := range iter.N(t.torrent.Info.NumPieces()) {
1967 t.torrent.pendPiece(i, t.cl)
1971 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1972 // metainfo has the correct infohash.
1973 func (cl *Client) torrentCacheMetaInfo(ih InfoHash) (mi *metainfo.MetaInfo, err error) {
1974 if cl.config.DisableMetainfoCache {
1977 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1979 if os.IsNotExist(err) {
1985 dec := bencode.NewDecoder(f)
1986 err = dec.Decode(&mi)
1990 if !bytes.Equal(mi.Info.Hash, ih[:]) {
1991 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1997 // Specifies a new torrent for adding to a client. There are helpers for
1998 // magnet URIs and torrent metainfo files.
1999 type TorrentSpec struct {
2000 // The tiered tracker URIs.
2003 Info *metainfo.InfoEx
2004 // The name to use if the Name field from the Info isn't available.
2006 // The chunk size to use for outbound requests. Defaults to 16KiB if not
2011 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
2012 m, err := ParseMagnetURI(uri)
2016 spec = &TorrentSpec{
2017 Trackers: [][]string{m.Trackers},
2018 DisplayName: m.DisplayName,
2019 InfoHash: m.InfoHash,
2024 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
2025 spec = &TorrentSpec{
2026 Trackers: mi.AnnounceList,
2028 DisplayName: mi.Info.Name,
2031 if len(spec.Trackers) == 0 {
2032 spec.Trackers = [][]string{[]string{mi.Announce}}
2034 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
2037 CopyExact(&spec.InfoHash, &mi.Info.Hash)
2041 // Add or merge a torrent spec. If the torrent is already present, the
2042 // trackers will be merged with the existing ones. If the Info isn't yet
2043 // known, it will be set. The display name is replaced if the new spec
2044 // provides one. Returns new if the torrent wasn't already in the client.
2045 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
2048 defer cl.mu.Unlock()
2050 t, ok := cl.torrents[spec.InfoHash]
2054 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
2055 err = errors.New("banned torrent")
2059 t, err = newTorrent(spec.InfoHash)
2063 if spec.ChunkSize != 0 {
2064 t.chunkSize = pp.Integer(spec.ChunkSize)
2067 if spec.DisplayName != "" {
2068 t.setDisplayName(spec.DisplayName)
2070 // Try to merge in info we have on the torrent. Any err left will
2071 // terminate the function.
2073 if spec.Info != nil {
2074 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
2076 var mi *metainfo.MetaInfo
2077 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
2079 log.Printf("error getting cached metainfo: %s", err)
2081 } else if mi != nil {
2082 t.addTrackers(mi.AnnounceList)
2083 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
2090 t.addTrackers(spec.Trackers)
2092 cl.torrents[spec.InfoHash] = t
2095 // From this point onwards, we can consider the torrent a part of the
2098 if !cl.config.DisableTrackers {
2099 go cl.announceTorrentTrackers(T.torrent)
2102 go cl.announceTorrentDHT(T.torrent, true)
2108 func (me *Client) dropTorrent(infoHash InfoHash) (err error) {
2109 t, ok := me.torrents[infoHash]
2111 err = fmt.Errorf("no such torrent")
2118 delete(me.torrents, infoHash)
2122 // Returns true when peers are required, or false if the torrent is closing.
2123 func (cl *Client) waitWantPeers(t *torrent) bool {
2125 defer cl.mu.Unlock()
2127 defer t.stateMu.Unlock()
2130 case <-t.ceasingNetworking:
2134 if len(t.Peers) > torrentPeersLowWater {
2137 if t.needData() || cl.seeding(t) {
2149 // Returns whether the client should make effort to seed the torrent.
2150 func (cl *Client) seeding(t *torrent) bool {
2151 if cl.config.NoUpload {
2154 if !cl.config.Seed {
2163 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2164 for cl.waitWantPeers(t) {
2165 // log.Printf("getting peers for %q from DHT", t)
2166 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2168 log.Printf("error getting peers from dht: %s", err)
2171 // Count all the unique addresses we got during this announce.
2172 allAddrs := make(map[string]struct{})
2176 case v, ok := <-ps.Peers:
2180 addPeers := make([]Peer, 0, len(v.Peers))
2181 for _, cp := range v.Peers {
2183 // Can't do anything with this.
2186 addPeers = append(addPeers, Peer{
2189 Source: peerSourceDHT,
2191 key := (&net.UDPAddr{
2195 allAddrs[key] = struct{}{}
2198 cl.addPeers(t, addPeers)
2199 numPeers := len(t.Peers)
2201 if numPeers >= torrentPeersHighWater {
2204 case <-t.ceasingNetworking:
2210 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2214 func (cl *Client) trackerBlockedUnlocked(tr tracker.Client) (blocked bool, err error) {
2215 url_, err := url.Parse(tr.URL())
2219 host, _, err := net.SplitHostPort(url_.Host)
2223 addr, err := net.ResolveIPAddr("ip", host)
2228 _, blocked = cl.ipBlockRange(addr.IP)
2233 func (cl *Client) announceTorrentSingleTracker(tr tracker.Client, req *tracker.AnnounceRequest, t *torrent) error {
2234 blocked, err := cl.trackerBlockedUnlocked(tr)
2236 return fmt.Errorf("error determining if tracker blocked: %s", err)
2239 return fmt.Errorf("tracker blocked: %s", tr)
2241 if err := tr.Connect(); err != nil {
2242 return fmt.Errorf("error connecting: %s", err)
2244 resp, err := tr.Announce(req)
2246 return fmt.Errorf("error announcing: %s", err)
2249 for _, peer := range resp.Peers {
2250 peers = append(peers, Peer{
2256 cl.addPeers(t, peers)
2259 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2261 time.Sleep(time.Second * time.Duration(resp.Interval))
2265 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers [][]tracker.Client, t *torrent) (atLeastOne bool) {
2266 oks := make(chan bool)
2268 for _, tier := range trackers {
2269 for _, tr := range tier {
2271 go func(tr tracker.Client) {
2272 err := cl.announceTorrentSingleTracker(tr, req, t)
2277 for outstanding > 0 {
2287 // Announce torrent to its trackers.
2288 func (cl *Client) announceTorrentTrackers(t *torrent) {
2289 req := tracker.AnnounceRequest{
2290 Event: tracker.Started,
2292 Port: uint16(cl.incomingPeerPort()),
2294 InfoHash: t.InfoHash,
2296 if !cl.waitWantPeers(t) {
2300 req.Left = uint64(t.bytesLeft())
2301 trackers := t.Trackers
2303 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2304 req.Event = tracker.None
2307 for cl.waitWantPeers(t) {
2309 req.Left = uint64(t.bytesLeft())
2310 trackers = t.Trackers
2312 numTrackersTried := 0
2313 for _, tier := range trackers {
2314 for trIndex, tr := range tier {
2316 err := cl.announceTorrentSingleTracker(tr, &req, t)
2320 // Float the successful announce to the top of the tier. If
2321 // the trackers list has been changed, we'll be modifying an
2322 // old copy so it won't matter.
2324 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2327 req.Event = tracker.None
2328 continue newAnnounce
2331 if numTrackersTried != 0 {
2332 log.Printf("%s: all trackers failed", t)
2334 // TODO: Wait until trackers are added if there are none.
2335 time.Sleep(10 * time.Second)
2339 func (cl *Client) allTorrentsCompleted() bool {
2340 for _, t := range cl.torrents {
2344 if t.numPiecesCompleted() != t.numPieces() {
2351 // Returns true when all torrents are completely downloaded and false if the
2352 // client is stopped before that.
2353 func (me *Client) WaitAll() bool {
2355 defer me.mu.Unlock()
2356 for !me.allTorrentsCompleted() {
2365 // Handle a received chunk from a peer.
2366 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) error {
2367 chunksReceived.Add(1)
2369 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2371 // Request has been satisfied.
2372 if me.connDeleteRequest(t, c, req) {
2373 defer c.updateRequests()
2375 unexpectedChunksReceived.Add(1)
2378 index := int(req.Index)
2379 piece := &t.Pieces[index]
2381 // Do we actually want this chunk?
2382 if !t.wantChunk(req) {
2383 unwantedChunksReceived.Add(1)
2384 c.UnwantedChunksReceived++
2388 c.UsefulChunksReceived++
2389 c.lastUsefulChunkReceived = time.Now()
2393 piece.pendingWritesMutex.Lock()
2394 piece.pendingWrites++
2395 piece.pendingWritesMutex.Unlock()
2397 defer me.event.Broadcast()
2399 piece.pendingWritesMutex.Lock()
2400 piece.pendingWrites--
2401 if piece.pendingWrites == 0 {
2402 piece.noPendingWrites.Broadcast()
2404 piece.pendingWritesMutex.Unlock()
2406 // Write the chunk out.
2407 tr := perf.NewTimer()
2408 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2410 log.Printf("error writing chunk: %s", err)
2413 tr.Stop("write chunk")
2415 if c.peerTouchedPieces == nil {
2416 c.peerTouchedPieces = make(map[int]struct{})
2418 c.peerTouchedPieces[index] = struct{}{}
2422 // log.Println("got chunk", req)
2423 me.event.Broadcast()
2424 defer t.publishPieceChange(int(req.Index))
2425 // Record that we have the chunk.
2426 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2427 // It's important that the piece is potentially queued before we check if
2428 // the piece is still wanted, because if it is queued, it won't be wanted.
2429 if t.pieceAllDirty(index) {
2430 me.queuePieceCheck(t, int(req.Index))
2433 // Cancel pending requests for this chunk.
2434 for _, c := range t.Conns {
2435 if me.connCancel(t, c, req) {
2443 // Return the connections that touched a piece, and clear the entry while
2445 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2446 for _, c := range t.Conns {
2447 if _, ok := c.peerTouchedPieces[piece]; ok {
2448 ret = append(ret, c)
2449 delete(c.peerTouchedPieces, piece)
2455 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2456 p := &t.Pieces[piece]
2458 // Don't score the first time a piece is hashed, it could be an
2461 pieceHashedCorrect.Add(1)
2463 log.Printf("%s: piece %d failed hash", t, piece)
2464 pieceHashedNotCorrect.Add(1)
2468 touchers := me.reapPieceTouches(t, int(piece))
2470 err := t.data.PieceCompleted(int(piece))
2472 log.Printf("error completing piece: %s", err)
2475 } else if len(touchers) != 0 {
2476 log.Printf("dropping %d conns that touched piece", len(touchers))
2477 for _, c := range touchers {
2478 me.dropConnection(t, c)
2481 me.pieceChanged(t, int(piece))
2484 func (me *Client) onCompletedPiece(t *torrent, piece int) {
2485 delete(t.pendingPieces, piece)
2486 for _, conn := range t.Conns {
2488 for r := range conn.Requests {
2489 if int(r.Index) == piece {
2493 // Could check here if peer doesn't have piece, but due to caching
2494 // some peers may have said they have a piece but they don't.
2499 func (me *Client) onFailedPiece(t *torrent, piece int) {
2500 if t.pieceAllDirty(piece) {
2501 t.pendAllChunkSpecs(piece)
2503 if !t.wantPiece(piece) {
2507 for _, conn := range t.Conns {
2508 if conn.PeerHasPiece(piece) {
2509 conn.updateRequests()
2514 func (me *Client) pieceChanged(t *torrent, piece int) {
2515 correct := t.pieceComplete(piece)
2516 defer t.publishPieceChange(piece)
2517 defer me.event.Broadcast()
2519 me.onCompletedPiece(t, piece)
2521 me.onFailedPiece(t, piece)
2525 func (cl *Client) verifyPiece(t *torrent, piece int) {
2527 defer cl.mu.Unlock()
2528 p := &t.Pieces[piece]
2529 for p.Hashing || t.data == nil {
2532 p.QueuedForHash = false
2533 if t.isClosed() || t.pieceComplete(piece) {
2538 sum := t.hashPiece(piece)
2546 cl.pieceHashed(t, piece, sum == p.Hash)
2549 // Returns handles to all the torrents loaded in the Client.
2550 func (me *Client) Torrents() (ret []Torrent) {
2552 for _, t := range me.torrents {
2553 ret = append(ret, Torrent{me, t})
2559 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2560 spec, err := TorrentSpecFromMagnetURI(uri)
2564 T, _, err = me.AddTorrentSpec(spec)
2568 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2569 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2573 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2574 mi, err := metainfo.LoadFromFile(filename)
2578 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2582 func (me *Client) DHT() *dht.Server {