Exemplo n.º 1
0
 private static void OnCompressedGump(PacketReader p, PacketHandlerEventArgs e)
 {
     p.MoveToData();
     uint sender = p.ReadUInt32();
     uint id = p.ReadUInt32();
     if (id == responseID)
         _responseSender = sender;
     if (id != compressedID)
         return;
     p.Seek(19, SeekOrigin.Begin);
     p.Seek(p.ReadInt32(), SeekOrigin.Current);
     int lines = p.ReadInt32(), cLen = p.ReadInt32(), dLen = p.ReadInt32();
     if (cLen < 5)
         return;
     byte[] buffer = new byte[dLen];
     ZLib.uncompress(buffer, ref dLen, p.CopyBytes(p.Position, cLen - 4), cLen - 4);
     string afk = string.Empty;
     for (int i = 0, pos = 0; i < lines; i++)
     {
         int strLen = (buffer[pos++] << 8) | buffer[pos++];
         string str = Encoding.BigEndianUnicode.GetString(buffer, pos, strLen * 2);
         int index = str.IndexOf('>');
         if (index != -1 && index < str.Length - 1)
             afk += str[index + 1].ToString().ToUpper().Normalize(NormalizationForm.FormD)[0];
         pos += strLen * 2;
     }
     afk = afk.Trim();
     if (afk.Length == 5 && _responseSender != 0)
     {
         /*ClientCommunication.SendToClient(new CloseGump(responseID));
         WorldEx.SendToServer(new GumpResponse(responseSender, responseID, 0x310, new int[0], new[] { new GumpTextEntry(0x310, afk) }));
         responseSender = 0;*/
         WorldEx.OverHeadMessage(afk);
     }
 }
Exemplo n.º 2
0
        public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size)
        {
            if (context.User == null || context.Character == null)
                return;

            // Looks/Jobs
            if (size > 0)
            {
                var reader = new PacketReader(data);

                reader.BaseStream.Seek(0x38, SeekOrigin.Begin);
                context.Character.Looks = reader.ReadStruct<Character.LooksParam>();
                context.Character.Jobs = reader.ReadStruct<Character.JobParam>();

                using(var db = new PolarisEf())
                    db.ChangeTracker.DetectChanges();
            }

            Map lobbyMap = ZoneManager.Instance.MapFromInstance("lobby", "lobby");
            lobbyMap.SpawnClient(context, lobbyMap.GetDefaultLocation(), "lobby");

            // Unlock Controls
            context.SendPacket(new NoPayloadPacket(0x03, 0x2B));

            //context.SendPacket(File.ReadAllBytes("testbed/237.23-7.210.189.208.30.bin"));

            // Give a blank palette
            context.SendPacket(new PalettePacket());

            // memset packet - Enables menus
            // Also holds event items and likely other stuff too
            var memSetPacket = File.ReadAllBytes("Resources/setMemoryPacket.bin");
            context.SendPacket(memSetPacket);
        }
Exemplo n.º 3
0
        public GameClient(TcpClient selfClient, Guid onlineId, IClientKiller killer, ChatManager manager, GameLoop game)
        {
            _self = selfClient;
            _self.NoDelay = true;
            _self.Client.NoDelay = true;
            _reader = new BinaryReader(_self.GetStream());
            _writer = new BinaryWriter(_self.GetStream());
            _clientKiller = killer;
            _game = game;
            ChatManager chatManager = manager;
            chatManager.Join(this);
            _auth = AuthorisationManager.Resolve();

            _packetReader = PacketReader.Resolve<ServerPacketReader>();
            _packetReader.InitialiseMapping();

            OnlineId = onlineId;
            _active = true;

            _subs = new List<PacketSubscriber>
                    {
                        this,
                        _game,
                        chatManager
                    };

            Task.Factory.StartNew(Receive);
        }
