コード例 #1
0
ファイル: LoginHandler.cs プロジェクト: cvanherk/3d-engine
        public void HandlePacket(Connection connection, Packet packet)
        {
            var playerData = new PacketBuilder(packet);

            var name = playerData.ReadString();
            var password = playerData.ReadString();


            

            var player = new Player(connection);

            //player aanmaken
            //player inladen

            //-- versturen --
            //player positie
            //player rotation
            //map init
            //name

            var packetBuilder = new PacketBuilder(PacketId.Login);

            connection.SendPacket(packetBuilder.ToPacket());
        }
コード例 #2
0
ファイル: Stack.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Send the ammount of stacked Item to defined Container Slot.
        /// </summary>
        public void ContainerToContainer(ISlot fromSlot, ISlot toSlot)
        {
            #region " Packet Structure Analyze "
            //---------------------------------------------------
            // SZ    ID       BP    ST  ITM  ST       BP    ST QT
            // 0F 00 78 FF FF 41 00 02 7E 0C 02 FF FF 40 00 02 01
            //---------------------------------------------------
            // 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
            //---------------------------------------------------
            #endregion

            var Builder = new PacketBuilder(0x78, Connection);
            Builder.Append(0xFF);
            Builder.Append(0xFF);
            Builder.Append(fromSlot.Container.Position);
            Builder.Append(0x00);
            Builder.Append(fromSlot.Position);
            Builder.Append(fromSlot.Item.Id);
            Builder.Append(fromSlot.Position);
            Builder.Append(0xFF);
            Builder.Append(0xFF);
            Builder.Append(toSlot.Container.Position);
            Builder.Append(0x00);
            Builder.Append(toSlot.Position);
            Builder.Append(fromSlot.Item.Count);
            Connection.Send(Builder.GetPacket());
        }
コード例 #3
0
ファイル: Use.cs プロジェクト: alexisjojo/ktibiax
 /// <summary>
 /// Close the Defined Container.
 /// </summary>
 public void CloseContainer(IContainer containerSource)
 {
     //TODO: Need Test this Feature. Probably is a Client Packet.
     PacketBuilder Builder = new PacketBuilder(0x6F, connection);
     Builder.Append(containerSource.Index);
     Connection.Send(Builder.GetPacket());
 }
コード例 #4
0
 public override byte[] GetByteArray()
 {
     OPCode = 0x0;
     PacketBuilder p = new PacketBuilder();
     p.Write(Version);
     Payload = p.GetBytes();
     return Package();
 }
コード例 #5
0
ファイル: Attack.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Attack the Defined Creature.
        /// </summary>
        public void Creature(Creature target)
        {
            Model.Player nPlayer = new Model.Player(Connection);
            nPlayer.Target = target;

            PacketBuilder Builder = new PacketBuilder(0xA1, connection);
            Builder.Append(target.Id);
            Connection.Send(Builder.GetPacket());
        }
コード例 #6
0
 public override byte[] GetByteArray()
 {
     PacketBuilder p = new PacketBuilder();
     p.Write(((byte)0));
     p.Write(Salt);
     p.Write(Rounds);
     Payload = p.GetBytes();
     byte[] lel = Package();
     return Package();
 }
コード例 #7
0
ファイル: ChatSend.cs プロジェクト: patrickb8man/MultiBound
 public override byte[] GetByteArray()
 {
     PacketBuilder p = new PacketBuilder();
     p.Write(Convert.ToByte(Channel));
     p.Write(World);
     p.Write(ID);
     p.Write(Name);
     p.Write(Text);
     Payload = p.GetBytes();
     return Package();
 }
コード例 #8
0
ファイル: Attack.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Change the Current Attack Mode.
        /// </summary>
        public void SetMode(AttackMode mode)
        {
            Memory.Writer.Uint(Memory.Addresses.Client.AttackMode, Convert.ToUInt32(mode.Type.GetHashCode()), 1);
            Memory.Writer.Uint(Memory.Addresses.Client.FollowMode, Convert.ToUInt32(mode.Follow.GetHashCode()), 1);

            PacketBuilder Builder = new PacketBuilder(0xA0, connection);
            Builder.Append(mode.Type.GetHashCode());      //[01 = OFFENSIVE | 02 = BALANCED | 03 = DEFENSIVE]
            Builder.Append(mode.Follow.GetHashCode());    //[00 = STAND| 01 = CHASE]
            if (mode.AttackUnmarkedPlayers) { Builder.Append(0x00); } else { Builder.Append(0x01); }
            Connection.Send(Builder.GetPacket());
        }
コード例 #9
0
ファイル: Position.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Follow the Defined Creature.
        /// </summary>
        public void Follow(uint creatureID)
        {
            #region " Packet Structure Analyze "
            //SZ    ID [ CreatID ]
            //--------------------
            //05 00 A2 4F 2D 45 01
            #endregion

            PacketBuilder Builder = new PacketBuilder(0xA2, connection);
            Builder.Append(creatureID);
            Connection.Send(Builder.GetPacket());
            Connection.Memory.Writer.Uint(Connection.Memory.Addresses.BattleList.GreenSQuare, creatureID, 4);
        }
コード例 #10
0
ファイル: PositionHandler.cs プロジェクト: cvanherk/3d-engine
        public void HandlePacket(Connection connection, Packet packet)
        {
            var packetBuilderGet = new PacketBuilder(packet);

            Console.WriteLine("packet postion : " + packetBuilderGet.ReadInt32());

            var p = new Packet(PacketId.Position);
            var packetBuilder = new PacketBuilder(p);

            packetBuilder.WriteInt32(12);

            p = packetBuilder.ToPacket();

            connection.SendPacket(p);
        }
コード例 #11
0
ファイル: Server.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Send a Message to Default Channel.
        /// </summary>
        public void Default(string message)
        {
            #region "[rgn] Packet Structure Analyze "
            //---------------------------------------
            //SZ      ID  SZ NM
            //---------------------------------------
            //07 00 96 01 03 00 61 65 77
            //0B 00 96 01 07 00 62 6C 7A 69 6E 68 61
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x96, Connection);
            Builder.Append(MessageType.Normal.GetHashCode());
            Builder.Append(message, true);
            Builder.SetPacketSource(PacketSource.Client);
            Connection.Send(Builder.GetPacket());
        }
コード例 #12
0
ファイル: Hotkeys.cs プロジェクト: alexisjojo/ktibiax
 /// <summary>
 /// Drink any kind of Fluid Item.
 /// </summary>
 public void DrinkFluid(uint fluidID)
 {
     PacketBuilder Builder = new PacketBuilder(0x84, connection);
     Builder.Append(0xFF);
     Builder.Append(0xFF);
     Builder.Append(0x00);
     Builder.Append(0x00);
     Builder.Append(0x00);
     Builder.Append(fluidID);
     if (connection.IsOtServer) {
         Builder.Append(0x02);
     }
     else { Builder.Append(0x0A); }
     Builder.Append(new Model.Player(Connection).Id);
     Connection.Send(Builder.GetPacket());
 }
コード例 #13
0
ファイル: Hotkeys.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Shoot a Rune against a defined Creature.
        /// </summary>
        public void Shoot(uint creatureID, uint runeID)
        {
            #region " Packet Structure Analyze "
            //SZ    ID                [ UH]    [Player ID]
            //0D 00 84 FF FF 00 00 00 58 0C 00 63 14 32 00
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x84, connection);
            Builder.Append(0xFF);
            Builder.Append(0xFF);
            Builder.Append(0x00);
            Builder.Append(0x00);
            Builder.Append(0x00);
            Builder.Append(runeID);
            Builder.Append(0x00);
            Builder.Append(creatureID);
            Connection.Send(Builder.GetPacket());
        }
コード例 #14
0
ファイル: System.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Open the specified Channel.
        /// </summary>
        /// <param name="channel"></param>
        public void OpenChannel(InternalChannels channel)
        {
            #region "[rgn] Packet Structure Analyze "
            //---------------------------------------
            //.  .  ID ID .  SZ .  H  e  l  p  .  .
            //---------------------------------------
            //0B 00 AC 0A 00 06 00 4B 65 79 58 00 00
            //---------------------------------------
            //00 01 02 03 04 05 06 07 08 09 10 11 12
            #endregion

            PacketBuilder Builder = new PacketBuilder(0xAC, Connection);
            Builder.Append(GetChannelInfo(channel).Key, 2);
            Builder.Append(GetChannelInfo(channel).Value, true, true);

            Builder.SetPacketSource(PacketSource.Server);
            Connection.Send(Builder.GetPacket());
        }
コード例 #15
0
ファイル: Use.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Use the Item stacked on defined Slot.
        /// e.g: Open Containers, Eat Food, etc.
        /// </summary>
        public void InContainer(ISlot slotSource, int openInPosition)
        {
            PacketBuilder Builder = new PacketBuilder(0x82, connection);
            if (slotSource.Id == InventoryID.Container) {

                #region " Packet Structure Analyze "
                //------------------------------------
                //SZ    ID       BP    ST [ ID] ST PS
                //------------------------------------
                //0A 00 82 FF FF 40 00 00 26 0B 00 01
                //------------------------------------
                #endregion

                Builder.Append(0xFF);
                Builder.Append(0XFF);
                Builder.Append(slotSource.Container.Position);
                Builder.Append(0x00);
                Builder.Append(slotSource.Position);
                Builder.Append(slotSource.Item.Id);
                Builder.Append(slotSource.Position);
            }
            else {

                #region " Packet Structure Analyze "
                //------------------------------------
                //SZ    ID       ST      [ ID ]    PS
                //------------------------------------
                //0A 00 82 FF FF 03 00 00 25 0B 00 00
                //------------------------------------
                #endregion

                Builder.Append(0xFF);
                Builder.Append(0XFF);
                Builder.Append(slotSource.Id.GetHashCode());
                Builder.Append(0x00);
                Builder.Append(0x00);
                Builder.Append(slotSource.Item.Id);
                Builder.Append(0x00);
            }
            Builder.Append(openInPosition);
            Connection.Send(Builder.GetPacket());
        }
コード例 #16
0
        /// <summary>
        /// Called everytime a party invitation is detected.
        /// </summary>
        public void OnPartyInvitation(uint uniqueID, SRParty.Setup Setup)
        {
            // Check GUI
            Window w = Window.Get;

            // All
            if (w.Party_cbxAcceptAll.Checked)
            {
                if (w.Party_cbxAcceptOnlyPartySetup.Checked)
                {
                    // Exactly same party setup?
                    if (w.GetPartySetup() == Setup)
                    {
                        PacketBuilder.PlayerPetitionResponse(true, SRTypes.PlayerPetition.PartyInvitation);
                    }
                    else if (w.Party_cbxRefuseInvitations.Checked)
                    {
                        PacketBuilder.PlayerPetitionResponse(false, SRTypes.PlayerPetition.PartyInvitation);
                    }
                }
                else
                {
                    PacketBuilder.PlayerPetitionResponse(true, SRTypes.PlayerPetition.PartyInvitation);
                }
                // Highest priority, has no sense continue checking ..
                return;
            }
            // Check party list
            if (w.Party_cbxAcceptPartyList.Checked)
            {
                string playerName = InfoManager.GetEntity(uniqueID).Name.ToUpper();

                bool found = false;
                w.Party_lstvPartyList.InvokeIfRequired(() => {
                    found = w.Party_lstvPartyList.Items.ContainsKey(playerName);
                });
                if (found)
                {
                    if (w.Party_cbxAcceptOnlyPartySetup.Checked)
                    {
                        if (w.GetPartySetup() == Setup)
                        {
                            PacketBuilder.PlayerPetitionResponse(true, SRTypes.PlayerPetition.PartyInvitation);
                            return;
                        }
                    }
                    else
                    {
                        PacketBuilder.PlayerPetitionResponse(true, SRTypes.PlayerPetition.PartyInvitation);
                        return;
                    }
                }
            }
            // Check leader list
            if (w.Party_cbxAcceptLeaderList.Checked)
            {
                string playerName = InfoManager.GetEntity(uniqueID).Name.ToUpper();

                bool found = false;
                w.Party_lstvLeaderList.InvokeIfRequired(() => {
                    w.Party_lstvLeaderList.InvokeIfRequired(() => {
                        found = w.Party_lstvLeaderList.Items.ContainsKey(playerName);
                    });
                });
                if (found)
                {
                    if (w.Party_cbxAcceptOnlyPartySetup.Checked)
                    {
                        if (w.GetPartySetup() == Setup)
                        {
                            PacketBuilder.PlayerPetitionResponse(true, SRTypes.PlayerPetition.PartyInvitation);
                            return;
                        }
                    }
                    else
                    {
                        PacketBuilder.PlayerPetitionResponse(true, SRTypes.PlayerPetition.PartyInvitation);
                        return;
                    }
                }
            }
            if (w.Party_cbxRefuseInvitations.Checked)
            {
                PacketBuilder.PlayerPetitionResponse(false, SRTypes.PlayerPetition.PartyInvitation);
            }
        }
コード例 #17
0
        private async Task <ICollection <Zone> > HandleZoneListRequest()
        {
            var zones   = new List <Zone>();
            var builder = new PacketBuilder();

            builder.AddInt16(0x0005);
            builder.AddBytes(new byte[26]);

            var buffer = builder.GetBytes();

            await this.networkClient.SendAsync(buffer, buffer.Length);

            int chunkBufferLength;
            int chunk;
            int offset = 0;

            byte[]       chunkBuffer = null;
            PacketReader reader;

            do
            {
                buffer = await this.networkClient.ReceiveAsync();

                reader = new PacketReader(buffer);

                reader.ReadInt16();
                reader.ReadInt16();
                chunk = reader.ReadByte();
                reader.ReadBytes(7);
                chunkBufferLength = reader.ReadLittleEndianInt16();
                reader.ReadInt16();

                if (chunkBuffer == null)
                {
                    chunkBuffer = new byte[chunkBufferLength];
                }

                offset += reader.CopyBytes(chunkBuffer, offset);

                builder = new PacketBuilder();
                builder.AddInt16(0x000b);
                builder.AddInt16(0);
                builder.AddByte((byte)chunk);
                builder.AddPadding(3);

                buffer = builder.GetBytes();

                await this.networkClient.SendAsync(buffer, buffer.Length);

                chunk++;
            } while (offset < (chunkBufferLength));

            reader = new PacketReader(chunkBuffer);

            // Discard the 0x01 at the beginning
            reader.ReadByte();

            while (reader.CanRead())
            {
                var zone = new Zone();

                zone.ServerAddress = reader.ReadIPAddress();
                zone.ServerPort    = reader.ReadUInt16();
                reader.ReadBytes(6);
                zone.Name = reader.ReadString(32);
                reader.ReadInt16();
                zone.IsAdvanced = reader.ReadBoolean();
                reader.ReadBytes(29);
                zone.Description = reader.ReadString();

                zones.Add(zone);
            }

            return(zones);
        }
