Exemple #1
0
 public override void Decode(Unmarshal context, MarshalOpcode op, BinaryReader source)
 {
     uint len = source.ReadSizeEx();
     RawData = source.ReadBytes((int) len);
     DataUnmarshal = new Unmarshal();
     Data = DataUnmarshal.Process(RawData);
 }
Exemple #2
0
 public PySubStream(byte[] data)
     : base(PyObjectType.SubStream)
 {
     RawData = data;
     DataUnmarshal = new Unmarshal();
     Data = DataUnmarshal.Process(data);
 }
Exemple #3
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (txtInput.Text.Length == 0)
            {
                txtOutput.Text = "";
                return;
            }
            string hex = txtInput.Text.Replace(" ", "").Replace(System.Environment.NewLine, "");

            try
            {
                //txtOutput.Text = hex;
                byte[] raw = new Byte[hex.Length / 2];
                for (int i = 0; i < raw.Length; i++)
                {
                    raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
                }
                Console.WriteLine(raw.Length + ", " + hex.Length);
                Unmarshal un = new Unmarshal();
                //un.DebugMode = true;
                //PyObject obj = un.Process(BinaryReader.);
                PyRep         obj = un.Process(raw);
                PrettyPrinter pp  = new PrettyPrinter();
                txtOutput.Text = pp.Print(obj);
            }
            catch
            {
                hex = txtInput.Text.Substring(8, txtInput.Text.Length - 8).Replace(" ", "").Replace(System.Environment.NewLine, "");
                byte[] raw = new Byte[hex.Length / 2];
                for (int i = 0; i < raw.Length; i++)
                {
                    raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
                }
                Console.WriteLine(raw.Length + ", " + hex.Length);
                Unmarshal un = new Unmarshal();
                un.DebugMode = true;
                // un.DebugMode = true;
                //PyObject obj = un.Process(BinaryReader.);
                PyRep         obj = un.Process(raw);
                PrettyPrinter pp  = new PrettyPrinter();
                txtOutput.Text = pp.Print(obj);
            }

            /*
             * //txtOutput.Text = hex;
             * byte[] raw = new Byte[hex.Length / 2];
             * for (int i = 0; i < raw.Length; i++) {
             *  raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
             * }
             * Console.WriteLine(raw.Length+", "+hex.Length);
             * Unmarshal un = new Unmarshal();
             * // un.DebugMode = true;
             * //PyObject obj = un.Process(BinaryReader.);
             * PyObject obj = un.Process(raw);
             * txtOutput.Text = PrettyPrinter.Print(obj);
             */
        }
Exemple #4
0
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem == null)
            {
                richTextBox2.Text = "";
                return;
            }

            if (Cache.UpdateCache(listBox1.SelectedItem.ToString()) == false)
            {
                WindowLog.Error("Main::LoadCache", "Error loading cache");
                return;
            }

            PyObject cache = Cache.GetCache(listBox1.SelectedItem.ToString());

            PyCachedObject obj = new PyCachedObject();

            if (obj.Decode(cache) == false)
            {
                WindowLog.Error("Main::LoadCache", "Cannot decode the cache data");
                return;
            }

            if (Program.cacheDataDisplayMode == "Pretty")
            {
                try
                {
                    richTextBox2.Text = PrettyPrinter.Print(Unmarshal.Process <PyObject>(obj.cache.Data));
                }
                catch (Exception)
                {
                    WindowLog.Error("Main::LoadCache", "Cannot Unmarshal the cache data");
                    richTextBox2.Text = "Error";
                }
            }
            else
            {
                richTextBox2.Text = ByteToString(obj.cache.Data);
            }

            WindowLog.Debug("Main::LoadCache", "Cache loaded");
        }
Exemple #5
0
        public void ServerAsyncReceive(IAsyncResult ar)
        {
            try
            {
                AsyncState state = (AsyncState)(ar.AsyncState);

                byte[] serverData  = state.buffer;
                int    serverBytes = 0;

                serverBytes = connection.Socket.EndReceive(ar);

                if (serverBytes > 0)
                {
                    // Add the packets
                    serverPacketizer.QueuePackets(serverData, serverBytes);

                    int packets = serverPacketizer.ProcessPackets();

                    for (int i = 0; i < packets; i++)
                    {
                        byte[] packet = serverPacketizer.PopItem();

                        PyObject data = Unmarshal.Process <PyObject>(packet);

                        Log.Warning("PacketTracer::Server", PrettyPrinter.Print(data));

                        data = OldHandle(data);

                        SendClient(data);
                    }
                }

                connection.Socket.BeginReceive(state.buffer, 0, 8192, SocketFlags.None, serverReceive, state);
            }
            catch (Exception ex)
            {
                Log.Error("ExceptionHandler", ex.ToString());
                CloseConnection();
            }
        }