Exemplo n.º 4
0
        public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size)
        {
            var reader = new PacketReader(data);
            var id = reader.ReadInt32();

            Logger.Write("[CHR] {0} is deleting character with ID {1}", context.User.Username, id);

            // Delete Character
            using (var db = new PolarisEf())
            {

                foreach (var character in db.Characters)
                    if (character.CharacterId == id)
                    {
                        db.Characters.Remove(character);
                        db.ChangeTracker.DetectChanges();
                        break;
                    }

                // Detect the deletion and save the Database
                if (db.ChangeTracker.HasChanges())
                    db.SaveChanges();
            }

            // Disconnect for now
            // TODO: What do we do after a deletion?
            context.Socket.Close();
        }
Exemplo n.º 5
0
 public RicePacket(RiceClient sender, ushort id, byte[] buffer)
 {
     Sender = sender;
     Buffer = buffer;
     ID = id;
     Reader = new PacketReader(new MemoryStream(Buffer));
 }
Exemplo n.º 6
0
 //private readonly ILog _logger = LogManager.GetLogger("Runtime");
 /// <summary>
 /// Create the Runtime object to combine all the various components of the livetiming.
 /// </summary>
 /// <param name="liveStream">A stream used to represent the incoming data of the live stream.</param>
 /// <param name="authKeyService">Provider for authorization key requests.</param>
 /// <param name="keyFrameService">Provider for keyframes.</param>
 /// <param name="messageDispatch">A receiver for messages.</param>
 public Runtime(Stream liveStream, IAuthKey authKeyService, IKeyFrame keyFrameService, IMessageDispatch messageDispatch)
 {
     _decryptor = new DataDecryptor();
     _packetReader = new PacketReader(liveStream, new DecryptStreamDecorator(liveStream, _decryptor));
     _messageDispatch = messageDispatch;
     _authKeyService = authKeyService;
     _keyFrameService = keyFrameService;
 }
Exemplo n.º 7
0
 private static void OnServerStop(Client client, PacketReader reader)
 {
     MessageBox.Show("服务器关闭");
     try
     {
         client.Close(true);
     }
     catch { }
     client.ServerStop();
 }
Exemplo n.º 8
0
        private Connection(string server, int port)
        {
            _port = port;
            _server = server;
            _packetReader = PacketReader.Resolve<ClientPacketReader>();
            _packetReader.InitialiseMapping();

            _subs = new List<PacketSubscriber>();
            AddSubscriber(this);
        }
Exemplo n.º 9
0
        public static void ProcessPacket( byte[] data )
        {
            PacketHandler call = m_Table[data[0]] as PacketHandler;

            if ( call != null )
            {
                PacketReader pvSrc = new PacketReader( data, RPVEditor.PacketInfo.IsDyn( data[0] ) );
                pvSrc.MoveToData();
                call( pvSrc );
            }
        }
Exemplo n.º 10
0
        public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size)
        {
            if (context.Character == null)
                return;

            var reader = new PacketReader(data, position, size);
            reader.BaseStream.Seek(0xC, SeekOrigin.Begin);
            var channel = reader.ReadUInt32();
            var message = reader.ReadUtf16(0x9D3F, 0x44);

            if (message.StartsWith(PolarisApp.Config.CommandPrefix))
            {
                var valid = false;

                // Iterate commands
                foreach (var command in PolarisApp.ConsoleSystem.Commands)
                {
                    var full = message.Substring(1); // Strip the command chars
                    var args = full.Split(' ');

                    if (command.Names.Any(name => args[0].ToLower() == name.ToLower()))
                    {
                        command.Run(args, args.Length, full, context);
                        valid = true;
                        Logger.WriteCommand(null, "[CMD] {0} issued command {1}", context.User.Username, full);
                    }

                    if (valid)
                        break;
                }

                if (!valid)
                    Logger.WriteClient(context, "[CMD] {0} - Command not found", message.Split(' ')[0].Trim('\r'));
            }
            else
            {
                Logger.Write("[CHT] <{0}> <{1}>", context.Character.Name, message);

                var writer = new PacketWriter();
                writer.WritePlayerHeader((uint) context.User.PlayerId);
                writer.Write(channel);
                writer.WriteUtf16(message, 0x9D3F, 0x44);

                data = writer.ToArray();

                foreach (var c in Server.Instance.Clients)
                {
                    if (c.Character == null || c.CurrentZone != context.CurrentZone)
                        continue;

                    c.SendPacket(0x07, 0x00, 0x44, data);
                }
            }
        }