コード例 #18
0
        private void cmdImport_Click(object sender, System.EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();

            openDialog.Title       = "Open Prim.Blender File";
            openDialog.Filter      = "All files (*.*)|*.*|Prim files (*.prims)|*.prims";
            openDialog.FilterIndex = 2;

            if (openDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            XmlDocument xml  = new XmlDocument();
            XmlNodeList list = null;

            try
            {
                // Try to load the xml file
                xml.Load(openDialog.FileName);

                //If there is a document and it has children,
                if (xml != null && xml.HasChildNodes)
                {
                    //Get the children into the temp list
                    list = xml.GetElementsByTagName("primitive");
                }
                else
                {
                    txtLog.AppendText("ERROR: Failed to parse " + openDialog.FileName + "\n");
                    return;
                }
            }
            catch (Exception err)
            {
                txtLog.AppendText("ERROR: " + err.ToString() + "\n");
                return;
            }

            foreach (XmlNode node in list)
            {
                txtLog.AppendText("Parsing primitive " + node.Attributes["key"].Value + "\n");

                XmlNode properties = node["properties"];

                PrimObject prim = new PrimObject(new LLUUID("8955674724cb43ed920b47caed15465f"));

                prim.Material = Convert.ToUInt16(properties["material"].Attributes["val"].Value);
                prim.Name     = node.Attributes["key"].Value;
                // Either PathBegin/End or ProfileBegin/End should be dimple
                prim.PathBegin        = PrimObject.PathBeginByte(Convert.ToSingle(properties["cut"].Attributes["x"].Value));
                prim.PathEnd          = PrimObject.PathEndByte(Convert.ToSingle(properties["cut"].Attributes["y"].Value));
                prim.PathRadiusOffset = PrimObject.PathRadiusOffsetByte(Convert.ToSingle(properties["radiusoffset"].Attributes["val"].Value));
                prim.PathRevolutions  = PrimObject.PathRevolutionsByte(Convert.ToSingle(properties["revolutions"].Attributes["val"].Value));
                prim.PathScaleX       = PrimObject.PathScaleByte(Convert.ToSingle(properties["topsize"].Attributes["x"].Value));
                prim.PathScaleY       = PrimObject.PathScaleByte(Convert.ToSingle(properties["topsize"].Attributes["y"].Value));
                prim.PathShearX       = PrimObject.PathShearByte(Convert.ToSingle(properties["topshear"].Attributes["x"].Value));
                prim.PathShearY       = PrimObject.PathShearByte(Convert.ToSingle(properties["topshear"].Attributes["y"].Value));
                prim.PathSkew         = PrimObject.PathSkewByte(Convert.ToSingle(properties["skew"].Attributes["val"].Value));
                prim.PathTaperX       = PrimObject.PathTaperByte(Convert.ToSingle(properties["taper"].Attributes["x"].Value));
                prim.PathTaperY       = PrimObject.PathTaperByte(Convert.ToSingle(properties["taper"].Attributes["y"].Value));
                prim.PathTwist        = PrimObject.PathTwistByte(Convert.ToSingle(properties["twist"].Attributes["y"].Value));
                prim.PathTwistBegin   = PrimObject.PathTwistByte(Convert.ToSingle(properties["twist"].Attributes["x"].Value));
                prim.ProfileBegin     = PrimObject.ProfileBeginByte(Convert.ToSingle(properties["cut"].Attributes["x"].Value));
                prim.ProfileEnd       = PrimObject.ProfileEndByte(Convert.ToSingle(properties["cut"].Attributes["y"].Value));
                ushort curve = Convert.ToUInt16(properties["type"].Attributes["val"].Value);
                switch (curve)
                {
                case 0:
                    // Box
                    prim.ProfileCurve = 1;
                    prim.PathCurve    = 16;
                    break;

                case 1:
                    // Cylinder
                    prim.ProfileCurve = 0;
                    prim.PathCurve    = 16;
                    break;

                case 2:
                    // Prism
                    prim.ProfileCurve = 3;
                    prim.PathCurve    = 16;
                    break;

                case 3:
                    // Sphere
                    prim.ProfileCurve = 5;
                    prim.PathCurve    = 32;
                    break;

                case 4:
                    // Torus
                    prim.ProfileCurve = 0;
                    prim.PathCurve    = 32;
                    break;

                case 5:
                    // Tube
                    prim.ProfileCurve = 1;
                    prim.PathCurve    = 32;
                    break;

                case 6:
                    // Ring
                    prim.ProfileCurve = 3;
                    prim.PathCurve    = 16;
                    break;
                }
                prim.ProfileHollow = Convert.ToUInt32(properties["hollow"].Attributes["val"].Value);
                prim.Rotation      = new LLQuaternion(
                    Convert.ToSingle(properties["rotation"].Attributes["x"].Value),
                    Convert.ToSingle(properties["rotation"].Attributes["y"].Value),
                    Convert.ToSingle(properties["rotation"].Attributes["z"].Value),
                    Convert.ToSingle(properties["rotation"].Attributes["s"].Value));
                prim.Scale = new LLVector3(
                    Convert.ToSingle(properties["size"].Attributes["x"].Value),
                    Convert.ToSingle(properties["size"].Attributes["y"].Value),
                    Convert.ToSingle(properties["size"].Attributes["z"].Value));

                LLVector3 position = new LLVector3(
                    Convert.ToSingle(properties["position"].Attributes["x"].Value) + (float)Client.Avatar.Position.X,
                    Convert.ToSingle(properties["position"].Attributes["y"].Value) + (float)Client.Avatar.Position.Y,
                    Convert.ToSingle(properties["position"].Attributes["z"].Value) + (float)Client.Avatar.Position.Z + 50.0F);
                prim.Position = position;

                CurrentPrim     = prim;
                WaitingOnUpdate = true;

                Client.CurrentRegion.RezObject(prim, position, new LLVector3(Client.Avatar.Position));

                while (WaitingOnUpdate)
                {
                    System.Threading.Thread.Sleep(100);
                    Application.DoEvents();
                }

                txtLog.AppendText("Rezzed primitive with UUID " + CurrentPrim.UUID + " and ID " + CurrentPrim.ID + " \n");

                Hashtable blocks = new Hashtable();
                Hashtable fields = new Hashtable();

                /*fields["ObjectLocalID"] = CurrentPrim.ID;
                 * blocks[fields] = "ObjectData";
                 *
                 * fields = new Hashtable();
                 *
                 * fields["AgentID"] = Client.Network.AgentID;
                 * blocks[fields] = "AgentData";
                 *
                 * Packet packet = PacketBuilder.BuildPacket("ObjectSelect", Client.Protocol, blocks, Helpers.MSG_RELIABLE);
                 * Client.Network.SendPacket(packet);
                 *
                 * System.Threading.Thread.Sleep(100);*/
                Packet packet;

                byte[] byteArray = new byte[12];
                Array.Copy(position.GetBytes(), byteArray, 12);

                fields["Data"]          = byteArray;
                fields["Type"]          = (byte)9;
                fields["ObjectLocalID"] = CurrentPrim.ID;
                blocks[fields]          = "ObjectData";

                fields = new Hashtable();

                fields["AgentID"] = Client.Network.AgentID;
                blocks[fields]    = "AgentData";

                packet = PacketBuilder.BuildPacket("MultipleObjectUpdate", Client.Protocol, blocks, Helpers.MSG_RELIABLE);
                Client.Network.SendPacket(packet);
                Client.Network.SendPacket(packet);
                Client.Network.SendPacket(packet);

                System.Threading.Thread.Sleep(500);
            }
        }
コード例 #19
0
        /// <summary>
        /// Called when a message is received.
        /// </summary>
        public void OnChatReceived(SRTypes.Chat type, string playerName, string message)
        {
            Window w = Window.Get;

            // Check Bot commands
            if (type == SRTypes.Chat.All)
            {
                if (playerName == InfoManager.CharName)
                {
                    switch (message)
                    {
                    case "PING":
                        if (m_Ping != null)
                        {
                            m_Ping.Stop();
                            message = "[xBot] Your current ping : " + m_Ping.ElapsedMilliseconds + "(ms)";
                            PacketBuilder.Client.SendNotice(message);
                            m_Ping = null;
                            if (Proxy.ClientlessMode)
                            {
                                w.LogChatMessage(w.Chat_rtbxAll, "xBot", message);
                            }
                        }
                        return;
                    }
                }
            }
            // Check Leader Commands
            if (w.Party_cbxActivateLeaderCommands.Checked && playerName != "")
            {
                bool isLeader = false;
                w.Party_lstvLeaderList.InvokeIfRequired(() => {
                    isLeader = w.Party_lstvLeaderList.Items.ContainsKey(playerName.ToUpper());
                });

                if (isLeader)
                {
                    if (message.StartsWith("INJECT "))
                    {
                        string[] data = message.Substring(7).ToUpper().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        if (data.Length >= 1)
                        {
                            ushort opcode;
                            if (ushort.TryParse(data[0], NumberStyles.HexNumber, null, out opcode))
                            {
                                bool encrypted = false;
                                int  dataIndex = 1;
                                if (data.Length > 1 && (data[dataIndex] == "FALSE" || data[dataIndex] == "TRUE"))
                                {
                                    encrypted = bool.Parse(data[dataIndex++]);
                                }
                                List <byte> bytes = new List <byte>();
                                for (int j = dataIndex; j < data.Length; j++)
                                {
                                    byte temp;
                                    if (byte.TryParse(data[j], NumberStyles.HexNumber, null, out temp))
                                    {
                                        bytes.Add(temp);
                                    }
                                }
                                Proxy.Agent.InjectToServer(new Packet(opcode, encrypted, false, bytes.ToArray()));
                                PacketBuilder.SendChatPrivate(playerName, "Packet has been injected");
                            }
                        }
                    }
                    else if (message.StartsWith("TRACE"))
                    {
                        if (message == "TRACE")
                        {
                            StartTrace(playerName);
                            return;
                        }
                        else
                        {
                            string[] data = message.Substring(5).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (data.Length == 1)
                            {
                                StartTrace(data[0]);
                            }
                        }
                    }
                    else if (message.StartsWith("TELEPORT "))
                    {
                        message = message.Substring(9);
                        // Check params correctly
                        string[] data;
                        if (message.Contains(","))
                        {
                            data = message.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        }
                        else
                        {
                            data = message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        }
                        // IF there is at least 2 params
                        if (data.Length > 1)
                        {
                            // Check if the teleport link is from teleport model IDs
                            uint sourceTeleportID, destinationTeleportID;
                            if (uint.TryParse(data[0], out sourceTeleportID) && uint.TryParse(data[1], out destinationTeleportID))
                            {
                                uint destinationID = DataManager.GetTeleportLinkDestinationID(sourceTeleportID, destinationTeleportID);
                                if (destinationID != 0)
                                {
                                    SRTeleport teleport = InfoManager.TeleportAndBuildings.Find(t => t.ID == sourceTeleportID);
                                    if (teleport != null)
                                    {
                                        UseTeleportAsync(teleport, destinationID);
                                    }
                                    else
                                    {
                                        PacketBuilder.SendChatPrivate(playerName, "Teleport link is not near");
                                    }
                                }
                                else
                                {
                                    PacketBuilder.SendChatPrivate(playerName, "Teleport link not found. Please, verify the teleports ID correctly");
                                }
                                return;
                            }
                            // Check if the teleport link name exists
                            NameValueCollection teleportLinkData = DataManager.GetTeleportLink(data[0], data[1]);
                            if (teleportLinkData != null)
                            {
                                sourceTeleportID = uint.Parse(teleportLinkData["id"]);
                                // Check if the teleport source is near
                                SRTeleport teleport = InfoManager.TeleportAndBuildings.Find(t => t.ID == sourceTeleportID);
                                if (teleport != null)
                                {
                                    // Try to select teleport
                                    UseTeleportAsync(teleport, uint.Parse(teleportLinkData["destinationid"]));
                                }
                                else
                                {
                                    PacketBuilder.SendChatPrivate(playerName, "Teleport link is not near");
                                }
                            }
                            else
                            {
                                PacketBuilder.SendChatPrivate(playerName, "Teleport link not found. Please, verify the teleports location correctly");
                            }
                        }
                    }
                    else if (message.StartsWith("RECALL "))
                    {
                        message = message.Substring(7);
                        if (message != "")
                        {
                            NameValueCollection teleportLinkData = DataManager.GetTeleportLink(message);
                            if (teleportLinkData != null)
                            {
                                uint modelID = uint.Parse(teleportLinkData["id"]);
                                if (modelID != 0)
                                {
                                    // Check if the teleport is near
                                    SRTeleport teleport = InfoManager.TeleportAndBuildings.Find(t => t.ID == modelID);
                                    if (teleport != null)
                                    {
                                        PacketBuilder.DesignateRecall(teleport.UniqueID);
                                    }
                                    else
                                    {
                                        PacketBuilder.SendChatPrivate(playerName, "Teleport is not near");
                                    }
                                }
                            }
                            else
                            {
                                PacketBuilder.SendChatPrivate(playerName, "Wrong teleport name");
                            }
                        }
                    }
                    else if (message == "NOTRACE")
                    {
                        StopTrace();
                    }
                    else if (message == "RETURN")
                    {
                        if (!UseReturnScroll())
                        {
                            PacketBuilder.SendChatPrivate(playerName, "Return scroll not found");
                        }
                    }
                }
            }
        }
コード例 #20
0
ファイル: Use.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Use the Defined Item to the Ground.
        /// e.g: Rope on Ground, Obsidian Knife on Creature, Shovel on Role, etc.
        /// </summary>
        public void OnGround(ISlot slotSource, Location sqm, uint tileID, uint stackPosition)
        {
            #region " Packet Structure Analyze "
            //---------------------------------------------------------
            //USE ROPE
            //---------------------------------------------------------
            //00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18
            //---------------------------------------------------------
            //11 00 83 FF FF 40 00 0D BB 0B 0D 64 7F C3 7B 0A 82 01 00
            //SZ    ID       BP    ST ROPE  ST [ X ] [ Y ] ZZ [TID] ??
            //---------------------------------------------------------
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x83, connection);
            Builder.Append(0xFF);
            Builder.Append(0xFF);
            Builder.Append(slotSource.Container.Position);
            Builder.Append(0x00);

            Builder.Append(slotSource.Position);
            Builder.Append(slotSource.Item.Id);
            Builder.Append(slotSource.Position);

            Builder.Append(sqm.X);
            Builder.Append(sqm.Y);
            Builder.Append(sqm.Z);

            Builder.Append(tileID);
            Builder.Append(stackPosition);

            Connection.Send(Builder.GetPacket());
        }
コード例 #21
0
ファイル: Server.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Send a Private Message.
        /// </summary>
        public void Private(string playerName, string message)
        {
            #region "[rgn] Packet Structure Analyze "
            //------------------------------------------------------------------------
            //SZ      ID  SZ NM                         SZ MS
            //------------------------------------------------------------------------
            //16 00 96 04 08 00 53 75 64 75 64 69 67 75 08 00 62 6C 7A 20 63 61 72 61
            //00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x96, Connection);
            Builder.Append(ChannelType.GameChat.GetHashCode());
            Builder.Append(playerName, true);
            Builder.Append(message, true);
            Builder.SetPacketSource(PacketSource.Client);
            Connection.Send(Builder.GetPacket());
        }
コード例 #22
0
        private void btnSendPackets_Click(object sender, EventArgs e)
        {
            // Take the selected adapter
            //selectedDevice = allDevices[cmbAdapters.SelectedIndex];

            // Open the output device

            /*using (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
             *                                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
             *                                                           1000)) // read timeou`*/
            {
                // Supposing to be on ethernet, set mac source to 01:01:01:01:01:01
                MacAddress source = new MacAddress("30:3A:64:69:70:FD");

                // set mac destination to 02:02:02:02:02:02
                MacAddress destination = new MacAddress("F4:06:69:06:DC:EF");

                // Create the packets layers

                // Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                {
                    Source      = source,
                    Destination = destination
                };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                {
                    Source = new IpV4Address("10.20.228.173"),
                    Ttl    = 128,
                    // The rest of the important parameters will be set for each packet
                };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parameters
                for (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.CurrentDestination = new IpV4Address("10.20.229.46");
                    ipV4Layer.Identification     = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier     = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet

                    /*
                     * while (true)
                     * {
                     *  communicator.SendPacket(packet);
                     * }*/
                }
                communicator.SendPacket(createSynPack());
                communicator.SendPacket(PcapLib.BuildEthernetPacket());
                communicator.SendPacket(PcapLib.BuildArpPacket());
                communicator.SendPacket(PcapLib.BuildVLanTaggedFramePacket());
                communicator.SendPacket(PcapLib.BuildIpV4Packet());
                communicator.SendPacket(PcapLib.BuildIpV6Packet());
                communicator.SendPacket(PcapLib.BuildIcmpPacket());
                communicator.SendPacket(PcapLib.BuildIgmpPacket());
                communicator.SendPacket(PcapLib.BuildGrePacket());
                communicator.SendPacket(PcapLib.BuildUdpPacket());
                communicator.SendPacket(PcapLib.BuildTcpPacket());
                communicator.SendPacket(PcapLib.BuildDnsPacket());
                communicator.SendPacket(PcapLib.BuildHttpPacket());
                communicator.SendPacket(PcapLib.BuildComplexPacket());
            }
        }
