// TODO: logging
        public static async Task Ban(SausageConnection user)
        {
            try
            {
                if (!(user.Socket.Connected || MainSocket.Connected))
                {
                    return;
                }
                // user exists
                if (ConnectedUsers.Any(x => x.UserInfo.Guid == user.UserInfo.Guid))
                {
                    Blacklisted.Add(user.Ip.Address);
                    PacketFormat packet = new PacketFormat(PacketOption.UserBanned)
                    {
                        Guid    = user.UserInfo.Guid,
                        Content = "Place-holder reason"
                    };
                    Log(packet);
                    await Task.Delay(1000);

                    // delay for waiting on the client to recieve a message
                    user.Disconnect();
                    UiCtx.Send(x => ConnectedUsers.Remove(user));
                }
                else
                {
                    MessageBox.Show("User not found", "Ban result");
                }
            }
            catch (ArgumentNullException e)
            {
                MessageBox.Show($"User returned null {e}", "Exception Caught");
            }
        }
Exemple #2
0
    public bool Init()
    {
        // 文件位置
        if (Application.isEditor)
        {
            Framework.Instance.SetWritableRootDir(Application.temporaryCachePath);
            Framework.Instance.SetStreamAssetsRootDir(Application.streamingAssetsPath);
        }
        else
        {
            Framework.Instance.SetWritableRootDir(Application.temporaryCachePath);
            Framework.Instance.SetStreamAssetsRootDir(Application.streamingAssetsPath);
        }

        // console输出
        LoggerSystem.Instance.SetConsoleLogger(new Alkaid.Logger(UnityEngine.Debug.Log));

        // 网络
        PacketFormat         pf = new PacketFormat();
        PacketHandlerManager pm = new PacketHandlerManager();

        NetSystem.Instance.RegisterConnector((int)NetCtr.Lobby, ConnectionType.TCP, pf, pm, ConnectedCallback, null, DisConnectedCallback, null);
//		NetSystem.Instance.RegisterConnector((int)NetCtr.Room, ConnectionType.TCP, pf, pm, conne)

        return(Framework.Instance.Init());
    }
        // TODO: make a switch for the user messge (some packets don't have content)
        public async static Task Log(PacketFormat message, SausageConnection ignore = null)
        {
            if (message.Option == PacketOption.ClientMessage)
            {
                UiCtx.Send(x => Vm.Messages.Add(new UserMessage(message.Content, UsersDictionary[message.Guid])));
            }
            else
            {
                switch (message.Option)
                {
                case PacketOption.NameChange:
                    UiCtx.Send(x => Vm.Messages.Add(
                                   new ServerMessage($"{UsersDictionary[message.Guid]} changed their name to {message.NewName}")));
                    break;

                default:
                    UiCtx.Send(x => Vm.Messages.Add(new ServerMessage(message.Content)));
                    break;
                }
            }

            foreach (var user in ConnectedUsers)
            {
                if (user != ignore)
                {
                    user.SendAsync(JsonConvert.SerializeObject(message));
                }
            }
        }
Exemple #4
0
        public static bool ReceiveUpdates(out PacketFormat packet, out IPEndPoint remoteep)
        {
            //buffer = null; //2015.03.28.
            packet   = null;
            remoteep = null; //2015.03.28.

            IPEndPoint remoteEP;

            remoteEP = new IPEndPoint(IPAddress.Any, CurrentUser.Port); //2015.05.24.
            byte[] buf;
            try
            {
                buf = ReceiverConnection.Receive(ref remoteEP);
            }
            catch
            {
                return(false); //2015.03.28.
            }
            PacketFormat pf = PacketFormat.FromBytes(buf);

            if (pf.Response)
            {
                if (Senders.ContainsKey(pf.ID))
                {
                    Senders[pf.ID].OnReceiveResponse(pf, remoteEP);
                }
                return(false);
            }
            else
            {
                packet   = pf;
                remoteep = remoteEP;
                return(true);
            }
        }
 public static async Task Mute(SausageConnection user)
 {
     try
     {
         // user exists
         if (ConnectedUsers.Any(x => x.UserInfo.Guid == user.UserInfo.Guid))
         {
             PacketFormat packet = new PacketFormat(PacketOption.UserMuted)
             {
                 Guid    = user.UserInfo.Guid,
                 Content = "Place-holder reason"
             };
             user.UserInfo.IsMuted = true;
             await Log(packet);
         }
         else
         {
             MessageBox.Show("User not found", "Kick result");
         }
     }
     catch (ArgumentNullException e)
     {
         MessageBox.Show($"User returned null {e}", "Exception Caught");
     }
 }