Exemplo n.º 11
0
		private static void OnServerInfo(Client client, PacketReader reader){
			//服务器信息
			Program.Config.ChatPort = reader.ReadInt32();
			Program.Config.DuelPort = reader.ReadInt32();
			Program.Config.NeedAuth = reader.ReadBoolean();
            client.Pwd = reader.ReadUnicode(32);
#if DEBUG
			MessageBox.Show(Program.Config.ChatPort+":"+Program.Config.DuelPort+":"+Program.Config.NeedAuth + ":" + client.Pwd);
#endif
            client.OnLoginOk();
		}
Exemplo n.º 12
0
        private static void OnError(Client client, PacketReader reader){
			//错误
			string err = reader.ReadUnicode(256);
         //   int code = reader.ReadByte();
			MessageBox.Show(err);
			//if(!client.IsLogin){
				try{
					client.Close(client.IsLogin);
				}catch{}
			//}
		}
Exemplo n.º 13
0
 private static void ClientDoubleClick(PacketReader p, PacketHandlerEventArgs args)
 {
     Serial serial = p.ReadUInt32();
     if (items.ContainsKey(serial))
     {
         args.Block = true;
         WorldEx.SendToServer(new DoubleClick(items[serial].List.Last()));
     }
     else
         args.Block = PacketHandler.ProcessViewers(clientDoubleClick, p);
 }
Exemplo n.º 14
0
        private static void OnCompressedGump(PacketReader p, PacketHandlerEventArgs e)
        {
            p.Seek(7, SeekOrigin.Begin);
            if (p.ReadUInt32() != 0x1105B263)
                return;

            p.Seek(19, SeekOrigin.Begin);
            p.Seek(p.ReadInt32() + 4, SeekOrigin.Current);
            int cLen = p.ReadInt32(), dLen = p.ReadInt32();
            byte[] buffer = new byte[dLen];
            ZLib.uncompress(buffer, ref dLen, p.CopyBytes(p.Position, cLen - 4), cLen - 4);
            int strLen = (buffer[0] << 8) | buffer[1];
            string[] str = Encoding.BigEndianUnicode.GetString(buffer, 2, strLen * 2).Split(',');

            string[] lat = str[0].Split('°');
            int yLat = int.Parse(lat[0]);
            int yMins = int.Parse(lat[1].Split('\'')[0]);
            bool ySouth = lat[1][lat[1].Length - 1] == 'S';

            string[] lon = str[1].Split('°');
            int xLong = int.Parse(lon[0]);
            int xMins = int.Parse(lon[1].Split('\'')[0]);
            bool xEast = lon[1][lon[1].Length - 1] == 'E';

            const int xWidth = 5120;
            const int yHeight = 4096;
            const int xCenter = 1323;
            const int yCenter = 1624;

            double absLong = xLong + ((double)xMins / 60);
            double absLat = yLat + ((double)yMins / 60);

            if (!xEast)
                absLong = 360.0 - absLong;

            if (!ySouth)
                absLat = 360.0 - absLat;

            int x = xCenter + (int)((absLong * xWidth) / 360);
            int y = yCenter + (int)((absLat * yHeight) / 360);

            if (x < 0)
                x += xWidth;
            else if (x >= xWidth)
                x -= xWidth;

            if (y < 0)
                y += yHeight;
            else if (y >= yHeight)
                y -= yHeight;

            onGump(x, y);
        }
