コード例 #1
0
    public void OnClicked()
    {
        NetClient client = new NetClient(Global.Network.IPAdress, Global.Network.Port);

        try
        {
            client.Connect();

            Packet.LoginReq login = new Packet.LoginReq
            {
                Name = "Offline"
            };
            client.Send(Packet.Type.LoginReq, login);
            Debug.Log("Send");

            PacketInfo info = new PacketInfo();
            client.TryGetPacket(out info);

            if (info.Type == Packet.Type.LoginAck)
            {
                //   Packet.LoginAck ack = Packet.LoginAck.Parser.ParseFrom(info.Payload);
            }
        }
        catch (System.Exception) {
            Debug.Log("Error");
        }
        finally
        {
            client.Close();
        }
    }
コード例 #2
0
        // 큐를 꺼냄
        public int Dequeue(ref byte[] buffer, int size)
        {
            if (m_offsetList.Count <= 0)
            {
                return(-1);
            }

            int recvSize = 0;

            lock (lockObj)
            {
                PacketInfo info = m_offsetList[0];

                // 버퍼로부터 해당하는 패킷 데이터를 가져옴
                int dataSize = Math.Min(size, info.size);
                m_streamBuffer.Position = info.offset;
                recvSize = m_streamBuffer.Read(buffer, 0, dataSize);

                // 큐 데이터를 꺼냈으므로 선두 요소 삭제
                if (recvSize > 0)
                {
                    m_offsetList.RemoveAt(0);
                }

                // 모든 큐 데이터를 꺼냈을 때는 스트림 클리어
                if (m_offsetList.Count == 0)
                {
                    Clear();
                    m_offset = 0;
                }
            }

            return(recvSize);
        }
コード例 #3
0
        public async void Dispatch(Session session, PacketInfo packetInfo)
        {
            Type     messageType = Game.Scene.GetComponent <OpcodeTypeComponent>().GetType(packetInfo.Header.Opcode);
            IMessage message     = (IMessage)session.Network.MessagePacker.DeserializeFrom(messageType, packetInfo.Bytes, packetInfo.Index, packetInfo.Length);

            // gate session收到actor消息直接转发给actor自己去处理
            if (message is IActorMessage)
            {
                long       unitId     = session.GetComponent <SessionPlayerComponent>().Player.UnitId;
                ActorProxy actorProxy = Game.Scene.GetComponent <ActorProxyComponent>().Get(unitId);
                actorProxy.Send(message);
                return;
            }

            // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端
            if (message is IActorRequest aActorRequest)
            {
                long       unitId     = session.GetComponent <SessionPlayerComponent>().Player.UnitId;
                ActorProxy actorProxy = Game.Scene.GetComponent <ActorProxyComponent>().Get(unitId);
                IResponse  response   = await actorProxy.Call(aActorRequest);

                session.Reply(packetInfo.Header.RpcId, response);
                return;
            }

            if (message != null)
            {
                Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, packetInfo.Header.RpcId, message);
                return;
            }

            throw new Exception($"message type error: {message.GetType().FullName}");
        }
コード例 #4
0
ファイル: PacketQueue.cs プロジェクト: EsProgram/UnityChat
    /// <summary>
    /// 待ち行列から1つのパケットを取り出す
    /// 取り出すパケットがなかった場合は-1が返される
    /// </summary>
    /// <param name="buffer">パケットデータ</param>
    /// <returns>
    /// 受け取ったパケットデータのサイズ
    /// パケットが存在しなかった場合は-1
    /// </returns>
    public int Dequeue(ref byte[] buffer)
    {
        if (packets_info.Count <= 0)
        {
            return(-1);
        }

        PacketInfo info = packets_info[0];

        // バッファから該当するパケットデータを取得する.
        m_stream.Position = info.offset;
        int recvSize = m_stream.Read(buffer, 0, info.size);

        // キューデータを取り出したので先頭要素を削除.
        if (recvSize > 0)
        {
            packets_info.RemoveAt(0);
        }

        // すべてのキューデータを取り出したときはストリームをクリアしてメモリを節約する.
        if (packets_info.Count == 0)
        {
            Clear();
        }

        return(recvSize);
    }
コード例 #5
0
ファイル: InnerMessageDispatcher.cs プロジェクト: yph0011/ET
        public void Dispatch(Session session, PacketInfo packetInfo)
        {
            Type     messageType = Game.Scene.GetComponent <OpcodeTypeComponent>().GetType(packetInfo.Opcode);
            IMessage message     = (IMessage)session.Network.MessagePacker.DeserializeFrom(messageType, packetInfo.Bytes, packetInfo.Index, packetInfo.Length);

            // 收到actor rpc request
            if (message is ActorRequest actorRpcRequest)
            {
                Entity entity = Game.Scene.GetComponent <ActorManagerComponent>().Get(actorRpcRequest.Id);
                if (entity == null)
                {
                    Log.Warning($"not found actor: {actorRpcRequest.Id}");
                    ActorResponse response = new ActorResponse
                    {
                        Error = ErrorCode.ERR_NotFoundActor
                    };
                    session.Reply(packetInfo.RpcId, response);
                    return;
                }

                entity.GetComponent <ActorComponent>().Add(new ActorMessageInfo()
                {
                    Session = session, RpcId = packetInfo.RpcId, Message = actorRpcRequest
                });
                return;
            }

            Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, new MessageInfo(packetInfo.RpcId, packetInfo.Opcode, message));
        }
コード例 #6
0
ファイル: SwitchApp.cs プロジェクト: LancerBear/SDNSimulation
        /// <summary>
        /// 转发常规数据包
        /// </summary>
        /// <param name="packetInfo"></param>
        /// <returns></returns>
        public static void TranNormalPacket(PacketInfo packetInfo)
        {
            byte[]       packetByte   = packetInfo.GetPacketByte();
            PacketEntity packetEntity = (PacketEntity)Util.BytesToObject(packetByte);
            string       srcIP        = packetEntity.GetHead().strSrcIP;
            string       desIP        = packetEntity.GetHead().strDesIP;

            Const.EN_RET_CODE retVal = Const.EN_RET_CODE.EN_RET_INIT;
            int tranPort             = Const.INVALID_NUM;

            //流表中存在转发选项,直接转发
            if (FlowTable.GetInstance().TryGetItem(desIP, out tranPort))
            {
                retVal = Transmitter.SendViaPhyPort(tranPort, packetByte);
                if (Const.EN_RET_CODE.EN_RET_SUCC != retVal)
                {
                    Util.Log(Util.EN_LOG_LEVEL.EN_LOG_INFO, "数据包转发失败");
                }
            }
            //流表中不存在转发选项,将数据包暂存缓冲区,上报控制器
            else
            {
                Program.BufferQueue.Enqueue(packetInfo);
                PacketHead   head     = new PacketHead(srcIP, desIP, PacketHead.EN_PACKET_TYPE.EN_PACKET_IN);
                PacketEntity packetIn = new PacketEntity(head, "");
                retVal = Transmitter.SendViaPhyPort(0, Util.ObjectToBytes(packetIn));
                if (retVal != Const.EN_RET_CODE.EN_RET_SUCC)
                {
                    Util.Log(Util.EN_LOG_LEVEL.EN_LOG_INFO, "packet_in发送失败");
                }
            }
        }
コード例 #7
0
    public int Dequeue(ref byte[] buffer, int size)
    {
        if (m_offsetList.Count <= 0)
        {
            return(-1);
        }

        int recvSize = 0;

        lock (lockObj)
        {
            PacketInfo info     = m_offsetList[0];
            int        dataSize = Math.Min(size, info.size);
            m_streamBuffer.Position = info.offset;
            recvSize = m_streamBuffer.Read(buffer, 0, dataSize);
            if (recvSize > 0)
            {
                m_offsetList.RemoveAt(0);
            }
            if (m_offsetList.Count == 0)
            {
                Clear();
                m_offset = 0;
            }
        }

        return(recvSize);
    }