コード例 #23
0
ファイル: GreTests.cs プロジェクト: shrknt35/sonarlint-vs
        public void RandomGreTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("00:01:02:03:04:05"),
                                                  Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
                                              };

            Random random = new Random();

            IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
            ipV4Layer.HeaderChecksum = null;

            for (int i = 0; i != 200; ++i)
            {
                GreLayer greLayer = random.NextGreLayer();
                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));

                PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer, payloadLayer);

                Packet packet = packetBuilder.Build(DateTime.Now);
                if (greLayer.Checksum == null &&
                    !new[] { EthernetType.IpV4, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(packet.Ethernet.IpV4.Gre.ProtocolType))
                {
                    Assert.IsTrue(packet.IsValid, "IsValid, ProtocolType=" + packet.Ethernet.IpV4.Gre.ProtocolType);
                }

                // Ethernet
                ethernetLayer.EtherType = EthernetType.IpV4;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IPv4
                ipV4Layer.Protocol = IpV4Protocol.Gre;
                ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer());
                ipV4Layer.HeaderChecksum = null;
                Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
                Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
                Assert.AreEqual(ipV4Layer.Length + greLayer.Length + payloadLayer.Length,
                                packet.Ethernet.IpV4.TotalLength);
                Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.IpV4.Version);

                // GRE
                GreDatagram actualGre = packet.Ethernet.IpV4.Gre;
                GreLayer actualGreLayer = (GreLayer)actualGre.ExtractLayer();
                if (greLayer.ChecksumPresent && greLayer.Checksum == null)
                {
                    Assert.IsTrue(actualGre.IsChecksumCorrect);
                    greLayer.Checksum = actualGre.Checksum;
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGreLayer.Key != null)
                    actualGreLayer.SetKey(actualGreLayer.KeyPayloadLength.Value, actualGreLayer.KeyCallId.Value);
                else
                {
                    Assert.IsNull(actualGreLayer.KeyPayloadLength);
                    Assert.IsNull(actualGreLayer.KeyCallId);
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGre.KeyPresent)
                {
                    Assert.AreEqual(greLayer.KeyPayloadLength, actualGre.KeyPayloadLength, "KeyPayloadLength");
                    Assert.AreEqual(greLayer.KeyCallId, actualGre.KeyCallId, "KeyCallId");
                }
                Assert.AreNotEqual(random.NextGreLayer(), actualGreLayer, "Not Layer");
                Assert.AreEqual(greLayer.Length, actualGre.HeaderLength);
                Assert.IsTrue(actualGre.KeyPresent ^ (greLayer.Key == null));
                MoreAssert.IsSmaller(8, actualGre.RecursionControl);
                MoreAssert.IsSmaller(32, actualGre.FutureUseBits);
                Assert.IsTrue(actualGre.RoutingPresent ^ (greLayer.Routing == null && greLayer.RoutingOffset == null));
                Assert.IsTrue(actualGre.SequenceNumberPresent ^ (greLayer.SequenceNumber == null));
                Assert.IsTrue(!actualGre.StrictSourceRoute || actualGre.RoutingPresent);
                if (actualGre.RoutingPresent)
                {
                    Assert.IsNotNull(actualGre.ActiveSourceRouteEntryIndex);
                    if (actualGre.ActiveSourceRouteEntryIndex < actualGre.Routing.Count)
                        Assert.IsNotNull(actualGre.ActiveSourceRouteEntry);

                    foreach (GreSourceRouteEntry entry in actualGre.Routing)
                    {
                        Assert.AreNotEqual(entry, 2);
                        Assert.AreEqual(entry.GetHashCode(), entry.GetHashCode());
                        switch (entry.AddressFamily)
                        {
                            case GreSourceRouteEntryAddressFamily.AsSourceRoute:
                                GreSourceRouteEntryAs asEntry = (GreSourceRouteEntryAs)entry;
                                MoreAssert.IsInRange(0, asEntry.AsNumbers.Count, asEntry.NextAsNumberIndex);
                                if (asEntry.NextAsNumberIndex != asEntry.AsNumbers.Count)
                                    Assert.AreEqual(asEntry.AsNumbers[asEntry.NextAsNumberIndex], asEntry.NextAsNumber);
                                break;

                            case GreSourceRouteEntryAddressFamily.IpSourceRoute:
                                GreSourceRouteEntryIp ipEntry = (GreSourceRouteEntryIp)entry;
                                MoreAssert.IsInRange(0, ipEntry.Addresses.Count, ipEntry.NextAddressIndex);
                                if (ipEntry.NextAddressIndex != ipEntry.Addresses.Count)
                                    Assert.AreEqual(ipEntry.Addresses[ipEntry.NextAddressIndex], ipEntry.NextAddress);
                                break;

                            default:
                                GreSourceRouteEntryUnknown unknownEntry = (GreSourceRouteEntryUnknown)entry;
                                MoreAssert.IsInRange(0, unknownEntry.Data.Length, unknownEntry.PayloadOffset);
                                break;

                        }
                    }
                }
                else
                {
                    Assert.IsNull(actualGre.ActiveSourceRouteEntry);
                }

                Assert.IsNotNull(actualGre.Payload);
                switch (actualGre.ProtocolType)
                {
                    case EthernetType.IpV4:
                        Assert.IsNotNull(actualGre.IpV4);
                        break;

                    case EthernetType.Arp:
                        Assert.IsNotNull(actualGre.Arp);
                        break;
                }
            }
        }
コード例 #24
0
    }//update

    private void HandleSelection()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //print("Casting");
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))//, 50000, peiceMask))
        {
            PlayerPeice  p;
            BoardSegment b = null;

            //bool isPeice = true;

            //print("castHit");
            GameObject obj = hit.collider.gameObject;
            if (obj != null)
            {
                p = obj.GetComponentInParent <PlayerPeice>();

                b = obj.GetComponentInParent <BoardSegment>();

                if (p == null && b == null)//if it's not a player peice
                {
                    return;
                }
            }
            else
            {
                return;
            }



            if (p)
            {
                if (p.owner == playerState)
                {
                    if (p == peice) //we have clicked on our selected peice again
                    {
                        peiceSelected = false;
                        peice         = null;
                    }
                    else //we have clicked on one of our peices
                    {
                        peice = p;
                        ControllerGameClient.singleton.SendPacketToServer(PacketBuilder.Hover((int)peice.acessIndex.x, (int)peice.acessIndex.y));
                        peiceSelected = true;
                    }
                }
                else if (peiceSelected)   //we have a piece selected and we are clicking on the opponents peice

                {
                    SendMoveToServer((int)p.acessIndex.x, (int)p.acessIndex.y);
                }
            }
            else if (peiceSelected && b)   //we have selected a segmant and we have a piece selected

            {
                SendMoveToServer(b.pos.indexX, b.pos.indexY);
            }


            /*
             * //Debug.Log(hit.collider.gameObject.name);
             * peice = hit.collider.gameObject.GetComponentInParent<PlayerPeice>();
             * segment = hit.collider.gameObject.GetComponent<BoardSegment>();
             *
             *
             * if (IsPeice(peice, segment)) {
             *
             *  ControllerGameClient.singleton.SendPacketToServer(PacketBuilder.Hover((int)peice.acessIndex.x, (int)peice.acessIndex.y));
             * }
             * //Debug.Log(peice.peiceType + " " + peice.owner);
             */
        }

        /*
         *         else if (Physics.Raycast(ray, out hit, 50000, boardMask) && peiceSelected) {
         *
         *             segment = hit.collider.gameObject.GetComponent<BoardSegment>();
         *
         *
         *
         *
         *
         *         }//raycasthit
         */
    }
コード例 #25
0
 public void Close(byte index)
 {
     var builder = new PacketBuilder(Packets.SendToClient.CloseContainer);
     builder.AddU8(index);
     builder.Send(_player);
 }
コード例 #26
0
 public void SendChat(string message)
 {
     ControllerGameClient.singleton.SendPacketToServer(PacketBuilder.Chat(message));
 }
コード例 #27
0
ファイル: IpV4Tests.cs プロジェクト: yang123vc/WiFiSpy
        public void RandomIpV4Test()
        {
            MacAddress         ethernetSource      = new MacAddress("00:01:02:03:04:05");
            MacAddress         ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");
            const EthernetType EthernetType        = EthernetType.IpV4;

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = ethernetSource,
                Destination = ethernetDestination,
                EtherType   = EthernetType
            };

            int seed = new Random().Next();

            Console.WriteLine(seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer();
                ipV4Layer.HeaderChecksum = null;

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.NextInt(0, 50 * 1024));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, payloadLayer);

                Assert.IsTrue(ipV4Layer.Protocol == IpV4Protocol.Ip ||
                              ipV4Layer.Protocol == IpV4Protocol.IpV6 ||
                              ipV4Layer.Protocol == IpV4Protocol.Udp ||
                              ipV4Layer.Protocol == IpV4Protocol.Tcp ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetGroupManagementProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetControlMessageProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.Gre ||
                              packet.IsValid, "IsValid (" + ipV4Layer.Protocol + ")");

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IpV4
                ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
                Assert.AreEqual(ipV4Layer.Destination, packet.Ethernet.IpV4.Destination, "Destination");
                Assert.AreNotEqual(ipV4Layer, null);
                Assert.AreNotEqual(ipV4Layer, new PayloadLayer());
                Assert.IsNotNull(ipV4Layer.ToString());
                Assert.AreEqual(IpV4Datagram.HeaderMinimumLength + ipV4Layer.Options.BytesLength, packet.Ethernet.IpV4.HeaderLength, "IP HeaderLength");
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.IpV4.TotalLength, "IP TotalLength");
                Assert.AreNotEqual(2, packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsTrue(ipV4Layer.Fragmentation == packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation != packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation.Equals(0), "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Offset != 0)
                {
                    Assert.AreNotEqual(ipV4Layer.Fragmentation, IpV4Fragmentation.None, "IP Fragmentation");
                }
                Assert.AreEqual(ipV4Layer.Fragmentation.GetHashCode(), packet.Ethernet.IpV4.Fragmentation.GetHashCode(), "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Options, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Offset, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Equals(IpV4Fragmentation.None))
                {
                    Assert.AreEqual(IpV4FragmentationOptions.None, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                    Assert.AreEqual(0, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                }
                Assert.AreEqual(true, packet.Ethernet.IpV4.IsHeaderChecksumCorrect, "IP HeaderChecksumCorrect");
                Assert.AreNotEqual(null, packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreNotEqual(packet.Ethernet.IpV4.Options, null, "IP Options");
                Assert.AreNotEqual(new IpV4Options(new IpV4OptionUnknown(0, new byte[35])), packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreEqual(ipV4Layer.Options.GetHashCode(), packet.Ethernet.IpV4.Options.GetHashCode(), "IP Options HashCode");
                Assert.IsNotNull(packet.Ethernet.IpV4.Options.ToString());
                for (int optionIndex = 0; optionIndex != ipV4Layer.Options.Count; ++optionIndex)
                {
                    IpV4Option option = ipV4Layer.Options[optionIndex];
                    Assert.AreEqual(option, packet.Ethernet.IpV4.Options[optionIndex]);
                    Assert.IsFalse(option.Equals(null));
                }

                if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(TcpDatagram));
                }
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(UdpDatagram));
                }
                else
                {
                    Assert.IsNull(packet.Ethernet.IpV4.Transport);
                }

                if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Ip)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Ip, typeof(IpV4Datagram));
                }
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.IpV6)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Ip, typeof(IpV6Datagram));
                }
                else
                {
                    Assert.IsNull(packet.Ethernet.IpV4.Ip);
                }

                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.IpV4.Payload, "IP Payload");
            }
        }
コード例 #28
0
ファイル: RavenClient.cs プロジェクト: c2j/raven-csharp
        /// <summary>
        /// Sends the specified packet to Sentry.
        /// </summary>
        /// <param name="packet">The packet to send.</param>
        /// <param name="dsn">The Data Source Name in Sentry.</param>
        /// <returns>
        /// The <see cref="JsonPacket.EventID"/> of the successfully captured JSON packet, or <c>null</c> if it fails.
        /// </returns>
        protected virtual string Send(JsonPacket packet, Dsn dsn)
        {
            packet.Logger = Logger;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(dsn.SentryUri);
                request.Method = "POST";
                request.Accept = "application/json";
                request.Headers.Add("X-Sentry-Auth", PacketBuilder.CreateAuthenticationHeader(dsn));
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                request.UserAgent = PacketBuilder.UserAgent;

                if (Compression)
                {
                    request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
                    request.AutomaticDecompression = DecompressionMethods.Deflate;
                    request.ContentType = "application/octet-stream";
                }
                else
                    request.ContentType = "application/json; charset=utf-8";

                /*string data = packet.ToString(Formatting.Indented);
                Console.WriteLine(data);*/

                string data = packet.ToString(Formatting.None);

                if (LogScrubber != null)
                    data = LogScrubber.Scrub(data);

                // Write the messagebody.
                using (Stream s = request.GetRequestStream())
                {
                    if (Compression)
                        GzipUtil.Write(data, s);
                    else
                    {
                        using (StreamWriter sw = new StreamWriter(s))
                            sw.Write(data);
                    }
                }

                using (HttpWebResponse wr = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = wr.GetResponseStream())
                {
                    if (responseStream == null)
                        return null;

                    using (StreamReader sr = new StreamReader(responseStream))
                    {
                        string content = sr.ReadToEnd();
                        var response = JsonConvert.DeserializeObject<dynamic>(content);
                        return response.id;
                    }
                }
            }
            catch (Exception exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("[ERROR] ");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine(exception);

                WebException webException = exception as WebException;
                if (webException != null && webException.Response != null)
                {
                    string messageBody;
                    using (Stream stream = webException.Response.GetResponseStream())
                    {
                        if (stream == null)
                            return null;

                        using (StreamReader sw = new StreamReader(stream))
                            messageBody = sw.ReadToEnd();
                    }

                    Console.WriteLine("[MESSAGE BODY] " + messageBody);
                }
            }

            return null;
        }
コード例 #29
0
        // proscanování sítě pomocí arp
        public Device[] Scan(IPAddress start, IPAddress end, int tries)
        {
            List <Device> devices = new List <Device>();
            bool          tmp     = true;

            // zaznamenávání příchozích packetů
            new Thread(new ThreadStart(delegate()
            {
                using (PacketCommunicator pc = Device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    while (tmp)
                    {
                        var result = pc.ReceivePacket(out Packet p);
                        if (result == PacketCommunicatorReceiveResult.Ok)
                        {
                            if (p.Ethernet.EtherType == EthernetType.Arp && p.Ethernet.Arp.Operation == ArpOperation.Reply)
                            {
                                var temp = new Device(p.Ethernet.Arp.SenderProtocolAddress.ToArray(), p.Ethernet.Arp.SenderHardwareAddress.ToArray(), null);
                                //Console.WriteLine(temp.ToString());
                                if (!devices.Any(x => x.Compare(temp)))
                                {
                                    devices.Add(temp);
                                }
                            }
                        }
                    }
                }
            })).Start();
            // vysílání arp packetů
            using (PacketCommunicator pc = Device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                for (int i = 0; i < tries; i++)
                {
                    foreach (var addr in PosibleAddresses(start, end))
                    {
                        Packet p = PacketBuilder.Build
                                   (
                            DateTime.Now,
                            new EthernetLayer
                        {
                            EtherType   = EthernetType.None,
                            Destination = new MacAddress("ff:ff:ff:ff:ff:ff"),
                            Source      = new MacAddress(PhysicalAddrString)
                        },
                            new ArpLayer
                        {
                            Operation             = ArpOperation.Request,
                            ProtocolType          = EthernetType.IpV4,
                            SenderHardwareAddress = Array.AsReadOnly(PhysicalAddr.GetAddressBytes()),
                            SenderProtocolAddress = Array.AsReadOnly(Address.GetAddressBytes()),
                            TargetHardwareAddress = Array.AsReadOnly(new byte[] { 255, 255, 255, 255, 255, 255 }),
                            TargetProtocolAddress = Array.AsReadOnly(addr.GetAddressBytes())
                        }
                                   );
                        pc.SendPacket(p);
#if DEBUG
                        Console.WriteLine(addr.ToString());
#endif
                    }
                }
                tmp = false;
            }
            return(devices.ToArray());
        }