Exemplo n.º 15
0
		private static void OnRoomStart(DuelServer server, PacketReader packet){
			string name = packet.ReadUnicode(20);
			Logger.Debug("OnRoomStart:"+server.Port+","+name);
			lock(server.Rooms){
                GameConfig cfg = null;
                if(server.Rooms.TryGetValue(name, out cfg)){
                    cfg.IsStart = true;
				}else{
					Logger.Warn("no start room:"+name+" form "+server.Port);
				}
			}
			if(server.Server!=null)
				server.Server.server_OnRoomStart(server, name);
		}
Exemplo n.º 16
0
 private static void OnHuedEffect(PacketReader p, PacketHandlerEventArgs args)
 {
     byte type = p.ReadByte();
     Serial src = p.ReadUInt32();
     Serial dest = p.ReadUInt32();
     ItemID itemID = p.ReadUInt16();
     p.Seek(10, SeekOrigin.Current);
     byte speed = p.ReadByte();
     byte count = p.ReadByte();
     p.ReadUInt32();
     uint hue = p.ReadUInt32();
     uint mode = p.ReadUInt32();
     Handle(huedEffect, args, type, src, dest, itemID, speed, count, hue, mode);
 }
Exemplo n.º 17
0
 public void ReadPacket(PacketReader reader)
 {
     FailureReason = (LoginFailureReason)reader.ReadInt32();
     var fingerprintJson = reader.ReadString();
     if (fingerprintJson != null)
         Fingerprint = new Fingerprint(fingerprintJson);
     HostName = reader.ReadString();
     AssetsRootUrl = reader.ReadString();
     iTunesUrl = reader.ReadString();
     Unknown1 = reader.ReadString();
     RemainingTime = reader.ReadInt32();
     Unknown2 = reader.ReadByte();
     CompressedFingerprintJson = reader.ReadByteArray();
     Unknown3 = reader.ReadString();
     Unknown4 = reader.ReadString();
 }
Exemplo n.º 18
0
 public void GetConsumerPacketHeaderTestMethod()
 {
     using (MemoryStream _stream = new MemoryStream(new ArraySegment<byte>(CommonDefinitions.GetTestBinaryArrayVariant(), 0, 27).ToArray<byte>()))
       using (PacketReader _reader = new PacketReader(_stream))
       {
     PacketHeader _header = PacketHeader.GetConsumerPacketHeader(_reader);
     Assert.IsNotNull(_header);
     Assert.AreEqual<Guid>(CommonDefinitions.TestGuid, _header.PublisherId);
     Assert.AreEqual<Byte>(110, _header.ProtocolVersion);
     Assert.AreEqual<Byte>(0, _header.NetworkMessageFlags);
     Assert.AreEqual<UInt32>(0, _header.SecurityTokenId);
     Assert.AreEqual<Byte>(1, _header.NonceLength);
     CollectionAssert.AreEqual(new byte[] { 0xcc }, _header.Nonce);
     Assert.AreEqual<Byte>(1, _header.MessageCount);
     CollectionAssert.AreEqual(new UInt16[] { CommonDefinitions.DataSetId }, _header.DataSetWriterIds);
       }
 }
