public void TestRemoveItselfWriteBuffer()
        {
            IByteBuffer     buf     = Unpooled.Buffer().WriteBytes(new byte[] { (byte)'a', (byte)'b', (byte)'c' });
            EmbeddedChannel channel = new EmbeddedChannel(new RemoveItselfWriteBufferDecoder(buf));

            channel.WriteInbound(buf.Copy());
            IByteBuffer b = channel.ReadInbound <IByteBuffer>();

            Assert.Equal(b, Unpooled.WrappedBuffer(new byte[] { (byte)'b', (byte)'c' }));
            b.Release();
            buf.Release();
        }
        public void TestRemoveItselfWithReplayError()
        {
            EmbeddedChannel channel = new EmbeddedChannel(new RemoveItselfWithReplayErrorDecoder());

            IByteBuffer buf = Unpooled.WrappedBuffer(new byte[] { (byte)'a', (byte)'b', (byte)'c' });

            channel.WriteInbound(buf.Copy());
            IByteBuffer b = channel.ReadInbound <IByteBuffer>();

            Assert.Equal(b, buf); // "Expect to have still all bytes in the buffer"
            b.Release();
            buf.Release();
        }
        public void ShouldWrapInSequence()
        {
            IByteBuffer currentBuffer = WrappedBuffer(WrappedBuffer(Encoding.ASCII.GetBytes("a")),
                                                      WrappedBuffer(Encoding.ASCII.GetBytes("=")));

            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("1")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("&")));

            IByteBuffer copy = currentBuffer.Copy();
            string      s    = copy.ToString(Encoding.ASCII);

            Assert.Equal("a=1&", s);

            currentBuffer.Release();
            copy.Release();
        }
Beispiel #4
0
        static void WriteFrameMessage(IByteBufferAllocator allocator, FrameThriftMessage msg, List <object> output)
        {
            IByteBuffer buf = null;

            try
            {
                var len = 4 + msg.Content.ReadableBytes;
                buf = allocator.Buffer(len);
                buf.WriteInt(msg.Content.ReadableBytes);
                buf.WriteBytes(msg.Content);
                output.Add(buf.Copy(0, len));
            }
            finally
            {
                buf?.Release();
            }
        }
        public void ShouldConsolidationInSequence()
        {
            IByteBuffer currentBuffer = WrappedBuffer(WrappedBuffer(Encoding.ASCII.GetBytes("a")),
                                                      WrappedBuffer(Encoding.ASCII.GetBytes("=")));

            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("1")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("&")));

            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("b")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("=")));
            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("2")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("&")));

            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("c")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("=")));
            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("3")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("&")));

            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("d")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("=")));
            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("4")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("&")));

            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("e")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("=")));
            currentBuffer = WrappedBuffer(currentBuffer, WrappedBuffer(Encoding.ASCII.GetBytes("5")),
                                          WrappedBuffer(Encoding.ASCII.GetBytes("&")));

            IByteBuffer copy = currentBuffer.Copy();
            string      s    = copy.ToString(Encoding.ASCII);

            Assert.Equal("a=1&b=2&c=3&d=4&e=5&", s);

            currentBuffer.Release();
            copy.Release();
        }
Beispiel #6
0
        public void TestNioBuffersExpand()
        {
            TestChannel channel = new TestChannel();

            ChannelOutboundBuffer buffer = new ChannelOutboundBuffer(channel);

            IByteBuffer buf = Unpooled.DirectBuffer().WriteBytes(Encoding.ASCII.GetBytes("buf1"));

            for (int i = 0; i < 64; i++)
            {
                buffer.AddMessage(buf.Copy(), buf.ReadableBytes, channel.VoidPromise());
            }
            Assert.Equal(0, buffer.NioBufferCount); // Should still be 0 as not flushed yet
            buffer.AddFlush();
            var buffers = buffer.GetSharedBufferList();

            Assert.Equal(64, buffer.NioBufferCount);
            for (int i = 0; i < buffer.NioBufferCount; i++)
            {
                Assert.Equal(buffers[i], buf.GetIoBuffer(buf.ReaderIndex, buf.ReadableBytes));
            }
            Release(buffer);
            buf.Release();
        }
Beispiel #7
0
 public virtual IByteBuffer Copy(int index, int length) => Buf.Copy(index, length);
Beispiel #8
0
 public IByteBuffer Copy(int index, int length)
 {
     CheckIndex(index, length);
     return(_buffer.Copy(index, length));
 }