Exemple #6
0
        private void ClientAsyncReceive(IAsyncResult ar)
        {
            try
            {
                AsyncState state = (AsyncState)(ar.AsyncState);

                byte[] clientData  = state.buffer;
                int    clientBytes = 0;

                clientBytes = socket.Socket.EndReceive(ar);

                if (clientBytes > 0)
                {
                    clientPacketizer.QueuePackets(clientData, clientBytes);

                    int packets = clientPacketizer.ProcessPackets();

                    for (int i = 0; i < packets; i++)
                    {
                        byte[] packet = clientPacketizer.PopItem();

                        PyObject data = Unmarshal.Process <PyObject>(packet);

                        Log.Warning("PacketTracer::Client", PrettyPrinter.Print(data));

                        data = OldHandle(data);

                        SendServer(data);
                    }
                }

                socket.Socket.BeginReceive(state.buffer, 0, 8192, SocketFlags.None, clientReceive, state);
            }
            catch (Exception ex)
            {
                Log.Error("ExceptionHandler", ex.ToString());
                CloseConnection();
            }
        }
Exemple #7
0
 private static bool UpdateInternal(EVEServer server, out int serverBuild, out int clientBuild, out string codePackageURL)
 {
     try
     {
         var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
         {
             NoDelay = true
         };
         socket.Connect(ServerHosts[server], 26000);
         var reader = new BinaryReader(new NetworkStream(socket));
         var len    = reader.ReadInt32();
         var data   = reader.ReadBytes(len);
         var hello  = Unmarshal.Process <eveMarshal.PyTuple>(data);
         serverBuild = (int)hello[4].IntValue;
         if (hello[6] is PyNone)
         {
             // no client patch available
             clientBuild    = serverBuild;
             codePackageURL = null;
         }
         else
         {
             var updateInfo = (hello[6] as PyObjectData).Arguments as eveMarshal.PyDict;
             clientBuild    = (int)updateInfo.Get("build").IntValue;
             codePackageURL = updateInfo.Get("fileurl").StringValue;
         }
         socket.Close();
         return(true);
     }
     catch (Exception e)
     {
         serverBuild    = clientBuild = 0;
         codePackageURL = null;
         return(false);
     }
 }