Exemplo n.º 19
0
 public MultiplayerClient(TrueCraftUser user)
 {
     User = user;
     Client = new TcpClient();
     PacketReader = new PacketReader();
     PacketReader.RegisterCorePackets();
     PacketHandlers = new PacketHandler[0x100];
     Handlers.PacketHandlers.RegisterHandlers(this);
     World = new ReadOnlyWorld();
     var repo = new BlockRepository();
     repo.DiscoverBlockProviders();
     World.World.BlockRepository = repo;
     World.World.ChunkProvider = new EmptyGenerator();
     Physics = new PhysicsEngine(World, repo);
     SocketPool = new SocketAsyncEventArgsPool(100, 200, 65536);
     connected = 0;
     cancel = new CancellationTokenSource();
 }
        public void ReadPacket(PacketReader reader)
        {
            //TODO: Make
            var offset = 0x2A;
            File.WriteAllBytes("AvatarProfileResponsePacket dump", ((MemoryStream)reader.BaseStream).ToArray());
            Unknown1 = reader.ReadInt32();
            UserID1 = reader.ReadInt64();
            UserID2 = reader.ReadInt64();
            if (reader.ReadBoolean())
            {
                Clan = new Clan();
                Clan.ID = reader.ReadInt64();
                Clan.Name = reader.ReadString();
                Clan.Badge = reader.ReadInt32();
                reader.ReadInt32();
                Clan.Level = reader.ReadInt32();
                offset += 1;
            }
            if (Unknown2 = reader.ReadBoolean())
            {
                Unknown3 = reader.ReadInt64();
                offset += 1;
            }

            reader.Seek(offset, SeekOrigin.Current);
            Unknown4 = reader.ReadInt32();
            AllianceCastleLevel = reader.ReadInt32(); // -1 if not constructed
            AllianceCastleUnitCapacity = reader.ReadInt32();
            AllianceCastleUnitCount = reader.ReadInt32();
            TownHallLevel = reader.ReadInt32();
            Username = reader.ReadString();
            FacebookID = reader.ReadString();
            Level = reader.ReadInt32();
            Experience = reader.ReadInt32();
            Gems = reader.ReadInt32(); // they seemed randomized or scrambled for non local player
            Gems1 = reader.ReadInt32();
            Unknown5 = reader.ReadInt32();
            Unknown6 = reader.ReadInt32();
            Trophies = reader.ReadInt32();
            AttackWon = reader.ReadInt32();
            AttackLost = reader.ReadInt32(); // randomized
            DefenseWon = reader.ReadInt32();
            DefenseLost = reader.ReadInt32(); // randomized
        }
Exemplo n.º 21
0
		private static void OnRoomCreate(DuelServer server, PacketReader packet){
			string name = packet.ReadUnicode(20);
			string info = packet.ReadUnicode(20);
			string banlist=packet.ReadUnicode(50);
			GameConfig config=new GameConfig();
            config.RoomString = info;
            config.Parse(info);
			config.Name=name;
			config.BanList=banlist;
            
			Logger.Debug("OnRoomCreate:"+server.Port+","+name+"|"+info);
			lock(server.Rooms){
                server.Rooms[name] = config;
			}
            if (server.Server != null)
            {
                server.Server.server_OnRoomCreate(server, name, banlist, info);
            }
		}
        /// <summary>
        /// The read.
        /// </summary>
        /// <param name="client">
        /// </param>
        /// <param name="packet">
        /// </param>
        public static void Read(Client client, byte[] packet)
        {
            // TODO: Fix this mess.
            ushort data_length = BitConverter.ToUInt16(new[] { packet[3], packet[2] }, 0);
            byte[] sender_ID = BitConverter.GetBytes(client.Character.characterId);
            Array.Reverse(sender_ID);
            MemoryStream m_stream = new MemoryStream();
            m_stream.Write(packet, 0, 9);
            m_stream.Write(sender_ID, 0, 4);
            m_stream.Write(packet, 9, packet.Length - 9);
            m_stream.Capacity = (int)m_stream.Length;
            byte[] message = m_stream.GetBuffer();
            byte[] new_length = BitConverter.GetBytes(message.Length - 4);
            message[2] = new_length[1];
            message[3] = new_length[0];
            m_stream.Close();
            m_stream.Dispose();

            foreach (Client m_client in client.Server.Clients)
            {
                if (!m_client.KnownClients.Contains(client.Character.characterId))
                {
                    byte[] pname = PlayerName.New(client, client.Character.characterId);
                    m_client.Send(pname);
                    m_client.KnownClients.Add(client.Character.characterId);
                }

                m_client.Send(message);
            }

            PacketReader reader = new PacketReader(ref packet);
            reader.ReadUInt16();
            reader.ReadUInt16();
            reader.ReadUInt16();
            reader.ReadUInt16();
            reader.ReadByte();
            string text = reader.ReadString();
            string channelName = ChatChannels.GetChannel(packet).Name;
            ChatLogger.WriteString(channelName, text, client.Character.characterName);
        }