コード例 #30
0
    private void OnMsgRecv(object sender, Client.ClientMsgEventArgs e)
    {
        if (e.Len == 0)
        {
            Debug.Log("Disconnected from the server");
            online = false;
            return;
        }
        online = true;

        int    dataIndex = 0;
        Packet packet    = PacketBuilder.Parse(e.Buffer, ref dataIndex);

        // Process the packet
        switch (packet.Type)
        {
        case Packet.PacketType.Text:
            recvText        = ((PacketText)packet).Data;
            receivedNewText = true;
            Debug.Log("[S->C]: " + recvText + " (" + packet.Size + " of " + e.Len + " bytes)");
            break;

        case Packet.PacketType.Spawn:
            spawn       = ((PacketSpawn)packet).Data;
            justSpawned = true;
            Debug.Log("[S->C]: Spawn Position = " + spawn.Pos + " (" + packet.Size + " of " + e.Len + " bytes)");
            break;

        case Packet.PacketType.OtherClients:
            var others = ((PacketOtherClients)packet).Data;
            foreach (var c in others)
            {
                // Add or update an oponent by its Id (and restore its TTL)
                Oponent oponent = oponents.AddOponent(c.Id);
                for (int i = 0; i < c.TransCount; i++)
                {
                    oponent.AddTransform(c.GetTrans(i));
                }
            }
            break;

        case Packet.PacketType.Objects:
            List <Trans> objectsRecv = ((PacketObjects)packet).Data;
            foreach (var o in objectsRecv)
            {
                Trans t = objects.Where(x => x.Id == o.Id).FirstOrDefault();
                if (t == null)
                {
                    Debug.Log("Received " + o.Id + " for the first time");
                    objects.Add(o);
                }
                else
                {
                    t.Pos = o.Pos;
                    t.Rot = o.Rot;
                }
            }
            break;

        case Packet.PacketType.Benchmark:
            NetBenchmarks b = ((PacketBenchmark)packet).Data;
            b.recvTimeStamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
            Packet p = PacketBuilder.Build(Packet.PacketType.Benchmark, b);
            client.Send(p.ToArray(), p.Size);
            break;

        default:
            Debug.Assert(false);
            Debug.LogError("Invalid PacketType" + " (" + packet.Size + " of " + e.Len + " bytes)");
            break;
        }
    }
コード例 #31
0
ファイル: System.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Send a System Message to Client.
        /// </summary>
        public byte[] Send(string message, SystemMsgColor color)
        {
            #region "[rgn] Packet Structure Analyze "
            //---------------------------
            //07 00 B4 12 03 00 69 61 65
            //---------------------------
            //SZ    ID CR SZ    i  a  e
            //---------------------------
            #endregion

            PacketBuilder Builder = new PacketBuilder(0xB4, Connection);
            Builder.Append(color.GetHashCode());
            Builder.Append(message, true, true);
            Builder.SetPacketSource(PacketSource.Server);
            Connection.Send(Builder.GetPacket());
            return Builder.GetPacket().Data;
        }
コード例 #32
0
    void OnGUI()
    {
        if (!active)
        {
            return;
        }

        GUI.DrawTexture(MenuUtils.ResizeGUI(new Rect(20, 50, 600 * 0.4f, 189 * 0.4f)), logo, ScaleMode.ScaleToFit);
        GUI.Box(MenuUtils.ResizeGUI(new Rect(10, 530, 780, 50)), "", skin.box);

        GUI.Label(MenuUtils.ResizeGUI(new Rect(20, 535, 700, 40)), "BOMBERFALL - Student Project made in 50 days by Cyril Basset and Jean-Vincent Lamberti using the UnityEngine", skin.label);
        GUI.Label(MenuUtils.ResizeGUI(new Rect(20, 550, 800, 40)), "Music by PocketMaster. All musics, sounds and fonts are under Creative Commons Licences and free for non-commercial use", skin.label);

        if (GUI.Button(MenuUtils.ResizeGUI(new Rect(20, 200, 100, 30)), "PLAY", skin.button))
        {
            if (menu != MenuConfig.MainMenuSelected.PLAY_SELECTED)
            {
                menu    = MenuConfig.MainMenuSelected.PLAY_SELECTED;
                submenu = MenuConfig.SubMenuSelected.NO_SELECTED;
            }
            else
            {
                menu    = MenuConfig.MainMenuSelected.NO_SELECTED;
                submenu = MenuConfig.SubMenuSelected.NO_SELECTED;
            }
        }

        if (GUI.Button(MenuUtils.ResizeGUI(new Rect(20, 240, 100, 30)), "OPTIONS", skin.button))
        {
            if (menu != MenuConfig.MainMenuSelected.OPTION_SELECTED)
            {
                menu = MenuConfig.MainMenuSelected.OPTION_SELECTED;
            }
            else
            {
                menu    = MenuConfig.MainMenuSelected.NO_SELECTED;
                submenu = MenuConfig.SubMenuSelected.NO_SELECTED;
            }
        }

        if (GUI.Button(MenuUtils.ResizeGUI(new Rect(20, 280, 100, 30)), "QUIT", skin.button))
        {
            Application.Quit();
        }


        if (menu == MenuConfig.MainMenuSelected.OPTION_SELECTED)
        {
            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(140, 240, 100, 30)), "PRESENTATION", skin.button))
            {
                if (submenu != MenuConfig.SubMenuSelected.PRESENTATION_SELECTED)
                {
                    submenu = MenuConfig.SubMenuSelected.PRESENTATION_SELECTED;
                }
                else
                {
                    submenu = MenuConfig.SubMenuSelected.NO_SELECTED;
                }
            }
            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(140, 280, 100, 30)), "CONTROLS", skin.button))
            {
                if (submenu != MenuConfig.SubMenuSelected.CONTROLS_SELECTED)
                {
                    submenu = MenuConfig.SubMenuSelected.CONTROLS_SELECTED;
                }
                else
                {
                    submenu = MenuConfig.SubMenuSelected.NO_SELECTED;
                }
            }
        }

        if (menu == MenuConfig.MainMenuSelected.PLAY_SELECTED)
        {
            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(140, 200, 100, 30)), "HOST", skin.button))
            {
                if (submenu != MenuConfig.SubMenuSelected.HOST_SELECTED)
                {
                    submenu = MenuConfig.SubMenuSelected.HOST_SELECTED;
                }
                else
                {
                    submenu = MenuConfig.SubMenuSelected.NO_SELECTED;
                }
            }
            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(140, 240, 100, 30)), "JOIN", skin.button))
            {
                if (submenu != MenuConfig.SubMenuSelected.JOIN_SELECTED)
                {
                    submenu = MenuConfig.SubMenuSelected.JOIN_SELECTED;
                }
                else
                {
                    submenu = MenuConfig.SubMenuSelected.NO_SELECTED;
                }
            }
        }


        if (submenu == MenuConfig.SubMenuSelected.PRESENTATION_SELECTED)
        {
            GUI.Box(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)), "PRESENTATION SETTINGS", skin.box);
            GUI.BeginGroup(MenuUtils.ResizeGUI(new Rect(280, 120, 500, 600)));


            GUI.Label(MenuUtils.ResizeGUI(new Rect(240, 55, 100, 40)), "Aspect Ratio :", skin.label);

            int selGrid;
            if ((selGrid = comboBoxQuality.List(MenuUtils.ResizeGUI(new Rect(70, 225, 150, 20)), m_quality[quality].text, m_quality, skin.button, skin.box, skin.customStyles[0])) != quality)
            {
                quality = selGrid;
            }


            GUI.Label(MenuUtils.ResizeGUI(new Rect(240, 255, 100, 40)), "V-Sync :", skin.label);

            if ((selGrid = comboboxVsync.List(MenuUtils.ResizeGUI(new Rect(325, 255, 150, 20)), m_vsyncContent[m_vsync].text, m_vsyncContent, skin.button, skin.box, skin.customStyles[0])) != m_vsync)
            {
                m_vsync = selGrid;
            }



            GUI.Label(MenuUtils.ResizeGUI(new Rect(240, 225, 100, 40)), "Anti Aliasing :", skin.label);

            if ((selGrid = comboboxAA.List(MenuUtils.ResizeGUI(new Rect(325, 225, 150, 20)), m_aa[m_antialiasing].text, m_aa, skin.button, skin.box, skin.customStyles[0])) != m_antialiasing)
            {
                m_antialiasing = selGrid;
            }


            GUI.Label(MenuUtils.ResizeGUI(new Rect(240, 145, 100, 40)), "Resolution :", skin.label);


            switch (m_ratio)
            {
            case 0:
                if ((selGrid = comboBoxResolution.List(MenuUtils.ResizeGUI(new Rect(330, 145, 100, 20)), _4_3_combobox[m_resolution].text, _4_3_combobox, skin.button, skin.box, skin.customStyles[0])) != m_resolution)
                {
                    m_resolution = selGrid;
                }
                break;

            case 1:
                if ((selGrid = comboBoxResolution.List(MenuUtils.ResizeGUI(new Rect(330, 145, 100, 20)), _16_10_combobox[m_resolution].text, _16_10_combobox, skin.button, skin.box, skin.customStyles[0])) != m_resolution)
                {
                    m_resolution = selGrid;
                }
                break;

            case 2:
                if ((selGrid = comboBoxResolution.List(MenuUtils.ResizeGUI(new Rect(330, 145, 100, 20)), _16_9_combobox[m_resolution].text, _16_9_combobox, skin.button, skin.box, skin.customStyles[0])) != m_resolution)
                {
                    m_resolution = selGrid;
                }
                break;
            }

            if ((selGrid = comboBoxControl.List(MenuUtils.ResizeGUI(new Rect(330, 55, 100, 20)), ratio_combobox[m_ratio].text, ratio_combobox, skin.button, skin.box, skin.customStyles[0])) != m_ratio)
            {
                m_ratio = selGrid;
            }


            GUI.Label(MenuUtils.ResizeGUI(new Rect(0, 30, 200, 40)), "Music Volume", skin.label);
            m_music_volume = GUI.HorizontalSlider(MenuUtils.ResizeGUI(new Rect(0, 60, 180, 20)), m_music_volume, 0, 10.0f, skin.horizontalSlider, skin.horizontalSliderThumb);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(195, 55, 40, 40)), Math.Round(m_music_volume * 10, 0).ToString() + "%", skin.label);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(0, 120, 300, 40)), "Sound Effects Volume", skin.label);
            m_sound_effects_volume = GUI.HorizontalSlider(MenuUtils.ResizeGUI(new Rect(0, 150, 180, 20)), m_sound_effects_volume, 0, 10.0f, skin.horizontalSlider, skin.horizontalSliderThumb);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(195, 145, 60, 40)), Math.Round(m_sound_effects_volume * 10, 0).ToString() + "%", skin.label);

            GUI.Label(MenuUtils.ResizeGUI(new Rect(0, 195, 85, 20)), "Fullscreen :", skin.label);

            m_fullscreen = GUI.Toggle(MenuUtils.ResizeGUI(new Rect(70, 195, 100, 20)), m_fullscreen, m_fullscreen ? "True" : "False", skin.toggle);


            GUI.Label(MenuUtils.ResizeGUI(new Rect(0, 225, 100, 40)), "Quality :", skin.label);


            GUI.EndGroup();

            SetPlayerPrefs("video");
        }

        if (submenu == MenuConfig.SubMenuSelected.CONTROLS_SELECTED)
        {
            LoadFromPlayerPrefs("controls");

            GUI.Box(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)), "CONTROLS SETTINGS", skin.box);
            GUI.BeginGroup(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)));
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 30, 70, 40)), "Keybindings :", skin.label);
            //Key Bindings
            GUI.Box(MenuUtils.ResizeGUI(new Rect(80, 30, 400, 250)), "", skin.box);
            m_keybindings_scrollPosition = GUI.BeginScrollView(MenuUtils.ResizeGUI(new Rect(80, 30, 400, 250)), m_keybindings_scrollPosition, MenuUtils.ResizeGUI(new Rect(0, 0, 200, 25 * (MenuConfig.m_keybindings_labels.Length + 1))));
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 0, 400, 40)), "You can click and type any letter from A to Z to assign it", skin.label);

            int i;
            for (i = 0; i < MenuConfig.m_keybindings_labels.Length; i++)
            {
                GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 25 * (i + 1), 90, 40)), MenuConfig.m_keybindings_labels[i] + " :", skin.label);
                MenuConfig.m_keybindings[i] = GUI.TextField(MenuUtils.ResizeGUI(new Rect(130, 25 * (i + 1), 20, 20)), MenuConfig.m_keybindings[i], 1, skin.textField);
            }
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 25 * (i + 1), 80, 40)), "Jump :", skin.label);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(130, 25 * (i + 1), 80, 40)), "Space", skin.label);
            i++;
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 25 * (i + 1), 80, 40)), "Pause :", skin.label);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(130, 25 * (i + 1), 150, 40)), "Esc.", skin.label);



            GUI.EndScrollView();
            //End Key Bindings

            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(420, 290, 60, 20)), "Apply", skin.button))
            {
                SetPlayerPrefs("keybindings");
                LoadFromPlayerPrefs("keybindings");
            }
            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(350, 290, 60, 20)), "Default", skin.button))
            {
                MenuConfig.m_keybindings = MenuConfig.m_keybindings_default;
                SetPlayerPrefs("keybindings");
                LoadFromPlayerPrefs("keybindings");
            }

            GUI.EndGroup();
        }

        if (submenu == MenuConfig.SubMenuSelected.HOST_SELECTED)
        {
            LoadFromPlayerPrefs("host_params");

            GUI.Box(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)), "HOST SETTINGS", skin.box);
            GUI.BeginGroup(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)));
            int selGrid, selGrid2, nbPlayers, nbCPUs;

            GUI.Label(MenuUtils.ResizeGUI(new Rect(50, 85, 30, 40)), "Map", skin.label);

            if (hasMapFiles)
            {
                if ((selGrid2 = comboBoxMaps.List(MenuUtils.ResizeGUI(new Rect(90, 85, 150, 20)), maps_combobox[m_map_index].text, maps_combobox, skin.button, skin.box, skin.customStyles[0])) != m_map_index)
                {
                    m_map_index = selGrid2;
                }
            }
            else
            {
                GUI.Label(MenuUtils.ResizeGUI(new Rect(90, 85, 150, 100)), "No maps found. Please move you map files to the Maps directory located at the root of the game directory.", skin.label);
            }


            GUI.Label(MenuUtils.ResizeGUI(new Rect(50, 30, 100, 40)), "Gameplay Mode", skin.label);

            if ((selGrid = comboBoxGamemode.List(MenuUtils.ResizeGUI(new Rect(150, 30, 70, 20)), gameplay_mode_combobox[m_gameplay_mode].text, gameplay_mode_combobox, skin.button, skin.box, skin.customStyles[0])) != m_gameplay_mode)
            {
                m_gameplay_mode = selGrid;
            }

            if (1 == selGrid)
            {
                GUI.Label(MenuUtils.ResizeGUI(new Rect(250, 30, 100, 40)), "Game Duration", skin.label);
                m_game_duration = GUI.HorizontalSlider(MenuUtils.ResizeGUI(new Rect(350, 35, 85, 20)), m_game_duration, 30f, 300f, skin.horizontalSlider, skin.horizontalSliderThumb);
                GUI.Label(MenuUtils.ResizeGUI(new Rect(450, 30, 140, 40)), Math.Round(m_game_duration) + " sec.", skin.label);
            }


            GUI.Label(MenuUtils.ResizeGUI(new Rect(250, 50, 50, 40)), "Players", skin.label);

            if ((nbPlayers = comboboxNbPlayers.List(MenuUtils.ResizeGUI(new Rect(310, 50, 25, 20)), nb_players_combobox[m_nb_players].text, nb_players_combobox, skin.button, skin.box, skin.customStyles[0])) != m_nb_players)
            {
                /* nb_CPUs_combobox = MenuUtils.SetComboboxRange( 0, 3 - nbPlayers);*/
                m_nb_players = nbPlayers;
            }

            //GUI.Label(MenuUtils.ResizeGUI(new Rect(345, 50, 50, 40)), "CPUs", skin.label);

            //if ((nbCPUs = comboboxNbCPUs.List(MenuUtils.ResizeGUI(new Rect(405, 50, 25, 20)), nb_CPUs_combobox[m_nb_CPUs].text, nb_CPUs_combobox, skin.button, skin.box, skin.customStyles[0])) != m_nb_CPUs)
            //{
            //    nb_players_combobox = MenuUtils.SetComboboxRange(1, 4 - nbCPUs);
            //    m_nb_CPUs = nbCPUs;
            //}

            GUI.Label(MenuUtils.ResizeGUI(new Rect(250, 140, 200, 40)), "Active power-ups :", skin.label);

            for (int index = 0, j = 0, len = MenuConfig.power_ups_settings.Length; index < len; index++)
            {
                if (index != 4 && index != 8 && index != 3)
                {
                    continue;
                }

                MenuConfig.power_ups_settings[index] = GUI.Toggle(MenuUtils.ResizeGUI(new Rect(260, 160 + (j * 20), 250, 20)), MenuConfig.power_ups_settings[index], MenuConfig.power_ups_string[index], skin.toggle);
                j++;
            }

            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(260, 300, 190, 80)), "Create Game", skin.button))
            {
                Debug.Log("Create game " + m_nb_players);
                gameMgr.gameIntel = new GameIntel(m_game_duration, m_gameplay_mode, MenuConfig.power_ups_settings, m_nb_players + 2, m_nb_CPUs, m_auth_reco, m_disable_persp_change, MenuConfig.maps_string[m_map_index]);
                gameMgr.maps      = Maps.LoadMapsFromFile(MenuConfig.maps_string[m_map_index]);
                gameMgr.StartServer();
                gameMgr.StartClient("127.0.0.1");
                isHost  = true;
                submenu = MenuConfig.SubMenuSelected.LOBBY_SELECTED;
            }



            //GUI.Label(MenuUtils.ResizeGUI(new Rect(50, 260, 250, 20)), "Additionnal Settings :", skin.label);

            //GUI.Label(MenuUtils.ResizeGUI(new Rect(50, 290, 150, 20)), "Server password", skin.label);

            //m_server_password = GUI.PasswordField(MenuUtils.ResizeGUI(new Rect(140, 290, 100, 20)), m_server_password, '*', skin.textField);


            //m_disable_persp_change = GUI.Toggle(MenuUtils.ResizeGUI(new Rect(50, 320, 190, 20)), m_disable_persp_change, "Disable perspective's change", skin.toggle);
            //m_auth_reco = GUI.Toggle(MenuUtils.ResizeGUI(new Rect(50, 340, 190, 20)), m_auth_reco, "Allow players to reconnect", skin.toggle);



            GUI.EndGroup();

            SetPlayerPrefs("host_params");
        }

        if (submenu == MenuConfig.SubMenuSelected.JOIN_SELECTED)
        {
            LoadFromPlayerPrefs("join_params");

            GUI.Box(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)), "JOIN A GAME", skin.box);
            GUI.BeginGroup(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)));


            GUI.Label(MenuUtils.ResizeGUI(new Rect(50, 70, 150, 20)), "Server IP", skin.label);

            serverIP = GUI.TextField(MenuUtils.ResizeGUI(new Rect(140, 70, 100, 20)), serverIP, skin.textField);


            //GUI.Label(MenuUtils.ResizeGUI(new Rect(50, 110, 150, 20)), "Server password", skin.label);

            //m_server_password = GUI.PasswordField(MenuUtils.ResizeGUI(new Rect(140, 110, 100, 20)), m_server_password, '*', skin.textField);

            if (GUI.Button(new Rect(140, 240, 190, 80), "Join game", skin.button))
            {
                if (gameMgr.StartClient(serverIP))
                {
                    isHost = false;
                    m_connected_players.Add(new MenuConfig.ConnectedPlayer("Player " + (m_connected_players.Count + 1), false));
                    submenu = MenuConfig.SubMenuSelected.LOBBY_SELECTED;
                }
            }


            GUI.EndGroup();

            SetPlayerPrefs("join_params");
        }

        if (submenu == MenuConfig.SubMenuSelected.LOBBY_SELECTED)
        {
            GUI.Box(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)), "GAME LOBBY", skin.box);
            GUI.BeginGroup(MenuUtils.ResizeGUI(new Rect(260, 120, 500, 400)));


            //HOST SETTINGS OVERVIEW
            //GUI.Label(MenuUtils.ResizeGUI(new Rect(220, 50, 180, 40)), "Host settings overview :", skin.label);

            GUI.BeginGroup(MenuUtils.ResizeGUI(new Rect(120, 60, 300, 400)));
            GUI.Box(MenuUtils.ResizeGUI(new Rect(0, 0, 200, 200)), "SETTINGS OVERVIEW", skin.box);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 30, 150, 20)), "Game Mode :  " + (gameMgr.gameIntel.game_mode == Config.GameMode.ARCADE ? "Arcade" : "Survival"), skin.label);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 50, 150, 20)), "Map Name :  " + gameMgr.gameIntel.map_name, skin.label);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 70, 150, 20)), "Players :  " + gameMgr.gameIntel.nb_players, skin.label);
            if (gameMgr.gameIntel.game_mode == Config.GameMode.ARCADE)
            {
                GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 90, 150, 20)), "Game Duration :  " + gameMgr.gameIntel.nb_players, skin.label);
            }

            //GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 60, 150, 20)), "CPUs :  " + gameMgr.gameIntel.nb_cpus, skin.label);
            //GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 70, 150, 20)), "Perspective change :  " + (gameMgr.gameIntel.disable_persp_change ? "Deactivated" : "Activated"), skin.label);
            //GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 80, 150, 20)), "Reconnection :  " + (gameMgr.gameIntel.auth_reco ? "Authorized" : "Not Authorized"), skin.label);
            GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 100, 150, 200)), "Active power-ups :  " + gameMgr.gameIntel.powers_str + "Bomb Up", skin.label);

            GUI.EndGroup();

            //CHAT SECTION
            GUI.Box(MenuUtils.ResizeGUI(new Rect(80, 300, 250, 65)), "", skin.box);
            m_chat_scrollPosition = GUI.BeginScrollView(MenuUtils.ResizeGUI(new Rect(80, 300, 250, 65)), m_chat_scrollPosition, MenuUtils.ResizeGUI(new Rect(0, 0, 200, 10 * (m_chat_messages.Count + 1))));


            for (int i = 0; i < m_chat_messages.Count; i++)
            {
                GUI.Label(MenuUtils.ResizeGUI(new Rect(10, 10 * i, 380, 65)), m_chat_messages[i].sender + " : " + m_chat_messages[i].message, skin.label);
            }



            GUI.EndScrollView();


            GUI.Label(MenuUtils.ResizeGUI(new Rect(40, 368, 80, 20)), "Message", skin.label);

            m_message = GUI.TextField(MenuUtils.ResizeGUI(new Rect(80, 365, 250, 20)), m_message, 150); //Allows Multi line input if using custom skin


            if (GUI.Button(MenuUtils.ResizeGUI(new Rect(335, 365, 50, 20)), "Send", skin.button) || GUIKeyDown(KeyCode.Return))
            {
                if (m_message.Length > 0)
                {
                    if (gameMgr.s != null)
                    {
                        gameMgr.s.SendPacketBroadCast(PacketBuilder.BuildSendMessage("Server", m_message));
                        AddMessage("Server", m_message);
                    }
                    else if (gameMgr.c != null)
                    {
                        gameMgr.c.SendPacket(PacketBuilder.BuildSendMessage("Player", m_message));
                    }
                    m_message = "";
                }
            }



            if (isHost)
            {
                if (GUI.Button(MenuUtils.ResizeGUI(new Rect(400, 350, 80, 30)), "Start", skin.button))
                {
                    if (gameMgr.s.client_count > 1)
                    {
                        gameMgr.StartGame();
                        active = false;
                    }
                }
            }

            GUI.EndGroup();
        }

        if (prev_submenu != submenu && prev_submenu == MenuConfig.SubMenuSelected.LOBBY_SELECTED)
        {
            gameMgr.Reset();
        }

        prev_submenu = submenu;
    }