Exemple #6
0
        private static void BanKickMuteWrapper(Guid guid, PacketOption option, string Reason = null)
        {
            if (!ClientInfo.IsAdmin)
            {
                return;
            }
            PacketFormat packet;

            if (option != PacketOption.UserUnmuted)
            {
                if (Reason == null)
                {
                    Reason = "Place Holder Reason";
                }
                packet = new PacketFormat(option)
                {
                    Sender  = ClientInfo.Guid,
                    Guid    = guid,
                    Content = Reason
                };
            }
            else
            {
                packet = new PacketFormat(PacketOption.UserUnmuted)
                {
                    Sender = ClientInfo.Guid,
                    Guid   = guid
                };
            }
            Send(packet);
        }
Exemple #7
0
            public static PacketFormat FromBytes(byte[] bytes)
            {
                MemoryStream ms         = new MemoryStream(bytes);
                BinaryReader br         = new BinaryReader(ms);
                int          id         = br.ReadInt32();
                bool         response   = br.ReadBoolean();
                UpdateType   packettype = (UpdateType)br.ReadByte();
                int          keyindex   = br.ReadInt32();
                int          port       = br.ReadInt32();

                byte[] ebytes = new byte[ms.Length - ms.Position];
                br.Read(ebytes, 0, ebytes.Length);
                byte[] uebytes;
                if (CurrentUser.Keys.Length > keyindex && CurrentUser.Keys[keyindex] != null)
                {
                    uebytes = Storage.Decrypt(ebytes, true, CurrentUser.Keys[keyindex]);
                }
                else
                {
                    uebytes = Storage.Decrypt(ebytes, true, "ihavenokeys");
                }
                MemoryStream ems    = new MemoryStream(uebytes);
                BinaryReader ebr    = new BinaryReader(ems);
                int          userid = ebr.ReadInt32();
                PacketData   data   = (PacketData)Activator.CreateInstance(PacketData.PacketDataTypes[packettype], true);

                data.Response = response; //2015.04.03.
                data.FromBytes(uebytes);
                PacketFormat pf = new PacketFormat(response, keyindex, port, userid, data, id);

                return(pf);
            }
Exemple #8
0
        private void ContextMenuAdmin_Click(object sender, RoutedEventArgs e)
        {
            PacketFormat packet = new PacketFormat(PacketOption.AdminPermsRecieved)
            {
                Guid = SausageServer.Vm.SelectedUser.UserInfo.Guid
            };

            SausageServer.Log(packet);
        }
 public void OnReceiveResponse(PacketFormat response, IPEndPoint remoteep)
 {
     lock (Lock)
     {
         Response = response;
         RemoteEP = remoteep;
         Monitor.Pulse(Lock);
     }
 }
Exemple #10
0
        // the server will return the rename message thus no need for logging (in client)
        public static void Rename(string newName)
        {
            UsersList[ClientInfo.Guid].Name = newName;
            PacketFormat packet = new PacketFormat(PacketOption.NameChange)
            {
                Guid    = ClientInfo.Guid,
                NewName = newName
            };

            Send(packet);
        }
Exemple #11
0
        // Needs implementation
        public static void AddFriend(Guid guid)
        {
            PacketFormat packet = new PacketFormat(PacketOption.FriendRequest)
            {
                Sender = ClientInfo.Guid,
                Guid   = guid,
            };

            Send(packet);
            Log(new ServerMessage("Friend request sent"));
        }