Exemplo n.º 23
0
        private static void EquipmentUpdate( PacketReader p )
        {
            Serial serial = p.ReadUInt32();

            Item i = World.FindItem( serial );
            if ( i == null )
            {
                World.AddItem( i=new Item( serial ) );
                Item.UpdateContainers();
            }

            if ( World.Player != null && World.Player.Holding == i )
                World.Player.Holding = null;

            ushort iid = p.ReadUInt16();
            i.ItemID = (ushort)(iid + p.ReadSByte()); // signed, itemID offset
            i.Layer = p.ReadByte();
            Serial ser = p.ReadUInt32();// cont must be set after hue (for counters)
            i.Hue = p.ReadUInt16();

            i.Container = ser;
        }
Exemplo n.º 24
0
        public override void HandlePacket(Client context, byte flags, byte[] data, uint position, uint size)
        {
            PacketReader reader = new PacketReader(data);

            reader.ReadUInt64(); // Skip 8 bytes
            if(reader.ReadUInt32() != 0x10)
            {
                Logger.WriteWarning("[WRN] Packet 0x3 0x34's first value was not 0x10! Investigate.");
            }

            uint partOfLobby = reader.ReadUInt32();
            PSOLocation destination;
            if(partOfLobby == 0) // Gate area
            {
                destination = new PSOLocation(0f, 1f, 0f, 0f, -0.22f, 2.4f, 198.75f);
            }
            else // Shop area
            {
                destination = new PSOLocation(0f, 1f, 0f, 20f, 0.20f, 1.23f, -175.25f);
            }
            Map lobbyMap = ZoneManager.Instance.MapFromInstance("lobby", "lobby");
            lobbyMap.SpawnClient(context, destination, "lobby");
        }
Exemplo n.º 25
0
        PacketReader SendReceive(CommandSet command_set, int command, PacketWriter packet)
        {
            int packetId = IdGenerator;
            Stopwatch watch = null;

            if (disconnected)
                throw new VMDisconnectedException ();

            if (EnableConnectionLogging)
                watch = Stopwatch.StartNew ();

            byte[] encoded_packet;

            if (packet == null)
                encoded_packet = EncodePacket (packetId, (int)command_set, command, null, 0);
            else
                encoded_packet = EncodePacket (packetId, (int)command_set, command, packet.Data, packet.Offset);

            WritePacket (encoded_packet);
            if (EnableConnectionLogging) {
                LogPacket ("Send", packetId, command_set, command, encoded_packet);
            }

            /* Wait for the reply packet */
            while (true) {
                lock (reply_packets_monitor) {
                    if (reply_packets.ContainsKey (packetId)) {
                        byte[] reply = reply_packets [packetId];
                        reply_packets.Remove (packetId);
                        PacketReader r = new PacketReader (reply);

                        if (EnableConnectionLogging) {
                            LogPacket ("Recv", packetId, command_set, command, reply);
                        }

                        if (r.ErrorCode != 0) {
                            if (ErrorHandler != null)
                                ErrorHandler (this, new ErrorHandlerEventArgs () { ErrorCode = (ErrorCode)r.ErrorCode });
                            throw new NotImplementedException ("No error handler set.");
                        } else {
                            return r;
                        }
                    } else {
                        if (disconnected)
                            throw new VMDisconnectedException ();
                        Monitor.Wait (reply_packets_monitor);
                    }
                }
            }
        }
Exemplo n.º 26
0
        /* Send a request and call cb when a result is received */
        int Send(CommandSet command_set, int command, PacketWriter packet, Action<PacketReader> cb, int count)
        {
            int id = IdGenerator;

            byte[] encoded_packet;
            if (packet == null)
                encoded_packet = EncodePacket (id, (int)command_set, command, null, 0);
            else
                encoded_packet = EncodePacket (id, (int)command_set, command, packet.Data, packet.Offset);

            if (cb != null) {
                lock (reply_packets_monitor) {
                    reply_cbs [id] = delegate (int packet_id, byte[] p) {
                        if (EnableConnectionLogging) {
                            LogPacket ("Recv", packet_id, command_set, command, encoded_packet);
                        }
                        /* Run the callback on a tp thread to avoid blocking the receive thread */
                        PacketReader r = new PacketReader (p);
                        cb.BeginInvoke (r, null, null);
                    };
                    reply_cb_counts [id] = count;
                }
            }

            if (buffer_packets) {
                buffered_packets.Add (encoded_packet);
            } else {
                WritePacket (encoded_packet);
            }
            if (EnableConnectionLogging) {
                LogPacket ("Send", id, command_set, command, encoded_packet);
            }

            return id;
        }