コード例 #33
0
ファイル: HttpTests.cs プロジェクト: JackWangCUMT/WiFiSpy
        public void HttpResponseWithoutVersionStatusCodeOrReasonPhraseTest()
        {
            HttpResponseLayer httpLayer = new HttpResponseLayer();
            PacketBuilder builder = new PacketBuilder(new EthernetLayer(),
                                                      new IpV4Layer(),
                                                      new TcpLayer(),
                                                      httpLayer);

            // null version
            Packet packet = builder.Build(DateTime.Now);
            Assert.IsNull(packet.Ethernet.IpV4.Tcp.Http.Version);

            // null status code
            httpLayer.Version = HttpVersion.Version11;
            packet = builder.Build(DateTime.Now);
            Assert.IsNotNull(packet.Ethernet.IpV4.Tcp.Http.Version);
            Assert.IsNull(((HttpResponseDatagram)packet.Ethernet.IpV4.Tcp.Http).StatusCode);

            // null reason phrase
            httpLayer.StatusCode = 200;
            packet = builder.Build(DateTime.Now);
            Assert.IsNotNull(packet.Ethernet.IpV4.Tcp.Http.Version);
            Assert.IsNotNull(((HttpResponseDatagram)packet.Ethernet.IpV4.Tcp.Http).StatusCode);
            Assert.AreEqual(Datagram.Empty, ((HttpResponseDatagram)packet.Ethernet.IpV4.Tcp.Http).ReasonPhrase, "ReasonPhrase");
        }
コード例 #34
0
        public void RandomIgmpTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = new MacAddress("00:01:02:03:04:05"),
                Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
            };

            Random random = new Random();

            IpV4Layer ipV4Layer = random.NextIpV4Layer(null);

            ipV4Layer.HeaderChecksum = null;

            for (int i = 0; i != 200; ++i)
            {
                IgmpLayer igmpLayer = random.NextIgmpLayer();

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, igmpLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // Ethernet
                ethernetLayer.EtherType = EthernetType.IpV4;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IPv4
                ipV4Layer.Protocol       = IpV4Protocol.InternetGroupManagementProtocol;
                ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IPv4 Layer");
                ipV4Layer.HeaderChecksum = null;

                // IGMP
                Assert.IsTrue(packet.Ethernet.IpV4.Igmp.IsChecksumCorrect);
                Assert.AreEqual(igmpLayer, packet.Ethernet.IpV4.Igmp.ExtractLayer(), "IGMP Layer");
                Assert.AreEqual(igmpLayer.GetHashCode(), packet.Ethernet.IpV4.Igmp.ExtractLayer().GetHashCode(), "IGMP Layer");
                Assert.AreNotEqual(igmpLayer, null);
                Assert.AreNotEqual(igmpLayer, random.NextPayloadLayer(igmpLayer.Length));
                Assert.AreNotEqual(igmpLayer.GetHashCode(), random.NextPayloadLayer(igmpLayer.Length).GetHashCode());
                if (packet.Ethernet.IpV4.Igmp.QueryVersion != IgmpQueryVersion.Version3)
                {
                    MoreAssert.IsSmallerOrEqual(IgmpDatagram.MaxMaxResponseTime, packet.Ethernet.IpV4.Igmp.MaxResponseTime);
                }
                if (packet.Ethernet.IpV4.Igmp.MessageType != IgmpMessageType.MembershipQuery)
                {
                    Assert.AreEqual(IgmpQueryVersion.None, packet.Ethernet.IpV4.Igmp.QueryVersion);
                }
                switch (igmpLayer.MessageType)
                {
                case IgmpMessageType.MembershipQuery:
                    switch (igmpLayer.QueryVersion)
                    {
                    case IgmpQueryVersion.Version1:
                        Assert.AreEqual(1, packet.Ethernet.IpV4.Igmp.Version);
                        break;

                    case IgmpQueryVersion.Version2:
                        Assert.AreEqual(2, packet.Ethernet.IpV4.Igmp.Version);
                        break;

                    case IgmpQueryVersion.Version3:
                        Assert.AreEqual(3, packet.Ethernet.IpV4.Igmp.Version);
                        break;

                    default:
                        Assert.Fail(igmpLayer.QueryVersion.ToString());
                        break;
                    }
                    break;

                case IgmpMessageType.MembershipReportVersion1:
                    Assert.AreEqual(1, packet.Ethernet.IpV4.Igmp.Version);
                    break;

                case IgmpMessageType.MembershipReportVersion2:
                case IgmpMessageType.LeaveGroupVersion2:
                    Assert.AreEqual(2, packet.Ethernet.IpV4.Igmp.Version);
                    break;

                case IgmpMessageType.MembershipReportVersion3:
                    Assert.AreEqual(3, packet.Ethernet.IpV4.Igmp.Version);
                    break;

                default:
                    Assert.Fail(igmpLayer.MessageType.ToString());
                    break;
                }
                foreach (IgmpGroupRecordDatagram groupRecord in packet.Ethernet.IpV4.Igmp.GroupRecords)
                {
                    Assert.IsNotNull(groupRecord.ToString());
                }
            }
        }
コード例 #35
0
ファイル: System.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Send Message to defined Internal Channel.
        /// </summary>
        public void SendToChannel(InternalChannels channel, CustomMessageType color, string charname, uint level, string message)
        {
            #region "[rgn] Packet Structure Analyze "
            //--------------------------------------------------------------------------------------------------------------
            //SZ    ID ?? ?? ?? ?? SZ    [                   NAME                ] LV    CR CH    SZ    [        MSG       ]
            //--------------------------------------------------------------------------------------------------------------
            //23 00 AA 00 00 00 00 0E 00 4F 6D 65 67 61 20 4C 61 6D 62 61 20 4C 61 04 00 0C 0A 00 07 00 68 65 6C 6C 6F 00 00
            //.  .  .  .  S  .  .  .  .  N  i  g  h  t  .  C  r  e  a  t  u  r  e  .  .  .  .  .  .  .  H  e  l  l  o  .  .
            //--------------------------------------------------------------------------------------------------------------
            //00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
            //--------------------------------------------------------------------------------------------------------------
            #endregion

            PacketBuilder Builder = new PacketBuilder(0xAA, Connection);
            Builder.Append(0x00);
            Builder.Append(0x00);
            Builder.Append(0x00);
            Builder.Append(0x00);
            Builder.Append(charname, true);
            Builder.Append(level, 2);
            Builder.Append(color.GetHashCode());
            Builder.Append(GetChannelInfo(channel).Key, 2);
            Builder.Append(message, true, true);

            Builder.SetPacketSource(PacketSource.Server);
            Connection.Send(Builder.GetPacket());
        }