Exemple #12
0
        private void Send_message_Button_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(User_Message_client_Copy.Text))
            {
                PacketFormat packet = new PacketFormat(PacketOption.ClientMessage)
                {
                    Guid    = SausageClient.ClientInfo.Guid,
                    Content = User_Message_client_Copy.Text
                };
                SausageClient.Send(packet);

                User_Message_client_Copy.Text = string.Empty;
            }
        }
Exemple #13
0
 private void User_Message_client_Copy_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         // send the message
         PacketFormat packet = new PacketFormat(PacketOption.ClientMessage)
         {
             Guid    = SausageClient.ClientInfo.Guid,
             Content = User_Message_client_Copy.Text
         };
         SausageClient.Send(packet);
         // reset the text box
         User_Message_client_Copy.Text = string.Empty;
     }
 }
Exemple #14
0
        public PacketHandler(byte[] _packet)
        {
            // try handler packet
            if (!handlerPacket(_packet))
            {
                invalidData = "";
                for (int i = 0; i < _packet.Length; i++)
                {
                    invalidData += _packet[i] + " ";
                }

                _format = new PacketFormat("???");
                _packet = new byte[] { };
            }
        }
        // TODO: Add user list
        public static void OnUserConnect(IAsyncResult ar)
        {
            SausageConnection user;

            try
            {
                user = new SausageConnection(MainSocket.EndAccept(ar));
            }
            catch (SocketException ex)
            {
                Close();
                return;
            }
            catch (ObjectDisposedException ex)
            {
                return;
            }
            if (!Blacklisted.Any(x => x == user.Ip.Address))
            {
                UiCtx.Send(x => ConnectedUsers.Add(user));
                UiCtx.Send(x => Vm.ConnectedUsers = SortUsersList());
                UiCtx.Send(x => Vm.Messages.Add(new ServerMessage($"{user} has connected")));
                UiCtx.Send(x => Mw.AddTextToDebugBox($"User connected on {user.Ip}\n"));
                // global packet for all the users to know the user has joined
                PacketFormat GlobalPacket = new PacketFormat(PacketOption.UserConnected)
                {
                    Guid    = user.UserInfo.Guid,
                    NewName = user.UserInfo.Name
                };
                // local packet for the user (who joined) to get his GUID
                PacketFormat LocalPacket = new PacketFormat(PacketOption.GetGuid)
                {
                    Guid      = user.UserInfo.Guid,
                    UsersList = UsersDictionary.ToArray()
                };
                UsersDictionary.Add(user.UserInfo);
                user.SendAsync(LocalPacket);
                Log(GlobalPacket, user);
            }
            else
            {
                // doesn't log if the user is blacklisted
                user.Disconnect();
            }
            MainSocket.BeginAccept(OnUserConnect, null);
        }
 /// <summary>
 /// PacketSender
 /// </summary>
 /// <param name="data">PacketData</param>
 /// <param name="respid">Response ID</param>
 public PacketSender(PacketData data, int respid = -1)
 {
     if (NextID >= Int32.MaxValue)
     {
         NextID = 0;
     }
     if (respid == -1)
     {
         ID = NextID++;
     }
     else
     {
         ID = respid;
     }
     Packet = new PacketFormat(respid != -1, data, ID);
     if (respid == -1)
     {
         Senders.Add(ID, this);
     }
 }
        public static PacketFormat ExplainRxPacket(byte[] rxBuf)
        {
            PacketFormat rxData = new PacketFormat();

            try
            {
                int index = 0;
                rxData.Header   = rxBuf[index++];
                rxData.Length   = rxBuf[index++] + rxBuf[index++] * 256;
                rxData.CtrlWord = rxBuf[index++];
                if ((rxData.CtrlWord & 0x20) == 0x20)
                {
                    rxData.SrcAddr = new byte[LongAddrSize];
                    Array.Copy(rxBuf, index, rxData.SrcAddr, 0, LongAddrSize);
                    index         += LongAddrSize;
                    rxData.DstAddr = new byte[LongAddrSize];
                    Array.Copy(rxBuf, index, rxData.DstAddr, 0, LongAddrSize);
                    index += LongAddrSize;
                }
                else
                {
                    rxData.SrcAddr = null;
                    rxData.DstAddr = null;
                }
                rxData.Afn      = (Afn)(rxBuf[index++]);
                rxData.SerialNo = rxBuf[index++];
                rxData.DataId   = new byte[4];
                Array.Copy(rxBuf, index, rxData.DataId, 0, rxData.DataId.Length);
                index         += rxData.DataId.Length;
                rxData.DataBuf = new byte[rxData.Length - index - 2];
                Array.Copy(rxBuf, index, rxData.DataBuf, 0, rxData.DataBuf.Length);
                index      += rxData.DataBuf.Length;
                rxData.Crc8 = rxBuf[index++];
                rxData.Tail = rxBuf[index++];
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据解析错误" + ex.Message);
            }
            return(rxData);
        }