Exemplo n.º 27
0
        bool ReceivePacket()
        {
            byte[] packet = ReadPacket ();

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

                if (IsReplyPacket (packet)) {
                    int id = GetPacketId (packet);
                    ReplyCallback cb = null;
                    lock (reply_packets_monitor) {
                        reply_cbs.TryGetValue (id, out cb);
                        if (cb == null) {
                            reply_packets [id] = packet;
                            Monitor.PulseAll (reply_packets_monitor);
                        } else {
                            int c = reply_cb_counts [id];
                            c --;
                            if (c == 0) {
                                reply_cbs.Remove (id);
                                reply_cb_counts.Remove (id);
                            }
                        }
                    }

                    if (cb != null)
                        cb.Invoke (id, packet);
                } else {
                    PacketReader r = new PacketReader (packet);

                    if (r.CommandSet == CommandSet.EVENT && r.Command == (int)CmdEvent.COMPOSITE) {
                        int spolicy = r.ReadByte ();
                        int nevents = r.ReadInt ();

                        SuspendPolicy suspend_policy = decode_suspend_policy (spolicy);

                        EventInfo[] events = new EventInfo [nevents];

                        for (int i = 0; i < nevents; ++i) {
                            EventKind kind = (EventKind)r.ReadByte ();
                            int req_id = r.ReadInt ();

                            EventType etype = (EventType)kind;

                            long thread_id = r.ReadId ();
                            if (kind == EventKind.VM_START) {
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id };
                                //EventHandler.VMStart (req_id, thread_id, null);
                            } else if (kind == EventKind.VM_DEATH) {
                                int exit_code = 0;
                                if (Version.AtLeast (2, 27))
                                    exit_code = r.ReadInt ();
                                //EventHandler.VMDeath (req_id, 0, null);
                                events [i] = new EventInfo (etype, req_id) { ExitCode = exit_code };
                            } else if (kind == EventKind.THREAD_START) {
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
                                //EventHandler.ThreadStart (req_id, thread_id, thread_id);
                            } else if (kind == EventKind.THREAD_DEATH) {
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = thread_id };
                                //EventHandler.ThreadDeath (req_id, thread_id, thread_id);
                            } else if (kind == EventKind.ASSEMBLY_LOAD) {
                                long id = r.ReadId ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
                                //EventHandler.AssemblyLoad (req_id, thread_id, id);
                            } else if (kind == EventKind.ASSEMBLY_UNLOAD) {
                                long id = r.ReadId ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
                                //EventHandler.AssemblyUnload (req_id, thread_id, id);
                            } else if (kind == EventKind.TYPE_LOAD) {
                                long id = r.ReadId ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
                                //EventHandler.TypeLoad (req_id, thread_id, id);
                            } else if (kind == EventKind.METHOD_ENTRY) {
                                long id = r.ReadId ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
                                //EventHandler.MethodEntry (req_id, thread_id, id);
                            } else if (kind == EventKind.METHOD_EXIT) {
                                long id = r.ReadId ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
                                //EventHandler.MethodExit (req_id, thread_id, id);
                            } else if (kind == EventKind.BREAKPOINT) {
                                long id = r.ReadId ();
                                long loc = r.ReadLong ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
                                //EventHandler.Breakpoint (req_id, thread_id, id, loc);
                            } else if (kind == EventKind.STEP) {
                                long id = r.ReadId ();
                                long loc = r.ReadLong ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
                                //EventHandler.Step (req_id, thread_id, id, loc);
                            } else if (kind == EventKind.EXCEPTION) {
                                long id = r.ReadId ();
                                long loc = 0; // FIXME
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
                                //EventHandler.Exception (req_id, thread_id, id, loc);
                            } else if (kind == EventKind.APPDOMAIN_CREATE) {
                                long id = r.ReadId ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
                                //EventHandler.AppDomainCreate (req_id, thread_id, id);
                            } else if (kind == EventKind.APPDOMAIN_UNLOAD) {
                                long id = r.ReadId ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id };
                                //EventHandler.AppDomainUnload (req_id, thread_id, id);
                            } else if (kind == EventKind.USER_BREAK) {
                                long id = 0;
                                long loc = 0;
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Id = id, Location = loc };
                                //EventHandler.Exception (req_id, thread_id, id, loc);
                            } else if (kind == EventKind.USER_LOG) {
                                int level = r.ReadInt ();
                                string category = r.ReadString ();
                                string message = r.ReadString ();
                                events [i] = new EventInfo (etype, req_id) { ThreadId = thread_id, Level = level, Category = category, Message = message };
                                //EventHandler.Exception (req_id, thread_id, id, loc);
                            } else if (kind == EventKind.KEEPALIVE) {
                                events [i] = new EventInfo (etype, req_id) { };
                            } else {
                                throw new NotImplementedException ("Unknown event kind: " + kind);
                            }
                        }

                        EventHandler.Events (suspend_policy, events);
                    }
                }

                return true;
        }