コード例 #8
0
    public int Dequeue(ref byte[] buffer, int size)
    {
        if (m_offsetList.Count <= 0)
        {
            return(-1);
        }

        PacketInfo info = m_offsetList[0];

        // 패킷으로부터 해당하는 패킷 데이터를 가져옵니다.
        int dataSize = Math.Min(size, info.size);

        m_streamBuffer.Position = info.offset;
        int recvSize = m_streamBuffer.Read(buffer, 0, dataSize);

        // 큐 데이터를 추출했으므로 선두 요소를 삭제.
        if (recvSize > 0)
        {
            m_offsetList.RemoveAt(0);
        }

        // 모든 큐 데이터를 추출했을 때는 스트림을 비워 메모리를 절약합니다.
        if (m_offsetList.Count == 0)
        {
            Clear();
            m_offset = 0;
        }

        return(recvSize);
    }
コード例 #9
0
        public void OffsetTest()
        {
            var packetInfo = new PacketInfo(new DeliveryOptions(false, true), 100, ConsoleLogger, new Payload(new byte[] { 0, 0, 1, 2, 3, 9, 9 }, 2, 3));

            packetInfo.Append(new Payload(new byte[] { 2, 1 }));
            packetInfo.Append(new Payload(new byte[] { 3, 1 }, 0, 2));
            packetInfo.Append(new Payload(new byte[] { 4, 2, 3, 1, 8 }, 0, 4));
            packetInfo.Append(new Payload(new byte[] { 8, 5, 2, 3, 1 }, 1, 4));
            packetInfo.Append(new Payload(new byte[] { 8, 6, 2, 3, 1, 0 }, 1, 4));

            var offsets = PacketInfo.GetOffsetInfo(packetInfo.Buffer, packetInfo.Offset).ToArray();

            offsets.Length.Should().Be(6);

            offsets[0].Length.Should().Be(3);
            offsets[1].Length.Should().Be(2);
            offsets[2].Length.Should().Be(2);
            offsets[3].Length.Should().Be(4);
            offsets[4].Length.Should().Be(4);
            offsets[5].Length.Should().Be(4);

            new ArraySegment <byte>(packetInfo.Buffer, offsets[0].Offset, offsets[0].Length).ToArray().Should()
            .BeEquivalentTo(new byte[] { 1, 2, 3 });
            new ArraySegment <byte>(packetInfo.Buffer, offsets[1].Offset, offsets[1].Length).ToArray().Should()
            .BeEquivalentTo(new byte[] { 2, 1 });
            new ArraySegment <byte>(packetInfo.Buffer, offsets[2].Offset, offsets[2].Length).ToArray().Should()
            .BeEquivalentTo(new byte[] { 3, 1 });
            new ArraySegment <byte>(packetInfo.Buffer, offsets[3].Offset, offsets[3].Length).ToArray().Should()
            .BeEquivalentTo(new byte[] { 4, 2, 3, 1 });
            new ArraySegment <byte>(packetInfo.Buffer, offsets[4].Offset, offsets[4].Length).ToArray().Should()
            .BeEquivalentTo(new byte[] { 5, 2, 3, 1 });
            new ArraySegment <byte>(packetInfo.Buffer, offsets[5].Offset, offsets[5].Length).ToArray().Should()
            .BeEquivalentTo(new byte[] { 6, 2, 3, 1 });
        }
コード例 #10
0
        public void Update(PacketInfo packetInfo)
        {
            var packetInfoVM = new PacketInfoViewModel(packetInfo);

            PacketInfoHistory.Add(packetInfoVM);
            LatestPacketInfoVM = packetInfoVM;
        }
コード例 #11
0
        /// <summary>
        /// 处理游戏登录信息封包
        /// </summary>
        /// <param name="pack">封包数据结构体</param>
        /// <returns>处理结果标志</returns>
        private static int ProcessPlayerLoginInfo(PacketInfo pack)
        {
            JObject json = pack.data;

            if (json["user"] == null)
            {
                return(E_FAILED);
            }
            DataUtil.Game.isOnline  = true;
            DataUtil.Game.player.lv = json["user"]["levelId"].ToString() != null?int.Parse(json["user"]["levelId"].ToString()) : 1;

            DataUtil.Game.player.friendId = json["user"]["searchUserId"] != null ? json["user"]["searchUserId"].ToString() : "-";
            DataUtil.Game.CalcPlayerMaxAPExp();
            DataUtil.Game.player.maxBP = GameInfo.PLAYER_MAX_BP;
            DataUtil.Game.player.maxSP = GameInfo.PLAYER_MAX_SP;
            DataUtil.Game.CalcPlayerGamePoint(GameInfo.PlayerPointType.AP, json["user"]["stamina"], json["user"]["staminaTime"]);
            DataUtil.Game.CalcPlayerGamePoint(GameInfo.PlayerPointType.BP, json["user"]["battlePoint"], json["user"]["battlePointTime"]);
            DataUtil.Game.CalcPlayerGamePoint(GameInfo.PlayerPointType.SP, json["userSearchQuest"]["searchQuestPoint"], json["userSearchQuest"]["searchQuestPointTime"]);
            DataUtil.Game.player.money = json["user"]["gameMoney"] != null?int.Parse(json["user"]["gameMoney"].ToString()) : 0;

            DataUtil.Game.player.stone = json["user"]["chargeMoney"] != null?int.Parse(json["user"]["chargeMoney"].ToString()) : 0;

            DataUtil.Game.player.exp = json["user"]["levelExperience"] != null?int.Parse(json["user"]["levelExperience"].ToString()) : 0;

            DataUtil.Game.notifyRecord.lastAP = DataUtil.Game.player.AP;
            DataUtil.Game.notifyRecord.lastBP = DataUtil.Game.player.BP;
            DataUtil.Game.notifyRecord.lastSP = DataUtil.Game.player.SP;
            UpdateTimeLeft();
            MiscHelper.AddLog("已经成功登录游戏", MiscHelper.LogType.System);
            return(E_SUCCESS);
        }
コード例 #12
0
    public int Dequeue(ref byte[] buffer, int size)
    {
        if (m_offsetList.Count <= 0)
        {
            return(-1);
        }

        PacketInfo info = m_offsetList[0];

        // バッファから該当するパケットデータを取得する.
        int dataSize = Math.Min(size, info.size);

        m_streamBuffer.Position = info.offset;
        int recvSize = m_streamBuffer.Read(buffer, 0, dataSize);

        // キューデータを取り出したので先頭要素を削除.
        if (recvSize > 0)
        {
            m_offsetList.RemoveAt(0);
        }

        // すべてのキューデータを取り出したときはストリームをクリアしてメモリを節約する.
        if (m_offsetList.Count == 0)
        {
            Clear();
            m_offset = 0;
        }

        return(recvSize);
    }