コード例 #36
0
        private void attemptPlayerLogin(Connection connection)
        {
            if (connection == null)
            {
                return;
            }

            if (connection.loginStage == 0) //Attempt login or update server.
            {
                Packet fill_2 = fillStream(connection, 2);
                if (fill_2 == null)
                {
                    return;
                }

                int connectionType = fill_2.readByte();

                if (connectionType == 15)
                { //it's update server
                    connection.loginStage = 1;
                    updateServer(connection);
                    return;
                }
                else if (connectionType == 255)
                {
                    connection.SendPacket(new PacketBuilder()
                                          .setSize(Packet.Size.Bare)
                                          .addBytes(Misc.WORLD_LIST_DATA).toPacket());
                    connection.loginStage = 5;
                    updateServer(connection);
                    return;
                }
                else if (connectionType != 14)
                {
                    connection.loginStage = 255; //255 is used as fail.
                    return;
                }

                Random random           = new Random();
                long   serverSessionKey = ((long)(random.NextDouble() * 99999999D) << 32)
                                          + (long)(random.NextDouble() * 99999999D);

                int longPlayerName = fill_2.readByte();

                PacketBuilder s1Response = new PacketBuilder();
                s1Response.setSize(Packet.Size.Bare).addByte((byte)0).addLong(serverSessionKey);
                connection.SendPacket(s1Response.toPacket());
                connection.loginStage = 2;
                attemptPlayerLogin(connection);
            }
            else if (connection.loginStage == 2)
            {
                Packet fill_1 = fillStream(connection, 1);
                if (fill_1 == null)
                {
                    return;
                }

                int loginType = fill_1.readByte();

                if (loginType != 16 && loginType != 18 && loginType != 14)
                {
                    connection.loginStage = 255; //255 is used as fail.
                    return;
                }
                connection.loginStage = 4;
                attemptPlayerLogin(connection);
            }
            else if (connection.loginStage == 4)
            {
                Packet fill_2 = fillStream(connection, 2);
                if (fill_2 == null)
                {
                    return;
                }

                int loginPacketSize        = fill_2.readUShort();
                int loginEncryptPacketSize = loginPacketSize - (36 + 1 + 1 + 2);

                if (loginEncryptPacketSize <= 0)
                {
                    connection.loginStage = 255;
                    return;
                }
                Packet fill_loginPacketSize = fillStream(connection, loginPacketSize);
                if (fill_loginPacketSize == null)
                {
                    return;
                }

                int clientVersion = fill_loginPacketSize.readInt();

                if (clientVersion != 530)
                {
                    connection.loginStage = 255;
                    return;
                }

                byte   junk1  = fill_loginPacketSize.readByte();
                byte   lowMem = fill_loginPacketSize.readByte(); //0 is this still low mem ver?
                byte   zero   = fill_loginPacketSize.readByte();
                byte   b1     = fill_loginPacketSize.readByte();
                ushort s1     = fill_loginPacketSize.readUShort();
                ushort s2     = fill_loginPacketSize.readUShort();
                byte   b2     = fill_loginPacketSize.readByte();

                for (int i = 0; i < 24; i++)
                {
                    int cacheIDX = fill_loginPacketSize.readByte();
                }
                string appletSettings = fill_loginPacketSize.readRS2String(); //EkKmok3kJqOeN6D3mDdihco3oPeYN2KFy6W5--vZUbNA
                int    someInt1       = fill_loginPacketSize.readInt();
                int    someInt2       = fill_loginPacketSize.readInt();
                ushort short1         = fill_loginPacketSize.readUShort();

                for (int i = 0; i < 28; i++)
                {
                    int crcOfClientClasses = fill_loginPacketSize.readInt();
                }

                int junk2      = fill_loginPacketSize.readByte();
                int encryption = fill_loginPacketSize.readByte();

                if (encryption != 10 && encryption != 64)
                {
                    connection.loginStage = 255;
                    return;
                }

                long         clientSessionKey = fill_loginPacketSize.readLong();
                long         serverSessionKey = fill_loginPacketSize.readLong();
                LoginDetails loginDetails     = new LoginDetails();
                loginDetails.setLongName(fill_loginPacketSize.readLong()); //must start a 225.
                loginDetails.setUsername(Misc.longToPlayerName(loginDetails.getLongName()).ToLower().Replace("_", " ").Trim());
                loginDetails.setPassword(fill_loginPacketSize.readRS2String());

                Console.WriteLine("Attempting to login with Username: "******" Password: " + loginDetails.getPassword());
                connection.setLoginDetails(loginDetails);
                //start attempting to login the account.
                lock (playersToLoad)
                {
                    playersToLoad.Enqueue(connection);
                }

                connection.loginStage = 6;
            }
        }
コード例 #37
0
        public PlayerListPacket(bool showInChat)
        {
            this.builder = new PacketBuilder();

            this.builder.Write(showInChat);
        }
コード例 #38
0
        public void loadSaveThread()
        {
            while (true)
            {
                try
                {
                    Thread.Sleep(30);
                }
                catch (ThreadInterruptedException)
                {
                    forceSaveAllPlayers();
                    break;
                }

                lock (playersToLoad)
                {
                    if (playersToLoad.Count > 0)
                    {
                        Connection connection = null;
                        while (playersToLoad.Count > 0)
                        {
                            connection = playersToLoad.Dequeue();
                            if (connection != null)
                            {
                                ReturnCode    returnCode = loadPlayer(connection);
                                PacketBuilder pb         = new PacketBuilder().setSize(Packet.Size.Bare);
                                int           slot       = -1;
                                if (returnCode == ReturnCode.LOGIN_OK)
                                {
                                    slot = Server.register(connection);
                                    if (slot == -1)
                                    {
                                        returnCode = ReturnCode.WORLD_FULL;
                                    }
                                }
                                pb.addByte((byte)returnCode);
                                if (returnCode == ReturnCode.LOGIN_OK)
                                {
                                    pb.addByte((byte)connection.getPlayer().getRights()); // rights
                                    pb.addByte((byte)0);                                  //1
                                    pb.addByte((byte)0);                                  //Flagged, will genrate mouse packets
                                    pb.addByte((byte)0);                                  //3
                                    pb.addByte((byte)0);                                  //4
                                    pb.addByte((byte)0);                                  //5
                                    pb.addByte((byte)0);                                  // Generates packets
                                    pb.addUShort(slot);                                   //PlayerID
                                    pb.addByte((byte)1);                                  // membership flag #1?..this one enables all GE boxes
                                    pb.addByte((byte)1);                                  // membership flag #2?
                                    connection.SendPacket(pb.toPacket());
                                    connection.getPlayer().getPackets().sendMapRegion();
                                    connection.getPlayer().setActive(true);
                                    Console.WriteLine("Loaded " + connection.getPlayer().getLoginDetails().getUsername() + "'s game: returncode = " + returnCode + ".");
                                }
                                else
                                {
                                    connection.SendPacket(pb.toPacket());
                                }
                            }
                        }
                    }
                }
                lock (playersToSave)
                {
                    if (playersToSave.Count > 0)
                    {
                        Player p = null;
                        while (playersToSave.Count > 0)
                        {
                            p = playersToSave.Dequeue();
                            if (p != null)
                            {
                                if (savePlayer(p))
                                {
                                    Console.WriteLine("Saved " + p.getLoginDetails().getUsername() + "'s game.");
                                }
                                else
                                {
                                    Console.WriteLine("Could not save " + p.getLoginDetails().getUsername() + "'s game.");
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #39
0
 public LightSyncPacket()
 {
     this.builder = new();
 }
コード例 #40
0
        public void IgmpInvalidTest()
        {
            Packet queryVersion2 = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(),
                                                       new IgmpQueryVersion2Layer
            {
                MaxResponseTime = TimeSpan.FromSeconds(1),
            });

            Assert.IsTrue(queryVersion2.IsValid);
            Assert.IsTrue(queryVersion2.Ethernet.IpV4.Igmp.IsChecksumCorrect);

            // Small Packet
            byte[] buffer = new byte[queryVersion2.Length - 1];
            queryVersion2.Buffer.BlockCopy(0, buffer, 0, buffer.Length);
            Packet smallQueryVersion2 = new Packet(buffer, queryVersion2.Timestamp, queryVersion2.DataLink);

            Assert.IsFalse(smallQueryVersion2.IsValid);

            // Bad checksum
            buffer = new byte[queryVersion2.Length];
            queryVersion2.Buffer.BlockCopy(0, buffer, 0, buffer.Length);
            ++buffer[buffer.Length - 1];
            Packet badChecksumPacket = new Packet(buffer, queryVersion2.Timestamp, queryVersion2.DataLink);

            Assert.IsFalse(badChecksumPacket.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsFalse(badChecksumPacket.IsValid);

            // Big query version 3
            Packet queryVersion3 = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(),
                                                       new IgmpQueryVersion3Layer
            {
                MaxResponseTime = TimeSpan.FromSeconds(1),
                QueryInterval   = TimeSpan.FromSeconds(1),
            });

            Assert.IsTrue(queryVersion3.IsValid, "IsValid");
            buffer = new byte[queryVersion3.Length + 2];
            queryVersion3.Buffer.BlockCopy(0, buffer, 0, queryVersion3.Length);
            buffer[EthernetDatagram.HeaderLengthValue + 3]  += 2;
            buffer[EthernetDatagram.HeaderLengthValue + 11] -= 2;
            Packet bigQueryVersion3 = new Packet(buffer, queryVersion3.Timestamp, queryVersion3.DataLink);

            Assert.IsTrue(bigQueryVersion3.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsTrue(bigQueryVersion3.Ethernet.IpV4.IsHeaderChecksumCorrect, "IpV4.IsHeaderChecksumCorrect");
            Assert.IsFalse(bigQueryVersion3.IsValid, "bigQueryVersion3.IsValid");

            // Big report version 1
            Packet reportVersion1 = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(), new IgmpReportVersion1Layer());

            buffer = new byte[reportVersion1.Length + 2];
            reportVersion1.Buffer.BlockCopy(0, buffer, 0, reportVersion1.Length);
            buffer[EthernetDatagram.HeaderLengthValue + 3]  += 2;
            buffer[EthernetDatagram.HeaderLengthValue + 11] -= 2;
            Packet bigReportVersion1 = new Packet(buffer, reportVersion1.Timestamp, reportVersion1.DataLink);

            Assert.IsTrue(bigReportVersion1.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsTrue(bigReportVersion1.Ethernet.IpV4.IsHeaderChecksumCorrect);
            Assert.IsFalse(bigReportVersion1.IsValid);

            // Non zero max response code for report version 1
            buffer = new byte[reportVersion1.Length];
            reportVersion1.Buffer.BlockCopy(0, buffer, 0, buffer.Length);
            buffer.Write(EthernetDatagram.HeaderLengthValue + IpV4Datagram.HeaderMinimumLength + 1, 1);
            buffer.Write(EthernetDatagram.HeaderLengthValue + IpV4Datagram.HeaderMinimumLength + 2, (ushort)0xedfe, Endianity.Big);
            Packet nonZeroMaxResponseCodeReportVersion1 = new Packet(buffer, reportVersion1.Timestamp, reportVersion1.DataLink);

            Assert.IsTrue(nonZeroMaxResponseCodeReportVersion1.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsTrue(nonZeroMaxResponseCodeReportVersion1.Ethernet.IpV4.IsHeaderChecksumCorrect);
            Assert.IsFalse(nonZeroMaxResponseCodeReportVersion1.IsValid);

            // Big report version 2
            Packet reportVersion2 = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(),
                                                        new IgmpReportVersion2Layer
            {
                MaxResponseTime = TimeSpan.FromSeconds(1)
            });

            buffer = new byte[reportVersion2.Length + 2];
            reportVersion2.Buffer.BlockCopy(0, buffer, 0, reportVersion2.Length);
            buffer[EthernetDatagram.HeaderLengthValue + 3]  += 2;
            buffer[EthernetDatagram.HeaderLengthValue + 11] -= 2;
            Packet bigReportVersion2 = new Packet(buffer, reportVersion2.Timestamp, reportVersion2.DataLink);

            Assert.IsTrue(bigReportVersion2.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsTrue(bigReportVersion2.Ethernet.IpV4.IsHeaderChecksumCorrect);
            Assert.IsFalse(bigReportVersion2.IsValid);

            // non zero max response code report version 3
            Packet reportVersion3 = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(),
                                                        new IgmpReportVersion3Layer
            {
                GroupRecords = new[]
                {
                    new IgmpGroupRecord(
                        IgmpRecordType.CurrentStateRecordModeIsExclude,
                        IpV4Address.Zero, new List <IpV4Address>(), Datagram.Empty)
                }.AsReadOnly()
            });

            buffer = new byte[reportVersion3.Length];
            reportVersion3.Buffer.BlockCopy(0, buffer, 0, buffer.Length);
            buffer.Write(EthernetDatagram.HeaderLengthValue + IpV4Datagram.HeaderMinimumLength + 1, 1);
            buffer.Write(EthernetDatagram.HeaderLengthValue + IpV4Datagram.HeaderMinimumLength + 2, (ushort)0xdbfd, Endianity.Big);
            Packet nonZeroMaxResponseCodeReportVersion3 = new Packet(buffer, reportVersion3.Timestamp, reportVersion3.DataLink);

            Assert.IsTrue(nonZeroMaxResponseCodeReportVersion3.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsTrue(nonZeroMaxResponseCodeReportVersion3.Ethernet.IpV4.IsHeaderChecksumCorrect);
            Assert.IsFalse(nonZeroMaxResponseCodeReportVersion3.IsValid);

            // big report version 3
            buffer = new byte[reportVersion3.Length + 2];
            reportVersion3.Buffer.BlockCopy(0, buffer, 0, reportVersion3.Length);
            buffer[EthernetDatagram.HeaderLengthValue + 3]  += 2;
            buffer[EthernetDatagram.HeaderLengthValue + 11] -= 2;
            Packet bigReportVersion3 = new Packet(buffer, reportVersion3.Timestamp, reportVersion3.DataLink);

            Assert.IsTrue(bigReportVersion3.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsTrue(bigReportVersion3.Ethernet.IpV4.IsHeaderChecksumCorrect);
            Assert.IsFalse(bigReportVersion3.IsValid);

            // invalid group record report version 3
            buffer = new byte[reportVersion3.Length];
            reportVersion3.Buffer.BlockCopy(0, buffer, 0, reportVersion3.Length);
            buffer.Write(EthernetDatagram.HeaderLengthValue + IpV4Datagram.HeaderMinimumLength + IgmpDatagram.HeaderLength + 1, 1);
            buffer.Write(EthernetDatagram.HeaderLengthValue + IpV4Datagram.HeaderMinimumLength + 2, (ushort)0xdbfd, Endianity.Big);
            Packet invalidGroupRecordReportVersion3 = new Packet(buffer, reportVersion3.Timestamp, reportVersion3.DataLink);

            Assert.IsTrue(invalidGroupRecordReportVersion3.Ethernet.IpV4.Igmp.IsChecksumCorrect);
            Assert.IsTrue(invalidGroupRecordReportVersion3.Ethernet.IpV4.IsHeaderChecksumCorrect);
            Assert.IsFalse(invalidGroupRecordReportVersion3.IsValid);
        }
コード例 #41
0
        /// <summary>
        /// Called when on character selection but only if the AutoLogin fails.
        /// </summary>
        public void OnCharacterListing(List <SRCharSelection> CharacterList)
        {
            Window w = Window.Get;

            // Select character
            if (w.Login_cmbxCharacter.Items.Count > 0)
            {
                // Try Autologin
                if (hasAutoLoginMode)
                {
                    w.InvokeIfRequired(() => {
                        if (w.Login_cmbxCharacter.Text != "")
                        {
                            w.Control_Click(w.Login_btnStart, null);
                            return;
                        }
                    });
                }
                else
                {
                    // Select first one (UX)
                    w.Login_cmbxCharacter.InvokeIfRequired(() => {
                        w.Login_cmbxCharacter.SelectedIndex = 0;
                    });
                }
            }

            // Reset value
            CreatingCharacterName = "";
            // Delete characters that are not being deleted
            if (w.Settings_cbxDeleteChar40to50.Checked)
            {
                for (byte j = 0; j < CharacterList.Count; j++)
                {
                    if (!CharacterList[j].isDeleting &&
                        CharacterList[j].Level >= 40 && CharacterList[j].Level <= 50)
                    {
                        w.Log("Deleting character [" + CharacterList[j].Name + "]");
                        w.LogProcess("Deleting...");
                        PacketBuilder.DeleteCharacter(CharacterList[j].Name);
                        System.Threading.Thread.Sleep(500);
                    }
                }
            }
            // Select the first character available
            if (w.Settings_cbxSelectFirstChar.Checked)
            {
                SRCharSelection character = CharacterList.Find(c => !c.isDeleting);
                if (character != null)
                {
                    w.LogProcess("Selecting...");
                    w.InvokeIfRequired(() => {
                        w.Login_cmbxCharacter.Text = character.Name;
                        w.Control_Click(w.Login_btnStart, null);
                    });
                    return;
                }
                else
                {
                    w.Log("No character available to select!");
                }
            }
            // No characters selected, then create it?
            if (w.Settings_cbxCreateChar.Checked &&
                CharacterList.Count == 0)
            {
                w.Log("Empty character list, creating character...");
                CreateNickname();
            }
            else if (w.Settings_cbxCreateCharBelow40.Checked)
            {
                if (CharacterList.Count < 4)
                {
                    if (!CharacterList.Exists(c => !c.isDeleting && c.Level < 40))
                    {
                        w.Log("No characters below Lv.40, creating character...");
                        CreateNickname();
                    }
                }
                else
                {
                    w.Log("Character list full, you cannot create more characters!");
                }
            }
        }
コード例 #42
0
ファイル: PacketBuilderTests.cs プロジェクト: amitla/Pcap.Net
 public void NoLayersTest()
 {
     PacketBuilder packetBuilder = new PacketBuilder();
     Assert.IsNull(packetBuilder);
 }
コード例 #43
0
 /// <summary>
 /// 应答-请求处理完毕后发送结果给请求端
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="value"></param>
 public void Reply(SocketBase.IConnection connection, string value)
 {
     connection.BeginSend(PacketBuilder.ToCommandLine(value));
 }
コード例 #44
0
ファイル: Server.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Opens Trade Channel.
        /// </summary>
        public void OpenTradeChannel()
        {
            #region "[rgn] Packet Structure Analyze "
            //------------------------------------------------------------------------
            //SZ    ID CHANNEL
            //------------------------------------------------------------------------
            //03 00 98 05 00
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x98, Connection);
            Builder.Append(0x05, 2);
            Builder.SetPacketSource(PacketSource.Client);
            Connection.Send(Builder.GetPacket());
        }
コード例 #45
0
 public RemoveEntityPacket()
 {
     this.builder = new PacketBuilder();
 }
コード例 #46
0
        public void InvalidGreTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = new MacAddress("00:01:02:03:04:05"),
                Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
            };

            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 100; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(IpV4Protocol.Gre);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.Gre, false);

                GreLayer greLayer = random.NextGreLayer();
                greLayer.Checksum = null;
                greLayer.Routing  = new List <GreSourceRouteEntry>
                {
                    new GreSourceRouteEntryAs(new List <ushort> {
                        123
                    }.AsReadOnly(), 0),
                    new GreSourceRouteEntryIp(new List <IpV4Address> {
                        random.NextIpV4Address()
                    }.AsReadOnly(),
                                              0)
                }.AsReadOnly();

                PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, greLayer);
                Packet        packet        = packetBuilder.Build(DateTime.Now);
                Assert.IsTrue(packet.IsValid ||
                              new[] { EthernetType.IpV4, EthernetType.IpV6, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(greLayer.ProtocolType),
                              "IsValid. ProtoclType=" + greLayer.ProtocolType);

                GreDatagram gre = packet.Ethernet.Ip.Gre;

                // Remove a byte from routing
                Datagram newIpPayload = new Datagram(gre.Take(gre.Length - 1).ToArray());
                packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {
                    Data = newIpPayload
                });
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsNull(packet.Ethernet.Ip.Gre.Payload);
                Assert.IsFalse(packet.IsValid);

                // SreLength is too big
                byte[] buffer = gre.ToArray();
                buffer[buffer.Length - 1] = 200;
                newIpPayload  = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {
                    Data = newIpPayload
                });
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset is too big
                buffer = gre.ToArray();
                buffer[gre.Length - 10] = 100;
                newIpPayload            = new Datagram(buffer);
                packetBuilder           = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {
                    Data = newIpPayload
                });
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset isn't aligned to ip
                buffer = gre.ToArray();
                buffer[gre.Length - 10] = 3;
                newIpPayload            = new Datagram(buffer);
                packetBuilder           = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {
                    Data = newIpPayload
                });
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset isn't aligned to as
                buffer = gre.ToArray();
                buffer[gre.Length - 16] = 1;
                newIpPayload            = new Datagram(buffer);
                packetBuilder           = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {
                    Data = newIpPayload
                });
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);
            }
        }