Exemple #18
0
 public static void Send(PacketFormat packet) => Send(JsonConvert.SerializeObject(packet));
            private PacketFormat[] SendUpdate(IPEndPoint onlythisep = null)
            {
                if (Program.MainF != null && Program.MainF.IsHandleCreated)
                {
                    if (Program.MainF.InvokeRequired)
                    {
                        Program.MainF.Invoke(new Action <MainForm.StatType, int>(Program.MainF.UpdateStats),
                                             MainForm.StatType.Servers, UserInfo.IPs.Count);
                        Program.MainF.Invoke(new Action <MainForm.StatType, int>(Program.MainF.UpdateStats),
                                             MainForm.StatType.OnlineServers, UserInfo.IPs.Count - UserInfo.BannedIPs.Count);
                    }
                    else
                    {
                        MessageBox.Show("Internal error: Network call was made in the same thread as the UI. This could lead to freezes.\nNetwork update canceled.");
                        return(null);
                    }
                }
                if ((UserInfo.IPs.Count == 0 ||
                     (RemoteEP == null) ? false : !UserInfo.IPs.Any(entry => entry.Address.Equals(RemoteEP.Address))) && //<-- 2015.06.16.
                    Packet.PacketType != Networking.UpdateType.LoginUser)
                {
                    return(null);
                }
                byte[] senddata = Packet.ToBytes();
                if (UserInfo.BanTime < Environment.TickCount - 1000 * 10)
                {
                    UserInfo.BannedIPs = new List <IPEndPoint>();
                }
                if (onlythisep == null)
                {
                    foreach (var item in UserInfo.IPs)
                    { //Elküldi az összes ismert címre
                        try
                        {
                            if (!UserInfo.BannedIPs.Contains(item))
                            {
                                SenderConnection.Send(senddata, senddata.Length, item);
                            }
                        }
                        catch (ObjectDisposedException)
                        {
                            return(null);
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show("Network error:\n" + e.Message + "\n\n" + e.StackTrace);
                        }
                    }
                }
                else
                {
                    try
                    {
                        SenderConnection.Send(senddata, senddata.Length, onlythisep);
                    }
                    catch (ObjectDisposedException)
                    {
                        return(null);
                    }
                }

                if (!Packet.Response)
                {
                    int lasttick                     = Environment.TickCount;
                    List <PacketFormat> Ret          = new List <PacketFormat>();
                    List <IPEndPoint>   ResponsedIPs = new List <IPEndPoint>();
                    int count = 1;
                    while (Environment.TickCount - 1000 * 10 < lasttick && (
                               (onlythisep == null) ?
                               ResponsedIPs.Count < UserInfo.IPs.Count - UserInfo.BannedIPs.Count :
                               ResponsedIPs.Count == 0))
                    {
                        lock (Lock)
                        {
                            while (Response == null && Monitor.Wait(Lock, 1000))
                            {
                                ;
                            }
                        }
                        if (Response == null)
                        {
                            foreach (var item in UserInfo.IPs.Except(UserInfo.BannedIPs).Except(ResponsedIPs))
                            { //Elküldi az összes ismert címre
                                try
                                {
                                    SenderConnection.Send(senddata, senddata.Length, item);
                                }
                                catch (ObjectDisposedException)
                                {
                                    return(null);
                                }
                            }
                            count++;
                            continue;
                        }
                        if (!(!UserInfo.IPs.Any(entry => entry.Address.Equals(RemoteEP.Address)) &&
                              Packet.PacketType != Networking.UpdateType.LoginUser))
                        {
                            foreach (var item in UserInfo.IPs.Where(entry => entry.Address.Equals(RemoteEP.Address) && entry.Port == Response.Port))
                            {
                                ResponsedIPs.Add(item);
                            }
                            if (Response.KeyIndex != CurrentUser.KeyIndex && Response.PacketType != UpdateType.SetKey)
                            {
                                Response = null;
                                continue;
                            }

                            Ret.Add(Response);
                        }
                        Response = null;
                    }
                    Response = null;
                    RemoteEP = null;
                    return(Ret.ToArray());
                }
                return(null);
            }