Exemplo n.º 28
0
 void read_invoke_res(PacketReader r, out ValueImpl v, out ValueImpl exc, out ValueImpl out_this, out ValueImpl[] out_args)
 {
     int resflags = r.ReadByte ();
     v = null;
     exc = null;
     out_this = null;
     out_args = null;
     if (resflags == 0) {
         exc = r.ReadValue ();
     } else {
         v = r.ReadValue ();
         if ((resflags & 2) != 0)
             out_this = r.ReadValue ();
         if ((resflags & 4) != 0) {
             int nargs = r.ReadInt ();
             out_args = new ValueImpl [nargs];
             for (int i = 0; i < nargs; ++i)
                 out_args [i] = r.ReadValue ();
         }
     }
 }
Exemplo n.º 29
0
 CattrInfo[] ReadCattrs(PacketReader r)
 {
     CattrInfo[] res = new CattrInfo [r.ReadInt ()];
     for (int i = 0; i < res.Length; ++i) {
         CattrInfo info = new CattrInfo ();
         info.ctor_id = r.ReadId ();
         info.ctor_args = new ValueImpl [r.ReadInt ()];
         for (int j = 0; j < info.ctor_args.Length; ++j) {
             info.ctor_args [j] = r.ReadValue ();
         }
         info.named_args = new CattrNamedArgInfo [r.ReadInt ()];
         for (int j = 0; j < info.named_args.Length; ++j) {
             CattrNamedArgInfo arg = new CattrNamedArgInfo ();
             int arg_type = r.ReadByte ();
             arg.is_property = arg_type == 0x54;
             arg.id = r.ReadId ();
             arg.value = r.ReadValue ();
             info.named_args [j] = arg;
         }
         res [i] = info;
     }
     return res;
 }
Exemplo n.º 30
0
        public void TestPacketConsumption()
        {
            // This just tests the packet reader's ability to
            // munch through all the packets in the stream, and
            // gracefully reach the end without exception.
            // Therefore it will return true, and we will keep
            // calling into it, until it returns false. At
            // which point it's assumed we've reached the end
            // of the stream. If not something went wrong.

            PacketReader r = new PacketReader(Input, Input);
            while(Input.Position < (Input.Length - 1))
            {
                if (!r.ReadNext())
                {
                    // Have we reached the end, if not
                    // this is an error.
                    Assert.IsTrue(Input.Position == (Input.Length - 1));
                }
            }
        }