コード例 #47
0
ファイル: Server.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Send a Message to Default Channel.
        /// </summary>
        public void Trade(string message)
        {
            #region "[rgn] Packet Structure Analyze "
            //------------------------------------------------------------------------
            //SZ    ID          SZ    MSG
            //------------------------------------------------------------------------
            //14 00 96 05 05 00 0E 00 73 65 6C 6C 20 63 72 6F 73 73 20 62 6F 77
            //0A 00 96 05 05 00 04 00 73 65 6C 6C
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x96, Connection);
            Builder.Append(ChannelType.Trade.GetHashCode());
            Builder.Append(0x05);
            Builder.Append(0x00);
            Builder.Append(message, true);
            Builder.SetPacketSource(PacketSource.Client);
            Connection.Send(Builder.GetPacket());
        }
コード例 #48
0
        public void RandomGreTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = new MacAddress("00:01:02:03:04:05"),
                Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
            };

            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 200; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.Gre, false);

                GreLayer     greLayer     = random.NextGreLayer();
                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));

                PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, greLayer, payloadLayer);

                Packet packet = packetBuilder.Build(DateTime.Now);
                if (greLayer.Checksum == null &&
                    !new[] { EthernetType.IpV4, EthernetType.IpV6, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(packet.Ethernet.Ip.Gre.ProtocolType))
                {
                    Assert.IsTrue(packet.IsValid, "IsValid, ProtocolType=" + packet.Ethernet.Ip.Gre.ProtocolType);
                }

                // Ethernet
                ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // IP.
                if (ipLayer == ipV4Layer)
                {
                    // IPv4.
                    ipV4Layer.Protocol       = IpV4Protocol.Gre;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.Ip.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.Ip.ExtractLayer());
                    ipV4Layer.HeaderChecksum = null;
                    Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
                    Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
                    Assert.AreEqual(ipV4Layer.Length + greLayer.Length + payloadLayer.Length,
                                    packet.Ethernet.Ip.TotalLength);
                    Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.Ip.Version);
                }
                else
                {
                    // IPv6.
                    Assert.AreEqual(ipLayer, packet.Ethernet.Ip.ExtractLayer());
                }

                // GRE
                GreDatagram actualGre      = packet.Ethernet.Ip.Gre;
                GreLayer    actualGreLayer = (GreLayer)actualGre.ExtractLayer();
                if (greLayer.ChecksumPresent && greLayer.Checksum == null)
                {
                    Assert.IsTrue(actualGre.IsChecksumCorrect);
                    greLayer.Checksum = actualGre.Checksum;
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGreLayer.Key != null)
                {
                    actualGreLayer.SetKey(actualGreLayer.KeyPayloadLength.Value, actualGreLayer.KeyCallId.Value);
                }
                else
                {
                    Assert.IsNull(actualGreLayer.KeyPayloadLength);
                    Assert.IsNull(actualGreLayer.KeyCallId);
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGre.KeyPresent)
                {
                    Assert.AreEqual(greLayer.KeyPayloadLength, actualGre.KeyPayloadLength, "KeyPayloadLength");
                    Assert.AreEqual(greLayer.KeyCallId, actualGre.KeyCallId, "KeyCallId");
                }
                Assert.AreNotEqual(random.NextGreLayer(), actualGreLayer, "Not Layer");
                Assert.AreEqual(greLayer.Length, actualGre.HeaderLength);
                Assert.IsTrue(actualGre.KeyPresent ^ (greLayer.Key == null));
                MoreAssert.IsSmaller(8, actualGre.RecursionControl);
                MoreAssert.IsSmaller(32, actualGre.FutureUseBits);
                Assert.IsTrue(actualGre.RoutingPresent ^ (greLayer.Routing == null && greLayer.RoutingOffset == null));
                Assert.IsTrue(actualGre.SequenceNumberPresent ^ (greLayer.SequenceNumber == null));
                Assert.IsTrue(!actualGre.StrictSourceRoute || actualGre.RoutingPresent);
                if (actualGre.RoutingPresent)
                {
                    Assert.IsNotNull(actualGre.ActiveSourceRouteEntryIndex);
                    if (actualGre.ActiveSourceRouteEntryIndex < actualGre.Routing.Count)
                    {
                        Assert.IsNotNull(actualGre.ActiveSourceRouteEntry);
                    }

                    foreach (GreSourceRouteEntry entry in actualGre.Routing)
                    {
                        Assert.AreNotEqual(entry, 2);
                        Assert.AreEqual(entry.GetHashCode(), entry.GetHashCode());
                        switch (entry.AddressFamily)
                        {
                        case GreSourceRouteEntryAddressFamily.AsSourceRoute:
                            GreSourceRouteEntryAs asEntry = (GreSourceRouteEntryAs)entry;
                            MoreAssert.IsInRange(0, asEntry.AsNumbers.Count, asEntry.NextAsNumberIndex);
                            if (asEntry.NextAsNumberIndex != asEntry.AsNumbers.Count)
                            {
                                Assert.AreEqual(asEntry.AsNumbers[asEntry.NextAsNumberIndex], asEntry.NextAsNumber);
                            }
                            break;

                        case GreSourceRouteEntryAddressFamily.IpSourceRoute:
                            GreSourceRouteEntryIp ipEntry = (GreSourceRouteEntryIp)entry;
                            MoreAssert.IsInRange(0, ipEntry.Addresses.Count, ipEntry.NextAddressIndex);
                            if (ipEntry.NextAddressIndex != ipEntry.Addresses.Count)
                            {
                                Assert.AreEqual(ipEntry.Addresses[ipEntry.NextAddressIndex], ipEntry.NextAddress);
                            }
                            break;

                        default:
                            GreSourceRouteEntryUnknown unknownEntry = (GreSourceRouteEntryUnknown)entry;
                            MoreAssert.IsInRange(0, unknownEntry.Data.Length, unknownEntry.PayloadOffset);
                            break;
                        }
                    }
                }
                else
                {
                    Assert.IsNull(actualGre.ActiveSourceRouteEntry);
                }

                Assert.IsNotNull(actualGre.Payload);
                switch (actualGre.ProtocolType)
                {
                case EthernetType.IpV4:
                    Assert.IsNotNull(actualGre.IpV4);
                    break;

                case EthernetType.Arp:
                    Assert.IsNotNull(actualGre.Arp);
                    break;
                }
            }
        }
コード例 #49
0
ファイル: GreTests.cs プロジェクト: shrknt35/sonarlint-vs
        public void InvalidGreTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("00:01:02:03:04:05"),
                                                  Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
                                              };

            Random random = new Random();

            for (int i = 0; i != 100; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(IpV4Protocol.Gre);
                ipV4Layer.HeaderChecksum = null;

                GreLayer greLayer = random.NextGreLayer();
                greLayer.Checksum = null;
                greLayer.Routing = new List<GreSourceRouteEntry>
                                   {
                                       new GreSourceRouteEntryAs(new List<ushort> {123}.AsReadOnly(), 0),
                                       new GreSourceRouteEntryIp(new List<IpV4Address> {random.NextIpV4Address()}.AsReadOnly(),
                                                                 0)
                                   }.AsReadOnly();

                PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer);
                Packet packet = packetBuilder.Build(DateTime.Now);
                Assert.IsTrue(packet.IsValid ||
                              new[] {EthernetType.IpV4, EthernetType.Arp, EthernetType.VLanTaggedFrame}.Contains(greLayer.ProtocolType),
                              "IsValid. ProtoclType=" + greLayer.ProtocolType);

                GreDatagram gre = packet.Ethernet.IpV4.Gre;

                // Remove a byte from routing
                Datagram newIpPayload = new Datagram(gre.Take(gre.Length - 1).ToArray());
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsNull(packet.Ethernet.IpV4.Gre.Payload);
                Assert.IsFalse(packet.IsValid);

                // SreLength is too big
                byte[] buffer = gre.ToArray();
                buffer[buffer.Length - 1] = 200;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset is too big
                buffer = gre.ToArray();
                buffer[gre.Length - 10] = 100;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset isn't aligned to ip
                buffer = gre.ToArray();
                buffer[gre.Length - 10] = 3;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset isn't aligned to as
                buffer = gre.ToArray();
                buffer[gre.Length - 16] = 1;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);
            }
        }
コード例 #50
0
        public void ResetAutoWalk()
        {
            var builder = new PacketBuilder(Packets.SendToClient.ResetAutoWalk);

            builder.Send(_player);
        }
コード例 #51
0
ファイル: HttpTests.cs プロジェクト: JackWangCUMT/WiFiSpy
        public void HttpRequestWithoutUriTest()
        {
            PacketBuilder builder = new PacketBuilder(new EthernetLayer(),
                                                      new IpV4Layer(),
                                                      new TcpLayer(),
                                                      new HttpRequestLayer
                                                      {
                                                          Method = new HttpRequestMethod("UnknownMethod")
                                                      });

            Packet packet = builder.Build(DateTime.Now);
            Assert.IsNotNull(((HttpRequestDatagram)packet.Ethernet.IpV4.Tcp.Http).Method);
            Assert.AreEqual(HttpRequestKnownMethod.Unknown, ((HttpRequestDatagram)packet.Ethernet.IpV4.Tcp.Http).Method.KnownMethod);
            Assert.AreEqual(string.Empty, ((HttpRequestDatagram)packet.Ethernet.IpV4.Tcp.Http).Uri, "Uri");
        }
コード例 #52
0
        public void StopAttack()
        {
            var builder = new PacketBuilder(Packets.SendToClient.StopAttack);

            builder.Send(_player);
        }
コード例 #53
0
ファイル: Use.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Use the Defined Item in Ground.
        /// e.g: Eat Food in Ground, Up Stairs, Open Container.
        /// </summary>
        public void InGround(Location sqm, uint itemId, uint stackPosition, bool isContainer)
        {
            #region " Packet Structure Analyze "
            //------------------------------------
            //Bag
            //------------------------------------
            //0A 00 82 15 7E ED 7B 07 25 0B 01 01
            //------------------------------------
            //00 01 02 03 04 05 06 07 08 09 10 11
            //------------------------------------
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x82, connection);
            Builder.Append(sqm.X);
            Builder.Append(sqm.Y);
            Builder.Append(sqm.Z);
            Builder.Append(itemId);
            Builder.Append(stackPosition);

            if (isContainer) { Builder.Append(new Model.Player(Connection).Containers.Count); }
            else { Builder.Append(0x00); }
            Connection.Send(Builder.GetPacket());
        }
コード例 #54
0
ファイル: EthernetTests.cs プロジェクト: yang123vc/WiFiSpy
        public void AutomaticEthernetTypeNoNextLayer()
        {
            Packet packet = PacketBuilder.Build(DateTime.Now, new EthernetLayer());

            Assert.IsTrue(packet.IsValid);
        }
コード例 #55
0
ファイル: Use.cs プロジェクト: alexisjojo/ktibiax
        /// <summary>
        /// Use the Defined Item on a Player in Defined SQM and Drop after use if needed.
        /// e.g: Use Fluids on Players, Use Runes on Players, etc.
        /// </summary>
        public void OnPlayer(ISlot slotSource, Location sqm, bool dropAfterUse)
        {
            #region " Packet Structure Analyze "
            // SZ      ID         BP     SLOT  HMM         X      Y    Z   ??     QD
            //----------------------------------------------------------------------
            // 11  00  83  FF FF  40  00  00  7E 0C  00  15 7E  ED 7B  07  63 00  01
            //----------------------------------------------------------------------
            // 00  01  02  03 04  05  06  07  08 09  10  11 12  13 14  15  16 17  18
            #endregion

            PacketBuilder Builder = new PacketBuilder(0x83, connection);
            Builder.Append(0xFF);
            Builder.Append(0xFF);
            Builder.Append(slotSource.Container.Position);
            Builder.Append(0x00);
            Builder.Append(slotSource.Position);
            Builder.Append(slotSource.Item.Id);
            Builder.Append(slotSource.Position);
            Builder.Append(sqm.X);
            Builder.Append(sqm.Y);
            Builder.Append(sqm.Z);
            Builder.Append(0x63);
            Builder.Append(0x00);
            Builder.Append(0x01); //TODO: Test increase this ammount.
            Connection.Send(Builder.GetPacket());

            if (dropAfterUse) {
                System.Threading.Thread.Sleep(300);
                new Stack(Connection).ContainerToGround(slotSource, sqm);
            }
        }