コード例 #13
0
        /// <summary>
        /// 处理探索信息封包
        /// </summary>
        /// <param name="pack">封包数据结构体</param>
        /// <returns>处理结果标志</returns>
        private static int ProcessPlayerSearchInfo(PacketInfo pack)
        {
            JObject json = pack.data;

            DataUtil.Game.CalcPlayerGamePoint(GameInfo.PlayerPointType.AP, json["stamina"], json["staminaTime"]);
            DataUtil.Game.CalcPlayerGamePoint(GameInfo.PlayerPointType.BP, json["battlePoint"], json["battlePointTime"]);
            DataUtil.Game.CalcPlayerGamePoint(GameInfo.PlayerPointType.SP, json["searchQuestPoint"], json["searchQuestPointTime"]);
            JArray items = (JArray)json["masterSearchQuestList"];
            int    gold = 0, ap = 0, gp = 0;

            foreach (JObject item in items)
            {
                switch (item["searchQuestGivingItemId"].ToString())
                {
                case "1":     //金币
                    DataUtil.Game.player.money += int.Parse(item["value"].ToString());
                    gold += int.Parse(item["value"].ToString());
                    break;

                case "1002":     //体力
                    ap += int.Parse(item["value"].ToString());
                    break;

                case "3":     //种子
                    gp += int.Parse(item["value"].ToString());
                    break;
                }
            }
            UpdateTimeLeft();
            string log = string.Format("探索完成,获得体力{0:D},金币{1:D},种子{2:D}", ap, gold, gp);

            MiscHelper.AddLog(log, MiscHelper.LogType.Search);
            return(E_SUCCESS);
        }
コード例 #14
0
        /// <summary>
        /// 处理游戏花盆开花时间信息封包
        /// </summary>
        /// <param name="pack">封包数据结构体</param>
        /// <returns>处理结果标志</returns>
        private static int ProcessUserGardenPlant(PacketInfo pack)
        {
            JObject json = pack.data;

            if (json["userGardenPlantPotList"] == null)
            {
                return(E_FAILED);
            }
            JArray plants = (JArray)json["userGardenPlantPotList"];

            if (plants.Count <= 0)
            {
                return(E_FAILED);
            }
            foreach (JObject plant in plants)
            {
                if (plant["floweringTime"] != null)
                {
                    DateTime pTime = Convert.ToDateTime(plant["floweringTime"].ToString());
                    if (DataUtil.Game.player.plantTime < pTime)
                    {
                        DataUtil.Game.player.plantTime = pTime;
                    }
                }
            }
            UpdateTimeLeft();
            return(E_SUCCESS);
        }
コード例 #15
0
        /// <summary>
        /// 处理礼品箱物品取出全部物品信息封包
        /// </summary>
        /// <param name="pack">封包数据结构体</param>
        /// <returns>处理结果标志</returns>
        private static int ProcessPresentReceivedAll(PacketInfo pack)
        {
            JObject json = pack.data;

            DataUtil.Game.player.money += json["givingGameMoney"] != null?int.Parse(json["givingGameMoney"].ToString()) : 0;

            DataUtil.Game.player.stone += json["givingChargeMoney"] != null?int.Parse(json["givingChargeMoney"].ToString()) : 0;

            string log = "取出礼品箱内物品,获得";

            log += json["givingGameMoney"] != null && json["givingGameMoney"].ToString() != "0" ? "金币" + json["givingGameMoney"].ToString() + "," : "";
            log += json["givingChargeMoney"] != null && json["givingChargeMoney"].ToString() != "0" ? "华灵石" + json["givingChargeMoney"].ToString() + "," : "";
            log += json["givingGachaPoint"] != null && json["givingGachaPoint"].ToString() != "0" ? "种子" + json["givingGachaPoint"].ToString() + "," : "";
            log += json["givingRaidBossGachaPoint"] != null && json["givingRaidBossGachaPoint"].ToString() != "0" ? "初级装备种子" + json["givingRaidBossGachaPoint"].ToString() + "," : "";
            log += (json["givingUserCharacterList"] as JArray).Count > 0 ? "角色" + (json["givingUserCharacterList"] as JArray).Count.ToString() + "," : "";
            log += (json["givingUserCharacterEquipmentList"] as JArray).Count > 0 ? "装备" + (json["givingUserCharacterEquipmentList"] as JArray).Count.ToString() + "," : "";
            log += (json["givingUserGiftList"] as JArray).Count > 0 ? "赠物" + (json["givingUserGiftList"] as JArray).Count.ToString() + "," : "";
            JArray items = (JArray)json["givingUserPointItemList"];

            foreach (JObject item in items)
            {
                log += MiscHelper.ProcessUserPointItem(item);
            }
            log += (json["givingUserEventItemList"] as JArray).Count > 0 ? "活动物品" + (json["givingUserEventItemList"] as JArray).Count.ToString() + "," : "";
            log += (json["givingUserGachaTicketList"] as JArray).Count > 0 ? "扭蛋券" + (json["givingUserGachaTicketList"] as JArray).Count.ToString() + "," : "";
            log += (json["givingUserGardenMakeoverItemList"] as JArray).Count > 0 ? "庭院物品" + (json["givingUserGardenMakeoverItemList"] as JArray).Count.ToString() + "," : "";
            MiscHelper.AddLog(log.Substring(0, log.Length - 1), MiscHelper.LogType.Mailbox);
            return(E_SUCCESS);
        }
コード例 #16
0
 /// <summary>
 /// 处理主页BOSS列表封包
 /// </summary>
 /// <param name="pack">封包数据结构体</param>
 /// <returns>处理结果标志</returns>
 private static int ProcessRaidBossList(PacketInfo pack)
 {
     DataUtil.Game.canAuto = false;
     MiscHelper.ShowMapInfoButton(false);
     MiscHelper.SetAutoGo(false);
     return(E_SUCCESS);
 }
コード例 #17
0
ファイル: FormColours.cs プロジェクト: Epidal/Ostara
		public FormColours() {
			InitializeComponent();

			Pairs = new Dictionary<Key, Val>(Colours.I.Pairs);
			var data = new PacketInfo[8];

			for (int i = 0; i < 8; i++) {
				data[i] = new PacketInfo(new byte[] { });
				data[i].Time = DateTime.Now;
				data[i].Length = 42;
				data[i].Source = (i < 4) ? Client : (Daemon)(i - 3);
				data[i].Destination = (i < 4) ? (Daemon)(i + 1) : Client;
				data[i].Opcode = 1337;
			}

			olvPreview.SetObjects(data);

			SetComboColours(cpC2LFG, cpC2LBG, Client, Login);
			SetComboColours(cpC2WFG, cpC2WBG, Client, World);
			SetComboColours(cpC2CHFG, cpC2CHBG, Client, Chat);
			SetComboColours(cpC2AFG, cpC2ABG, Client, Auction);
			SetComboColours(cpL2CFG, cpL2CBG, Login, Client);
			SetComboColours(cpW2CFG, cpW2CBG, World, Client);
			SetComboColours(cpCH2CFG, cpCH2CBG, Chat, Client);
			SetComboColours(cpA2CFG, cpA2CBG, Auction, Client);
		}
コード例 #18
0
    public int Dequeue(ref byte[] buffer, int size) // 큐에서 데이터 리턴
    {
        if (m_offsetList.Count <= 0)
        {
            return(-1);
        }

        int recvSize = 0;

        lock (lockObj)
        {
            PacketInfo info     = m_offsetList[0]; // 버퍼에서 해당하는 패킷 데이터를 가져 온다.
            int        dataSize = Math.Min(size, info.size);
            m_streamBuffer.Position = info.offset;
            recvSize = m_streamBuffer.Read(buffer, 0, dataSize);

            if (recvSize > 0)// 큐 데이터를 앞으로 꺼냈으므로 맨 앞 데이터는 삭제
            {
                m_offsetList.RemoveAt(0);
            }

            //모든 큐 데이터를 꺼냈을 때는 스트림을 정리해서 메모리를 절약한다.
            if (m_offsetList.Count == 0)
            {
                Clear();
                m_offset = 0;
            }
        }
        return(recvSize);
    }