Exemple #8
0
        static void Main(string[] args)
        {
            Log.Init("evesharp");
            Log.Info("Main", "Starting node...");

            Log.Info("Database", "Loading database.conf file");

            string[] lines = File.ReadAllLines("database.conf");

            Database.Database.Username = lines[0];
            Database.Database.Password = lines[1];
            Database.Database.Host     = lines[2];
            Database.Database.DB       = lines[3];

            Log.Trace("Database", "Connecting to database...");

            if (Database.Database.Init() == false)
            {
                Log.Error("Main", "Cannot connect to database");
                while (true)
                {
                    ;
                }
            }

            /*
             * SHA1 sha1 = SHA1.Create();
             * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password"));
             * char[] strHash = new char[20];
             *
             * for (int i = 0; i < 20; i++)
             * {
             *  strHash[i] = (char)hash[i];
             * }
             *
             * string str = new string(strHash);
             *
             * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);");
             *
             * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', SHA1('password'), 2, 0, 0);");*/

            Log.Info("Main", "Connection to the DB sucessfull");

            Log.Info("Main", "Generating default cache data");
            Cache.GenerateCache();
            Log.Debug("Main", "Done");

            Log.Info("Main", "Connecting to proxy...");

            proxyConnection = new TCPSocket(ushort.Parse(proxy[0, 1]), false);
            if (proxyConnection.Connect(proxy[0, 0]) == false)
            {
                Log.Error("Main", "Cannot connect to proxy. Halting");
                Database.Database.Stop();
                while (true)
                {
                    ;
                }
            }

            Log.Trace("Main", "Server started");

            while (true)
            {
                Thread.Sleep(1);
                try
                {
                    byte[] data  = new byte[proxyConnection.Available];
                    int    bytes = proxyConnection.Recv(data);

                    if (bytes == -1)
                    {
                        // Proxy is closing, shutdown the node
                        break;
                    }
                    else if (bytes > 0)
                    {
                        packetizer.QueuePackets(data, bytes);
                        int p = packetizer.ProcessPackets();

                        for (int i = 0; i < p; i++)
                        {
                            byte[]   packet = packetizer.PopItem();
                            PyObject obj    = Unmarshal.Process <PyObject>(packet);

                            if (obj is PyObjectData)
                            {
                                PyObjectData info = obj as PyObjectData;

                                if (info.Name == "machoNet.nodeInfo")
                                {
                                    // Update our local info
                                    NodeInfo nodeinfo = new NodeInfo();

                                    if (nodeinfo.Decode(info) == true)
                                    {
                                        nodeID = nodeinfo.nodeID;

                                        Log.Debug("Main", "Found machoNet.nodeInfo, our new node id is " + nodeID.ToString("X4"));
                                        SystemManager.LoadSolarSystems(nodeinfo.solarSystems);
                                    }
                                }
                                else
                                {
                                    // Client packet
                                    PyPacket clientpacket = new PyPacket();

                                    if (clientpacket.Decode(info) == false)
                                    {
                                        Log.Error("Main", "Unknown packet");
                                    }
                                    else
                                    {
                                        // Something similar to Async calls
                                        new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket);
                                    }
                                }
                            }
                            else if (obj is PyChecksumedStream) // Checksumed packets
                            {
                                PyPacket clientpacket = new PyPacket();

                                if (clientpacket.Decode(obj) == false)
                                {
                                    Log.Error("Main", "Cannot decode packet");
                                }
                                else
                                {
                                    new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket);
                                }
                            }
                            else if (obj is PyTuple)
                            {
                                // The only tuple packet is the LowLevelVersionExchange
                                LowLevelVersionExchange ex = new LowLevelVersionExchange();

                                if (ex.Decode(obj) == false)
                                {
                                    Log.Error("Main", "LowLevelVersionExchange error");
                                }

                                // Reply with the node LowLevelVersionExchange
                                LowLevelVersionExchange reply = new LowLevelVersionExchange();

                                reply.codename     = Common.Constants.Game.codename;
                                reply.birthday     = Common.Constants.Game.birthday;
                                reply.build        = Common.Constants.Game.build;
                                reply.machoVersion = Common.Constants.Game.machoVersion;
                                reply.version      = Common.Constants.Game.version;
                                reply.region       = Common.Constants.Game.region;

                                Send(reply.Encode(true));
                            }
                            else if (obj is PyObjectEx)
                            {
                                Log.Error("PyObjectEx", PrettyPrinter.Print(obj));
                            }
                            else
                            {
                                Log.Error("Main", PrettyPrinter.Print(obj));
                                Log.Error("Main", "Unhandled packet type");
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            /* Code to ADD an account:
             * SHA1 sha1 = SHA1.Create();
             * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password"));
             * char[] strHash = new char[20];
             *
             * for (int i = 0; i < 20; i++)
             * {
             *  strHash[i] = (char)hash[i];
             * }
             *
             * string str = new string(strHash);
             *
             * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);");
             */
        }
Exemple #9
0
        private void Run()
        {
            try
            {
                while (true)
                {
                    Thread.Sleep(1);

                    byte[] data  = new byte[socket.Available];
                    int    bytes = 0;

                    try
                    {
                        bytes = socket.Recv(data);
                    }
                    catch (SocketException ex)
                    {
                        if (ex.ErrorCode != 10035)
                        {
                            throw new DisconnectException();
                        }
                    }
                    catch (Exception)
                    {
                        throw new DisconnectException();
                    }

                    if (bytes == -1) // Client disconnected
                    {
                        throw new DisconnectException();
                    }
                    else if (bytes > 0)
                    {
                        packetizer.QueuePackets(data, bytes);
                        int p = packetizer.ProcessPackets();

                        byte[] actual = null;

                        for (int i = 0; i < p; i++)
                        {
                            actual = packetizer.PopItem();
                            PyObject obj = Unmarshal.Process <PyObject>(actual);

                            if (obj is PyObjectEx)
                            {
                                // PyException
                                Log.Error("Client", "Got exception from client");
                            }
                            else
                            {
                                PyPacket packet = new PyPacket();
                                if (packet.Decode(obj) == false)
                                {
                                    Log.Error("Client", "Error decoding PyPacket");
                                }
                                else
                                {
                                    // Get the node ID to send
                                    if (packet.dest.type == PyAddress.AddrType.Node)
                                    {
                                        if (packet.dest.typeID == 1)
                                        {
                                            packet.dest.typeID = (ulong)nodeID; // We dont want to receive packets in the proxy
                                        }

                                        if (packet.source.type != PyAddress.AddrType.Client)
                                        {
                                            Log.Error("Client", string.Format("Wrong source data, expected client but got {0}", packet.source.type));
                                        }

                                        Log.Warning("Client", PrettyPrinter.Print(packet.Encode()));

                                        if (NodeManager.NotifyNode((int)packet.dest.typeID, obj) == false)
                                        {
                                            // We cant send the data to the node, what to do?
                                            Log.Error("Client", "Trying to send a packet to a non-existing node");
                                            throw new DisconnectException();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (DisconnectException)
            {
            }
            catch (Exception ex)
            {
                Log.Error("Client", "Unhandled exception... " + ex.Message);
                Log.Error("ExceptionHandler", "Stack trace: " + ex.StackTrace);
            }

            // We should notify our node about this
            Log.Error("Client", "Client disconnected");
            socket.Close();
            ClientManager.RemoveClient(this);
        }
Exemple #10
0
        public void ReceiveNodeAsync(IAsyncResult ar)
        {
            try
            {
                AsyncState state = (AsyncState)(ar.AsyncState);

                int bytes = Socket.Socket.EndReceive(ar);

                packetizer.QueuePackets(state.buffer, bytes);
                int p = packetizer.ProcessPackets();

                for (int i = 0; i < p; i++)
                {
                    byte[] packet = packetizer.PopItem();

                    PyObject obj = Unmarshal.Process <PyObject>(packet);

                    if (obj == null)
                    {
                        Log.Debug("Node", "Null packet received");
                        continue;
                    }

                    if ((obj is PyObjectData) == false)
                    {
                        Log.Debug("Node", "Non-valid node packet. Dropping");
                        continue;
                    }

                    PyObjectData item = obj as PyObjectData;

                    if (item.Name == "macho.CallRsp")
                    {
                        PyPacket final = new PyPacket();

                        if (final.Decode(item) == false)
                        {
                            Log.Error("Node", "Cannot decode packet");
                            continue;
                        }

                        if (final.dest.type == PyAddress.AddrType.Client)
                        {
                            ConnectionManager.NotifyClient((int)(final.userID), obj);
                        }
                        else if (final.dest.type == PyAddress.AddrType.Node)
                        {
                            ConnectionManager.NotifyNode((int)(final.dest.typeID), obj);
                        }
                        else if (final.dest.type == PyAddress.AddrType.Broadcast)
                        {
                            Log.Error("Node", "Broadcast packets not supported yet");
                        }
                        // TODO: Handle Broadcast packets
                    }
                    else
                    {
                        Log.Error("Node", string.Format("Wrong packet name: {0}", item.Name));
                    }
                }

                Socket.Socket.BeginReceive(state.buffer, 0, 8192, SocketFlags.None, recvAsync, state);
            }
            catch (ObjectDisposedException)
            {
                Log.Debug("Node", "Disconnected");
                ConnectionManager.RemoveConnection(this);
            }
            catch (SocketException)
            {
                Log.Debug("Node", "Disconnected");
                ConnectionManager.RemoveConnection(this);
            }
            catch (Exception ex)
            {
                Log.Error("Node", "Caught unhandled exception: " + ex.ToString());
            }
        }
Exemple #11
0
        private bool process(string filename, StreamWriter singleWriter)
        {
            // Does the file exist?
            if (!File.Exists(filename))
            {
                addText("File not found: " + filename);
                // No, fail!
                return(false);
            }
            byte[] data = null;
            using (var f = File.Open(filename, FileMode.Open))
            {
                if (f.Length == 0)
                {
                    if (singleWriter != null)
                    {
                        // Write the filename.
                        singleWriter.WriteLine(Path.GetFileName(filename));
                        // Write the decoded file.
                        singleWriter.WriteLine("Zero Length file.");
                    }
                    return(true);
                }
                data = new byte[f.Length];
                f.Read(data, 0, (int)f.Length);
                f.Close();
            }
            if (data == null)
            {
                // No data loaded.
                return(false);
            }
            // Is this a compressed file?
            if (data[0] == ZlibMarker)
            {
                // Yes, decompress it.
                data = Zlib.Decompress(data);
                if (data == null)
                {
                    // Decompress failed.
                    return(false);
                }
            }
            // Is this a proper python serial stream?
            if (data[0] != HeaderByte)
            {
                // No, is this a python file? If yes, ignore it but dont cause an error.
                if (data[0] == PythonMarker && decompilePython && !imbededPython)
                {
                    try
                    {
                        Bytecode code = new Bytecode();
                        code.load(data);
                        string outfile = null;
                        if (code.body != null)
                        {
                            Python.PyString fns = code.body.filename as Python.PyString;
                            if (fns != null)
                            {
                                outfile = fns.str;
                                outfile = outfile.Replace(':', '_');
                                outfile = outfile.Replace('\\', '-');
                                outfile = outfile.Replace('/', '-');
                            }
                        }
                        if (outfile != null)
                        {
                            string pyd = Path.GetDirectoryName(filename);
                            pyd += "\\py\\";
                            if (!Directory.Exists(pyd))
                            {
                                Directory.CreateDirectory(pyd);
                            }
                            outfile = pyd + "\\" + outfile + ".txt";
                            string dump = Python.PrettyPrinter.print(code, true);
                            File.WriteAllText(outfile, dump);
                        }
                    }
                    catch (Exception e)
                    {
                        string err = Path.GetFileName(filename) + Environment.NewLine + "Error: " + e.ToString();
                        // We, had an error but should still produce some kind of notice in the output.
                        addText(err + Environment.NewLine);
                        if (singleWriter != null)
                        {
                            //// Write the filename.
                            //singleWriter.WriteLine(Path.GetFileName(filename));
                            //// Write the decoded file.
                            //singleWriter.WriteLine("Python Decoder Error.");
                            //singleWriter.WriteLine(err);
                        }
                        else
                        {
                            //File.WriteAllText(filename + ".txt", err);
                        }
                        return(false);
                    }
                }
                return(data[0] == PythonMarker);
            }
            bool decodeDone = false;

            try
            {
                Unmarshal un = new Unmarshal();
                un.analizeInput = analizeInput;
                PyRep obj = un.Process(data);
                decodeDone = true;
                obj        = analyse(obj, filename);
                eveMarshal.PrettyPrinter printer = new eveMarshal.PrettyPrinter();
                printer.analizeInput    = analizeInput;
                printer.decompilePython = decompilePython;
                string decoded = printer.Print(obj);
                if (singleWriter != null)
                {
                    // Write the filename.
                    singleWriter.WriteLine(Path.GetFileName(filename));
                    // Write the decoded file.
                    singleWriter.Write(decoded);
                    singleWriter.Flush();
                }
                else
                {
                    File.WriteAllText(filename + ".txt", decoded);
                }
                if (un.unknown.Length > 0)
                {
                    addText(workingDirectory + Environment.NewLine);
                    addText(un.unknown.ToString() + Environment.NewLine);
                }
            }
            catch (Exception e)
            {
                string err = Path.GetFileName(filename) + Environment.NewLine + "Error: " + e.ToString();
                // We, had an error but should still produce some kind of notice in the output.
                addText(err + Environment.NewLine);
                if (singleWriter != null)
                {
                    // Write the filename.
                    singleWriter.WriteLine(Path.GetFileName(filename));
                    // Write the decoded file.
                    singleWriter.WriteLine(decodeDone ? "Printer Error. " : "Decoder Error.");
                    singleWriter.WriteLine(err);
                }
                else
                {
                    File.WriteAllText(filename + ".txt", err);
                }
                return(false);
            }
            return(true);
        }
Exemple #12
0
        public void Run()
        {
            try
            {
                SendLowLevelVersionExchange();

                while (true)
                {
                    Thread.Sleep(1);
                    byte[] data  = null;
                    int    bytes = 0;

                    try
                    {
                        data  = new byte[socket.Available];
                        bytes = socket.Recv(data);
                    }
                    catch (SocketException ex)
                    {
                        if (ex.ErrorCode != 10035)
                        {
                            throw new DisconnectException();
                        }
                    }

                    if (bytes == -1)
                    {
                        // Disconnected
                        throw new DisconnectException();
                    }
                    else if (bytes > 0)
                    {
                        packetizer.QueuePackets(data, bytes);
                        int p = packetizer.ProcessPackets();

                        byte[] packet = null;

                        for (int i = 0; i < p; i++)
                        {
                            packet = packetizer.PopItem();
                            PyObject obj = Unmarshal.Process <PyObject>(packet);
                            PyObject res = Process(obj);

                            if (res != null)
                            {
                                Send(res);
                            }
                        }
                    }
                }
            }
            catch (DisconnectException)
            {
                Log.Error("Connection", "Connection closed");
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                Log.Error("Connection", "Unhandled exception... " + ex.Message);
                Log.Error("ExceptionHandler", "Stack trace: " + ex.StackTrace);
            }

            Program.waiting.Remove(this);
            if (forClose)
            {
                socket.Close();
            }
        }
Exemple #13
0
        private bool process(string filename, StreamWriter singleWriter)
        {
            // Does the file exist?
            if (!File.Exists(filename))
            {
                // No, fail!
                return(false);
            }
            byte[] data = null;
            using (var f = File.Open(filename, FileMode.Open))
            {
                if (f.Length == 0)
                {
                    if (singleWriter != null)
                    {
                        // Write the filename.
                        singleWriter.WriteLine(Path.GetFileName(filename));
                        // Write the decoded file.
                        singleWriter.WriteLine("Zero Length file.");
                    }
                    return(true);
                }
                data = new byte[f.Length];
                f.Read(data, 0, (int)f.Length);
                f.Close();
            }
            if (data == null)
            {
                // No data loaded.
                return(false);
            }
            // Is this a compressed file?
            if (data[0] == ZlibMarker)
            {
                // Yes, decompress it.
                data = Zlib.Decompress(data);
                if (data == null)
                {
                    // Decompress failed.
                    return(false);
                }
            }
            // Is this a proper python serial stream?
            if (data[0] != HeaderByte)
            {
                // No, is this a python file? If yes, ignore it but dont cause an error.
                return(data[0] == PythonMarker);
            }
            bool decodeDone = false;

            try
            {
                Unmarshal un  = new Unmarshal();
                PyRep     obj = un.Process(data);
                decodeDone = true;
                obj        = analyse(obj, filename);
                string decoded = PrettyPrinter.Print(obj);
                if (singleWriter != null)
                {
                    // Write the filename.
                    singleWriter.WriteLine(Path.GetFileName(filename));
                    // Write the decoded file.
                    singleWriter.Write(decoded);
                    singleWriter.Flush();
                }
                else
                {
                    File.WriteAllText(filename + ".txt", decoded);
                }
                if (un.unknown.Length > 0)
                {
                    addText(workingDirectory + Environment.NewLine);
                    addText(un.unknown.ToString() + Environment.NewLine);
                }
            }
            catch (Exception e)
            {
                string err = Path.GetFileName(filename) + Environment.NewLine + "Error: " + e.ToString();
                // We, had an error but should still produce some kind of notice in the output.
                addText(err + Environment.NewLine);
                if (singleWriter != null)
                {
                    // Write the filename.
                    singleWriter.WriteLine(Path.GetFileName(filename));
                    // Write the decoded file.
                    singleWriter.WriteLine(decodeDone ? "Printer Error. " : "Decoder Error.");
                    singleWriter.WriteLine(err);
                }
                else
                {
                    File.WriteAllText(filename + ".txt", err);
                }
                return(false);
            }
            return(true);
        }
Exemple #14
0
        public void ReceiveAuthAsync(IAsyncResult ar)
        {
            try
            {
                AsyncState state = (AsyncState)(ar.AsyncState);

                int bytes = Socket.Socket.EndReceive(ar);

                packetizer.QueuePackets(state.buffer, bytes);
                int p = packetizer.ProcessPackets();

                for (int i = 0; i < p; i++)
                {
                    try
                    {
                        byte[] packet = packetizer.PopItem();

                        PyObject obj = Unmarshal.Process <PyObject>(packet);

                        if (obj != null)
                        {
                            PyObject result = TCPHandler.ProcessAuth(obj, this);

                            if (result != null)
                            {
                                Send(result);
                            }

                            if (StageEnded == true)
                            {
                                if (Type == ConnectionType.Node)
                                {
                                    recvAsync = new AsyncCallback(ReceiveNodeAsync);
                                }
                                else if (Type == ConnectionType.Client)
                                {
                                    recvAsync = new AsyncCallback(ReceiveClientAsync);
                                }

                                // Exit from the loop to keep the packets in the list ;)
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Connection", ex.ToString());
                    }
                }

                // Continue receiving data
                Socket.Socket.BeginReceive(state.buffer, 0, 8192, SocketFlags.None, recvAsync, state);
            }
            catch (ObjectDisposedException)
            {
                Log.Debug("Connection", "Disconnected");
                ConnectionManager.RemoveConnection(this);
            }
            catch (SocketException)
            {
                Log.Debug("Connection", "Disconnected");
                ConnectionManager.RemoveConnection(this);
            }
            catch (Exception ex)
            {
                Log.Error("Connection", "Caught unhandled exception: " + ex.ToString());
            }
        }
Exemple #15
0
        public void ReceiveClientAsync(IAsyncResult ar)
        {
            try
            {
                AsyncState state = (AsyncState)(ar.AsyncState);

                int bytes = Socket.Socket.EndReceive(ar);

                packetizer.QueuePackets(state.buffer, bytes);
                int p = packetizer.ProcessPackets();

                for (int i = 0; i < p; i++)
                {
                    byte[]   actual = packetizer.PopItem();
                    PyObject obj    = Unmarshal.Process <PyObject>(actual);

                    if (obj == null)
                    {
                        continue;
                    }

                    if (obj is PyObjectEx)
                    {
                        // PyException
                        Log.Error("Client", "Got exception from client");
                    }
                    else
                    {
                        PyPacket packet = new PyPacket();

                        if (packet.Decode(obj) == false)
                        {
                            Log.Error("Client", "Error decoding PyPacket");
                        }
                        else
                        {
                            if (packet.dest.type == PyAddress.AddrType.Node)
                            {
                                if (packet.source.type != PyAddress.AddrType.Client)
                                {
                                    Log.Error("Client", string.Format("Wrong source data, expected client but got {0}", packet.source.type));
                                }

                                // Notify the node, be careful here, the client will be able to send packets to game clients
                                if (packet.dest.typeID == 0xFFAA)
                                {
                                    Log.Warning("Client", "Sending packet to proxy");
                                    ConnectionManager.NotifyNode((int)(packet.dest.typeID), obj);
                                }
                                else
                                {
                                    ConnectionManager.NotifyNode((int)(packet.dest.typeID), obj);
                                }
                            }
                        }
                    }
                }

                Socket.Socket.BeginReceive(state.buffer, 0, 8192, SocketFlags.None, recvAsync, state);
            }
            catch (ObjectDisposedException)
            {
                Log.Debug("Client", "Disconnected");
                ConnectionManager.RemoveConnection(this);
            }
            catch (SocketException)
            {
                Log.Debug("Client", "Disconnected");
                ConnectionManager.RemoveConnection(this);
            }
            catch (Exception ex)
            {
                Log.Error("Client", "Caught unhandled exception: " + ex.ToString());
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            Log.Init("evesharp");
            Log.Info("Main", "Starting node...");
            Log.Trace("Database", "Connecting to database...");

            if (Database.Database.Init() == false)
            {
                Log.Error("Main", "Cannot connect to database");
                while (true)
                {
                    ;
                }
            }

            /*
             * DBRowDescriptor descriptor = new DBRowDescriptor();
             *
             * descriptor.AddColumn("itemID", FieldType.I4);
             * descriptor.AddColumn("custominfo", FieldType.Str);
             *
             * PyPackedRow packed = new PyPackedRow(descriptor);
             *
             * packed.SetValue("itemID", new PyInt(500));
             * packed.SetValue("custominfo", new PyString("hello world"));
             *
             * byte[] marshaled = Marshal.Marshal.Process(packed);
             *
             * PyPackedRow unmarshaled = Unmarshal.Process<PyPackedRow>(marshaled);
             *
             * Console.WriteLine(PrettyPrinter.Print(unmarshaled));
             */

            byte[] raw = new byte[] { 1, 0, 55, 1, 22, 33, 0, 33, 25, 33, 14, 0, 0, 25, 45 };

            MemoryStream output = new MemoryStream(raw);
            BinaryReader reader = new BinaryReader(output);

            MemoryStream stream       = new MemoryStream();
            BinaryWriter streamWriter = new BinaryWriter(stream);
            BinaryReader streamReader = new BinaryReader(stream);

            PyPackedRow.ZeroCompress(reader, output, streamWriter);

            byte[] compressed = stream.ToArray();
            stream.Seek(0, SeekOrigin.Begin);

            byte[] uncompress = PyPackedRow.LoadZeroCompressed(streamReader);

            while (true)
            {
                Thread.Sleep(1);
            }

            /*
             * SHA1 sha1 = SHA1.Create();
             * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password"));
             * char[] strHash = new char[20];
             *
             * for (int i = 0; i < 20; i++)
             * {
             *  strHash[i] = (char)hash[i];
             * }
             *
             * string str = new string(strHash);
             *
             * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);");
             */

            Log.Info("Main", "Connection to the DB sucessfull");

            Log.Trace("Main", "Registering services...");

            SvcMgr.AddService(new Services.Network.machoNet());
            SvcMgr.AddService(new Services.Network.alert());
            SvcMgr.AddService(new Services.CacheSvc.objectCaching());

            Log.Info("Main", "Done");
            Log.Info("Main", "Connecting to proxy...");

            proxyConnection = new TCPSocket(ushort.Parse(proxy[0, 1]), false);
            if (proxyConnection.Connect(proxy[0, 0]) == false)
            {
                Log.Error("Main", "Cannot connect to proxy. Halting");
                Database.Database.Stop();
                while (true)
                {
                    ;
                }
            }

            Log.Trace("Main", "Server started");

            while (true)
            {
                Thread.Sleep(1);
                try
                {
                    byte[] data  = new byte[proxyConnection.Available];
                    int    bytes = proxyConnection.Recv(data);

                    if (bytes == -1)
                    {
                        // Proxy is closing, shutdown the node
                        break;
                    }
                    else if (bytes > 0)
                    {
                        packetizer.QueuePackets(data, bytes);
                        int p = packetizer.ProcessPackets();

                        for (int i = 0; i < p; i++)
                        {
                            byte[]   packet = packetizer.PopItem();
                            PyObject obj    = Unmarshal.Process <PyObject>(packet);

                            if (obj is PyObjectData)
                            {
                                PyObjectData info = obj as PyObjectData;

                                if (info.Name == "machoNet.nodeInfo")
                                {
                                    // Update our local info
                                    NodeInfo nodeinfo = new NodeInfo();

                                    if (nodeinfo.Decode(info) == true)
                                    {
                                        nodeID = nodeinfo.nodeID;

                                        SystemManager.LoadSolarSystems(nodeinfo.solarSystems);
                                    }
                                }
                                else
                                {
                                    // Client packet
                                    PyPacket clientpacket = new PyPacket();

                                    if (clientpacket.Decode(info) == false)
                                    {
                                        Log.Error("Main", "Unknown packet");
                                    }
                                    else
                                    {
                                        // Something similar to Async calls
                                        new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket);
                                    }
                                }
                            }
                            else if (obj is PyChecksumedStream) // Checksumed packets
                            {
                                PyPacket clientpacket = new PyPacket();

                                if (clientpacket.Decode(obj) == false)
                                {
                                    Log.Error("Main", "Cannot decode packet");
                                }
                                else
                                {
                                    new Thread(new ParameterizedThreadStart(HandlePacket)).Start(clientpacket);
                                }
                            }
                            else if (obj is PyTuple)
                            {
                                // The only tuple packet is the LowLevelVersionExchange
                                LowLevelVersionExchange ex = new LowLevelVersionExchange();

                                if (ex.Decode(obj) == false)
                                {
                                    Log.Error("Main", "LowLevelVersionExchange error");
                                }

                                // Reply with the node LowLevelVersionExchange
                                LowLevelVersionExchange reply = new LowLevelVersionExchange();

                                reply.codename     = Common.Constants.Game.codename;
                                reply.birthday     = Common.Constants.Game.birthday;
                                reply.build        = Common.Constants.Game.build;
                                reply.machoVersion = Common.Constants.Game.machoVersion;
                                reply.version      = Common.Constants.Game.version;
                                reply.region       = Common.Constants.Game.region;

                                Send(reply.Encode(true));
                            }
                            else if (obj is PyObjectEx)
                            {
                                Log.Error("PyObjectEx", PrettyPrinter.Print(obj));
                            }
                            else
                            {
                                Log.Error("Main", PrettyPrinter.Print(obj));
                                Log.Error("Main", "Unhandled packet type");
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            /* Code to ADD an account:
             * SHA1 sha1 = SHA1.Create();
             * byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("password"));
             * char[] strHash = new char[20];
             *
             * for (int i = 0; i < 20; i++)
             * {
             *  strHash[i] = (char)hash[i];
             * }
             *
             * string str = new string(strHash);
             *
             * Database.Database.Query("INSERT INTO account(accountID, accountName, password, role, online, banned)VALUES(NULL, 'Username', '" + str + "', 2, 0, 0);");
             */
        }
Exemple #17
0
        public void Run()
        {
            while (true)
            {
                Thread.Sleep(1);

                try
                {
                    byte[] data  = new byte[socket.Available];
                    int    bytes = socket.Recv(data);

                    if (bytes == -1)
                    {
                        throw new DisconnectException();
                    }
                    else if (bytes > 0)
                    {
                        packetizer.QueuePackets(data, bytes);
                        int p = packetizer.ProcessPackets();

                        for (int i = 0; i < p; i++)
                        {
                            byte[]   packet = packetizer.PopItem();
                            PyObject obj    = Unmarshal.Process <PyObject>(packet);

                            if (obj.Type == PyObjectType.ObjectData)
                            {
                                Log.Warning("Node", PrettyPrinter.Print(obj));
                                PyObjectData item = obj as PyObjectData;

                                if (item.Name == "macho.CallRsp")
                                {
                                    PyPacket final = new PyPacket();

                                    if (final.Decode(item) == true)
                                    {
                                        if (final.dest.type == PyAddress.AddrType.Client)
                                        {
                                            try
                                            {
                                                ClientManager.NotifyClient((int)final.userID, obj);
                                            }
                                            catch (Exception)
                                            {
                                                Log.Error("Node", "Trying to send a packet to a non-existing client");
                                            }
                                        }
                                        else if (final.dest.type == PyAddress.AddrType.Node)
                                        {
                                            NodeManager.NotifyNode((int)final.dest.typeID, obj);
                                        }
                                        else if (final.dest.type == PyAddress.AddrType.Broadcast)
                                        {
                                            // This should not be coded like this here, but will do the trick for now
                                            // TODO: Add a ClientManager
                                            ClientManager.NotifyClients(obj);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Log.Error("Node", "Unknown type");
                            }
                        }
                    }
                }
                catch (SocketException ex)
                {
                    if (ex.ErrorCode != 10035)
                    {
                        break;
                    }
                }
                catch (DisconnectException)
                {
                    Log.Error("Node", "Node " + NodeManager.GetNodeID(this) + " disconnected");
                    break;
                }
                catch (Exception)
                {
                }
            }
        }