Ejemplo n.º 1
0
 public string OpenDatabase(string name, string key, string iv)
 {
     if (isConnected == true)
     {
         AdvancedStream.SendMessage(ref Writer, $"L2KDB:Basic:OpenDatabase,{name},{key},{iv}|{sessionID}", aes);
         string content = AdvancedStream.ReadToCurrentEnd(ref Reader, aes);
         if (content == "L2KDB:Basic:DatabaseOpen")
         {
             return("[S]");
         }
         else if (content == "L2KDB:Basic:AccessForbidden")
         {
             return("[F]Access Forbidden");
         }
         else if (content == "L2KDB:Basic:DatabaseNoFound")
         {
             return("[F]NotFound");
         }
         else
         {
             return(content);
         }
     }
     return("[F]Unconnected");
 }
Ejemplo n.º 2
0
        private void ProcessHandshake(TcpClient request)
        {
            var          stream       = request.GetStream();
            StreamReader streamReader = new StreamReader(stream);
            var          str          = AdvancedStream.ReadToCurrentEnd(ref streamReader);
            var          req          = str.Split('|');

            if (req.Length > 2)
            {
                if (req[0] == "L2KDB:Basic:OpenSession")
                {
                    //Example
                    //L2KDB:Basic:OpenSession|CreeperLv|123456
                    Session session = new Session(request, streamReader, stream, Authentication.ObtainID(req[1], req[2]))
                    {
                    };
                    SessionPool.Add(session);
                }
            }
            else
            {
                StreamWriter streamWriter = new StreamWriter(stream);
                streamWriter.Write("HTTP/1.1 200 OK\r\nServer: L2KDB\r\nContent-Encoding: gzip\r\nContent-Type: text/html;charset=UTF-8\r\n\r\n<!DOCTYPE html>\r\n<html><head><title>L2KDB</title></head><body><p>Wrong Handshaking Protocol.</p></html>");
                Diagnotor.CurrentDiagnotor.LogWarning("[WRONG CLIENT]Sending Refuse.");
                streamWriter.Flush();
                streamWriter.Close();
            }
        }
Ejemplo n.º 3
0
        public string Connect(string ip, int port, string usr, string pwd)
        {
            var ips      = IPAddress.Parse(ip);
            var Endpoint = new IPEndPoint(ips, port);

            //tcpClient = new TcpClient(Endpoint);
            tcpClient.Connect(Endpoint);
            //tcpClient.Connect(ip, port);
            usrname  = usr;
            password = pwd;
            stream   = tcpClient.GetStream();
            Writer   = new StreamWriter(stream);
            Reader   = new StreamReader(stream);
            AdvancedStream.SendMessage(ref Writer, $"L2KDB:Basic:OpenSession|{usr}|{pwd}");
            string content   = AdvancedStream.ReadToCurrentEnd(ref Reader);
            var    Responses = content.Split(',');

            if (Responses[0] == "L2KDB:Basic:ConnectionAccept")
            {
                sessionID = Responses[1];
                aes       = new CustomedAES();

                aesKey      = Responses[2];
                aesIV       = Responses[3];
                aes.Key     = aesKey;
                aes.IV      = aesIV;
                isConnected = true;
                return("[S]");
            }
            else
            {
                return("[F]" + Responses[0]);
            }
        }