コード例 #19
0
    public int Dequeue(ref byte[] buffer, int size)
    {
        if (offsetList.Count <= 0)
        {
            return(-1);
        }

        PacketInfo info = offsetList[0];

        int dataSize = Math.Min(size, info.size);

        memoryStreamBuffer.Position = info.offset;
        int recvSize = memoryStreamBuffer.Read(buffer, 0, dataSize);

        if (recvSize > 0)
        {
            offsetList.RemoveAt(0);
        }

        if (offsetList.Count == 0)
        {
            Clear();
            offset = 0;
        }

        return(recvSize);
    }
コード例 #20
0
ファイル: AprsMessageTests.cs プロジェクト: skyhop/Aprs
        public void ParseMessageWithAlternativeSymbols()
        {
            var data = @"KB9VBR-N>APDG03,TCPIP*,qAC,T2INDIANA:!4456.70ND08937.08W&/A=000000440 MMDVM Voice 431.50000MHz +0.0000MHz, KB9VBR_Pi-Star
KD9GCX-S>APDG01,TCPIP*,qAC,KD9GCX-GS:;KD9GCX B 160126z4415.63ND08817.60Wa/A=000010RNG0001 440 Voice 433.00000MHz +0.0000MHz
WE9C0M-8>APN391,qAR,K9FR:!4541.60NS09120.85W#PHG6560 W3, In honor to Bill W9NNS
KD9GCX-B>APDG02,TCPIP,qAC,KD9GCX-BS:!4415.63ND08817.60W&/A=000010RNG0001 440 Voice 433.00000MHz +0.0000MHz";

            var messages = data.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            var first = PacketInfo.Parse(messages[0]);

            Assert.AreEqual("KB9VBR-N", first.Callsign);
            Assert.AreEqual(Skyhop.Aprs.Client.Enums.DataType.PositionWithoutTimestampNoAprsMessaging, first.DataType);
            Assert.AreEqual(new Latitude(44, 56, 42, LatitudeHemisphere.North).ToString(), first.Latitude.ToString());
            Assert.AreEqual(new Longitude(89, 37, 4.8, LongitudeHemisphere.West).ToString(), first.Longitude.ToString());
            //Assert.AreEqual(Skyhop.Aprs.Client.Enums.Symbol.HfGateway, first.Symbol);

            var second = PacketInfo.Parse(messages[1]);

            Assert.IsNotNull(second);

            var third = PacketInfo.Parse(messages[2]);

            Assert.IsNotNull(third);

            var fourth = PacketInfo.Parse(messages[3]);

            Assert.IsNotNull(fourth);
        }
コード例 #21
0
ファイル: SwitchApp.cs プロジェクト: LancerBear/SDNSimulation
        /// <summary>
        /// 阻塞的方式处理控制器的消息,处理完之前无法接受控制器消息,属于监听子线程
        /// </summary>
        /// <param name="packetInfo"></param>
        public static void DealControllerPacket(PacketInfo packetInfo)
        {
            int iPhyPortNo = packetInfo.GetPhyPort();

            byte[]       buffer  = packetInfo.GetPacketByte();
            PacketEntity packet  = (PacketEntity)Util.BytesToObject(buffer);
            string       content = packet.GetStrContent();
            string       srcIP   = packet.GetHead().strSrcIP;
            string       desIP   = packet.GetHead().strDesIP;

            PacketHead.EN_PACKET_TYPE packetType = packet.GetHead().enPacketType;

            switch (packetType)
            {
            case PacketHead.EN_PACKET_TYPE.EN_ACK_SWITCH_ONLINE:
                Util.Log(Util.EN_LOG_LEVEL.EN_LOG_INFO, "控制器上线");
                break;

            //收到控制器下发的流表
            case PacketHead.EN_PACKET_TYPE.EN_PACKET_OUT_WITH_FLOW_ITEM:
                DealPacketOut(packetInfo);
                break;

            case PacketHead.EN_PACKET_TYPE.EN_PACKET_OUT_DUMP:
                //TODO
                break;

            default:
                break;
            }
        }
