コード例 #1
0
 private int PackSort(PacketWrapper x, PacketWrapper y)
 {
     if (x.tcpPacket.SequenceNumber > y.tcpPacket.SequenceNumber)
     {
         return(1);
     }
     else
     {
         return(-1);
     }
 }
コード例 #2
0
    public byte[] SerializePacket <T>(NetworkPacket <T> networkPacket, uint senderID = 0, uint objectID = 0,
                                      ReliablePacketHeader reliablePacketHeader      = null)
    {
        byte[] data = null;

        PacketWrapper packetWrapper = new PacketWrapper();
        MemoryStream  memoryStream  = new MemoryStream();
        PacketHeader  packetHeader  = new PacketHeader();

        packetHeader.ProtocolID      = ProtocolID;
        packetHeader.PacketTypeIndex = networkPacket.PacketTypeIndex;

        packetHeader.Serialize(memoryStream);

        if ((PacketType)networkPacket.PacketTypeIndex == PacketType.User)
        {
            UserNetworkPacket <T> userNetworkPacket = networkPacket as UserNetworkPacket <T>;
            UserPacketHeader      userPacketHeader  = new UserPacketHeader();

            userPacketHeader.UserPacketTypeIndex = userNetworkPacket.UserPacketTypeIndex;
            userPacketHeader.SenderID            = senderID;
            userPacketHeader.ObjectID            = objectID;
            userPacketHeader.Reliable            = (reliablePacketHeader != null);

            userPacketHeader.Serialize(memoryStream);

            if (reliablePacketHeader != null)
            {
                reliablePacketHeader.Serialize(memoryStream);
            }
        }

        networkPacket.Serialize(memoryStream);
        memoryStream.Close();

        data = memoryStream.ToArray();

        packetWrapper.Crc        = crcCalculator.ComputeCrc32(data);
        packetWrapper.PacketData = data;

        memoryStream = new MemoryStream();

        packetWrapper.Serialize(memoryStream);
        memoryStream.Close();

        data = memoryStream.ToArray();

        return(data);
    }
コード例 #3
0
        private void BackgroundThreadFunc()
        {
            while (!_backgroundThreadStop)
            {
                bool shouldSleep = true;
                lock (QueueLock)
                {
                    if (_packetQueue.Count != 0)
                    {
                        shouldSleep = false;
                    }
                }

                if (shouldSleep)
                {
                    System.Threading.Thread.Sleep(250);
                }
                else
                {
                    List <RawCapture> ourQueue;
                    lock (QueueLock)
                    {
                        ourQueue     = _packetQueue;
                        _packetQueue = new List <RawCapture>();
                    }
                    foreach (var packet in ourQueue)
                    {
                        // Здесь мы можем обрабатывать пакеты свободно, не занимая перехватываемое устройство
                        var packetWrapper = new PacketWrapper(_packetCount, packet);
                        packetStrings.Enqueue(packetWrapper);
                        _packetCount++;
                    }

                    _view.BeginInvoke(bs, packetStrings);
                    if (statisticsUiNeedsUpdate)
                    {
                        UpdateCaptureStatistics();
                        statisticsUiNeedsUpdate = false;
                    }
                }
            }
        }
コード例 #4
0
    bool DeserializePacket(byte[] data, out MemoryStream memoryStream, out PacketHeader packetHeader,
                           ref UserPacketHeader userPacketHeader, ref ReliablePacketHeader reliablePacketHeader)
    {
        bool isFaultless;

        PacketWrapper packetWrapper = new PacketWrapper();

        memoryStream = new MemoryStream(data);
        packetHeader = new PacketHeader();

        packetWrapper.Deserialize(memoryStream);

        memoryStream.Close();

        isFaultless = crcCalculator.PerformCrcCheck(packetWrapper.PacketData, packetWrapper.Crc);

        if (isFaultless)
        {
            memoryStream = new MemoryStream(packetWrapper.PacketData);

            packetHeader.Deserialize(memoryStream);

            if ((PacketType)packetHeader.PacketTypeIndex == PacketType.User)
            {
                userPacketHeader = new UserPacketHeader();
                userPacketHeader.Deserialize(memoryStream);

                if (userPacketHeader.Reliable)
                {
                    reliablePacketHeader = new ReliablePacketHeader();
                    reliablePacketHeader.Deserialize(memoryStream);
                }
            }
        }

        return(isFaultless);
    }
