Exemplo n.º 1
0
        Dictionary <BENObject, BENObject> handleSha(string sha)
        {
            Dictionary <BENObject, BENObject> sha_dict = new Dictionary <BENObject, BENObject>();

            using (SqlConnection myConnection = new SqlConnection(DatabaseConnectionString))
            {
                myConnection.Open();
                string stmt = "SELECT count(*) FROM peers WHERE dl_left=0 AND sha=@sha;";
                using (SqlCommand cmdCount = new SqlCommand(stmt, myConnection))
                {
                    cmdCount.Parameters.AddWithValue("sha", sha);
                    sha_dict[new BENObject("complete")] = new BENObject((int)cmdCount.ExecuteScalar());
                }
                stmt = "SELECT count(*) FROM peers WHERE dl_left!=0 AND sha=@sha;";
                using (SqlCommand cmdCount = new SqlCommand(stmt, myConnection))
                {
                    cmdCount.Parameters.AddWithValue("sha", sha);
                    sha_dict[new BENObject("incomplete")] = new BENObject((int)cmdCount.ExecuteScalar());
                }
                stmt = "SELECT downloaded FROM torrents WHERE sha=@sha;";
                using (SqlCommand cmdCount = new SqlCommand(stmt, myConnection))
                {
                    cmdCount.Parameters.AddWithValue("sha", sha);
                    sha_dict[new BENObject("downloaded")] = new BENObject((int)cmdCount.ExecuteScalar());
                }
            }

            return(sha_dict);
        }
Exemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Dictionary <BENObject, BENObject> dict = new Dictionary <BENObject, BENObject>();
            BENObject obj = new BENObject(dict);

            Dictionary <BENObject, BENObject> files = new Dictionary <BENObject, BENObject>();

            dict[new BENObject("files")] = new BENObject(files);

            string info_hash = bin2hex(queryBin("info_hash=", Request.RawUrl));

            if (info_hash != null && info_hash.Length == 40)
            {
                try {
                    files[new BENObject(hex2bin(info_hash))] = new BENObject(handleSha(info_hash));
                }
                catch
                {
                }
            }
            else
            {
                try {
                    using (SqlConnection myConnection = new SqlConnection(DatabaseConnectionString))
                    {
                        myConnection.Open();
                        string stmt = "SELECT sha FROM torrents;";
                        using (SqlCommand cmdCount = new SqlCommand(stmt, myConnection))
                        {
                            using (SqlDataReader reader = cmdCount.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    string sha = reader.GetString(0);
                                    try {
                                        files[new BENObject(hex2bin(info_hash))] = new BENObject(handleSha(info_hash));
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            Response.BinaryWrite(obj.ToBytes());
        }
Exemplo n.º 3
0
 private bool is_valid_torrent(ref BENObject obj)
 {
     if (obj.getType() == BENObjectType.Dictionary && obj.getDictonary().ContainsKey(new BENObject("info")))
     {
         BENObject info = obj.getDictonary()[new BENObject("info")];
         if (info.getType() == BENObjectType.Dictionary &&
             info.getDictonary().ContainsKey(new BENObject("piece length")) &&
             info.getDictonary().ContainsKey(new BENObject("pieces")) &&
             info.getDictonary().ContainsKey(new BENObject("name")) &&
             (info.getDictonary().ContainsKey(new BENObject("length")) ||
              (info.getDictonary().ContainsKey(new BENObject("files")) &&
               info.getDictonary()[new BENObject("files")].getType() == BENObjectType.List)))
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 4
0
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return(false);
            }

            BENObject item = obj as BENObject;

            if (item.type != this.type)
            {
                return(false);
            }
            if (type == BENObjectType.String)
            {
                byte[] b1 = (byte[])item.data;
                byte[] b2 = (byte[])data;
                return(b1.SequenceEqual(b2));
            }
            return(item.data == this.data);
        }
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            BENObject obj = new BENObject(new Dictionary <BENObject, BENObject>());

            if (Request.QueryString["info_hash"] == null)
            {
                obj.getDictonary()[new BENObject("failure reason")] = new BENObject("Missing info_hash");
                obj.getDictonary()[new BENObject("failure code")]   = new BENObject(100);
                Response.Write(obj.ToString());
                return;
            }
            if (Request.QueryString["peer_id"] == null)
            {
                obj.getDictonary()[new BENObject("failure reason")] = new BENObject("Missing peer_id");
                obj.getDictonary()[new BENObject("failure code")]   = new BENObject(102);
                Response.Write(obj.ToString());
                return;
            }
            if (Request.QueryString["port"] == null)
            {
                obj.getDictonary()[new BENObject("failure reason")] = new BENObject("Missing port");
                obj.getDictonary()[new BENObject("failure code")]   = new BENObject(103);
                Response.Write(obj.ToString());
                return;
            }

            string sha     = bin2hex(queryBin("info_hash=", Request.RawUrl));
            string peer_id = bin2hex(queryBin("peer_id=", Request.RawUrl));

            if (sha != null && sha.Length != 40)
            {
                obj.getDictonary()[new BENObject("failure reason")] = new BENObject("Invalid infohash: infohash is not 20 bytes long");
                obj.getDictonary()[new BENObject("failure code")]   = new BENObject(150);
                Response.Write(obj.ToString());
                return;
            }

            if (peer_id != null && peer_id.Length != 40)
            {
                obj.getDictonary()[new BENObject("failure reason")] = new BENObject("Invalid peerid: peerid is not 20 bytes long");
                obj.getDictonary()[new BENObject("failure code")]   = new BENObject(151);
                Response.Write(obj.ToString());
                return;
            }
            try {
                using (SqlConnection myConnection = new SqlConnection(DatabaseConnectionString))
                {
                    string stmt;
                    myConnection.Open();

                    int interval;
                    if (Int32.TryParse(ConfigurationManager.AppSettings["config_interval"], out interval) == false)
                    {
                        interval = 300;
                    }

                    stmt = "DELETE FROM peers WHERE date < DATEADD(SECOND, -@interval, GETDATE())";
                    using (SqlCommand command = new SqlCommand(stmt, myConnection))
                    {
                        command.Parameters.AddWithValue("interval", (int)(interval * 1.2));
                        command.ExecuteScalar();
                    }

                    string ip;
                    if (Request.QueryString["ip"] != null)
                    {
                        ip = Request.QueryString["ip"];
                    }
                    else
                    {
                        ip = GetIPAddress();
                    }

                    int port;
                    Int32.TryParse(Request.QueryString["port"], out port);

                    if (Request.QueryString["event"] != null && Request.QueryString["event"].Equals("stopped"))
                    {
                        stmt = "DELETE FROM peers WHERE sha=@sha AND port=@port AND peer_id=@peer_id";
                        using (SqlCommand command = new SqlCommand(stmt, myConnection))
                        {
                            command.Parameters.AddWithValue("sha", sha);
                            command.Parameters.AddWithValue("peer_id", peer_id);
                            command.Parameters.AddWithValue("port", port);
                            command.ExecuteNonQuery();
                            return;
                        }
                    }

                    if (Request.QueryString["event"] != null && Request.QueryString["event"].Equals("completed"))
                    {
                        stmt = "UPDATE torrents SET downloaded = downloaded + 1 WHERE sha=@sha";
                        using (SqlCommand command = new SqlCommand(stmt, myConnection))
                        {
                            command.Parameters.AddWithValue("sha", sha);
                            command.ExecuteNonQuery();
                        }
                    }

                    int numwant;
                    int numwant_max;

                    if (Int32.TryParse(Request.QueryString["numwant"], out numwant) == false)
                    {
                        numwant = 50;
                    }

                    if (Int32.TryParse(ConfigurationManager.AppSettings["config_max_numwant"], out numwant_max) == false)
                    {
                        numwant_max = 200;
                    }

                    if (numwant > numwant_max)
                    {
                        obj.getDictonary()[new BENObject("failure reason")] = new BENObject("Invalid numwant.Client requested more peers than allowed by tracker.");
                        obj.getDictonary()[new BENObject("failure code")]   = new BENObject(152);
                        Response.Write(obj.ToString());
                        return;
                    }

                    long uploaded;
                    long downloaded;
                    long left;

                    Int64.TryParse(Request.QueryString["uploaded"], out uploaded);
                    Int64.TryParse(Request.QueryString["downloaded"], out downloaded);
                    Int64.TryParse(Request.QueryString["left"], out left);

                    stmt = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n" +
                           "BEGIN TRANSACTION;\n" +
                           "UPDATE peers SET peer_id=@peer_id, date=@date, uploaded=@uploaded, downloaded=@downloaded, dl_left=@dl_left WHERE sha=@sha AND ip=@ip AND port=@port\n" +
                           "IF @@ROWCOUNT = 0\n" +
                           "INSERT INTO peers(sha, ip, port, peer_id, uploaded, downloaded, dl_left) VALUES(@sha, @ip, @port, @peer_id, @uploaded, @downloaded, @dl_left)\n" +
                           "COMMIT TRANSACTION;";
                    try {
                        using (SqlCommand command = new SqlCommand(stmt, myConnection))
                        {
                            command.Parameters.AddWithValue("sha", sha);
                            command.Parameters.AddWithValue("peer_id", peer_id);
                            command.Parameters.AddWithValue("ip", ip);
                            command.Parameters.AddWithValue("port", port);
                            command.Parameters.AddWithValue("date", DateTime.Now);
                            command.Parameters.AddWithValue("uploaded", uploaded);
                            command.Parameters.AddWithValue("downloaded", downloaded);
                            command.Parameters.AddWithValue("dl_left", left);
                            command.ExecuteNonQuery();
                        }
                    }
                    catch
                    {
                        obj.getDictonary()[new BENObject("failure reason")] = new BENObject("info_hash not found in the database");
                        obj.getDictonary()[new BENObject("failure code")]   = new BENObject(200);
                        Response.Write(obj.ToString());
                        return;
                    }


                    int no_peer_id;
                    Int32.TryParse(Request.QueryString["no_peer_id"], out no_peer_id);
                    no_peer_id = 0;
                    obj.getDictonary()[new BENObject("interval")] = new BENObject(interval);
                    List <BENObject> peers = new List <BENObject>();
                    obj.getDictonary()[new BENObject("peers")] = new BENObject(peers);

                    if (numwant > 0)
                    {
                        if (no_peer_id == 0)
                        {
                            stmt = String.Format("SELECT TOP {0} ip, port, peer_id FROM peers WHERE sha=@sha;", numwant);
                        }
                        else
                        {
                            stmt = String.Format("SELECT TOP {0} ip, port FROM peers WHERE sha=@sha;", numwant);
                        }

                        using (SqlCommand command = new SqlCommand(stmt, myConnection))
                        {
                            command.Parameters.AddWithValue("sha", sha);
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                BENObject ben_peer_id = new BENObject("peer id");
                                BENObject ben_ip      = new BENObject("ip");
                                BENObject ben_port    = new BENObject("port");
                                while (reader.Read())
                                {
                                    Dictionary <BENObject, BENObject> dic = new Dictionary <BENObject, BENObject>();
                                    if (no_peer_id == 0)
                                    {
                                        dic.Add(ben_peer_id, new BENObject(hex2bin(reader.GetString(2))));
                                    }
                                    dic.Add(ben_ip, new BENObject(reader.GetString(0)));
                                    dic.Add(ben_port, new BENObject(reader.GetInt32(1)));

                                    peers.Add(new BENObject(dic));
                                }
                            }
                        }
                    }
                    Response.BinaryWrite(obj.ToBytes());
                }
            }
            catch
            {
                obj.getDictonary()[new BENObject("failure reason")] = new BENObject("Generic error");
                obj.getDictonary()[new BENObject("failure code")]   = new BENObject(900);
                Response.Write(obj.ToString());
            }
        }
Exemplo n.º 6
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (fileToUpload.HasFile)
            {
                Stream fileStream;
                int    length = fileToUpload.PostedFile.ContentLength;

                Byte[] Input = new Byte[length];
                fileStream = fileToUpload.FileContent;
                fileStream.Read(Input, 0, length);
                BENObject obj;
                try
                {
                    obj = new BENObject(ref Input);
                }
                catch
                {
                    BotLabel.Text = "Torrent parsing fail";
                    return;
                }
                if (is_valid_torrent(ref obj))
                {
                    obj.getDictonary()[new BENObject("announce")] = new BENObject(ConfigurationManager.AppSettings["config_announce"]);
                    obj.getDictonary().Remove(new BENObject("announce-list"));
                    BENObject info = obj.getDictonary()[new BENObject("info")];

                    SHA1   sha_crypto = new SHA1CryptoServiceProvider();
                    byte[] result     = sha_crypto.ComputeHash(info.ToBytes());
                    string sha        = BitConverter.ToString(result).Replace("-", string.Empty);
                    BotLabel.Text = sha + "<br />";

                    try {
                        using (SqlConnection myConnection = new SqlConnection(DatabaseConnectionString))
                        {
                            myConnection.Open();
                            string stmt = "INSERT INTO torrents (sha, name, username) values(@sha, @name, @username);";
                            using (SqlCommand myCommand = new SqlCommand(stmt, myConnection))
                            {
                                myCommand.Parameters.AddWithValue("sha", sha);
                                myCommand.Parameters.AddWithValue("name", info.getDictonary()[new BENObject("name")].getString());
                                myCommand.Parameters.AddWithValue("username", (String)Session["username"]);
                                myCommand.ExecuteNonQuery();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BotLabel.Text += "Error: " + ex.Message;
                        return;
                    }
                    try {
                        string   file_path = String.Format("{0}/{1}.torrent", ConfigurationManager.AppSettings["config_upload_dir"], sha);
                        FileInfo file      = new FileInfo(Server.MapPath(file_path));

                        file.Directory.Create();
                        File.WriteAllBytes(file.FullName, obj.ToBytes());

                        BotLabel.Text += "New record created successfully";
                    }
                    catch (Exception ex)
                    {
                        try {
                            using (SqlConnection myConnection = new SqlConnection(DatabaseConnectionString))
                            {
                                myConnection.Open();
                                string stmt = "DELETE FROM torrents WHERE sha=@sha;";
                                using (SqlCommand cmdCount = new SqlCommand(stmt, myConnection))
                                {
                                    cmdCount.Parameters.AddWithValue("sha", sha);
                                    cmdCount.ExecuteNonQuery();
                                }
                            }
                        }
                        catch
                        {
                        }
                        BotLabel.Text += "Error: " + ex.Message;
                    }
                }
                else
                {
                    BotLabel.Text = "Torrent validation fail";
                }
            }
        }
Exemplo n.º 7
0
        private void handleRecord(string sha, SqlDataReader reader)
        {
            StringBuilder sb   = new StringBuilder();
            String        user = reader.GetString(2);

            sb.AppendFormat("{0}<a href=\"{1}/{2}.torrent\" download=\"{3}.torrent\">{3}</a> ", NameLabel.Text, ConfigurationManager.AppSettings["config_upload_dir"], sha, reader.GetString(0));
            if (Session["login"] != null)
            {
                if (user == (String)Session["username"])
                {
                    sb.AppendFormat("<a href=\"torrent.aspx?action=delete&sha={0}\">[X]</a>", sha);
                }
            }
            NameLabel.Text = sb.ToString();
            sb.Length      = 0;

            sb.Append(DateLabel.Text);
            sb.Append(reader.GetDateTime(1));
            DateLabel.Text = sb.ToString();
            sb.Length      = 0;

            string   file_path = String.Format("{0}/{1}.torrent", ConfigurationManager.AppSettings["config_upload_dir"], sha);
            FileInfo file      = new FileInfo(Server.MapPath(file_path));

            if (file.Exists)
            {
                byte[] bytes = File.ReadAllBytes(file.FullName);

                BENObject obj = new BENObject(ref bytes);

                BENObject ben_lenght = new BENObject("length");
                BENObject ben_name   = new BENObject("name");
                Dictionary <BENObject, BENObject> info_dict = obj.getDictonary()[new BENObject("info")].getDictonary();

                if (info_dict.ContainsKey(ben_lenght) && info_dict[ben_lenght].getType() == BENObjectType.Integer &&
                    info_dict.ContainsKey(ben_name) && info_dict[ben_name].getType() == BENObjectType.String)
                {
                    sb.Append(SizeLabel.Text);
                    sb.Append(get_format_size(info_dict[ben_lenght].getInt()));
                    SizeLabel.Text = sb.ToString();
                    sb.Length      = 0;

                    sb.Append(FilesLabel.Text);
                    sb.Append(info_dict[ben_name].getString());
                    FilesLabel.Text = sb.ToString();
                    sb.Length       = 0;
                }
                else
                {
                    long             size       = 0;
                    List <BENObject> files_list = info_dict[new BENObject("files")].getList();
                    BENObject        ben_length = new BENObject("length");
                    BENObject        ben_path   = new BENObject("path");
                    sb.Append(FilesLabel.Text);
                    foreach (BENObject files in files_list)
                    {
                        Dictionary <BENObject, BENObject> file_dict = files.getDictonary();
                        size += file_dict[ben_length].getInt();
                        List <BENObject> list  = file_dict[ben_path].getList();
                        Boolean          first = true;
                        foreach (BENObject path in list)
                        {
                            sb.Append(first ? "" : "/");
                            sb.Append(path.getString());
                            first = false;
                        }
                        sb.Append("<br>");
                    }
                    FilesLabel.Text = sb.ToString();;
                    sb.Length       = 0;

                    sb.Append(SizeLabel.Text);
                    sb.Append(get_format_size(size));
                    SizeLabel.Text = sb.ToString();
                    sb.Length      = 0;
                }
            }
        }