コード例 #22
0
        public override void OnReceivePacketFromClient(IPEndPoint endPoint, DataPacket dataPacket)
        {
            GamePeer peer = null;

            try
            {
                peer = PeerCollection.Get(endPoint);
                var offsets = PacketInfo.GetOffsetInfo(dataPacket.Buffer, dataPacket.Offset);
                foreach (var item in offsets)
                {
                    try
                    {
                        var messageData = new Payload(dataPacket.Buffer, item.Offset, item.Length);
                        ProcessMessage(endPoint, messageData, dataPacket.DeliveryOptions, peer);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"Error processing message: {ex}");
                        if (peer != null)
                        {
                            _messageSender.Send(new ErrorResponse(ResultCode.MessageProcessingError), peer);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"OnReceivePacketFromClient: Error processing package: {ex}");
                if (peer != null)
                {
                    _messageSender.Send(new ErrorResponse(ResultCode.MessageProcessingError), peer);
                }
            }
        }
コード例 #23
0
ファイル: TcpStream.cs プロジェクト: lOlbas/010Proxy
        public void AppendPacket(TimedPacket newPacket)
        {
            // Assuming the packet is correct for this stream

            var payloadData   = newPacket.Packet.PayloadData;
            var payloadLength = payloadData.Length;

            if (payloadLength == 0)
            {
                return;
            }

            lock (_packetsInfo)
            {
                // An extra validation step here would be verifying that the order of packets is not messed up, i.e packet #3 did not arrive before packet #2.
                // This approach however does not take into account the client data that change server sequence number,
                // so we rely on the SharpPcap giving us packets in the correct order
                var newPacketInfo = new PacketInfo(newPacket, base.Length);
                lock (this)
                {
                    var position = base.Position;

                    _packetsInfo.AddLast(newPacketInfo);

                    base.Seek(0, SeekOrigin.End);
                    base.Write(payloadData, 0, payloadLength);
                    base.Position = position;
                }
            }
        }
コード例 #24
0
        protected override void OnStart(string[] args)
        {
            //ConfigInfo info = new ConfigInfo();
            //var path = "F:\\设备管理\\DeviceMonitor\\SubServiceForDeviceMonitor\\bin\\Debug\\soft.ini";//info.GetCurrentPath();
            //var io = info.GetConfigInfo(path);
            //softinfo= info.SerialObj(io);

            PacketInfo       pinfo = new PacketInfo();
            LANAllComputerIp lan   = new LANAllComputerIp();

            lan.GetLocalMachineIp();
            lan.localMachine.status = LANAllComputerIp.ComputerStatus.ON_LINE;
            pinfo.ip.Add(lan.localMachine);
            SoftInfo sinfo = new SoftInfo();

            sinfo.SoftName = "coach.exe";
            sinfo.status   = SoftStatus.Init;
            pinfo.soft.Add(sinfo);
            Packet pt   = new Packet();
            var    data = pt.Package(pinfo);

            sc.Start();
            sc.RD += Sc_RD;
            sc.SendInfo("", data);
        }
コード例 #25
0
    // Dequeue packets
    public int Dequeue(ref byte[] buffer, int size)
    {
        if (m_offsetList.Count <= 0)
        {
            return(-1);
        }

        int recvSize = 0;

        lock (lockObj){
            PacketInfo info = m_offsetList[0];
            // Get the packet from the buffer
            int dataSize = Math.Min(size, info.size);
            m_streamBuffer.Position = info.offset;
            recvSize = m_streamBuffer.Read(buffer, 0, dataSize);

            // Remove the first data from the Queue
            if (recvSize > 0)
            {
                m_offsetList.RemoveAt(0);
            }

            // Arragne the streams to save memory
            if (m_offsetList.Count == 0)
            {
                //Clear ();
                m_offset = 0;
            }
        }
        return(recvSize);
    }
コード例 #26
0
ファイル: PacketParser.cs プロジェクト: gerzoid/NetworkShow
 public int FindConnectionUnion(PacketInfo conn)
 {
     for (int x = 0; x <= connections_.Count - 1; x++)
     {
         if (connections_[x].ipSource == conn.ipSource)
         {
             if (connections_[x].ipDestination == conn.ipDestination)
             {
                 if (connections_[x].portSource == conn.portSource)
                 {
                     if (connections_[x].portDestination == conn.portDestination)
                     {
                         if (connections_[x].protocol == conn.protocol)
                         {
                             return(x);
                         }
                     }
                 }
             }
         }
         if ((connections_[x].ipSource == conn.ipDestination) && (connections_[x].portDestination == conn.portSource) && (connections_[x].protocol == conn.protocol))
         {
             return(x);
         }
     }
     return(-1);
 }
コード例 #27
0
        /// <summary>
        /// Writes a packet to the server to figure out what to do.
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="serverPacket"></param>
        private void writePackageInfo(NetOutgoingMessage msg, ServerPacketTypes serverPacket)
        {
            PacketInfo packet = new PacketInfo(SenderPackets.Client, ClientPacketTypes.None_None, serverPacket);

            packet.writeToMessage(msg);
            Console.WriteLine(packet.ToString());
        }
コード例 #28
0
ファイル: PacketParser.cs プロジェクト: gerzoid/NetworkShow
 public PacketInfo UpdateConnection(int id, PacketInfo conn)
 {
     connections_[id].size += conn.size;
     connections_[id].count++;
     connections_[id].lastActiveTime = conn.time;
     return(connections_[id]);
 }
コード例 #29
0
ファイル: PacketParser.cs プロジェクト: gerzoid/NetworkShow
        public void UpdateActiveConnection()
        {
            PacketInfo cconnect = new PacketInfo();

            for (int x = 0; x <= connections_.Count - 1; x++)
            {
                cconnect = connections_[x];
                if (cconnect.protocol == "TCP")
                {
                    if ((DateTime.Now - cconnect.lastActiveTime).Minutes >= 4)
                    {
                        cconnect.active = "F";
                        RemoveConnection(x);
                    }
                }
                else
                if (cconnect.protocol == "UDP")
                {
                    if ((DateTime.Now - cconnect.lastActiveTime).Minutes >= 1)
                    {
                        cconnect.active = "F";
                        RemoveConnection(x);
                    }
                }
                else
                {
                    cconnect.active = "F";
                    RemoveConnection(x);
                }
                db.UpdateConnection(cconnect.pos, cconnect);
                UpdateInfoEvent(cconnect.protocol);
            }
        }
コード例 #30
0
ファイル: PacketQueue.cs プロジェクト: griddummy/StillAlive1
    public int Dequeue(out Socket sourceSock, ref byte[] buffer, int size)
    {
        sourceSock = null;

        if (m_offsetQueue.Count <= 0)
        {
            return(-1);
        }

        int        recvSize = 0;
        PacketInfo info     = m_offsetQueue.Peek();

        sourceSock = info.sockSource;

        // 버퍼에서 데이터 가져오기
        m_streamBuffer.Position = info.offset;
        recvSize = m_streamBuffer.Read(buffer, 0, info.size);


        // 큐 데이터를 꺼냈으면 맨 앞 데이터는 삭제
        if (recvSize > 0)
        {
            m_offsetQueue.Dequeue();
        }

        // 모든 큐 데이터를 꺼냇으면 스트림 정리해서 메모리 절약한다.
        if (m_offsetQueue.Count == 0)
        {
            Clear();
            m_offest = 0;
        }
        return(recvSize);
    }
コード例 #31
0
    // 큐를 추출.
    public int Dequeue(ref byte[] buffer, int size)
    {
        if (m_offsetList.Count <= 0)
        {
            return(-1);
        }

        int recvSize = 0;

        lock (lockObj) {
            PacketInfo info = m_offsetList[0];

            // 버퍼에서 해당하는 패킷 데이터를 획득한다.
            int dataSize = Math.Min(size, info.size);
            m_streamBuffer.Position = info.offset;
            recvSize = m_streamBuffer.Read(buffer, 0, dataSize);

            // 큐 데이터를 추출했으므로 선두 요소를 삭제.
            if (recvSize > 0)
            {
                m_offsetList.RemoveAt(0);
            }

            // 모든 큐 데이터를 추출했을 때는 스티림을 클리어해서 메모리를 절약한다.
            if (m_offsetList.Count == 0)
            {
                Clear();
                m_offset = 0;
            }
        }

        return(recvSize);
    }
コード例 #32
0
ファイル: PacketQueue.cs プロジェクト: fotoco/006772
	// 
	public int Enqueue(byte[] data, int size)
	{
		PacketInfo	info = new PacketInfo();
	
		info.offset = m_offset;
		info.size = size;
			
		// 패킷 저장 정보를 보존.
		m_offsetList.Add(info);
		
		// 패킷 데이터를 보존.
		m_streamBuffer.Position = m_offset;
		m_streamBuffer.Write(data, 0, size);
		m_streamBuffer.Flush();
		m_offset += size;
		
		return size;
	}
コード例 #33
0
ファイル: PacketQueue.cs プロジェクト: cckato/UniChat
    //-------------------------------
    // Public Logic
    //-------------------------------
    public int Enqueue(byte[] data, int size)
    {
        PacketInfo info = new PacketInfo();
        info.offset = offset;
        info.size = size;

        lock (lockObj)
        {
            offsetList.Add(info);

            streamBuffer.Position = offset;
            streamBuffer.Write(data, 0, size);
            streamBuffer.Flush();
            offset += size;
        }

        return size;
    }
コード例 #34
0
ファイル: PacketLog.cs プロジェクト: Epidal/Ostara
        public static List<PacketInfo> Load(string file)
        {
            var result = new List<PacketInfo>();

            var f = File.OpenRead(file);
            var r = new BinaryReader(f, Encoding.ASCII);

            while (r.PeekChar() != -1) {
                var length = r.ReadInt32();
                var data = r.ReadBytes(length);
                var p = new PacketInfo(data);
                p.Opcode = r.ReadUInt16();
                p.Time = DateTime.FromFileTimeUtc(r.ReadInt64());
                p.Source = (PacketInfo.Daemon)r.ReadByte();
                p.Destination = (PacketInfo.Daemon)r.ReadByte();

                result.Add(p);
            }

            r.Dispose();

            return result;
        }
コード例 #35
0
ファイル: Client.cs プロジェクト: Jaex/Chat
 public void SendPacket(PacketInfo packetInfo)
 {
     new Thread(() => SendPacketThread(packetInfo)).Start();
 }
コード例 #36
0
ファイル: FormMain.cs プロジェクト: Epidal/Ostara
			public PacketClass(TcpDatagram tcp, bool inc, PacketInfo.Daemon daemon, ushort port) {
				Tcp = tcp;
				IsIncoming = inc;
				Daemon = daemon;
				Port = port;
			}
コード例 #37
0
ファイル: Client.cs プロジェクト: Jaex/Chat
 private void SendPacketThread(PacketInfo packetInfo)
 {
     try
     {
         StreamWriter sw = new StreamWriter(client.GetStream());
         JsonSerializerSettings jsonSettings = new JsonSerializerSettings
         {
             NullValueHandling = NullValueHandling.Ignore
         };
         string data = JsonConvert.SerializeObject(packetInfo, jsonSettings);
         Debug.WriteLine("SendPacket: " + data);
         sw.Write(data);
         sw.Flush();
     }
     catch (Exception e)
     {
         Debug.WriteLine("Send packet failed: " + e.ToString());
     }
 }
コード例 #38
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
 public void SendToAll(PacketInfo packetInfo)
 {
     foreach (Client client in Clients)
     {
         client.SendPacket(packetInfo);
     }
 }
コード例 #39
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
 public void SendMessageToAll(string nickname, string message)
 {
     if (!string.IsNullOrEmpty(nickname) && !string.IsNullOrEmpty(message))
     {
         PacketInfo packetInfoMessage = new PacketInfo("Message");
         MessageInfo messageInfo = new MessageInfo(message);
         messageInfo.FromUser = new UserInfo(nickname);
         packetInfoMessage.Data = messageInfo;
         SendToAll(packetInfoMessage);
     }
 }
コード例 #40
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
        private void ClientMessageReceived(Client client, string text)
        {
            OnConsoleOutput(string.Format("{0} {1}: {2}", client.UserInfo.Nickname, client.IP, text));

            PacketInfo packetInfo;

            try
            {
                packetInfo = JsonConvert.DeserializeObject<PacketInfo>(text);
            }
            catch
            {
                return;
            }

            if (packetInfo != null && !string.IsNullOrEmpty(packetInfo.Command))
            {
                if (packetInfo.Command == "Connect")
                {
                    client.UserInfo.Nickname = packetInfo.GetParameter("Nickname");
                    string password = packetInfo.GetParameter("Password");
                    ClientConnect(client, password);
                }
                else if (client.Authorized)
                {
                    switch (packetInfo.Command)
                    {
                        case "Disconnect":
                            string reason = packetInfo.GetParameter("Reason");
                            ClientDisconnected(client, reason);
                            break;
                        case "Message":
                            if (client.Authorized)
                            {
                                PacketInfo packetInfoMessage = new PacketInfo("Message");
                                MessageInfo messageInfo = packetInfo.GetData<MessageInfo>();
                                messageInfo.FromUser = client.UserInfo;
                                packetInfoMessage.Data = messageInfo;

                                if (messageInfo.ToUser != null && !string.IsNullOrEmpty(messageInfo.ToUser.Nickname))
                                {
                                    SendTo(messageInfo.ToUser, packetInfoMessage);
                                    SendTo(messageInfo.FromUser, packetInfoMessage);
                                }
                                else
                                {
                                    SendToAll(packetInfoMessage);
                                }
                            }
                            break;
                        case "Ping":
                            SendTo(client.UserInfo, new PacketInfo("Pong"));
                            break;
                    }
                }
            }
        }
コード例 #41
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
        private bool ClientConnect(Client client, string password = "")
        {
            if (!string.IsNullOrEmpty(Password) && !password.Equals(Password, StringComparison.InvariantCultureIgnoreCase))
            {
                KickClient(client, "Wrong password.");
                return false;
            }

            string nickname = client.UserInfo.Nickname;

            if (string.IsNullOrEmpty(nickname) || nickname.Equals(Nickname, StringComparison.InvariantCultureIgnoreCase))
            {
                KickClient(client, "Invalid nickname.");
                return false;
            }

            if (Clients.Any(x => nickname.Equals(x.UserInfo.Nickname, StringComparison.InvariantCultureIgnoreCase)))
            {
                KickClient(client, "Nickname is already in use: " + nickname);
                return false;
            }

            Clients.Add(client);
            OnUserConnected(client.UserInfo);
            client.Authorized = true;

            SendUserList(client);

            PacketInfo packetInfoConnected = new PacketInfo("Connected");
            packetInfoConnected.Data = client.UserInfo;
            SendToAll(packetInfoConnected);

            return true;
        }
コード例 #42
0
ファイル: ClientManager.cs プロジェクト: Jaex/Chat
 public void Disconnect()
 {
     PacketInfo packetInfo = new PacketInfo("Disconnect");
     packetInfo.AddParameter("Reason", "User disconnect");
     client.SendPacket(packetInfo);
     client.Disconnect();
 }
コード例 #43
0
        /// <summary>
        /// Sets the visible packet.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="packetInfo">The packet info.</param>
        public void SetVisiblePacket(int index, PacketInfo packetInfo)
        {
            if (index >= visiblePacketsCount)
            {
                throw new ArgumentOutOfRangeException("index", index, "Index of visible packets should be less that count of visible packets");
            }
            if (index != 0 && packetInfo.TextEndIndex <= m_packetInfos[index - 1].TextEndIndex)
            {
                throw new ArgumentException("New text index should be greater than previous");
            }

            // Store packet info
            m_packetInfos[index] = packetInfo;
        }
コード例 #44
0
ファイル: FormMain.cs プロジェクト: Epidal/Ostara
		string GetSchemaFilename(PacketInfo packet) {
			PacketInfo.Daemon daemon;
			var opcode = packet.Opcode;

			if (packet.IsIncoming)
				daemon = packet.Source;
			else
				daemon = packet.Destination;

			var dchar =
				(daemon == PacketInfo.Daemon.Auction) ? 'a' :
				(daemon == PacketInfo.Daemon.Chat) ? 'c' :
				(daemon == PacketInfo.Daemon.Login) ? 'l' :
				'w';

			var ichar = (packet.IsIncoming) ? 'i' : 'o';

			return $"{opcode}.{ichar}.{dchar}.bee";
		}
コード例 #45
0
ファイル: FormMain.cs プロジェクト: Epidal/Ostara
		void AddPacket(PacketInfo p) {
			if (!Ignores.I.Values.Contains(p.Opcode))
				flvPackets.AddObject(p);
		}
コード例 #46
0
ファイル: FormMain.cs プロジェクト: Epidal/Ostara
		ResultCollection ParsePacketData(PacketInfo packet) {
			var filename = $"cfg\\structs\\{GetSchemaFilename(packet)}";

			if (!File.Exists(filename))
				return null;

			ResultCollection r = null;

			try {
				r = Schema.FromFile(filename).Parse(packet.Data);
			} catch (Exception e) {
#if DEBUG
				Console.WriteLine(e.Message);
#else
				MessageBox.Show(e.Message);
#endif
			}

			return r;
		}
コード例 #47
0
ファイル: FormMain.cs プロジェクト: Epidal/Ostara
		void ProcessPacket(byte[] data, bool inc, PacketInfo.Daemon daemon, ushort port) {
			int s;
			byte[] tmp;

			if (inc) {
				switch (daemon) {
					case PacketInfo.Daemon.Login:
						if (partil == null)
							break;

						s = partil.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partil, 0, tmp, 0, partil.Length);
						Array.ConstrainedCopy(data, 0, tmp, partil.Length, data.Length);
						data = tmp;
						partil = null;
						break;
					case PacketInfo.Daemon.World:
						if (partiw == null)
							break;

						s = partiw.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partiw, 0, tmp, 0, partiw.Length);
						Array.ConstrainedCopy(data, 0, tmp, partiw.Length, data.Length);
						data = tmp;
						partiw = null;
						break;
					case PacketInfo.Daemon.Chat:
						if (partic == null)
							break;

						s = partic.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partic, 0, tmp, 0, partic.Length);
						Array.ConstrainedCopy(data, 0, tmp, partic.Length, data.Length);
						data = tmp;
						partic = null;
						break;
					case PacketInfo.Daemon.Auction:
						if (partia == null)
							break;

						s = partia.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partia, 0, tmp, 0, partia.Length);
						Array.ConstrainedCopy(data, 0, tmp, partia.Length, data.Length);
						data = tmp;
						partia = null;
						break;
				}
			}
			else {
				switch (daemon) {
					case PacketInfo.Daemon.Login:
						if (partol == null)
							break;

						s = partol.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partol, 0, tmp, 0, partol.Length);
						Array.ConstrainedCopy(data, 0, tmp, partol.Length, data.Length);
						data = tmp;
						partol = null;
						break;
					case PacketInfo.Daemon.World:
						if (partow == null)
							break;

						s = partow.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partow, 0, tmp, 0, partow.Length);
						Array.ConstrainedCopy(data, 0, tmp, partow.Length, data.Length);
						data = tmp;
						partow = null;
						break;
					case PacketInfo.Daemon.Chat:
						if (partoc == null)
							break;

						s = partoc.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partoc, 0, tmp, 0, partoc.Length);
						Array.ConstrainedCopy(data, 0, tmp, partoc.Length, data.Length);
						data = tmp;
						partoc = null;
						break;
					case PacketInfo.Daemon.Auction:
						if (partoa == null)
							break;

						s = partoa.Length + data.Length;
						tmp = new byte[s];
						Array.ConstrainedCopy(partoa, 0, tmp, 0, partoa.Length);
						Array.ConstrainedCopy(data, 0, tmp, partoa.Length, data.Length);
						data = tmp;
						partoa = null;
						break;
				}
			}

			var size = (inc)
				? serverCrypt[port].GetPacketSize(data)
				: clientCrypt[port].GetPacketSize(data);

			if (size > data.Length) {
#if DEBUG
				//Console.WriteLine("Found partial packet. Storing...");
#endif

				if (inc) {
					if (daemon == PacketInfo.Daemon.Login) {
						partil = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partil, 0, data.Length);
					}
					else if (daemon == PacketInfo.Daemon.World) {
						partiw = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partiw, 0, data.Length);
					}
					else if (daemon == PacketInfo.Daemon.Chat) {
						partic = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partic, 0, data.Length);
					}
					else if (daemon == PacketInfo.Daemon.Auction) {
						partia = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partia, 0, data.Length);
					}
				}
				else {
					if (daemon == PacketInfo.Daemon.Login) {
						partol = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partol, 0, data.Length);
					}
					else if (daemon == PacketInfo.Daemon.World) {
						partow = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partow, 0, data.Length);
					}
					else if (daemon == PacketInfo.Daemon.Chat) {
						partoc = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partoc, 0, data.Length);
					}
					else if (daemon == PacketInfo.Daemon.Auction) {
						partoa = new byte[data.Length];
						Array.ConstrainedCopy(data, 0, partoa, 0, data.Length);
					}
				}

				return;
			}

			if (size < data.Length) {
				// Process the first subpacket
				var sub = new byte[size];
				Array.ConstrainedCopy(data, 0, sub, 0, size);
				ProcessPacket(sub, inc, daemon, port);

				// Process the rest of the data.  May contain further subpackets, or a partial packet.  We don't care
				sub = new byte[data.Length - size];
				Array.ConstrainedCopy(data, size, sub, 0, data.Length - size);
				ProcessPacket(sub, inc, daemon, port);

				return;
			}

			if (inc)
				serverCrypt[port].Decrypt(data);
			else
				clientCrypt[port].Decrypt(data);

			var ppkt = new PacketInfo(data, DateTime.Now, inc, daemon);

			if (inc && ((ppkt.Opcode == 101 && daemon == PacketInfo.Daemon.Login) ||
						(ppkt.Opcode == 140 && daemon == PacketInfo.Daemon.World) ||
						(ppkt.Opcode == 401 && daemon == PacketInfo.Daemon.Chat) ||
						(ppkt.Opcode == 101 && daemon == PacketInfo.Daemon.Auction))) {
				unsafe
				{
					fixed (byte* pp = data)
					{
						var key = *(uint*)&pp[6];
						var step = *(ushort*)&pp[16];

						serverCrypt[port].ChangeKey(key, step);
						clientCrypt[port].ChangeKey(key, step);
					}
				}
			}

			if (!paused) {
				if (flvPackets.InvokeRequired)
					this.Invoke(new AddPacketDel(AddPacket), new object[] { ppkt });
				else
					AddPacket(ppkt);
			}
		}