Beispiel #9
0
 protected override IByteBuffer ExtractFrame(IChannelHandlerContext ctx, IByteBuffer buffer, int index, int length)
 {
     return(buffer.Copy(index, length));
 }
        public void LookUp(IByteBuffer buffer, GameClient client)
        {
            try
            {
                var parser = new ByteParser(buffer.Copy());

                if (parser.CMD_ID == commands.old_client.requests.VersionRequest.ID)
                {
                    var cmd = new commands.old_client.requests.VersionRequest();
                    cmd.readCommand(buffer);
                    new ShipInitalizationHandler(client, cmd.playerId, cmd.sessionId);
                    return;
                }

                if (parser.CMD_ID == commands.new_client.requests.LoginRequest.ID)
                {
                    var cmd = new commands.new_client.requests.LoginRequest();
                    cmd.readCommand(buffer);
                    new ShipInitalizationHandler(client, cmd.playerId, cmd.sessionId, true);
                    return;
                }

                var gameSession = World.StorageManager.GetGameSession(client.UserId);

                if (gameSession != null)
                {
                    if (gameSession.Player.UsingNewClient)
                    {
                        if (NewClientCommands.ContainsKey(parser.CMD_ID))
                        {
                            NewClientCommands[parser.CMD_ID].execute(gameSession, buffer);
                        }
                        //else if (parser.CMD_ID != commands.new_client.LegacyModule.ID) Console.WriteLine("[3D] Received->{0} Instance: {1}", parser.CMD_ID, client.UserId);
                    }
                    else
                    {
                        if (OldClientCommands.ContainsKey(parser.CMD_ID))
                        {
                            OldClientCommands[parser.CMD_ID].execute(gameSession, buffer);
                        }
                        //else if (parser.CMD_ID != commands.old_client.LegacyModule.ID) Console.WriteLine("[7.5.3] Received->{0} Instance: {1}", parser.CMD_ID, client.UserId);
                    }

                    if (parser.CMD_ID == commands.new_client.LegacyModule.ID ||
                        parser.CMD_ID == commands.old_client.LegacyModule.ID)
                    {
                        var packet = parser.readUTF();

                        if (packet.Contains('|'))
                        {
                            var splittedPacket = packet.Split('|');
                            if (LegacyCommands.ContainsKey(splittedPacket[0]))
                            {
                                LegacyCommands[splittedPacket[0]].execute(gameSession, splittedPacket);
                            }
                            //else Console.WriteLine("Received->{0} Instance: {1}", packet, client.UserId);
                        }
                        else
                        {
                            if (LegacyCommands.ContainsKey(packet))
                            {
                                LegacyCommands[packet].execute(gameSession, new[] { packet });
                            }
                            //else Console.WriteLine("Received->{0} Instance: {1}", packet, client.UserId);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception found.. Disconnecting user");
                Console.WriteLine("Exception: " + exception + ";" + exception.StackTrace + ";" + exception.Message);
                if (client.UserId != 0)
                {
                    // find session
                    var session = World.StorageManager.GetGameSession(client.UserId);
                    if (session != null)
                    {
                        session.Kick();
                    }
                    else
                    {
                        client.Disconnect();
                    }
                }
                else
                {
                    client.Disconnect();
                }
            }
        }
Beispiel #11
0
        public void LookUp(IByteBuffer buffer, GameClient client)
        {
            try
            {
                if (client.Initialized)
                {
                    var parser = new ByteParser(buffer.Copy());

                    Console.WriteLine("ID: " + parser.CommandId);

                    var gameSession = GameStorageManager.Instance.GetGameSession(client.UserId);

                    if (gameSession != null)
                    {
                        if (gameSession.Player.UsingNewClient)
                        {
                            if (NewClientCommands.ContainsKey(parser.CommandId))
                            {
                                NewClientCommands[parser.CommandId].Execute(gameSession, buffer);
                            }
                        }
                        else
                        {
                            if (OldClientCommands.ContainsKey(parser.CommandId))
                            {
                                OldClientCommands[parser.CommandId].Execute(gameSession, buffer);
                            }
                        }

                        if (parser.CommandId == commands.new_client.LegacyModule.ID ||
                            parser.CommandId == commands.old_client.LegacyModule.ID)
                        {
                            var packet = parser.readUTF();

                            if (packet.Contains('|'))
                            {
                                var splittedPacket = packet.Split('|');
                                if (LegacyCommands.ContainsKey(splittedPacket[0]))
                                {
                                    LegacyCommands[splittedPacket[0]].Execute(gameSession, splittedPacket);
                                }
                                else
                                {
                                    Console.WriteLine("Received->{0} Instance: {1}", packet, client.UserId);
                                }
                            }
                            else
                            {
                                if (LegacyCommands.ContainsKey(packet))
                                {
                                    LegacyCommands[packet].Execute(gameSession, new[] { packet });
                                }
                                else
                                {
                                    Console.WriteLine("Received->{0} Instance: {1}", packet, client.UserId);
                                }
                            }
                        }
                    }
                }
                else
                {
                    LoginSequence(client, buffer);
                }
            }
            catch (Exception exception)
            {
                Out.QuickLog("Exception found.. Disconnecting user", LogKeys.ERROR_LOG);
                Out.QuickLog("Exception: " + exception + ";" + exception.StackTrace + ";" + exception.Message, LogKeys.ERROR_LOG);
            }
        }
 public virtual IByteBufferHolder Copy() => Replace(_data.Copy());
Beispiel #13
0
        public List <IByteBuffer> decode(FecPacket pkt)
        {
            if (pkt.Flag == Fec.typeParity)
            {
                Snmp.snmp.FECParityShards++;
            }
            else
            {
                Snmp.snmp.FECDataShards++;
            }

            int n         = rx.Count - 1;
            int insertIdx = 0;

            for (int i = n; i >= 0; i--)
            {
                //去重
                if (pkt.Seqid == rx[i].Seqid)
                {
                    Snmp.snmp.FECRepeatDataShards++;
                    pkt.release();
                    return(null);
                }

                if (pkt.Seqid > rx[i].Seqid)
                {
                    // insertion
                    insertIdx = i + 1;
                    break;
                }
            }

            //插入 rx中
            if (insertIdx == n + 1)
            {
                this.rx.Add(pkt);
            }
            else
            {
                rx.Insert(insertIdx, pkt);
            }

            //所有消息列表中的第一个包
            // shard range for current packet
            long shardBegin = pkt.Seqid - pkt.Seqid % shardSize;
            long shardEnd   = shardBegin + shardSize - 1;

            //rx数组中的第一个包
            // max search range in ordered queue for current shard
            int searchBegin = (int)(insertIdx - pkt.Seqid % shardSize);

            if (searchBegin < 0)
            {
                searchBegin = 0;
            }

            int searchEnd = searchBegin + shardSize - 1;

            if (searchEnd >= rx.Count)
            {
                searchEnd = rx.Count - 1;
            }

            List <IByteBuffer> result = null;

            if (searchEnd - searchBegin + 1 >= dataShards)
            {
                //当前包组的已收到的包数量
                int numshard = 0;
                //当前包组中属于数据包的数量
                int numDataShard = 0;
                //搜到第一个包在搜索行中的位置
                int first = 0;
                //收到的最大包的字节长度
                int maxlen = 0;

                // zero cache
                IByteBuffer[] shards     = decodeCache;
                bool[]        shardsflag = flagCache;
                for (int i = 0; i < shards.Length; i++)
                {
                    shards[i]     = null;
                    shardsflag[i] = false;
                }

                for (int i = searchBegin; i <= searchEnd; i++)
                {
                    FecPacket fecPacket = rx[i];
                    long      seqid     = fecPacket.Seqid;
                    if (seqid > shardEnd)
                    {
                        break;
                    }
                    if (seqid < shardBegin)
                    {
                        continue;
                    }
                    shards[(int)(seqid % shardSize)]     = fecPacket.Data;
                    shardsflag[(int)(seqid % shardSize)] = true;
                    numshard++;
                    if (fecPacket.Flag == Fec.typeData)
                    {
                        numDataShard++;
                    }

                    if (numshard == 1)
                    {
                        first = i;
                    }

                    if (fecPacket.Data.ReadableBytes > maxlen)
                    {
                        maxlen = fecPacket.Data.ReadableBytes;
                    }
                }

                if (numDataShard == dataShards)
                {
                    freeRange(first, numshard, rx);
                }
                else if (numshard >= dataShards)
                {
                    for (int i = 0; i < shards.Length; i++)
                    {
                        IByteBuffer shard = shards[i];
                        //如果数据不存在 用0填充起来
                        if (shard == null)
                        {
                            shards[i] = zeros.Copy(0, maxlen);
                            shards[i].SetWriterIndex(maxlen);
                            continue;
                        }

                        int left = maxlen - shard.ReadableBytes;
                        if (left > 0)
                        {
                            shard.WriteBytes(this.zeros, left);
                            zeros.ResetReaderIndex();
//                            zeros.resetReaderIndex();
                        }
                    }

                    codec.decodeMissing(shards, shardsflag, 0, maxlen);
                    result = new List <IByteBuffer>(this.dataShards);
                    for (int i = 0; i < shardSize; i++)
                    {
                        if (shardsflag[i])
                        {
                            continue;
                        }

                        IByteBuffer byteBufs = shards[i];
                        //释放构建的parityShards内存
                        if (i >= dataShards)
                        {
                            byteBufs.Release();
                            continue;
                        }

                        int packageSize = byteBufs.ReadShort();
                        if (byteBufs.ReadableBytes < packageSize)
                        {
////                            System.out.println("bytebuf长度: " + byteBufs.writerIndex() + " 读出长度" + packageSize);
//                            byte[] bytes = new byte[byteBufs.writerIndex()];
//                            byteBufs.getBytes(0, bytes);
//                            for (byte aByte :
//                            bytes) {
//                                System.out.print("[" + aByte + "] ");
//                            }
                            Snmp.snmp.FECErrs++;
                        }
                        else
                        {
                            Snmp.snmp.FECRecovered++;
                        }

                        //去除fec头标记的消息体长度2字段
                        byteBufs = byteBufs.Slice(Fec.fecDataSize, packageSize);
                        //int packageSize =byteBufs.readUnsignedShort();
                        //byteBufs = byteBufs.slice(0,packageSize);
                        result.Add(byteBufs);
                        Snmp.snmp.FECRecovered++;
                        //int packageSize =byteBufs.getUnsignedShort(0);
                        ////判断长度
                        //if(byteBufs.writerIndex()-Fec.fecHeaderSizePlus2>=packageSize&&packageSize>0)
                        //{
                        //    byteBufs = byteBufs.slice(Fec.fecHeaderSizePlus2,packageSize);
                        //    result.add(byteBufs);
                        //    Snmp.snmp.FECRecovered.incrementAndGet();
                        //}else{
                        //    System.out.println("bytebuf长度: "+byteBufs.writerIndex()+" 读出长度"+packageSize);
                        //    byte[] bytes = new byte[byteBufs.writerIndex()];
                        //    byteBufs.getBytes(0,bytes);
                        //    for (byte aByte : bytes) {
                        //        System.out.print("["+aByte+"] ");
                        //    }
                        //    Snmp.snmp.FECErrs.incrementAndGet();
                        //}
                    }

                    freeRange(first, numshard, rx);
                }
            }

            if (rx.Count > rxlimit)
            {
                if (rx[0].Flag == Fec.typeData)
                {
                    Snmp.snmp.FECShortShards++;
                }

                freeRange(0, 1, rx);
            }

            return(result);
        }
Beispiel #14
0
        public List <IByteBuffer> Receive(IByteBuffer record)
        {
            List <IByteBuffer> outputList = new List <IByteBuffer>();

            while (record.ReadableBytes > RECORD_HEADER_LENGTH)
            {
                byte            type    = (byte)(record.ReadByte() & 0x00FF);
                ProtocolVersion version = ProtocolVersion.Get(record.ReadByte() & 0xFF, record.ReadByte() & 0xFF);
                int             epoch   = record.ReadUnsignedShort();
                long            seq     = DtlsHelper.ReadUint48(record);
                //just reading length,not using it
                short  packetLength = record.ReadShort();
                byte[] realData     = new byte[packetLength];
                record.ReadBytes(realData);

                AsyncDtlsEpoch recordEpoch = null;
                if (epoch == readEpoch.Epoch)
                {
                    recordEpoch = readEpoch;
                }

                if (recordEpoch == null)
                {
                    continue;
                }

                if (recordEpoch.ReplayWindow.ShouldDiscard(seq))
                {
                    continue;
                }

                if (!version.IsDtls)
                {
                    continue;
                }

                if (readVersion != null && !readVersion.Equals(version))
                {
                    continue;
                }

                byte[]      plaintext = recordEpoch.getCipher().DecodeCiphertext(GetMacSequenceNumber(recordEpoch.Epoch, seq), type, realData, 0, realData.Length);
                IByteBuffer output    = Unpooled.WrappedBuffer(plaintext);

                recordEpoch.ReplayWindow.ReportAuthenticated(seq);
                if (plaintext.Length > this.plaintextLimit)
                {
                    continue;
                }

                if (readVersion == null)
                {
                    readVersion = version;
                }

                switch (type)
                {
                case ContentType.alert:
                    if (output.ReadableBytes == 2)
                    {
                        byte alertLevel       = (byte)(output.ReadByte() & 0x0FF);
                        byte alertDescription = (byte)(output.ReadByte() & 0x0FF);

                        peer.NotifyAlertReceived(alertLevel, alertDescription);

                        if (alertLevel == AlertLevel.fatal)
                        {
                            Failed();
                            throw new TlsFatalAlert(alertDescription);
                        }

                        if (alertDescription == AlertDescription.close_notify)
                        {
                            CloseTransport();
                        }
                    }

                    continue;

                case ContentType.application_data:
                    if (inHandshake)
                    {
                        continue;
                    }
                    break;

                case ContentType.change_cipher_spec:
                    while (output.ReadableBytes > 0)
                    {
                        short message = (short)(output.ReadByte() & 0x0FF);
                        if (message != ChangeCipherSpec.change_cipher_spec)
                        {
                            continue;
                        }

                        if (pendingEpoch != null)
                        {
                            readEpoch = pendingEpoch;
                        }
                    }

                    continue;

                case ContentType.handshake:
                    if (!inHandshake)
                    {
                        continue;
                    }

                    HandshakeHeader handshakeHeader = DtlsHelper.ReadHandshakeHeader(output);

                    if (handshakeHeader != null)
                    {
                        if (!handshakeHeader.FragmentLength.Equals(handshakeHeader.TotalLength))
                        {
                            PendingMessageData data = null;
                            if (pendingBuffers.ContainsKey(handshakeHeader.MessageSequence))
                            {
                                data = pendingBuffers[handshakeHeader.MessageSequence];
                            }

                            if (data == null)
                            {
                                data = new PendingMessageData(Unpooled.Buffer(handshakeHeader.TotalLength));
                                pendingBuffers[handshakeHeader.MessageSequence] = data;
                            }

                            data.WriteBytes(output, handshakeHeader.FragmentOffset);
                            if (data.WrottenBytes.Equals(handshakeHeader.TotalLength))
                            {
                                data.Buffer.SetWriterIndex(handshakeHeader.TotalLength);
                                byte[]      packetData = null;
                                IByteBuffer copy       = data.Buffer.Copy();
                                packetData = new byte[copy.ReadableBytes];
                                copy.ReadBytes(packetData);

                                if (handshakeHeader.MessageType.HasValue && handshakeHandler != null)
                                {
                                    handshakeHandler.HandleHandshake(handshakeHeader.MessageType.Value, data.Buffer);
                                }

                                byte[]      pseudoHeader = new byte[DtlsHelper.HANDSHAKE_MESSAGE_HEADER_LENGTH];
                                IByteBuffer headerBuffer = Unpooled.WrappedBuffer(pseudoHeader);
                                headerBuffer.SetWriterIndex(0);
                                DtlsHelper.WriteHandshakeHeader(handshakeHeader.MessageSequence, handshakeHeader.MessageType.Value, headerBuffer, handshakeHeader.TotalLength);
                                headerBuffer.SetReaderIndex(0);
                                handshakeHash.BlockUpdate(pseudoHeader, 0, pseudoHeader.Length);
                                handshakeHash.BlockUpdate(packetData, 0, packetData.Length);

                                if (handshakeHeader.MessageType.HasValue && handshakeHandler != null)
                                {
                                    handshakeHandler.PostProcessHandshake(handshakeHeader.MessageType.Value, data.Buffer);
                                }

                                pendingBuffers.Remove(handshakeHeader.MessageSequence);
                            }
                        }
                        else
                        {
                            byte[]      packetData = null;
                            IByteBuffer copy       = output.Copy();
                            packetData = new byte[copy.ReadableBytes];
                            copy.ReadBytes(packetData);

                            if (handshakeHeader.MessageType.HasValue && handshakeHandler != null)
                            {
                                handshakeHandler.HandleHandshake(handshakeHeader.MessageType.Value, output);
                            }

                            byte[]      pseudoHeader = new byte[DtlsHelper.HANDSHAKE_MESSAGE_HEADER_LENGTH];
                            IByteBuffer headerBuffer = Unpooled.WrappedBuffer(pseudoHeader);
                            headerBuffer.SetWriterIndex(0);
                            DtlsHelper.WriteHandshakeHeader(handshakeHeader.MessageSequence, handshakeHeader.MessageType.Value, headerBuffer, handshakeHeader.TotalLength);
                            headerBuffer.SetReaderIndex(0);
                            handshakeHash.BlockUpdate(pseudoHeader, 0, pseudoHeader.Length);
                            handshakeHash.BlockUpdate(packetData, 0, packetData.Length);

                            if (handshakeHeader.MessageType.HasValue && handshakeHandler != null)
                            {
                                handshakeHandler.PostProcessHandshake(handshakeHeader.MessageType.Value, output);
                            }
                        }
                    }

                    continue;

                case ContentType.heartbeat:
                    continue;
                }

                outputList.Add(output);
            }

            return(outputList);
        }