Exemple #20
0
        private static void Parse(string msg)
        {
            PacketFormat Message = JsonConvert.DeserializeObject <PacketFormat>(msg);

            switch (Message.Option)
            {
            case PacketOption.ClientMessage:
                Log(new UserMessage(Message.Content, UsersList[Message.Guid]));
                break;

            case PacketOption.IsServer:
                Log(new ServerMessage(Message.Content));
                break;

            case PacketOption.NameChange:
                if (Message.Guid != ClientInfo.Guid)
                {
                    Log(new ServerMessage($"{UsersList[Message.Guid].Name} has changed their name to {Message.NewName}"));
                    UsersList[Message.Guid].Name = Message.NewName;
                    break;
                }
                Log(new ServerMessage($"You changed your name to {ClientInfo.Name}"));
                break;

            case PacketOption.UserBanned:
                if (ClientInfo.Guid == Message.Guid)
                {
                    Disconnect();
                    Log(new ServerMessage("You've been banned:"));
                    Log(new ServerMessage(Message.Content));
                    break;
                }
                Log(new ServerMessage($"{UsersList[Message.Guid]} has been banned:"));
                Log(new ServerMessage(Message.Content));
                UsersList.Remove(Message.Guid);
                break;

            case PacketOption.UserKicked:
                if (ClientInfo.Guid == Message.Guid)
                {
                    Disconnect();
                    Log(new ServerMessage("You've been kicked:"));
                    Log(new ServerMessage(Message.Content));
                    break;
                }
                Log(new ServerMessage($"{UsersList[Message.Guid]} has been kicked:"));
                Log(new ServerMessage(Message.Content));
                UsersList.Remove(Message.Guid);
                break;

            case PacketOption.UserMuted:
                if (ClientInfo.Guid == Message.Guid)
                {
                    // disable chat box
                    Log(new ServerMessage("You've been muted:"));
                }
                else
                {
                    Log(new ServerMessage($"{UsersList[Message.Guid]} has been muted:"));
                }
                Log(new ServerMessage(Message.Content));
                UsersList[Message.Guid].IsMuted = true;
                break;

            case PacketOption.UserUnmuted:
                Log(new ServerMessage($"{UsersList[Message.Guid]} has been unmuted"));
                UsersList[Message.Guid].IsMuted = false;
                break;

            case PacketOption.UserConnected:
                Log(new ServerMessage($"{Message.Guid} has joined"));
                UsersList.Add(new User(Message.NewName, Message.Guid));
                break;

            case PacketOption.UserDisconnected:
                Log(new ServerMessage($"{UsersList[Message.Guid]} has disconnected"));
                UsersList.Remove(Message.Guid);
                break;

            case PacketOption.GetGuid:
                ClientInfo = new User(Message.Guid.ToString(), Message.Guid);
                Log(new ServerMessage($"{Message.Guid.ToString()} has joined."));
                if (Message.UsersList != null)
                {
                    UsersList.Add(Message.UsersList);
                }
                UsersList.Add(ClientInfo);
                break;

            case PacketOption.FriendRequest:
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                string            content = $"Friend request recieved from {UsersList[Message.Sender].Name}, Accept?";
                string            caption = "Sausage Chat friend request";
                DialogResult      result;

                result = MessageBox.Show(content, caption, buttons);
                if (result == DialogResult.Yes)
                {
                    Log(new ServerMessage("Accepted friend request"));
                    Friends["OnlineFriends"].Add(UsersList[Message.Sender]);
                }
                else
                {
                    break;
                }
                PacketFormat packet = new PacketFormat(PacketOption.FriendRequestAccepted)
                {
                    Sender = ClientInfo.Guid,
                    Guid   = Message.Sender
                };
                Send(packet);
                break;

            case PacketOption.FriendRequestAccepted:
                Friends["OnlineFriends"].Add(UsersList[Message.Guid]);
                Log(new ServerMessage($"Friend request accepted by {UsersList[Message.Guid].Name}"));
                break;

            case PacketOption.FriendRequestDenied:
                Log(new ServerMessage("Friend request denied"));
                break;

            case PacketOption.AdminPermsRecieved:
                if (Message.Guid == ClientInfo.Guid)
                {
                    ClientInfo.IsAdmin = true;
                    Log(new ServerMessage($"You are now admin"));
                }
                else
                {
                    Log(new ServerMessage($"{UsersList[Message.Guid]} is now admin"));
                }
                break;

            case PacketOption.AdminPermsRemoved:
                if (Message.Guid == ClientInfo.Guid)
                {
                    ClientInfo.IsAdmin = false;
                    Log(new ServerMessage($"You are no longer admin"));
                }
                else
                {
                    Log(new ServerMessage($"{UsersList[Message.Guid]} is no longer admin"));
                }
                break;
            }
        }