コード例 #48
0
ファイル: FormMain.cs プロジェクト: Epidal/Ostara
		void AddPacket(TcpDatagram tcp, bool inc, PacketInfo.Daemon daemon, ushort port) {
			foreach (var p in packets) {
				if (p.Tcp.SequenceNumber == tcp.SequenceNumber) {
#if DEBUG
					Console.WriteLine("Dropping duplicate packet...");
#endif
					return;
				}
			}

			packets.Enqueue(new PacketClass(tcp, inc, daemon, port));

			if (packets.Count > 10) {
				var p = packets.Dequeue();
				var data = p.Tcp.Payload.ToMemoryStream();
				ProcessPacket(data.ToArray(), p.IsIncoming, p.Daemon, p.Port);
			}
		}
コード例 #49
0
ファイル: TCPParser.cs プロジェクト: ewcasas/DVTK
        public void AnalysePacket(PacketInfo data)
        {
            byte [] PacketData = data.Data;
            int StartIndex = data.StartIndex;

            int Index = StartIndex;

            // Start by eliminating non IP and non TCP packets
            if( ( Index + LENGTH_OF_INTERNET + LENGTH_OF_TCP ) > PacketData.Length )
            {
                return ;
            }

            PacketINTERNET.PACKET_INTERNET PInternet = new PacketINTERNET.PACKET_INTERNET();
            PInternet.Version = PacketData[ Index++ ];
            PInternet.HeaderLength = (byte) ( ( (int) PInternet.Version & 0x0f ) * 4 );
            PInternet.Version = (byte) ( (int) PInternet.Version >> 4 );
            PInternet.DifferentiatedServicesField = PacketData[ Index++ ];
            PInternet.Length = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PInternet.Identification = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PInternet.FragmentOffset = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PInternet.Flags = (byte)( (int) PInternet.FragmentOffset >> 12 );
            PInternet.FragmentOffset = (ushort) ( (int) PInternet.FragmentOffset & 0x0f );
            PInternet.TimeToLive = PacketData[ Index++ ];
            PInternet.Protocol = PacketData[ Index++ ];
            PInternet.HeaderChecksum = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PInternet.Source = Function.GetIpAddress( PacketData , ref Index );
            PInternet.Destination  = Function.GetIpAddress( PacketData , ref Index );
            if(PInternet.Protocol  != IPPROTO_TCP )
                return;

            // Check IPs
            //if(!analysisFromCapFile)
            //{
                if(((PInternet.Source == IP1) && (PInternet.Destination == IP1)) ||
                    (PInternet.Source == PInternet.Destination))
                {
                    return;
                }
            //}

            PacketTCP.PACKET_TCP PTcp = new PacketTCP.PACKET_TCP();

            PTcp.SourcePort = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PTcp.DestinationPort = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PTcp.SequenceNumber = Function.Get4Bytes( PacketData , ref Index , Const.NORMAL );
            PTcp.Acknowledgement = Function.Get4Bytes( PacketData , ref Index , Const.NORMAL );
            PTcp.HeaderLength = PacketData[ Index++ ];
            PTcp.HeaderLength = (byte) ( ( (int) PTcp.HeaderLength >> 4 ) * 4 );
            PTcp.Flags = PacketData[ Index++ ];
            PTcp.WindowSize = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PTcp.Checksum = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );
            PTcp.Options = Function.Get2Bytes( PacketData , ref Index , Const.NORMAL );

            //if(!analysisFromCapFile)
            //{
                if(((PTcp.SourcePort == Port1) && (PTcp.DestinationPort == Port1)) ||
                    ((PTcp.SourcePort == Port2) && (PTcp.DestinationPort == Port2)))
                {
                    return;
                }
            //}

            String signature = Signature(PInternet.Source, PTcp.SourcePort, PInternet.Destination, PTcp.DestinationPort);
            //Keep track of the connections which have been established.(The list will be used later to populate the Associations Combo Box.)
            if (!listOfConnections.Contains(signature))
            {
                listOfConnections.Add(signature);
            }
            TCPPacket packet = new TCPPacket(PacketData, StartIndex , PInternet, PTcp, data.TimeStamp);

            LastParsedPacketTime = packet.TimeStamp;

            int match = -1;
            TCPState state;
            for(int i=0;i<2;i++)
            {
                if(List[i].Contains(signature))
                {
                    match=i;
                }
            }

            // add as new item if necessary
            if(match==(-1))
            {
                //Need to check here that we have SYNs
                String signature1 = Signature(PInternet.Destination, PTcp.DestinationPort,PInternet.Source, PTcp.SourcePort);
                state = new TCPState(packet,signature, signature1);
                List[0].Add(signature,state);
                List[1].Add(signature1,state);
                match=0;
            }
            else
            {
                state = (TCPState) List[match][signature];
            }

            lock(state)
            {
                if(state.State[match] != TCPState.States.REPORTED)
                {
                    state.AddPacket(match,packet);
                    TCPState.PacketAction LastAction;
                    while((LastAction = state.Defragment(match)) == TCPState.PacketAction.DATA)
                    {
                        if(FragmentAdded != null)
                        {
                            FragmentAdded(state, match);
                        }
                        nrOfCapturedPackets++;
                    }
                    if(LastAction == TCPState.PacketAction.FIN)
                    {
                        if(EndOfStream != null)
                            EndOfStream(state, match, "FIN Seen (" + signature + ")");
                    }
                    if(LastAction == TCPState.PacketAction.RST)
                    {
                        if(EndOfStream != null)
                            EndOfStream(state, match, "RST Seen (" + signature + ")");
                    }
                    if(LastAction == TCPState.PacketAction.DEAD)
                    {
                        //Error("DEAD seen" + signature);
                        if(EndOfStream != null)
                            EndOfStream(state, match, "DEAD data seen (" + signature + ")");
                    }
                }
            }
        }