コード例 #5
0
ファイル: CaptureForm.cs プロジェクト: tooktech/sharppcap
        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of
        /// work done while the queue is locked.
        ///
        /// The background thread can then process queue that it saved without holding
        /// the queue lock.
        /// </summary>
        private void BackgroundThread()
        {
            while (!BackgroundThreadStop)
            {
                bool shouldSleep = true;

                lock (QueueLock)
                {
                    if (PacketQueue.Count != 0)
                    {
                        shouldSleep = false;
                    }
                }

                if (shouldSleep)
                {
                    System.Threading.Thread.Sleep(250);
                }
                else // should process the queue
                {
                    List <RawCapture> ourQueue;
                    lock (QueueLock)
                    {
                        // swap queues, giving the capture callback a new one
                        ourQueue    = PacketQueue;
                        PacketQueue = new List <RawCapture>();
                    }

                    Console.WriteLine("BackgroundThread: ourQueue.Count is {0}", ourQueue.Count);

                    foreach (var packet in ourQueue)
                    {
                        // Here is where we can process our packets freely without
                        // holding off packet capture.
                        //
                        // NOTE: If the incoming packet rate is greater than
                        //       the packet processing rate these queues will grow
                        //       to enormous sizes. Packets should be dropped in these
                        //       cases

                        var packetWrapper = new PacketWrapper(packetCount, packet);
                        this.BeginInvoke(new MethodInvoker(delegate
                        {
                            packetStrings.Enqueue(packetWrapper);
                        }
                                                           ));

                        packetCount++;

                        var time = packet.Timeval.Date;
                        var len  = packet.Data.Length;
                        Console.WriteLine("BackgroundThread: {0}:{1}:{2},{3} Len={4}",
                                          time.Hour, time.Minute, time.Second, time.Millisecond, len);
                    }

                    this.BeginInvoke(new MethodInvoker(delegate
                    {
                        bs.DataSource = packetStrings.Reverse();
                    }
                                                       ));

                    if (statisticsUiNeedsUpdate)
                    {
                        UpdateCaptureStatistics();
                        statisticsUiNeedsUpdate = false;
                    }
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of
        /// work done while the queue is locked.
        ///
        /// The background thread can then process queue that it saved without holding
        /// the queue lock.
        /// </summary>
        private void BackgroundThread()
        {
            while (!BackgroundThreadStop)
            {
                bool shouldSleep = true;

                lock (QueueLock)
                {
                    if (PacketQueue.Count != 0)
                    {
                        shouldSleep = false;
                    }
                }

                if (shouldSleep)
                {
                    System.Threading.Thread.Sleep(250);
                }
                else // should process the queue
                {
                    List <RawCapture> ourQueue;

                    lock (QueueLock)
                    {
                        // swap queues, giving the capture callback a new one
                        ourQueue    = PacketQueue;
                        PacketQueue = new List <RawCapture>();
                    }

                    ProcessQueueTick?.Invoke(this, new L2RProcessQueueTickEventArgs(ourQueue.Count));

                    foreach (RawCapture packet in ourQueue)
                    {
                        // Here is where we can process our packets freely without
                        // holding off packet capture.
                        //
                        // NOTE: If the incoming packet rate is greater than
                        //       the packet processing rate these queues will grow
                        //       to enormous sizes. Packets should be dropped in these
                        //       cases

                        try
                        {
                            PacketWrapper packetWrapper = new PacketWrapper(packetCount, packet);

                            Packet parsepacket = Packet.ParsePacket(packet.LinkLayerType, packet.Data);

                            TcpPacket tcpPacket = (TcpPacket)parsepacket.Extract(typeof(TcpPacket));
                            if (tcpPacket != null)
                            {
                                byte[] packetData = tcpPacket.PayloadData;

                                if (packetData != null)
                                {
                                    ProcessPackets(packetData);
                                }

                                packetCount++;
                            }

                            if (statisticsUiNeedsUpdate)
                            {
                                UpdateCaptureStatistics();
                                statisticsUiNeedsUpdate = false;
                            }
                        }
                        catch (Exception ex)
                        {
                            PacketError?.Invoke(this, new L2RPacketErrorEventArgs(ex, packet));
                            throw;
                        }
                    }
                }
            }
        }
コード例 #7
0
ファイル: CaptureForm.cs プロジェクト: pingfu/SharpPcap
        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of
        /// work done while the queue is locked.
        ///
        /// The background thread can then process queue that it saved without holding
        /// the queue lock.
        /// </summary>
        private void BackgroundThread()
        {
            while (!BackgroundThreadStop)
            {
                bool shouldSleep = true;

                lock (QueueLock)
                {
                    if (PacketQueue.Count != 0)
                    {
                        shouldSleep = false;
                    }
                }

                if (shouldSleep)
                {
                    System.Threading.Thread.Sleep(250);
                }
                else // should process the queue
                {
                    List<RawCapture> ourQueue;
                    lock (QueueLock)
                    {
                        // swap queues, giving the capture callback a new one
                        ourQueue = PacketQueue;
                        PacketQueue = new List<RawCapture>();
                    }

                    Console.WriteLine("BackgroundThread: ourQueue.Count is {0}", ourQueue.Count);

                    foreach (var packet in ourQueue)
                    {
                        // Here is where we can process our packets freely without
                        // holding off packet capture.
                        //
                        // NOTE: If the incoming packet rate is greater than
                        //       the packet processing rate these queues will grow
                        //       to enormous sizes. Packets should be dropped in these
                        //       cases

                        var packetWrapper = new PacketWrapper(packetCount, packet);
                        this.BeginInvoke(new MethodInvoker(delegate
                        {
                            packetStrings.Enqueue(packetWrapper);
                        }
                        ));

                        packetCount++;

                        var time = packet.Timeval.Date;
                        var len = packet.Data.Length;
                        Console.WriteLine("BackgroundThread: {0}:{1}:{2},{3} Len={4}",
                            time.Hour, time.Minute, time.Second, time.Millisecond, len);
                    }

                    this.BeginInvoke(new MethodInvoker(delegate
                    {
                        bs.DataSource = packetStrings.Reverse();
                    }
                    ));

                    if (statisticsUiNeedsUpdate)
                    {
                        UpdateCaptureStatistics();
                        statisticsUiNeedsUpdate = false;
                    }
                }
            }
        }
コード例 #8
0
            public PacketWrapper(PacketWrapper envelope)
            {
                if (envelope == null)
                    return;

                _isPseudoPacket		= envelope._isPseudoPacket;
                _packetNumber		= envelope._packetNumber;
                _timestamp			= envelope._timestamp;
                _elapsedMs			= envelope._elapsedMs;
                _readerIndex		= envelope._readerIndex;
                _readerName			= envelope._readerName;
                _packetType			= envelope._packetType;
                _packet				= envelope._packet;
                _rawPacket			= (byte[])(envelope._rawPacket == null ? null : envelope._rawPacket.Clone());
                _requestNumber		= envelope._requestNumber;
            }
コード例 #9
0
        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of
        /// work done while the queue is locked.
        ///
        /// The background thread can then process queue that it saved without holding
        /// the queue lock.
        /// </summary>
        private void BackgroundThread()
        {
            while (!BackgroundThreadStop)
            {
                bool shouldSleep = true;

                lock (QueueLock)
                {
                    if (PacketQueue.Count != 0)
                    {
                        shouldSleep = false;
                    }
                }

                if (shouldSleep)
                {
                    System.Threading.Thread.Sleep(250);
                }
                else // should process the queue
                {
                    List <CaptureEventArgs> ourQueue;
                    lock (QueueLock)
                    {
                        // swap queues, giving the capture callback a new one
                        ourQueue    = PacketQueue;
                        PacketQueue = new List <CaptureEventArgs>();
                    }

                    Console.WriteLine("BackgroundThread: ourQueue.Count is {0}", ourQueue.Count);

                    foreach (var packetQueue in ourQueue)
                    {
                        // Here is where we can process our packets freely without
                        // holding off packet capture.
                        //
                        // NOTE: If the incoming packet rate is greater than
                        //       the packet processing rate these queues will grow
                        //       to enormous sizes. Packets should be dropped in these
                        //       cases

                        var packet    = PacketDotNet.Packet.ParsePacket(packetQueue.Packet.LinkLayerType, packetQueue.Packet.Data);
                        var tcpPacket = packet.Extract <PacketDotNet.TcpPacket>();

                        if (tcpPacket != null)
                        {
                            var ipPacket = (PacketDotNet.IPPacket)tcpPacket.ParentPacket;
                            System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                            System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
                            int    srcPort             = tcpPacket.SourcePort;
                            int    dstPort             = tcpPacket.DestinationPort;
                            byte[] payload             = tcpPacket.PayloadData;
                            int    packetLength        = tcpPacket.PayloadData.Length;
                            uint   sequenceNumber      = tcpPacket.SequenceNumber;


                            if (textBoxCaptureServerIpAddress.Text == srcIp.ToString() && textBoxCaptureServerPortNumber.Text.ToString() == srcPort.ToString())
                            {
                                var packetWrapper = new PacketWrapper(packetCount, packetQueue.Packet, srcIp, dstIp, srcPort, dstPort, payload, packetLength, sequenceNumber);
                                this.BeginInvoke(new MethodInvoker(delegate
                                {
                                    packetStrings.Enqueue(packetWrapper);
                                }
                                                                   ));

                                packetCount++;

                                var time = packetQueue.Packet.Timeval.Date;
                                var len  = packetQueue.Packet.Data.Length;
                                Console.WriteLine("BackgroundThread: {0}:{1}:{2},{3} Len={4}",
                                                  time.Hour, time.Minute, time.Second, time.Millisecond, len);
                            }
                        }
                    }

                    this.BeginInvoke(new MethodInvoker(delegate
                    {
                        bs.DataSource = packetStrings.Reverse();
                    }
                                                       ));

                    if (statisticsUiNeedsUpdate)
                    {
                        UpdateCaptureStatistics();
                        statisticsUiNeedsUpdate = false;
                    }
                }
            }
        }
コード例 #10
0
ファイル: CaptureForm.cs プロジェクト: Vex788/TrafficAnalyzer
        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of
        /// work done while the queue is locked.
        ///
        /// The background thread can then process queue that it saved without holding
        /// the queue lock.
        /// </summary>
        private void BackgroundThread()
        {
            try
            {
                while (!BackgroundThreadStop)
                {
                    bool shouldSleep = true;

                    lock (QueueLock)
                    {
                        if (PacketQueue.Count != 0)
                        {
                            shouldSleep = false;
                        }
                    }

                    if (shouldSleep)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    else // should process the queue
                    {
                        List <RawCapture> ourQueue;
                        lock (QueueLock)
                        {
                            // swap queues, giving the capture callback a new one
                            ourQueue    = PacketQueue;
                            PacketQueue = new List <RawCapture>();
                        }

                        logWriting(string.Format("BackgroundThread: ourQueue.Count is {0}", ourQueue.Count));

                        try
                        {
                            foreach (var packet in ourQueue)
                            {
                                // Here is where we can process our packets freely without
                                // holding off packet capture.
                                //
                                // NOTE: If the incoming packet rate is greater than
                                //       the packet processing rate these queues will grow
                                //       to enormous sizes. Packets should be dropped in these
                                //       cases
                                var packetWrapper = new PacketWrapper(packetCount, packet);
                                var pack          = Packet.ParsePacket(packetWrapper.p.LinkLayerType, packetWrapper.p.Data);
                                var eth           = (PacketDotNet.EthernetPacket)pack.Extract(typeof(PacketDotNet.EthernetPacket));
                                if (eth != null)
                                {
                                    packetWrapper.Type = eth.Type;
                                }

                                var ip = (PacketDotNet.IPPacket)pack.Extract(typeof(PacketDotNet.IPPacket));
                                if (ip != null)
                                {
                                    packetWrapper.SourceIP      = ip.SourceAddress;
                                    packetWrapper.DestinationIP = ip.DestinationAddress;
                                }
                                // filter
                                this.BeginInvoke(new MethodInvoker(delegate
                                {
                                    try
                                    {
                                        if (Filter.OutThis(textBoxFilterSourceIP,
                                                           textBoxFilterDestinationIP,
                                                           textBoxFilterType,
                                                           packetWrapper,
                                                           packetStrings))
                                        {
                                            packetStrings.Enqueue(packetWrapper);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        // ignore null
                                    }
                                }));

                                packetCount++;

                                var time = packet.Timeval.Date;
                                var len  = packet.Data.Length;
                                logWriting(string.Format("BackgroundThread: {0}:{1}:{2},{3} Len={4}",
                                                         time.Hour, time.Minute, time.Second, time.Millisecond, len));
                            }
                        }
                        catch (Exception ex)
                        {
                            logWriting(string.Format("{0}:\n{1}", "Error BackgroundThread", ex.ToString()));
                        }

                        this.BeginInvoke(new MethodInvoker(delegate
                        {
                            bs.DataSource = packetStrings.Reverse();
                        }));

                        if (statisticsUiNeedsUpdate)
                        {
                            UpdateCaptureStatistics();
                            statisticsUiNeedsUpdate = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logWriting(string.Format("{0}:\n{1}", "Error BackgroundThread", ex.ToString()));
            }
        }
コード例 #11
0
    private void OnPacketArrival(object sender, CaptureEventArgs e)
    {
        PacketWrapper packetWrapper = new PacketWrapper(packetId++, e.Packet);

        uint ackn = packetWrapper.tcpPacket.AcknowledgmentNumber;

        if (!packDic.ContainsKey(ackn))
        {
            packDic.Add(ackn, new List <PacketWrapper>());
            packTimeRest.Add(ackn, new int[] { packTimeMax });
        }
        packDic[ackn].Add(packetWrapper);

        List <uint> nd = new List <uint>();

        foreach (var p in packTimeRest)
        {
            packTimeRest[p.Key][0]--;
            if (packTimeRest[p.Key][0] <= 0)
            {
                nd.Add(p.Key);
            }
        }

        foreach (var p in nd)
        {
            packTimeRest.Remove(p);
            packDic.Remove(p);
        }

        if (!packetWrapper.tcpPacket.Psh)
        {
            return;
        }

        byte[] data = CombinePacket(ackn);

        if (data == null)
        {
            return;
        }

        string s = Encoding.UTF8.GetString(data);

        int index = s.IndexOf("\r\n\r\n");

        if (index < 0)
        {
            return;
        }
        index += 4;

        string header = s.Substring(0, index);

        if (!HttpCheck(header))
        {
            return;
        }

        onNewHttpAdd?.Invoke(s);

        if (!LLHttpCheck(header))
        {
            return;
        }

        Console.WriteLine("datalen" + data.Length);

        string body = s.Substring(index);

        if (body.Length < 10)
        {
            return;
        }

        if (header.IndexOf("POST") == 0)
        {
            int lk = body.IndexOf("{");
            int rk = body.LastIndexOf("}");
            body = body.Substring(lk, rk - lk + 1);

            string sj = Utils.FormatJsonString(body);
            onNewHttpLLAdd?.Invoke(header + "\r\n\r\n\r\n" + sj);
            onNewJsonAdd?.Invoke(sj);
            return;
        }

        byte[] bodyBytes = null;

        for (int i = 0; i < data.Length - 1; i++)
        {
            if (data[i] == 13 && data[i + 2] == 13 && data[i + 1] == 10 && data[i + 3] == 10)
            {
                i        += 4;
                bodyBytes = new byte[data.Length - i];
                for (int t = 0; t < bodyBytes.Length; t++, i++)
                {
                    bodyBytes[t] = data[i];
                }
                break;
            }
        }

        if (bodyBytes == null)
        {
            return;
        }

        byte[] bodyUncompressedBytes = Utils.Decompress(bodyBytes);

        if (bodyUncompressedBytes == null)
        {
            return;
        }
        string json = Encoding.UTF8.GetString(bodyUncompressedBytes);

        if (!json.Contains("{"))
        {
            return;
        }

        json = Utils.Unicode2String(json);
        json = Utils.FormatJsonString(json);


        onNewHttpLLAdd?.Invoke(header + "\r\n\r\n\r\n" + json);
        onNewJsonAdd?.Invoke(json);
    }
コード例 #12
0
        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of
        /// work done while the queue is locked.
        ///
        /// The background thread can then process queue that it saved without holding
        /// the queue lock.
        /// </summary>
        private void BackgroundThread()
        {
            while (!BackgroundThreadStop)
            {
                bool shouldSleep = true;

                lock (QueueLock)
                {
                    if (PacketQueue.Count != 0)
                    {
                        shouldSleep = false;
                    }
                }

                if (shouldSleep)
                {
                    System.Threading.Thread.Sleep(250);
                }
                else // should process the queue
                {
                    List <RawCapture> ourQueue;
                    lock (QueueLock)
                    {
                        // swap queues, giving the capture callback a new one
                        ourQueue    = PacketQueue;
                        PacketQueue = new List <RawCapture>();
                    }

                    Console.WriteLine("BackgroundThread: ourQueue.Count is {0}", ourQueue.Count);

                    foreach (RawCapture packet in ourQueue)
                    {
                        // Here is where we can process our packets freely without
                        // holding off packet capture.
                        //
                        // NOTE: If the incoming packet rate is greater than
                        //       the packet processing rate these queues will grow
                        //       to enormous sizes. Packets should be dropped in these
                        //       cases

                        try
                        {
                            PacketWrapper packetWrapper = new PacketWrapper(packetCount, packet);

                            Packet parsepacket = PacketDotNet.Packet.ParsePacket(packet.LinkLayerType, packet.Data);

                            TcpPacket tcpPacket = (PacketDotNet.TcpPacket)parsepacket.Extract(typeof(PacketDotNet.TcpPacket));
                            if (tcpPacket != null)
                            {
                                byte[] packetData = tcpPacket.PayloadData;

                                if (packetData != null)
                                {
                                    ProcessPackets(packetData);
                                }

                                packetCount++;

                                DateTime time = packet.Timeval.Date;
                                int      len  = packet.Data.Length;
                                //Console.WriteLine("BackgroundThread: {0}:{1}:{2},{3} Len={4}",
                                //    time.Hour, time.Minute, time.Second, time.Millisecond, len);
                            }

                            if (statisticsUiNeedsUpdate)
                            {
                                UpdateCaptureStatistics();
                                statisticsUiNeedsUpdate = false;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            throw;
                        }
                    }

                    //this.BeginInvoke(new MethodInvoker(delegate
                    //{
                    //    //bs.DataSource = packetQue.Reverse();
                    //}
                    //));
                }
            }
        }
コード例 #13
0
        internal void HandleSecMsg(MIMCUser user, V6Packet feV6Packet)
        {
            if (feV6Packet == null || feV6Packet.Body.Payload == null || feV6Packet.Body.Payload.Length == 0)
            {
                logger.WarnFormat("HandleSecMsg fail, invalid packet");
                return;
            }
            MIMCPacket packet = null;

            using (MemoryStream ms = new MemoryStream(feV6Packet.Body.Payload))
            {
                packet = Serializer.Deserialize <MIMCPacket>(ms);
            }
            if (packet == null)
            {
                logger.WarnFormat("{0} HandleSecMsg fail, parse MIMCPacket fail", user.AppAccount);
                return;
            }
            logger.InfoFormat("HandleSecMsg, type:{0} , uuid:{1}, packetId:{2}, chid:{3}",
                              packet.type, user.Uuid, packet.packetId, user.Chid);


            if (packet.type == MIMC_MSG_TYPE.PACKET_ACK)
            {
                logger.DebugFormat("{0} <--- receive PACKET_ACK :{1}", user.AppAccount, packet.packetId);

                MIMCPacketAck packetAck = null;
                using (MemoryStream ackStream = new MemoryStream(packet.payload))
                {
                    packetAck = Serializer.Deserialize <MIMCPacketAck>(ackStream);
                }
                if (packetAck == null)
                {
                    logger.WarnFormat("{0} HandleSecMsg parse MIMCPacketAck fail", user.AppAccount);
                    return;
                }
                user.HandleServerACK(new ServerAck(packetAck.packetId, packetAck.sequence, packetAck.timestamp, packetAck.code, packetAck.errorMsg));
                logger.DebugFormat("{0} HandleSecMsg MIMCPacketAck packetId:{1}, msg:{2}", user.AppAccount, packetAck.packetId, packetAck.errorMsg);
                logger.DebugFormat("{0} HandleSecMsg timeoutPackets TimeoutPackets before size :{1}", user.AppAccount, user.TimeoutPackets.Count);

                TimeoutPacket timeoutPacket = new TimeoutPacket(packet, MIMCUtil.CurrentTimeMillis());
                if (user.TimeoutPackets.TryRemove(packetAck.packetId, out timeoutPacket))
                {
                    logger.DebugFormat("{0} HandleSecMsg timeoutPackets TryRemove sucess,packetId:{1}", user.AppAccount, packetAck.packetId);
                }
                else
                {
                    logger.WarnFormat("{0} HandleSecMsg timeoutPackets TryRemove fail,packetId:{1}", user.AppAccount, packetAck.packetId);
                }
                logger.DebugFormat("{0} HandleSecMsg timeoutPackets TimeoutPackets after size :{1}", user.AppAccount, user.TimeoutPackets.Count);

                return;
            }

            if (packet.type == MIMC_MSG_TYPE.UC_PACKET)
            {
                logger.DebugFormat(" UC_PACKET packetId:{0}", packet.packetId);
                UCPacket ucPacket = null;
                using (MemoryStream ucStream = new MemoryStream(packet.payload))
                {
                    ucPacket = Serializer.Deserialize <UCPacket>(ucStream);
                }
                if (ucPacket == null)
                {
                    logger.WarnFormat("HandleSecMsg p2tMessage is null");
                }
                logger.DebugFormat("UC_PACKET UC_MSG_TYPE:{0}", ucPacket.type);


                if (ucPacket.type == UC_MSG_TYPE.MESSAGE_LIST)
                {
                    UCMessageList messageList = null;
                    using (MemoryStream stream = new MemoryStream(ucPacket.payload))
                    {
                        messageList = Serializer.Deserialize <UCMessageList>(stream);
                    }
                    if (messageList == null || messageList.message.Count == 0 || messageList.message == null)
                    {
                        logger.WarnFormat("HandleUnlimitedGroupMessage messageList is null");
                        return;
                    }

                    List <P2UMessage> p2uMessagesList = new List <P2UMessage>();
                    foreach (UCMessage ucMessage in messageList.message)
                    {
                        logger.DebugFormat("HandleSecMsg UC_MSG_TYPE.MESSAGE_LIST:{0},size:{1}", ucPacket.type, messageList.message.Count);
                        p2uMessagesList.Add(new P2UMessage(ucMessage.packetId, ucMessage.sequence,
                                                           ucMessage.user.appAccount, ucMessage.user.resource,
                                                           (long)ucMessage.group.topicId, ucMessage.payload, ucMessage.bizType, ucMessage.timestamp));
                        continue;
                    }
                    if (p2uMessagesList.Count > 0)
                    {
                        user.HandleUnlimitedGroupMessage(p2uMessagesList, messageList.group, messageList.maxSequence);
                    }
                }
                if (ucPacket.type == UC_MSG_TYPE.JOIN_RESP)
                {
                    logger.DebugFormat("HandleJoinUnlimitedGroup UC_MSG_TYPE.JOIN_RESP:{0}", ucPacket.type);
                    user.HandleJoinUnlimitedGroup(ucPacket);
                }

                if (ucPacket.type == UC_MSG_TYPE.QUIT_RESP)
                {
                    logger.DebugFormat("HandleQuitUnlimitedGroup UC_MSG_TYPE.QUIT_RESP:{0}", ucPacket.type);
                    user.HandleQuitUnlimitedGroup(ucPacket);
                }
                if (ucPacket.type == UC_MSG_TYPE.DISMISS)
                {
                    UCDismiss ucDismiss = null;
                    using (MemoryStream ucStream = new MemoryStream(ucPacket.payload))
                    {
                        ucDismiss = Serializer.Deserialize <UCDismiss>(ucStream);
                    }
                    logger.DebugFormat("HandleDismissUnlimitedGroup UC_MSG_TYPE.DISMISS:{0}", ucPacket.type);
                    user.HandleDismissUnlimitedGroup(new DismissUnlimitedGroupEventArgs(ucDismiss.group.topicId));
                }

                else if (ucPacket.type == UC_MSG_TYPE.PONG)
                {
                    logger.DebugFormat("HandleSecMsg UC_MSG_TYPE.PONG:{0}", ucPacket.type);
                }
            }
            if (packet.type == MIMC_MSG_TYPE.COMPOUND)
            {
                MIMCPacketList packetList = null;
                using (MemoryStream comStream = new MemoryStream(packet.payload))
                {
                    packetList = Serializer.Deserialize <MIMCPacketList>(comStream);
                }
                if (packetList == null || packetList.packets.ToArray().Length == 0)
                {
                    logger.WarnFormat("HandleSecMsg parse MIMCPacketList fail ,packetList:{0}, packetList.packets.ToArray().Length:{1}", packetList, packetList.packets.ToArray().Length);
                    return;
                }
                logger.DebugFormat("HandleSecMsg MIMCPacketList resource:{0}", user.Resource);

                if (user.Resource != packetList.resource)
                {
                    logger.WarnFormat("HandleSecMsg MIMCPacketList parse fail,resource not match,{0}!={1}", user.Resource, packetList.resource);
                    return;
                }

                V6Packet      mimcSequenceAckPacket = MIMCUtil.BuildSequenceAckPacket(user, packetList);
                PacketWrapper packetWrapper         = new PacketWrapper(Constant.MIMC_C2S_SINGLE_DIRECTION, mimcSequenceAckPacket);
                user.Connection.PacketWaitToSend.Enqueue(packetWrapper);

                int packetListNum = packetList.packets.Count;
                List <P2PMessage> p2pMessagesList = new List <P2PMessage>();
                List <P2TMessage> p2tMessagesList = new List <P2TMessage>();

                logger.DebugFormat("{0} HandleSecMsg MIMCPacketList packetListNum:{1}", user.AppAccount, packetListNum);

                foreach (MIMCPacket p in packetList.packets)
                {
                    if (p == null)
                    {
                        logger.WarnFormat("{0} HandleSecMsg packet is null", user.AppAccount);
                        continue;
                    }
                    logger.DebugFormat("HandleSecMsg MIMC_MSG_TYPE:{0}", p.type);

                    if (p.type == MIMC_MSG_TYPE.P2P_MESSAGE)
                    {
                        logger.DebugFormat("HandleSecMsg P2P_MESSAGE packetId:{0}", p.packetId);
                        MIMCP2PMessage p2pMessage = null;
                        using (MemoryStream p2pStream = new MemoryStream(p.payload))
                        {
                            p2pMessage = Serializer.Deserialize <MIMCP2PMessage>(p2pStream);
                        }
                        if (p2pMessage == null)
                        {
                            logger.WarnFormat("HandleSecMsg p2pMessage is null");
                            continue;
                        }

                        p2pMessagesList.Add(new P2PMessage(p.packetId, p.sequence,
                                                           p2pMessage.from.appAccount, p2pMessage.from.resource,
                                                           p2pMessage.to.appAccount, p2pMessage.to.resource, p2pMessage.payload, p2pMessage.bizType, p.timestamp));
                        logger.DebugFormat("HandleSecMsg P2P_MESSAGE packetId:{0}", p2pMessagesList[0]);

                        continue;
                    }
                    if (p.type == MIMC_MSG_TYPE.P2T_MESSAGE)
                    {
                        logger.DebugFormat("HandleSecMsg P2T_MESSAGE packetId:{0}", p.packetId);
                        MIMCP2TMessage p2tMessage = null;
                        using (MemoryStream p2tStream = new MemoryStream(p.payload))
                        {
                            p2tMessage = Serializer.Deserialize <MIMCP2TMessage>(p2tStream);
                        }
                        if (p2tMessage == null)
                        {
                            logger.WarnFormat("HandleSecMsg p2tMessage is null");
                            continue;
                        }

                        p2tMessagesList.Add(new P2TMessage(p.packetId, p.sequence,
                                                           p2tMessage.from.appAccount, p2tMessage.from.resource,
                                                           (long)p2tMessage.to.topicId, p2tMessage.payload, p2tMessage.bizType, p.timestamp));
                        continue;
                    }

                    logger.WarnFormat("HandleSecMsg RECV_MIMC_PACKET ,invalid type, Type:{0}", p.type);
                }

                if (p2pMessagesList.Count > 0)
                {
                    user.HandleMessage(p2pMessagesList);
                }
                if (p2tMessagesList.Count > 0)
                {
                    user.HandleGroupMessage(p2tMessagesList);
                }
            }
        }