Exemple #21
0
 /// <summary>
 ///  Send a UTF8 String mapped with format to the client
 /// </summary>
 /// <param name="format">DarkKnight.Data.PacketFormat object</param>
 /// <param name="toSend">the string to send</param>
 public void SendFormatedString(PacketFormat format, string toSend)
 {
     SendFormated(format, Encoding.UTF8.GetBytes(toSend));
 }
Exemple #22
0
 /// <summary>
 /// Send a array of bytes 8-bits mapped with format to the client
 /// </summary>
 /// <param name="format">DarkKnight.Data.PacketFormat object</param>
 /// <param name="toSend">the int to send</param>
 public void SendFormated(PacketFormat format, byte[] toSend)
 {
     SendEncodingPacket(new PacketCreator(format, toSend));
 }
Exemple #23
0
 /// <summary>
 /// Send a mapped with format to the client
 /// </summary>
 /// <param name="format">DarkKnight.Data.PacketFormat object</param>
 public void SendFormated(PacketFormat format)
 {
     SendEncodingPacket(new PacketCreator(format, new byte[] { }));
 }
        private static Packet GetNextPacket(ref MemoryStream stream)
        {
            Packet packet = new Packet();

            byte   firstbyte = (byte)stream.ReadByte();
            string first     = ToBitString(firstbyte);

            if (!first[0].Equals('1'))
            {
                throw new InvalidPacketSyntaxException("First byte's first bit is 0.");
            }

            PacketFormat format = (PacketFormat)Int32.Parse(first[1].ToString());

            MemoryStream outstream = new MemoryStream();

            if (format.Equals(PacketFormat.Old))
            {
                PacketType type = (PacketType)((firstbyte & 60) >> 2);

#if !PocketPC
                packet = (Packet)(System.Activator.CreateInstance("ActiveUp.Mail", "ActiveUp.Net.Security.OpenPGP.Packets." + type.ToString()).Unwrap());
#else
                packet = (Packet)(System.Activator.CreateInstance(Type.GetType("ActiveUp.Net.Security.OpenPGP.Packets." + type.ToString())));
#endif

                //ActiveUp.Net.Mail.Logger.AddEntry("Packet : "+packet.ToString());

                packet.Format = format;
                packet.Type   = type;

                byte lengthType = (byte)(firstbyte & 3);
                byte next       = (byte)stream.ReadByte();
                if (lengthType == 0)
                {
                    packet.BodyLength  = next;
                    packet.TotalLength = packet.BodyLength + 2;
                }
                else if (lengthType == 1)
                {
                    byte nextnext = (byte)stream.ReadByte();
                    packet.BodyLength  = (next << 8) + nextnext;
                    packet.TotalLength = packet.BodyLength + 3;
                }
                else if (lengthType == 2)
                {
                    // A VERIFIER !
                    byte nextnext         = (byte)stream.ReadByte();
                    byte nextnextnext     = (byte)stream.ReadByte();
                    byte nextnextnextnext = (byte)stream.ReadByte();
                    packet.BodyLength  = (next << 24) + (nextnext << 16) + (nextnextnext << 8) + nextnextnextnext;
                    packet.TotalLength = packet.BodyLength + 5;
                }
                else if (lengthType == 3)
                {
                    packet.TotalLength = packet.BodyLength + 1;
                }
                else
                {
                    throw new InvalidPacketSyntaxException("Invalid old format packet length type : " + lengthType.ToString());
                }
                outstream.Write(stream.ToArray(), (int)stream.Position, packet.BodyLength);
                stream.Position += packet.BodyLength;
            }
            if (format.Equals(PacketFormat.New))
            {
                PacketType type = (PacketType)(firstbyte & 63);

                #if !PocketPC
                packet = (Packet)(System.Activator.CreateInstance("ActiveUp.Mail", "ActiveUp.Net.Security.OpenPGP.Packets." + type.ToString()).Unwrap());
                #else
                packet = (Packet)(System.Activator.CreateInstance(Type.GetType("ActiveUp.Net.Security.OpenPGP.Packets." + type.ToString())));
                #endif

                packet.Format = format;
                packet.Type   = type;

                AddNextPacketNewFormat(ref packet, ref stream, ref outstream);
            }
            packet.RawData = outstream.ToArray();
            outstream.Close();

#if !PocketPC
            outstream.Dispose();
#endif
            return(packet);
        }