コード例 #50
0
ファイル: DataSetHelper.cs プロジェクト: san90279/UK_OAS
 public static DataSet GetDataSet(string packageName, string commandName, PacketInfo packetInfo)
 {
     var clientInfo = EFClientTools.ClientUtility.ClientInfo;
     var xml = (string)EFClientTools.ClientUtility.Client.GetDataSet(clientInfo, packageName, commandName, packetInfo);
     return Deserialize(xml);
 }
コード例 #51
0
ファイル: TCPParser.cs プロジェクト: ewcasas/DVTK
 public void AddPacket(PacketInfo p)
 {
     // NOTE - this is designed to be called asynchronously from the
     // packet sniffing thread
     lock(Packets)
     {
         Packets.Enqueue(p);
     }
 }
コード例 #52
0
ファイル: DataSetHelper.cs プロジェクト: san90279/UK_OAS
 public static DataSet ExecuteSql(SQLCommandInfo sqlCommand, PacketInfo packetInfo, SDTableType tableType)
 {
     var clientInfo = EFClientTools.ClientUtility.ClientInfo;
     var xml = (string)EFClientTools.ClientUtility.Client.SDExcuteSql(clientInfo, sqlCommand, packetInfo, tableType);
     return Deserialize(xml);
 }
コード例 #53
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
        private void ClientDisconnected(Client client, string reason)
        {
            if (client.Authorized)
            {
                Clients.Remove(client);
                OnUserDisconnected(client.UserInfo);
                OnConsoleOutput(string.Format("Client disconnected: {0} {1} {2}", client.UserInfo.Nickname, client.IP, reason));

                if (IsWorking)
                {
                    PacketInfo packetInfoDisconnected = new PacketInfo("Disconnected");
                    packetInfoDisconnected.Data = client.UserInfo;
                    SendToAll(packetInfoDisconnected);
                }
            }
        }
