[C#] El cervanBot para underc0de

Iniciado por Cervantes_xD, Agosto 22, 2011, 09:57:06 AM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Agosto 22, 2011, 09:57:06 AM Ultima modificación: Mayo 27, 2014, 09:46:43 PM por Expermicid
Bueno, pues en MitM ya lo tengo posteado xD

Es el mismo bot que estoy haciendo pero con modificaciones para UC, ya que el comando principal lo he implementado que es el de poder ver los post recientes en un foro SMF 2.0 como este y como mitm. Obviamente el cargo de Admin se lo dejo a ANTRAX que es el admin del canal, pero el code estará aquí para quien quiera bajarlo y ver las chapuzas que he hecho (LOL)

Código: csharp
//Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocketsC;

namespace SocketsC
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket cliente = new Socket();
            cliente.Connect();
        }
    }
}


Código: csharp
//getWebDoc.cs
using System.Web;
using System.Net;
using System.IO;
using System.Text;


namespace SocketsC
{
    class getWebDoc
    {
        public static void getDocMitM(ref List<String> noticias)
        {
            int ultimos = 0;
            StringBuilder final = new StringBuilder("");

            if (noticias == null)
            {
                noticias = new List<String>();
            }
            else
                if (noticias.Count != 0)
                    noticias.RemoveAt(0);

            try
            {

                String baseUri = "http://www.underc0de.org/foro/SSI.php?ssi_function=recentTopics";
                HttpWebRequest connection =
                (HttpWebRequest)HttpWebRequest.Create(baseUri);

                connection.Method = "GET";
                HttpWebResponse response =
                (HttpWebResponse)connection.GetResponse();

                StreamReader sr =
                new StreamReader(response.GetResponseStream(),
                Encoding.UTF8);

                String respuesta;

                while (!sr.EndOfStream)
                {
                    respuesta = sr.ReadLine();
                    //Console.WriteLine(respuesta);
                    try
                    {
                        if (respuesta.Length > 5)
                        {
                            if (respuesta.Substring(0, 6) == "\t\t\t\t\t[")
                            {
                                //Console.WriteLine(respuesta);
                                sr.ReadLine();
                                sr.ReadLine();
                                respuesta = sr.ReadLine();
                                int i = 0;

                                while (respuesta.ElementAt<char>(i) != '\"')
                                    i++;
                                i++;

                                while (respuesta.ElementAt<char>(i) != '\"')
                                {
                                    final.Append(respuesta.ElementAt<char>(i));
                                    i++;
                                }

                                final.Append(" - ");
                                i = i+2;

                                while (respuesta.ElementAt<char>(i) != '<')
                                {
                                    final.Append(respuesta.ElementAt<char>(i));
                                    i++;
                                }
                                final.Append("\r\n");
                                noticias.Add(final.ToString());
                                final.Clear();
                               
                                ultimos++;
                                if (ultimos == 5)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    catch { }
                }
                sr.Dispose();
                sr.Close();
            }
            catch
            {
                Console.WriteLine("No se ha podido obtener documento");
            }
        }       
    }
}


Código: csharp
//Socket.cs
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace SocketsC
{
    class Socket
    {
        string admin = "ANTRAX";
        string publicos = "Publicos: <!help> <!MD5 cadena> <!news>\r\n";
        string privados = "Privados: <quit> <exit> <reconnect>\r\n";

        TcpClient socketForServer;
        string server = "ifg.ircnode.com";
        int puerto = 6667;
        string canal = "#underc0de";
        StreamReader streamReader;
        StreamWriter streamWriter;
        String usuario = "";
        String comando;
        int salidaApp = 0;
        List<String> noticias = new List<String>();

        public static int numPalabras(string cad)
        {
            int pal = 1;
            int i = 0;
            try
            {
                while (i < cad.Length)
                {
                    if (cad.ElementAt<char>(i) == ' ')
                    {
                        pal++;
                        //Console.WriteLine((int)cad.ElementAt<char>(i));
                    }
                    i++;
                }
            }
            catch
            { }
            return pal;
        }

        public static string MD5(string password)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            password = s.ToString();
            return password;
        }

        public void getComUser(String orden, ref String user, ref String command)
        {
            try
            {
                String commandPri = "";
                //Capturando el comando
                command = "";
                int i = 1;
                while (orden.ElementAt<char>(i) != ':')
                {
                    i++;
                }
                i++;
                command = orden.Substring(i, orden.Length - i);
                if (numPalabras(command) > 1)
                {
                    i = 0;
                    while (command.ElementAt<char>(i) != ' ')
                    {
                        i++;
                    }
                   
                    commandPri = command.Substring(0, i);
                    //Console.WriteLine(commandPri);
                }
               

                //Capturando el user
                user = "";
                i = 1;
                while (orden.ElementAt<char>(i) != '!')
                {
                    i++;
                }
                user = orden.Substring(1, i-1);
                Console.WriteLine(user+"/"+command);

                if (command == "quit")
                {
                    if (user == admin)
                    {
                        streamWriter.WriteLine("PART "+canal+"\r\n");
                        streamWriter.Flush();
                        streamWriter.WriteLine("QUIT\r\n");
                        streamWriter.Flush();
                        streamWriter.Close();
                        streamReader.Close();
                        salidaApp = 1;
                    }
                }
                if (commandPri == "!MD5")
                {
                    i = 0;
                    while (command.ElementAt<char>(i) != ' ')
                        i++;
                    i++;

                    streamWriter.WriteLine("PRIVMSG "+canal+" :" + user + ": " + MD5(command.Substring(i, command.Length - i)));
                    streamWriter.Flush();
                }
                if (command == "reconnect")
                {
                    if (user == admin)
                    {
                        streamWriter.WriteLine("JOIN " + canal + "\r\n");
                        streamWriter.Flush();
                    }
                }
                if (command == "exit")
                {
                    if (user == admin)
                    {
                        streamWriter.WriteLine("PART " + canal + "\r\n");
                        streamWriter.Flush();
                    }
                }
                if (command == "!news")
                {
                    getWebDoc.getDocMitM(ref noticias);
                    while(noticias.Count != 0)
                    {
                        string notAct = noticias.ElementAt<String>(0);
                        streamWriter.WriteLine("PRIVMSG " + canal + " :" + notAct);
                        streamWriter.Flush();
                        noticias.RemoveAt(0);
                    }
                }
                if (command == "!help")
                {
                    streamWriter.WriteLine("PRIVMSG " + canal + " :" + user);
                    streamWriter.Flush();
                    streamWriter.WriteLine("PRIVMSG "+ canal + " :" + publicos);
                    streamWriter.Flush();
                    streamWriter.WriteLine("PRIVMSG " + canal + " :" + privados);
                    streamWriter.Flush();
                }

            }
            catch
            {
                //Console.WriteLine("Crap");
            }
        }

        public void Connect()
        {
             
            try
            { 
                //Creamos un TcpCliente y le pasamos
                //el server y el puerto.
                socketForServer = new TcpClient(server, puerto);
            }
            catch
            {
                Console.WriteLine(
                "No se pudo conectar a {0}:{1}", server, puerto);
                return;
            }


            //aqui es lo mismo que en el server. Usamos StreamWriter y Reader.
            NetworkStream networkStream = socketForServer.GetStream();

            streamReader =
                  new System.IO.StreamReader(networkStream);

            streamWriter =
                  new System.IO.StreamWriter(networkStream);

            try
            {
                //Básico para la conexión
                String salida;
                String outputString = streamReader.ReadLine();
                Console.WriteLine(outputString);
                outputString = streamReader.ReadLine();
                Console.WriteLine(outputString);

                streamWriter.WriteLine("PASS miclavedered1"); //1.- Clave de red
                streamWriter.Flush();
                streamWriter.WriteLine("NICK cervanBot\r\n"); //2.- Nick del bot
                streamWriter.Flush();
                //A partir de aquí el servidor comenzará a enviar PINGS
                outputString = streamReader.ReadLine();
                salida = outputString.Substring(0, 4);
                Console.WriteLine(outputString);
                if (salida == "PING")
                {
                    streamWriter.WriteLine("PONG" + outputString.Substring(4, outputString.Length - 4));
                    streamWriter.Flush();
                }
                streamWriter.WriteLine("USER cervbot tolmoon tolsun :Bot Cervantes\r\n");
                            //3.- Nombre de usuario. Ya desde aquí oficialmente estás dentro de la red
                streamWriter.Flush();

                outputString = streamReader.ReadLine();
                salida = outputString.Substring(0, 4);
                Console.WriteLine(outputString);
                if (salida == "PING")
                {
                    streamWriter.WriteLine("PONG" + outputString.Substring(4, outputString.Length - 4));
                    streamWriter.Flush();
                }
                streamWriter.WriteLine("JOIN "+canal+"\r\n"); //4.- Nos unimos al canal

                streamWriter.Flush();

                while (true)
                {
                    outputString = streamReader.ReadLine();
                    salida = outputString.Substring(0, 4);
                    if (salida == "PING")
                    {
                        Console.WriteLine(outputString);
                        streamWriter.WriteLine("PONG" + outputString.Substring(4, outputString.Length - 4));
                        streamWriter.Flush();
                        //Respondiendo a los PINGS
                    }
                    else
                        getComUser(outputString, ref usuario, ref comando);
                    if (salidaApp == 1)
                        break;
                }
             
            }
            catch
            {
                Console.WriteLine("Exception reading from Server");
                //Se cagó el socket
            }
            finally
            {
                networkStream.Close();
            }
        }

    }
}


Espero que les guste y que no me fusilen por las cagadas que de seguro tendrá el code xD pero sobretodo no quería usar regex y me he quebrado la cabeza para lograrlo. No obstante, mereció la pena x)

Un saludo.
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Lindo code, muy elaborado ;)
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

trata de implementar DISPOSABLE, sino los socket pueden dar error, o si ai un error inesperado y no controlado puede aver un cuelgue en muchos casos, en fin..detalles