Exemple #25
0
        /// <summary>
        /// Here we filter the received packet in bytes to turn into a readable package for the Packet class.
        /// We took the package format and also took the given package.
        /// </summary>
        /// <returns>true if packet is handled with success</returns>
        private bool handlerPacket(byte[] packet)
        {
            int lengthFormat         = 0;
            int lengthFormatPosition = 0;

            do
            {
                lengthFormat += packet[lengthFormatPosition];
                lengthFormatPosition++;
                if (lengthFormatPosition >= packet.Length || lengthFormat > packet.Length)
                {
                    return(false);
                }
            } while (packet[lengthFormatPosition] > 0);

            int lengthData         = 0;
            int lengthDataPosition = lengthFormat + lengthFormatPosition + 1;

            if (lengthDataPosition >= packet.Length)
            {
                return(false);
            }

            do
            {
                lengthData += packet[lengthDataPosition];
                lengthDataPosition++;
                if (lengthDataPosition >= packet.Length || lengthData > packet.Length)
                {
                    return(false);
                }
            } while (packet[lengthDataPosition] > 0);


            int lengthDataLengthInformation = lengthDataPosition - (lengthFormat + lengthFormatPosition + 1);
            int totalDataLength             = lengthData + lengthFormat + lengthFormatPosition + lengthDataLengthInformation + 2;

            if (packet.Length < totalDataLength)
            {
                return(false);
            }

            try
            {
                byte[] format = new byte[lengthFormat];
                _packet = new byte[lengthData];

                Array.Copy(packet, lengthFormatPosition + 1, format, 0, lengthFormat);
                Array.Copy(packet, lengthDataPosition + 1, _packet, 0, lengthData);

                _format = new PacketFormat(Encoding.UTF8.GetString(format));

                packetHandled.Add((Packet)MemberwiseClone());

                if (packet.Length == totalDataLength)
                {
                    return(true);
                }

                byte[] morePacket = new byte[packet.Length - totalDataLength];
                Array.Copy(packet, totalDataLength, morePacket, 0, packet.Length - totalDataLength);

                return(handlerPacket(morePacket));
            }
            catch
            {
                return(false);
            }
        }
 public void SendAsync(PacketFormat packet) => SendAsync(JsonConvert.SerializeObject(packet));
        private void Parse(string msg)
        {
            byte[] m = Encoding.ASCII.GetBytes(msg);
            SausageHelper.StripData(ref m);
            msg = Encoding.ASCII.GetString(m);
            PacketFormat      Message = JsonConvert.DeserializeObject <PacketFormat>(msg);
            SausageConnection Reciever;

            switch (Message.Option)
            {
            case PacketOption.ClientMessage:
                if (!SausageServer.UsersDictionary[Message.Guid].IsMuted)
                {
                    SausageServer.Log(Message);
                }
                break;

            case PacketOption.NameChange:
                SausageServer.Log(Message);
                SausageServer.UsersDictionary[Message.Guid].Name = Message.NewName;
                break;

            // don't need to check for user connected as that is dealt with in OnUserConnect
            case PacketOption.UserDisconnected:
                SausageServer.Log(Message);
                Disconnect();
                SausageServer.UsersDictionary.Remove(Message.Guid);
                break;

            case PacketOption.UserBanned:
                if (UserInfo.IsAdmin)
                {
                    SausageServer.Ban(SausageServer.ConnectedUsers.First(x => x.UserInfo.Guid == Message.Guid));
                }
                break;

            case PacketOption.UserKicked:
                if (UserInfo.IsAdmin)
                {
                    SausageServer.Kick(SausageServer.ConnectedUsers.First(x => x.UserInfo.Guid == Message.Guid));
                }
                break;

            case PacketOption.UserMuted:
                if (UserInfo.IsAdmin)
                {
                    SausageServer.Mute(SausageServer.ConnectedUsers.First(x => x.UserInfo.Guid == Message.Guid));
                }
                break;

            case PacketOption.UserUnmuted:
                if (UserInfo.IsAdmin)
                {
                    SausageServer.Unmute(SausageServer.ConnectedUsers.First(x => x.UserInfo.Guid == Message.Guid));
                }
                break;

            case PacketOption.FriendRequest:
                Reciever = SausageServer.ConnectedUsers.FirstOrDefault(x => x.UserInfo.Guid == Message.Guid);
                if (Reciever == null)
                {
                    SendAsync(new PacketFormat(PacketOption.IsServer)
                    {
                        Content = "User not found"
                    });
                }
                else
                {
                    Reciever.SendAsync(Message);
                    SausageServer.UiCtx.Send(x => SausageServer.Vm.Messages.Add(new ServerMessage($"{UserInfo} requested {Reciever} for a friend request.")));
                }
                break;

            case PacketOption.FriendRequestAccepted:
                Reciever = SausageServer.ConnectedUsers.FirstOrDefault(x => x.UserInfo.Guid == Message.Guid);
                Reciever.SendAsync(Message);
                break;

            case PacketOption.FriendRequestDenied:
                Reciever = SausageServer.ConnectedUsers.FirstOrDefault(x => x.UserInfo.Guid == Message.Guid);
                Reciever.SendAsync(Message);
                break;

            case PacketOption.DmMessage:
                Reciever = SausageServer.ConnectedUsers.FirstOrDefault(x => x.UserInfo.Guid == Message.Guid);
                Reciever.SendAsync(Message);
                break;

            case PacketOption.DmAccepted:
                Reciever = SausageServer.ConnectedUsers.FirstOrDefault(x => x.UserInfo.Guid == Message.Guid);
                Reciever.SendAsync(Message);
                break;

            case PacketOption.DmDenied:
                Reciever = SausageServer.ConnectedUsers.FirstOrDefault(x => x.UserInfo.Guid == Message.Guid);
                Reciever.SendAsync(Message);
                break;

            case PacketOption.DmStartRequest:
                Reciever = SausageServer.ConnectedUsers.FirstOrDefault(x => x.UserInfo.Guid == Message.Guid);
                Reciever.SendAsync(Message);
                break;
            }
        }