コード例 #54
0
ファイル: DataSetHelper.cs プロジェクト: san90279/UK_OAS
 public static DataSet ExecuteSql(string commandText, PacketInfo packetInfo, SDTableType tableType)
 {
     return ExecuteSql(new SQLCommandInfo() { CommandText = commandText }, packetInfo, tableType);
 }
コード例 #55
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
 public void SendUserList(Client client)
 {
     if (Clients.Count > 0)
     {
         PacketInfo packetInfo = new PacketInfo("UserList");
         packetInfo.Data = Clients.Select(x => x.UserInfo).ToArray();
         client.SendPacket(packetInfo);
     }
 }
コード例 #56
0
ファイル: SnifferObject.cs プロジェクト: ewcasas/DVTK
        void wincap_OnReceivePacket(object sender, PacketHeader p, byte[] s)
        {
            if (p.Caplength >= p.Length)  // no point in trying to handle incomplete packets
            {
                PacketInfo data = new PacketInfo();

                data.Data = s;
                data.TimeStamp = p.TimeStamp;
                data.Length = (uint)s.Length;
                data.StartIndex = 14;

                nrOfCapturedPackets++;

                if (DataReceived != null)
                    DataReceived(data);
            }
        }
コード例 #57
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
        public bool SendTo(UserInfo userInfo, PacketInfo packetInfo)
        {
            if (userInfo != null && !string.IsNullOrEmpty(userInfo.Nickname))
            {
                Client client = Clients.FirstOrDefault(x => x.UserInfo.Nickname == userInfo.Nickname);

                if (client != null)
                {
                    client.SendPacket(packetInfo);
                    return true;
                }
            }

            return false;
        }
コード例 #58
0
        private static void DefinePackets()
        {
            clientToServerPackets = new ConcurrentDictionary<string, PacketInfo>();
            serverToClientPackets = new ConcurrentDictionary<Type, PacketInfo>();

            uint packetCount = 0u;
            DateTime startTime = DateTime.Now;

            foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
            {
                foreach (var packetAttribute in type.GetCustomAttributes<PacketAttribute>())
                {
                    var packetInfo = new PacketInfo()
                    {
                        Name         = packetAttribute.Name,
                        Direction    = packetAttribute.Direction,
                        SessionType  = packetAttribute.SessionType,
                        AuthRequired = packetAttribute.AuthRequired,
                        Type         = type
                    };

                    if (packetAttribute.HasDirection(PacketDirection.ClientToServer))
                        if (!clientToServerPackets.ContainsKey(packetAttribute.Name))
                            clientToServerPackets[packetAttribute.Name] = packetInfo;

                    if (packetAttribute.HasDirection(PacketDirection.ServerToClient))
                        if (!serverToClientPackets.ContainsKey(type))
                            serverToClientPackets[type] = packetInfo;

                    packetCount++;
                }
            }

            LogManager.Write("Packet Manager", "Initialised {0} packet(s) in {1} milliseconds(s).", packetCount, (DateTime.Now - startTime).Milliseconds);
        }
コード例 #59
0
ファイル: ClientManager.cs プロジェクト: Jaex/Chat
 public void SendMessage(string message, string toUser, Color color)
 {
     if (!string.IsNullOrEmpty(message))
     {
         PacketInfo packetInfo = new PacketInfo("Message");
         MessageInfo messageInfo = new MessageInfo(message);
         if (!string.IsNullOrEmpty(toUser)) messageInfo.ToUser = new UserInfo(toUser);
         messageInfo.TextColor = color;
         packetInfo.Data = messageInfo;
         client.SendPacket(packetInfo);
     }
 }
コード例 #60
0
ファイル: ServerManager.cs プロジェクト: Jaex/Chat
 public void KickClient(Client client, string reason = "")
 {
     PacketInfo packetInfo = new PacketInfo("Kick");
     if (!string.IsNullOrEmpty(reason)) packetInfo.AddParameter("Reason", reason);
     client.SendPacket(packetInfo);
     client.Disconnect();
 }