コード例 #56
0
        /// <summary>
        /// Handle the sending of a player's character list.
        /// </summary>
        public override void Execute()
        {
            var localPlayer = _player;

            var dbClient = GameService.GetDbClient();

            var bldr = new PacketBuilder(Common.Database.Opcodes.GET_CHARACTER_LIST_DATA);

            bldr.WriteInt(localPlayer.index);

            bldr.WriteByte((byte)GameService.GetServerId());

            dbClient.Write(bldr.ToPacket(), (_data, _length) =>
            {
                int characterCount = BitConverter.ToInt32(_data);

                List <Common.Database.Structs.Game.Character> characters = Serializer.Deserialize <List <Common.Database.Structs.Game.Character> >(_data.Skip(4).ToArray());

                List <int> slots = new List <int>(new int[] { 0, 1, 2, 3, 4 });

                foreach (var character in characters)
                {
                    slots.Remove(character.slot);

                    var responseBldr = new PacketBuilder(Common.Packets.Opcodes.CHARACTER_LIST);

                    responseBldr.WriteByte(character.slot);

                    responseBldr.WriteInt(character.characterId);

                    // Unknown (Character creation time?)
                    responseBldr.WriteInt(0);

                    responseBldr.WriteShort(character.level);

                    responseBldr.WriteByte(character.race);

                    responseBldr.WriteByte(character.gameMode);

                    responseBldr.WriteByte(character.hair);

                    responseBldr.WriteByte(character.face);

                    responseBldr.WriteByte(character.height);

                    responseBldr.WriteByte(character.profession);

                    responseBldr.WriteByte(character.sex);

                    responseBldr.WriteShort(character.map);

                    responseBldr.WriteShort(character.strength);
                    responseBldr.WriteShort(character.dexterity);
                    responseBldr.WriteShort(character.resistance);
                    responseBldr.WriteShort(character.intelligence);
                    responseBldr.WriteShort(character.wisdom);
                    responseBldr.WriteShort(character.luck);

                    // Unknown array
                    for (int j = 0; j < 11; j++)
                    {
                        responseBldr.WriteByte(0);
                    }

                    // The item types
                    responseBldr.WriteBytes(character.itemTypes);

                    // The item type ids
                    responseBldr.WriteBytes(character.itemTypeIds);

                    // Write 535 null bytes
                    for (int j = 0; j < 535; j++)
                    {
                        responseBldr.WriteByte(0);
                    }

                    responseBldr.WriteBytes(character.name);

                    // Write the character deletion flag
                    responseBldr.WriteByte(0);

                    localPlayer.Write(responseBldr.ToPacket());
                }

                // Loop through the empty slots
                foreach (byte slot in slots)
                {
                    var responseBldr = new PacketBuilder(Common.Packets.Opcodes.CHARACTER_LIST);

                    responseBldr.WriteByte(slot);

                    // Write the empty character id
                    responseBldr.WriteInt(0);

                    localPlayer.Write(responseBldr.ToPacket());
                }
            });
        }
コード例 #57
0
        public void RandomIgmpTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = new MacAddress("00:01:02:03:04:05"),
                Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
            };

            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 200; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.InternetGroupManagementProtocol, false);

                IgmpLayer igmpLayer = random.NextIgmpLayer();

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, igmpLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // Ethernet
                ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // IP.
                if (ipV4Layer == ipLayer)
                {
                    // IPv4.
                    ipV4Layer.Protocol       = IpV4Protocol.InternetGroupManagementProtocol;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IPv4 Layer");
                    ipV4Layer.HeaderChecksum = null;
                }
                else
                {
                    // IPv6.
                    Assert.AreEqual(ipLayer, packet.Ethernet.IpV6.ExtractLayer(), "IPv6 Layer");
                }

                // IGMP
                Assert.IsTrue(packet.Ethernet.Ip.Igmp.IsChecksumCorrect);
                Assert.AreEqual(igmpLayer, packet.Ethernet.Ip.Igmp.ExtractLayer(), "IGMP Layer");
                Assert.AreEqual(igmpLayer.GetHashCode(), packet.Ethernet.Ip.Igmp.ExtractLayer().GetHashCode(), "IGMP Layer");
                Assert.AreNotEqual(igmpLayer, null);
                Assert.AreNotEqual(igmpLayer, random.NextPayloadLayer(igmpLayer.Length));
                Assert.AreNotEqual(igmpLayer.GetHashCode(), random.NextPayloadLayer(igmpLayer.Length).GetHashCode());
                if (packet.Ethernet.Ip.Igmp.QueryVersion != IgmpQueryVersion.Version3)
                {
                    MoreAssert.IsSmallerOrEqual(IgmpDatagram.MaxMaxResponseTime, packet.Ethernet.Ip.Igmp.MaxResponseTime);
                }
                if (packet.Ethernet.Ip.Igmp.MessageType != IgmpMessageType.MembershipQuery)
                {
                    Assert.AreEqual(IgmpQueryVersion.None, packet.Ethernet.Ip.Igmp.QueryVersion);
                }
                switch (igmpLayer.MessageTypeValue)
                {
                case IgmpMessageType.CreateGroupRequestVersion0:
                case IgmpMessageType.CreateGroupReplyVersion0:
                case IgmpMessageType.JoinGroupRequestVersion0:
                case IgmpMessageType.JoinGroupReplyVersion0:
                case IgmpMessageType.LeaveGroupRequestVersion0:
                case IgmpMessageType.LeaveGroupReplyVersion0:
                case IgmpMessageType.ConfirmGroupRequestVersion0:
                case IgmpMessageType.ConfirmGroupReplyVersion0:
                    Assert.AreEqual(0, packet.Ethernet.Ip.Igmp.Version);
                    IgmpVersion0Layer igmpVersion0Layer = (IgmpVersion0Layer)igmpLayer;
                    Assert.AreEqual(igmpVersion0Layer.IdentifierValue, packet.Ethernet.Ip.Igmp.Identifier);
                    Assert.AreEqual(igmpVersion0Layer.AccessKeyValue, packet.Ethernet.Ip.Igmp.AccessKey);

                    switch (igmpLayer.MessageTypeValue)
                    {
                    case IgmpMessageType.CreateGroupRequestVersion0:
                        Assert.AreEqual(((IgmpCreateGroupRequestVersion0Layer)igmpLayer).CreateGroupRequestCode, packet.Ethernet.Ip.Igmp.CreateGroupRequestCode);
                        break;

                    case IgmpMessageType.CreateGroupReplyVersion0:
                    case IgmpMessageType.JoinGroupReplyVersion0:
                    case IgmpMessageType.LeaveGroupReplyVersion0:
                    case IgmpMessageType.ConfirmGroupReplyVersion0:
                        IgmpReplyVersion0Layer igmpReplyVersion0Layer = (IgmpReplyVersion0Layer)igmpVersion0Layer;
                        Assert.AreEqual(igmpReplyVersion0Layer.Code, packet.Ethernet.Ip.Igmp.ReplyCode);
                        if (packet.Ethernet.Ip.Igmp.ReplyCode == IgmpVersion0ReplyCode.RequestPendingRetryInThisManySeconds)
                        {
                            Assert.AreEqual(igmpReplyVersion0Layer.RetryInThisManySeconds, packet.Ethernet.Ip.Igmp.RetryInThisManySeconds);
                        }
                        break;
                    }

                    break;

                case IgmpMessageType.MembershipQuery:
                    switch (igmpLayer.QueryVersion)
                    {
                    case IgmpQueryVersion.Version1:
                        Assert.AreEqual(1, packet.Ethernet.Ip.Igmp.Version);
                        break;

                    case IgmpQueryVersion.Version2:
                        Assert.AreEqual(2, packet.Ethernet.Ip.Igmp.Version);
                        break;

                    case IgmpQueryVersion.Version3:
                        Assert.AreEqual(3, packet.Ethernet.Ip.Igmp.Version);
                        break;

                    default:
                        Assert.Fail(igmpLayer.QueryVersion.ToString());
                        break;
                    }
                    break;

                case IgmpMessageType.MembershipReportVersion1:
                    Assert.AreEqual(1, packet.Ethernet.Ip.Igmp.Version);
                    break;

                case IgmpMessageType.MembershipReportVersion2:
                case IgmpMessageType.LeaveGroupVersion2:
                    Assert.AreEqual(2, packet.Ethernet.Ip.Igmp.Version);
                    break;

                case IgmpMessageType.MembershipReportVersion3:
                    Assert.AreEqual(3, packet.Ethernet.Ip.Igmp.Version);
                    break;

                default:
                    Assert.Fail(igmpLayer.MessageTypeValue.ToString());
                    break;
                }
                foreach (IgmpGroupRecordDatagram groupRecord in packet.Ethernet.Ip.Igmp.GroupRecords)
                {
                    Assert.IsNotNull(groupRecord.ToString());
                }
            }
        }
コード例 #58
0
ファイル: IcmpTests.cs プロジェクト: amitla/Pcap.Net
        public void RandomIcmpTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("00:01:02:03:04:05"),
                                                  Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
                                              };

            int seed = new Random().Next();
            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 2000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.InternetControlMessageProtocol, false);

                IcmpLayer icmpLayer = random.NextIcmpLayer();
                icmpLayer.Checksum = null;
                if (icmpLayer.MessageType == IcmpMessageType.DestinationUnreachable && 
                    icmpLayer.MessageTypeAndCode != IcmpMessageTypeAndCode.DestinationUnreachableFragmentationNeededAndDoNotFragmentSet)
                {
                    ((IcmpDestinationUnreachableLayer)icmpLayer).NextHopMaximumTransmissionUnit = 0;
                }

                IEnumerable<ILayer> icmpPayloadLayers = random.NextIcmpPayloadLayers(icmpLayer);

                int icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();

                switch (icmpLayer.MessageType)
                {
                    case IcmpMessageType.ParameterProblem:
                        if (icmpPayloadLength % 4 != 0)
                            icmpPayloadLayers = icmpPayloadLayers.Concat(new[] {new PayloadLayer {Data = random.NextDatagram(4 - icmpPayloadLength % 4)}});
                        icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();
                        IcmpParameterProblemLayer icmpParameterProblemLayer = (IcmpParameterProblemLayer)icmpLayer;
                        icmpParameterProblemLayer.Pointer = (byte)(icmpParameterProblemLayer.Pointer % icmpPayloadLength);
                        icmpParameterProblemLayer.OriginalDatagramLength = icmpPayloadLength - icmpPayloadLayers.First().Length;
                        break;

                    case IcmpMessageType.SecurityFailures:
                        ((IcmpSecurityFailuresLayer)icmpLayer).Pointer %= (ushort)icmpPayloadLength;
                        break;
                }

                PacketBuilder packetBuilder = new PacketBuilder(new ILayer[] { ethernetLayer, ipLayer, icmpLayer }.Concat(icmpPayloadLayers));

                Packet packet = packetBuilder.Build(DateTime.Now);
                Assert.IsTrue(packet.IsValid, "IsValid");

                byte[] buffer = (byte[])packet.Buffer.Clone();
                buffer.Write(ethernetLayer.Length + ipLayer.Length, random.NextDatagram(icmpLayer.Length));
                Packet illegalPacket = new Packet(buffer, DateTime.Now, packet.DataLink);
                Assert.IsFalse(illegalPacket.IsValid, "IsInvalid");
                if (illegalPacket.Ethernet.Ip.Icmp is IcmpUnknownDatagram)
                {
                    byte[] icmpBuffer = new byte[illegalPacket.Ethernet.Ip.Icmp.ExtractLayer().Length];
                    ILayer layer = illegalPacket.Ethernet.Ip.Icmp.ExtractLayer();
                    layer.Write(icmpBuffer,0,icmpBuffer.Length, null,null);
                    layer.Finalize(icmpBuffer,0,icmpBuffer.Length,null);
                    MoreAssert.AreSequenceEqual(illegalPacket.Ethernet.Ip.Icmp.ToArray(),
                                    icmpBuffer);

                    Assert.AreEqual(illegalPacket,
                                    PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, illegalPacket.Ethernet.Ip.Icmp.ExtractLayer()));
                }

                // Ethernet
                ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // IP.
                if (ipLayer == ipV4Layer)
                {
                    // IPv4.
                    ipV4Layer.Protocol = IpV4Protocol.InternetControlMessageProtocol;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer());
                    ipV4Layer.HeaderChecksum = null;
                    Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
                    Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
                    Assert.AreEqual(ipV4Layer.Length + icmpLayer.Length + icmpPayloadLength,
                                    packet.Ethernet.IpV4.TotalLength);
                    Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.IpV4.Version);
                } 
                else
                {
                    // IPv6.
                    Assert.AreEqual(ipLayer, packet.Ethernet.IpV6.ExtractLayer());
                }

                // ICMP
                IcmpDatagram actualIcmp = packet.Ethernet.Ip.Icmp;
                IcmpLayer actualIcmpLayer = (IcmpLayer)actualIcmp.ExtractLayer();
                icmpLayer.Checksum = actualIcmpLayer.Checksum;
                Assert.AreEqual(icmpLayer, actualIcmpLayer);
                Assert.AreEqual(icmpLayer.GetHashCode(), actualIcmpLayer.GetHashCode());
                if (actualIcmpLayer.MessageType != IcmpMessageType.RouterSolicitation)
                {
                    Assert.AreNotEqual(random.NextIcmpLayer(), actualIcmpLayer);
                    IcmpLayer otherIcmpLayer = random.NextIcmpLayer();
                    Assert.AreNotEqual(otherIcmpLayer.GetHashCode(), actualIcmpLayer.GetHashCode());
                }
                Assert.IsTrue(actualIcmp.IsChecksumCorrect);
                Assert.AreEqual(icmpLayer.MessageType, actualIcmp.MessageType);
                Assert.AreEqual(icmpLayer.CodeValue, actualIcmp.Code);
                Assert.AreEqual(icmpLayer.MessageTypeAndCode, actualIcmp.MessageTypeAndCode);
                Assert.AreEqual(packet.Length - ethernetLayer.Length - ipLayer.Length - IcmpDatagram.HeaderLength, actualIcmp.Payload.Length);
                Assert.IsNotNull(icmpLayer.ToString());

                switch (packet.Ethernet.Ip.Icmp.MessageType)
                {
                    case IcmpMessageType.RouterSolicitation:
                    case IcmpMessageType.SourceQuench:
                    case IcmpMessageType.TimeExceeded:
                        Assert.AreEqual<uint>(0, actualIcmp.Variable);
                        break;

                    case IcmpMessageType.DestinationUnreachable:
                    case IcmpMessageType.ParameterProblem:
                    case IcmpMessageType.Redirect:
                    case IcmpMessageType.ConversionFailed:
                    case IcmpMessageType.Echo:
                    case IcmpMessageType.EchoReply:
                    case IcmpMessageType.Timestamp:
                    case IcmpMessageType.TimestampReply:
                    case IcmpMessageType.InformationRequest:
                    case IcmpMessageType.InformationReply:
                    case IcmpMessageType.RouterAdvertisement:
                    case IcmpMessageType.AddressMaskRequest:
                    case IcmpMessageType.AddressMaskReply:
                        break;
                    case IcmpMessageType.TraceRoute:
                        Assert.AreEqual(((IcmpTraceRouteLayer)icmpLayer).OutboundHopCount == 0xFFFF, ((IcmpTraceRouteDatagram)actualIcmp).IsOutbound);
                        break;
                    case IcmpMessageType.DomainNameRequest:
                    case IcmpMessageType.SecurityFailures:
                        break;

                    case IcmpMessageType.DomainNameReply:
                    default:
                        throw new InvalidOperationException("Invalid icmpMessageType " + packet.Ethernet.Ip.Icmp.MessageType);

                }
            }
        }
コード例 #59
0
ファイル: PacketBuilderTests.cs プロジェクト: amitla/Pcap.Net
 public void BadFirstLayerTest()
 {
     PacketBuilder packetBuilder = new PacketBuilder(new TcpLayer());
     Assert.IsNull(packetBuilder);
 }
コード例 #60
0
        public void GreAutomaticProtocolTypeBadNextLayer()
        {
            Packet packet = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(), new GreLayer(), new PayloadLayer());

            Assert.IsTrue(packet.IsValid);
        }