public void DictShouldEqualExpect(short version, Codec codec, int tag) { var buffer = Unpooled.Buffer(1); var options = new TarsConvertOptions() { Codec = codec, Version = version, Tag = tag }; var dict = new Dictionary <string, string> { { "str", "ok" } }; sut.Serialize(dict, buffer, options); headHandler.ReadHead(buffer, options); var result = sut.Deserialize <Dictionary <string, string> >(buffer, options); Assert.Single(result); Assert.Equal("ok", result["str"]); Assert.Equal(tag, options.Tag); Assert.Equal(TarsStructType.Map, options.TarsType); }
public void DecodeFullHttpRequestWithUrlEncodedBodyWithInvalidHexNibbleLo() { byte[] bodyBytes = Encoding.UTF8.GetBytes("foo=bar&a=b&empty=%2g&city=london"); IByteBuffer content = Unpooled.DirectBuffer(bodyBytes.Length); content.WriteBytes(bodyBytes); IFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, "/", content); try { new HttpPostRequestDecoder(req); Assert.False(true); // Was expecting an ErrorDataDecoderException } catch (ErrorDataDecoderException e) { Assert.Equal("Invalid hex byte at index '0' in string: '%2g'", e.Message); } finally { req.Release(); } }
public void ReleaseWhenMergeCumulateThrows() { WriteFailingByteBuf oldCumulation = new WriteFailingByteBuf(1, 64); oldCumulation.WriteZero(1); var input = Unpooled.Buffer().WriteZero(12); Exception thrown = null; try { ByteToMessageDecoder.MergeCumulator.Cumulate(UnpooledByteBufferAllocator.Default, oldCumulation, input); } catch (Exception t) { thrown = t; } Assert.Same(oldCumulation.WriteError(), thrown); Assert.Equal(0, input.ReferenceCount); Assert.Equal(1, oldCumulation.ReferenceCount); oldCumulation.Release(); }
public void TestUpgradeChunk() { EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true)); var hello = Unpooled.CopiedBuffer("hello world", Encoding.UTF8); var content = new DefaultHttpContent(hello); Assert.True(ch.WriteOutbound(content)); var dataFrame = ch.ReadOutbound <IHttp2DataFrame>(); try { Assert.Equal("hello world", dataFrame.Content.ToString(Encoding.UTF8)); Assert.False(dataFrame.IsEndStream); } finally { dataFrame.Release(); } Assert.Null(ch.ReadOutbound()); Assert.False(ch.Finish()); }
public void TestPartialMessage() { var ch = new EmbeddedChannel(new FrameDecoder(1024, _prepend, _append)); for (var i = 0; i < 2; i++) { ch.WriteInbound(Unpooled.Buffer(2) .WriteBytes(_prepend) .WriteBytes(_iso.GetBytes("A"))); var buf = ch.ReadInbound <IByteBuffer>(); Assert.Null(buf); ch.WriteInbound(Unpooled.Buffer(1).WriteByte(_append[0])); buf = ch.ReadInbound <IByteBuffer>(); Assert.Null(buf); ch.WriteInbound(Unpooled.Buffer(1).WriteByte(_append[1])); buf = ch.ReadInbound <IByteBuffer>(); ReferenceCountUtil.ReleaseLater(buf); Assert.Equal("A", buf.ToString(_iso)); buf.Release(); } }
public void ResetContentResponseWithTransferEncoding() { var ch = new EmbeddedChannel(new HttpResponseDecoder()); Assert.True(ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes( "HTTP/1.1 205 Reset Content\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0\r\n" + "\r\n")))); var res = ch.ReadInbound <IHttpResponse>(); Assert.Same(HttpVersion.Http11, res.ProtocolVersion); Assert.Equal(HttpResponseStatus.ResetContent, res.Status); var lastContent = ch.ReadInbound <ILastHttpContent>(); Assert.False(lastContent.Content.IsReadable()); lastContent.Release(); Assert.False(ch.Finish()); }
protected override void Encode(IChannelHandlerContext context, IJT808Reply message, IByteBuffer output) { if (message.Package != null) { try { var sendData = JT808Serializer.Serialize(message.Package, message.MinBufferSize); output.WriteBytes(Unpooled.WrappedBuffer(sendData)); } catch (JT808.Protocol.Exceptions.JT808Exception ex) { logger.LogError(ex, context.Channel.Id.AsShortText()); } catch (System.Exception ex) { logger.LogError(ex, context.Channel.Id.AsShortText()); } } else if (message.HexData != null) { output.WriteBytes(Unpooled.WrappedBuffer(message.HexData)); } }
public void EncodeVarint32Size(int size, byte[] data) { IByteBuffer written = null; try { var channel = new EmbeddedChannel(new ProtobufVarint32LengthFieldPrepender()); IByteBuffer content = Unpooled.WrappedBuffer(data, size, data.Length - size); Assert.True(channel.WriteOutbound(content)); written = channel.ReadOutbound <IByteBuffer>(); Assert.NotNull(written); byte[] output = TestUtil.GetReadableBytes(written); Assert.Equal(data.Length, output.Length); Assert.True(output.SequenceEqual(data)); Assert.False(channel.Finish()); } finally { written?.Release(); } }
public void WriteHeaders() { int streamId = 1; var headers = new DefaultHttp2Headers(); headers.Method = (AsciiString)"GET"; headers.Path = (AsciiString)"/"; headers.Authority = (AsciiString)"foo.com"; headers.Scheme = (AsciiString)"https"; _frameWriter.WriteHeadersAsync(_ctx.Object, streamId, headers, 0, true, _promise); byte[] expectedPayload = HeaderPayload(streamId, headers); byte[] expectedFrameBytes = { (byte)0x00, (byte)0x00, (byte)0x0a, // payload length = 10 (byte)0x01, // payload type = 1 (byte)0x05, // flags = (0x01 | 0x04) (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01 // stream id = 1 }; _expectedOutbound = Unpooled.CopiedBuffer(expectedFrameBytes, expectedPayload); Assert.Equal(_expectedOutbound, _outbound); }
public void TestSetMaxHeaderListSizeEnforcedAfterSet() { Assert.Throws <Http2Exception>(() => { var buf = Unpooled.Buffer(); IHttp2Headers headers = new DefaultHttp2Headers(); headers.Add( (AsciiString)"x-big-header", (AsciiString) new string(new char[1024 * 16]).Replace('\0', 'X') ); hpackEncoder.SetMaxHeaderListSize(1000); try { hpackEncoder.EncodeHeaders(0, buf, headers, NeverSensitiveDetector.Instance); } finally { buf.Release(); } }); }
public void FragmentedDecode() { EmbeddedChannel ch = new EmbeddedChannel(new LineBasedFrameDecoder(8192, false, false)); Assert.False(ch.WriteInbound(Unpooled.CopiedBuffer("huu", Encoding.ASCII))); Assert.Null(ch.ReadInbound <IByteBuffer>()); Assert.False(ch.WriteInbound(Unpooled.CopiedBuffer("haa\r", Encoding.ASCII))); Assert.Null(ch.ReadInbound <IByteBuffer>()); Assert.True(ch.WriteInbound(Unpooled.CopiedBuffer("\nhuuhaa\r\n", Encoding.ASCII))); var buf = ch.ReadInbound <IByteBuffer>(); Assert.Equal("huuhaa\r\n", buf.ToString(Encoding.ASCII)); var buf2 = ch.ReadInbound <IByteBuffer>(); Assert.Equal("huuhaa\r\n", buf2.ToString(Encoding.ASCII)); Assert.False(ch.FinishAndReleaseAll()); buf.Release(); buf2.Release(); }
public void TestWillEncode16MBHeaderByDefault() { var buf = Unpooled.Buffer(); var bigHeaderName = "x-big-header"; int bigHeaderSize = 1024 * 1024 * 16; var bigHeaderVal = new string(new char[bigHeaderSize]).Replace('\0', 'X'); IHttp2Headers headersIn = new DefaultHttp2Headers(); headersIn.Add((AsciiString)"x-big-header", (AsciiString)bigHeaderVal); IHttp2Headers headersOut = new DefaultHttp2Headers(); try { hpackEncoder.EncodeHeaders(0, buf, headersIn, NeverSensitiveDetector.Instance); hpackDecoder.SetMaxHeaderListSize(bigHeaderSize + 1024); hpackDecoder.Decode(0, buf, headersOut, false); } finally { buf.Release(); } Assert.Equal(bigHeaderVal, headersOut.Get((AsciiString)bigHeaderName, null).ToString()); }
protected override void Encode(IChannelHandlerContext context, string message, List <object> output) { Span <byte> strBytes = Encoding.Convert(Encoding.UTF8, Encoding, Encoding.UTF8.GetBytes(message)); int bytesLength = strBytes.Length; Span <byte> encryptedData = new byte[bytesLength + (int)Math.Ceiling((decimal)bytesLength / 0x7E) + 1]; int j = 0; for (int i = 0; i < bytesLength; i++) { if ((i % 126) == 0) { encryptedData[i + j] = (byte)(bytesLength - i > 126 ? 126 : bytesLength - i); j++; } encryptedData[i + j] = (byte)~strBytes[i]; } encryptedData[encryptedData.Length - 1] = 0xFF; output.Add(Unpooled.WrappedBuffer(encryptedData.ToArray())); }
public void ShouldEqualExpect(short version, Codec codec, int tag, int age, string name) { var buffer = Unpooled.Buffer(1); var options = new TarsConvertOptions() { Codec = codec, Version = version, Tag = tag }; TestData data = new TestData() { Age = age, Name = name }; sut.Serialize(data, buffer, options); headHandler.ReadHead(buffer, options); var result = sut.Deserialize <TestData>(buffer, options); Assert.Equal(tag, options.Tag); Assert.Equal(age, result.Age); Assert.Equal(name, result.Name); }
public void Identity() { var ch = new EmbeddedChannel(new HttpContentCompressor()); Assert.True(ch.WriteInbound(NewRequest())); var res = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("Hello, World"))); int len = res.Content.ReadableBytes; res.Headers.Set(HttpHeaderNames.ContentLength, len); res.Headers.Set(HttpHeaderNames.ContentEncoding, HttpHeaderValues.Identity); Assert.True(ch.WriteOutbound(res)); var response = ch.ReadOutbound <IFullHttpResponse>(); Assert.Equal(len.ToString(), response.Headers.Get(HttpHeaderNames.ContentLength, null).ToString()); Assert.Equal(HttpHeaderValues.Identity.ToString(), response.Headers.Get(HttpHeaderNames.ContentEncoding, null).ToString()); Assert.Equal("Hello, World", response.Content.ToString(Encoding.ASCII)); response.Release(); Assert.True(ch.FinishAndReleaseAll()); }
private static byte[] Encode(HpackEncoder hpackEncoder, List <HpackHeaderField> headers, int maxHeaderTableSize, bool sensitive) { IHttp2Headers http2Headers = ToHttp2Headers(headers); ISensitivityDetector sensitivityDetector = sensitive ? AlwaysSensitiveDetector.Instance : NeverSensitiveDetector.Instance; var buffer = Unpooled.Buffer(); try { if (maxHeaderTableSize != -1) { hpackEncoder.SetMaxHeaderTableSize(buffer, maxHeaderTableSize); } hpackEncoder.EncodeHeaders(3 /* randomly chosen */, buffer, http2Headers, sensitivityDetector); byte[] bytes = new byte[buffer.ReadableBytes]; buffer.ReadBytes(bytes); return(bytes); } finally { buffer.Release(); } }
public void PrematureClosureWithChunkedEncoding1() { var ch = new EmbeddedChannel(new HttpResponseDecoder()); ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"))); // Read the response headers. var res = ch.ReadInbound <IHttpResponse>(); Assert.Same(HttpVersion.Http11, res.ProtocolVersion); Assert.Equal(HttpResponseStatus.OK, res.Status); Assert.Equal("chunked", res.Headers.Get(HttpHeaderNames.TransferEncoding, null).ToString()); res = ch.ReadInbound <IHttpResponse>(); Assert.Null(res); // Close the connection without sending anything. ch.Finish(); // The decoder should not generate the last chunk because it's closed prematurely. var last = ch.ReadInbound <IByteBufferHolder>(); Assert.Null(last); }
private byte[] EncodeMediaAsFlvTagAndPrevTagSize(AbstractRtmpMediaMessage msg) { int tagType = msg.GetMsgType(); byte[] data = msg.Raw(); int dataSize = data.Length; int timestamp = (msg.Timestamp ?? 0) & 0xffffff; int timestampExtended = (int)(((msg.Timestamp ?? 0) & 0xff000000) >> 24); var buffer = Unpooled.Buffer(); buffer.WriteByte(tagType); buffer.WriteMedium(dataSize); buffer.WriteMedium(timestamp); buffer.WriteByte(timestampExtended); // timestampExtended buffer.WriteMedium(0); // streamid buffer.WriteBytes(data); buffer.WriteInt(data.Length + 11); // prevousTagSize byte[] r = new byte[buffer.ReadableBytes]; buffer.ReadBytes(r); return(r); }
protected override void Encode(IChannelHandlerContext context, string message, List <object> output) { try { var tmp = _loginServerConfiguration.UserLanguage.GetEncoding().GetBytes($"{message} "); for (var i = 0; i < message.Length; i++) { tmp[i] = Convert.ToByte(tmp[i] + 15); } tmp[tmp.Length - 1] = 25; if (tmp.Length == 0) { return; } output.Add(Unpooled.WrappedBuffer(tmp)); } catch (Exception ex) { Logger.Log.Info(LogLanguage.Instance.GetMessageFromKey(LanguageKey.ENCODE_ERROR), ex); } }
protected override void Encode(IChannelHandlerContext context, T message, List <object> output) { Contract.Requires(context != null); Contract.Requires(message != null); Contract.Requires(output != null); IByteBuffer buffer = null; try { buffer = Unpooled.WrappedBuffer(ProtoUtils.Serialize(message)); output.Add(buffer); buffer = null; } catch (Exception exception) { throw new CodecException(exception); } finally { buffer?.Release(); } }
public override void Encode(IByteBuffer buffer) { var buf = Unpooled.Buffer(); try { buf.WriteShort(PacketId); foreach (var item in _topics) { buf.WriteString(item); } FixedHeader.RemaingLength = buf.ReadableBytes; FixedHeader.WriteTo(buffer); buffer.WriteBytes(buf); buf = null; } finally { buf?.Release(); } }
public override void Encode(IByteBuffer buffer) { var buf = Unpooled.Buffer(); try { buf.WriteUnsignedShort(PacketId); foreach (var item in _subscribeTopics) { buf.WriteString(item.Topic); buf.WriteByte((byte)item.Qos); } FixedHeader.RemaingLength = buf.ReadableBytes; FixedHeader.WriteFixedHeader(buffer); buffer.WriteBytes(buf); } finally { buf?.Release(); } }
public void TestEncodeDataEndAsClient() { EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false)); IByteBuffer hello = Unpooled.CopiedBuffer("hello world", Encoding.UTF8); ILastHttpContent end = new DefaultLastHttpContent(hello, true); Assert.True(ch.WriteOutbound(end)); var dataFrame = ch.ReadOutbound <IHttp2DataFrame>(); try { Assert.Equal("hello world", dataFrame.Content.ToString(Encoding.UTF8)); Assert.True(dataFrame.IsEndStream); } finally { dataFrame.Release(); } Assert.Null(ch.ReadOutbound()); Assert.False(ch.Finish()); }
private void SendRealMsg2Server(IChannelHandlerContext context, string msg) { Logger.Info($"发送消息到Server, msg:{msg}"); msg = msg.Replace("-", ""); var bytes = BytesUtil.Hex2Bytes(msg); var buffer = Unpooled.WrappedBuffer(bytes); DatagramPacket packet = null; if (Index == 0) { packet = new DatagramPacket(buffer, new IPEndPoint(IPAddress.Parse((string)RemoteHost), RemotePort)); } else { packet = new DatagramPacket(buffer, context.Channel.RemoteAddress); } context.WriteAndFlushAsync(packet); Index++; // var packet = new DatagramPacket(buffer,context.Channel.RemoteAddress); // context.WriteAndFlushAsync(packet); }
public void DecodeMalformedNotEncodedContentDispositionFieldParameters() { const string Boundary = "74e78d11b0214bdcbc2f86491eeb4902"; const string Body = "--" + Boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename*=not-encoded\r\n" + "\r\n" + "foo\r\n" + "\r\n" + "--" + Boundary + "--"; var req = new DefaultFullHttpRequest( HttpVersion.Http11, HttpMethod.Post, "http://localhost", Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(Body))); req.Headers.Add(HttpHeaderNames.ContentType, "multipart/form-data; boundary=" + Boundary); var inMemoryFactory = new DefaultHttpDataFactory(false); Assert.Throws <ErrorDataDecoderException>(() => new HttpPostRequestDecoder(inMemoryFactory, req)); req.Release(); }
protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket msg) { Logger.Info("GkDevice收到server端消息"); var buffer = msg.Content; if (buffer == null) { return; } var serverMsg = Unpooled.Buffer(buffer.ReadableBytes); buffer.ReadBytes(serverMsg); var hexMsg = BytesUtil.BytesToHex(serverMsg.Array); Logger.Info($"收到server端消息, data:{hexMsg}"); if (hexMsg.Contains("7ffe0048")) { var deviceInfo = DeviceInfoMsg.Replace("-", ""); var bytes = BytesUtil.Hex2Bytes(deviceInfo); var deviceBuffer = Unpooled.WrappedBuffer(bytes); ctx.WriteAndFlushAsync(new DatagramPacket(deviceBuffer, msg.Sender)); } }
public override Task WriteAsync(IChannelHandlerContext context, object msg) { if (!(msg is ClusterMessage message)) { return(base.WriteAsync(context, null)); } message.Encode(); if (message.Id != 20103) { message.Encrypt(); } var header = Unpooled.Buffer(5); header.WriteUnsignedShort(message.Id); header.WriteMedium(message.Length); base.WriteAsync(context, header); return(base.WriteAsync(context, message.Writer)); }
protected override void Encode(IChannelHandlerContext context, string message, List <object> output) { try { var tmp = Encoding.Default.GetBytes($"{message} "); for (var i = 0; i < message.Length; i++) { tmp[i] = Convert.ToByte(tmp[i] + 15); } tmp[tmp.Length - 1] = 25; if (tmp.Length == 0) { return; } output.Add(Unpooled.WrappedBuffer(tmp)); } catch { //do nothing maybe log it } }
public void Send(byte[] bytes) { kcpChannel?.write(Unpooled.WrappedBuffer(bytes)); if (kcpChannel != null) { Log.Info(string.Format("sento_sender({0}): {1} {2} => {3} Channel:{4} DATA:{5}", this.netType, kcpChannel.user().RemoteAddress.ToIPv4String(), Global.Host.Id, ConnId, this.kcpChannel.user().Channel.Id.AsLongText(), StringUtil.ToHexString(bytes))); } tcpChannel?.WriteAndFlushAsync(Unpooled.WrappedBuffer(bytes)); if (tcpChannel != null) { Log.Info(string.Format("sento_sender({0}): {1} {2} => {3} Channel:{4} DATA:{5}", this.netType, tcpChannel.RemoteAddress.ToIPv4String(), Global.Host.Id, ConnId, tcpChannel.Id.AsLongText(), StringUtil.ToHexString(bytes))); } kcpClient?.Send(bytes); if (kcpClient != null) { Log.Info(string.Format("sento_receiver({0}): {1} {2} => {3} Channel:{4} DATA:{5}", this.netType, kcpClient.RemoteAddress.ToIPv4String(), Global.Host.Id, ConnId, kcpClient.ChannelId, StringUtil.ToHexString(bytes))); } tcpClient?.Send(bytes); if (tcpClient != null) { Log.Info(string.Format("sento_receiver({0}): {1} {2} => {3} Channel:{4} DATA:{5}", this.netType, tcpClient.RemoteAddress.ToIPv4String(), Global.Host?.Id, ConnId, tcpClient.ChannelId, StringUtil.ToHexString(bytes))); } }
public IByteBuffer ToByteBuffer() { var apiNameBytes = Encoding.UTF8.GetBytes(this.ApiName); var headLength = apiNameBytes.Length + 16; this.TotalBytes = this.Body == null ? headLength : headLength + this.Body.Length; this.ApiNameLength = (byte)apiNameBytes.Length; var bb = Unpooled.Buffer(TotalBytes); bb.WriteByte(FastPacket.Mark); //1 bb.WriteInt(this.TotalBytes); //4 bb.WriteByte(this.ApiNameLength); //1 bb.WriteBytes(apiNameBytes); // bb.WriteLong(this.Id); //8 bb.WriteBoolean(this.IsFromClient); //1 bb.WriteBoolean(this.IsException); //1 if (this.Body != null) { bb.WriteBytes(this.Body); } return(bb); }