Ejemplo n.º 4
0
        public List <string> GetID2s(string id1)
        {
            List <string> vs = new List <string>();

            if (isConnected == true)
            {
                {
                    AdvancedStream.SendMessage(ref Writer, $"L2KDB:Basic:GetID2,{id1}|{sessionID}", aes);
                    var Command = aes.Decrypt(Reader.ReadLine());
                    var data    = AdvancedStream.ReadToCurrentEnd(ref Reader, aes, false);
                    if (Command == "L2KDB:Basic:DatabaseGetID2Result")
                    {
                        StringReader stringReader = new StringReader(data);
                        var          temp         = "";
                        while ((temp = stringReader.ReadLine()) != null)
                        {
                            if (temp == "L2KDB:Basic:NoID2")
                            {
                            }
                            else
                            {
                                vs.Add(temp);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("" + Command);
                    }
                }
                return(vs);
            }
            throw new Exception("Unconnected");
        }
Ejemplo n.º 5
0
 public void Stop(StopReason stopReason = StopReason.ShutdownServer)
 {
     willStop = true;
     try
     {
         AdvancedStream.SendMessage(ref Writer, "L2KDB:Basic:Stop," + stopReason.ToString(), CustomedAES);
     }
     catch (Exception)
     {
     }
     try
     {
         Reader.Dispose();
     }
     catch (Exception)
     {
     }
     try
     {
         Writer.Dispose();
     }
     catch (Exception)
     {
     }
     try
     {
         OriginalStream.Dispose();
     }
     catch (Exception)
     {
     }
     try
     {
         Client.Dispose();
     }
     catch (Exception)
     {
     }
     try
     {
         ServerCore.SessionPool.Remove(this);
     }
     catch (Exception)
     {
     }
     System.GC.Collect();
 }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient();

            client.Connect("127.0.0.1", 9341);
            var          s            = client.GetStream();
            StreamWriter streamWriter = new StreamWriter(s);
            {
                AdvancedStream.SendMessage(ref streamWriter, "L2KDB:Basic:OpenSession|Creeper Lv|123456\r\nL2KDB:Basic:EndOfCurrentTransmission");
                //streamWriter.Flush();
            }
            String       SessionID    = "";
            String       Key          = "";
            String       IV           = "";
            CustomedAES  aes          = new CustomedAES();
            StreamReader streamReader = new StreamReader(s);
            {
                string receive; receive = AdvancedStream.ReadToCurrentEnd(ref streamReader);
                Console.WriteLine(receive);
                var blocks = receive.Split(':');
                if (blocks[2].StartsWith("ConnectionAccept"))
                {
                    var c = blocks[2].Split(',');
                    SessionID = c[1];
                    Key       = c[2];
                    IV        = c[3];
                    aes.Key   = Key;
                    aes.IV    = IV;
                    Console.WriteLine($"Obtain:{SessionID}\t{Key}\t{IV}");
                    {
                        AdvancedStream.SendMessage(ref streamWriter, "L2KDB:Basic:GetDatabaseVersion|" + SessionID, aes);
                        Console.WriteLine(AdvancedStream.ReadToCurrentEnd(ref streamReader, aes));
                    }
                    {
                        AdvancedStream.SendMessage(ref streamWriter, "L2KDB:Basic:OpenDatabase,TestDataBase,,|" + SessionID, aes);
                        Console.WriteLine(AdvancedStream.ReadToCurrentEnd(ref streamReader, aes));
                    }
                }
                else
                {
                }
            }
            //Console.WriteLine("Hello World!");
        }
Ejemplo n.º 7
0
 public string Query(string id1, string id2, string content)
 {
     if (isConnected == true)
     {
         {
             AdvancedStream.SendMessage(ref Writer, $"L2KDB:Basic:Query,{id1},{id2}|{sessionID}", aes);
             var Command = aes.Decrypt(Reader.ReadLine());
             var data    = AdvancedStream.ReadToCurrentEnd(ref Reader, aes, false);
             if (Command == "L2KDB:Basic:DatabaseQueryResult")
             {
                 return(data);
             }
             else
             {
                 throw new Exception("" + Command);
             }
         }
     }
     throw new Exception("Unconnected");
 }
Ejemplo n.º 8
0
 public string OpenForm(string name)
 {
     if (isConnected == true)
     {
         AdvancedStream.SendMessage(ref Writer, $"L2KDB:Basic:OpenForm,{name}|{sessionID}", aes);
         string content = AdvancedStream.ReadToCurrentEnd(ref Reader, aes);
         if (content == "L2KDB:Basic:FromOpen")
         {
             return("[S]");
         }
         else if (content == "L2KDB:Basic:UnknownError")
         {
             return("[F]An Error Has Occurred On Server");
         }
         else
         if (content == "L2KDB:Basic:AccessForbidden")
         {
             return("[F]Access Forbidden");
         }
     }
     return("[F]Unconnected");
 }
Ejemplo n.º 9
0
        // Get packet data length. (Packet protocol requires us to know the length before we write the packet)
        public override int getLength(AdvancedStream s)
        {
            int dataLength = 0;

            if (data != null)
            {
                for (int i = 0; i < data.Length; i++)
                {
                    Data d = data[i];
                    dataLength += s.getLengthVarInt(d.name.Length) + d.name.Length;
                    dataLength += s.getLengthVarInt(d.value.Length) + d.value.Length;
                    dataLength += s.getLengthVarInt(d.signature.Length) + d.signature.Length;
                }
            }

            int metaDataLength = 0;

            foreach (MetaData metadata in metaDatas)
            {
                metaDataLength += metadata.getLength(s) + 1;
            }

            metaDataLength += 1; // end

            return
                (+s.getLengthVarInt(entitiyId)                          // entitiyId
                 + s.getLengthVarInt(uuid.Length) + uuid.Length         // uuid
                 + s.getLengthVarInt(username.Length) + username.Length // username
                 + s.getLengthVarInt(dataCount)                         // dataCount
                 + dataLength                                           // data
                 + 4                                                    // x
                 + 4                                                    // y
                 + 4                                                    // z
                 + 1                                                    // yaw
                 + 1                                                    // pitch
                 + 2                                                    // curItem
                 + metaDataLength                                       // metaDatas
                );
        }
Ejemplo n.º 10
0
        // Write packet data.
        public override bool Write(AdvancedStream s)
        {
            s.WriteVarInt(entitiyId);
            s.WriteString(uuid);
            s.WriteString(username);
            s.WriteVarInt(dataCount);

            if (data != null)
            {
                for (int i = 0; i < data.Length; i++)
                {
                    s.WriteString(data[i].name);
                    s.WriteString(data[i].value);
                    s.WriteString(data[i].signature);
                }
            }

            s.WriteInt((int)(x * 32.0));
            s.WriteInt((int)(y * 32.0));
            s.WriteInt((int)(z * 32.0));
            s.WriteByte((byte)(256.0f / 360.0f * (this.yaw % 360.0f)));
            s.WriteByte((byte)(256.0f / 360.0f * (this.pitch % 360.0f)));
            s.WriteShort(curItem);

            // meta data
            foreach (MetaData metadata in metaDatas)
            {
                // header
                s.WriteByte((byte)((metadata.type << 5) + metadata.index));
                // data
                metadata.Write(s);
            }

            // end
            s.WriteByte(127);

            return(false);
        }
Ejemplo n.º 11
0
 public string  Save(string id1, string id2, string content)
 {
     if (isConnected == true)
     {
         {
         }
         AdvancedStream.SendMessage(ref Writer, $"L2KDB:Basic:Save,{id1},{id2}|{sessionID}", content, aes);
         string result = AdvancedStream.ReadToCurrentEnd(ref Reader, aes);
         if (result == "L2KDB:Basic:OperationCompleted")
         {
             return("[S]");
         }
         else if (result == "L2KDB:Basic:UnknownError")
         {
             return("[F]An Error Has Occurred On Server");
         }
         else
         if (result == "L2KDB:Basic:AccessForbidden")
         {
             return("[F]Access Forbidden");
         }
     }
     return("[F]Unconnected");
 }
Ejemplo n.º 12
0
        public async void SessionWorker()
        {
            SessionID = Guid.NewGuid();
            Diagnotor.CurrentDiagnotor.Log("Session Opened:" + SessionID + ", AuthID=" + AuthID);
            SessionKey      = CustomedAES.GenerateKey();
            SessionIV       = CustomedAES.GenerateIV();
            CustomedAES.Key = SessionKey;
            CustomedAES.IV  = SessionIV;
            int ExceptionOccurred = 0;

            AdvancedStream.SendMessage(ref Writer, "L2KDB:Basic:ConnectionAccept," + SessionID.ToString() + $",{SessionKey},{SessionIV}");
            while (willStop == false)
            {
                try
                {
                    var Command = CustomedAES.Decrypt(await Reader.ReadLineAsync());
                    var data    = AdvancedStream.ReadToCurrentEnd(ref Reader, CustomedAES, false);

                    /**
                     * Data Structure:
                     * [Command]|[SessionID]|[Key(Optional)]|[IV(Optional)]
                     * [Cont...
                     * en...
                     * t]
                     **/
                    Diagnotor.CurrentDiagnotor.Log($"Command from {SessionID}:" + Command);

                    var cmd = Command.Split('|');
                    if (cmd[1] != SessionID.ToString())
                    {
                        Stop(StopReason.Unknown);
                    }

                    var result = CmdletProcesser(cmd, data);
                    if (result != "-1")
                    {
                        AdvancedStream.SendMessage(ref Writer, $"{result}", CustomedAES);
                    }
                }
                catch (Exception e)
                {
                    if (e.GetType() == typeof(SocketException))
                    {
                        Diagnotor.CurrentDiagnotor.Log($"Shutting {SessionID} Down.");

                        Stop();
                        break;
                    }
                    else if (e.GetType() == typeof(IOException))
                    {
                        Diagnotor.CurrentDiagnotor.Log($"Shutting {SessionID} Down.");
                        Stop();
                        break;
                    }
                    else
                    {
                        ExceptionOccurred++;
                        Diagnotor.CurrentDiagnotor.LogWarning("Captured:" + e.Message);
                        if (ExceptionOccurred >= 100)
                        {
                            Diagnotor.CurrentDiagnotor.LogError($"Session:{SessionID} occurred too many errors, force to shutdown.");
                            Stop();
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
 public void SendData(string title, String Data)
 {
     AdvancedStream.SendMessage(ref Writer, title, Data, CustomedAES);
 }
Ejemplo n.º 14
0
 public async Task SendDataAsync(string Data)
 {
     AdvancedStream.SendMessage(ref Writer, Data, CustomedAES);
 }