Ejemplo n.º 1
0
 protected override void ChannelRead0(IChannelHandlerContext ctx, IFullHttpRequest msg)
 {
     StringBuilder stringBuilder = new StringBuilder("请求参数:\r\n");
     {
         if (msg.Method == HttpMethod.Get)
         {
             var fer = new QueryStringDecoder(msg.Uri);
             foreach (var item in fer.Parameters)
             {
                 stringBuilder.AppendFormat("{0}:{1}\r\n", item.Key, item.Value[0]);
             }
         }
         if (msg.Method == HttpMethod.Post)
         {
             var postRequestDecoder = new HttpPostRequestDecoder(msg).Offer(msg);
             foreach (var item in postRequestDecoder.GetBodyHttpDatas())
             {
                 var mixedAttribute = postRequestDecoder.Next() as MixedAttribute;
                 stringBuilder.AppendFormat("{0}:{1}\r\n", mixedAttribute?.Name, mixedAttribute?.Value);
                 mixedAttribute.Release();
             }
         }
         byte[] text = Encoding.UTF8.GetBytes(stringBuilder.ToString());
         WriteResponse(ctx, Unpooled.WrappedBuffer(text), AsciiString.Cached("text/plain"), AsciiString.Cached(text.Length.ToString()));
     }
 }
Ejemplo n.º 2
0
        public static async Task <IFullHttpRequest> ToFullHttpRequestAsync(this HttpRequestMessage message, bool fullUri = true)
        {
            var request = new DefaultFullHttpRequest(DNHttpVersion.Http11, new DNHttpMethod(message.Method.Method), fullUri ? message.RequestUri.AbsoluteUri : message.RequestUri.PathAndQuery);

            foreach (var item in message.Headers)
            {
                request.Headers.Add(AsciiString.Cached(item.Key), item.Value);
            }

            if (message.Content != null)
            {
                //HACK 优化其余Header的处理
                if (message.Content.Headers.ContentType != null)
                {
                    request.Headers.Add(HttpHeaderNames.ContentType, message.Content.Headers.ContentType);
                }
                if (message.Content.Headers.ContentLength != null)
                {
                    request.Headers.Add(HttpHeaderNames.ContentLength, message.Content.Headers.ContentLength);
                }

                var content = await message.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                request.Content.WriteBytes(content, 0, content.Length);
            }

            return(request);
        }
        public static async Task DoRequest(Channel channel)
        {
            DefaultFullHttpRequest req = null;

            req = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get, "/");
            req.Headers.Add(AsciiString.Cached("Host"), AsciiString.Cached("localhost"));
            req.Headers.Add(AsciiString.Cached("Connection"), AsciiString.Cached("Keep-Alive"));
            // Console.WriteLine("send get");
            channel.Busy = true;

            if (!upChannels.ContainsKey(channel.upstream))
            {
                upChannels.TryAdd(channel.upstream, channel);
            }
            Task.Run(async() =>
            {
                try
                {
                    await channel.upstream.WriteAndFlushAsync(req).ConfigureAwait(false);

                    // Console.WriteLine("send done");
                }
                catch (Exception ex)
                {
                    await channel.request.DisconnectAsync();
                    //Console.WriteLine("close connection");
                    Channel old = null;
                    upChannels.TryRemove(channel.upstream, out old);
                    Console.WriteLine(ex.Message);
                }
            });
        }
        async Task Process(IChannelHandlerContext ctx, IHttpRequest request)
        {
            string uri = request.Uri;

            switch (uri)
            {
            case "/lock":
                LockOper op2 = new LockOper()
                {
                    Key     = "key",
                    Oper    = "lock",
                    Session = "session1"
                };
                var ack1 = Task.Run(async() =>
                {
                    return(await this.BeginRequest(op2));
                }).GetAwaiter().GetResult();

                //byte[] json2 = Encoding.UTF8.GetBytes(NewMessage2().ToJsonFormat());
                //this.WriteResponse(ctx, Unpooled.WrappedBuffer(json2), TypeJson, JsonClheaderValue);
                string str = "null";
                if (ack1 != null)
                {
                    str = Newtonsoft.Json.JsonConvert.SerializeObject(ack1);
                }
                byte[] json2  = Encoding.UTF8.GetBytes(new MessageBody(str).ToJsonFormat());
                var    length = json2.Length;
                this.WriteResponse(ctx, Unpooled.WrappedBuffer(json2), TypeJson, AsciiString.Cached($"{length}"));
                break;

            case "/plaintext":
                LockOper op = new LockOper()
                {
                    Key     = "key",
                    Oper    = "lock",
                    Session = "session1"
                };
                var ack = Task.Run(async() =>
                {
                    return(await this.BeginRequest(op));
                }).GetAwaiter().GetResult();

                this.WriteResponse(ctx, PlaintextContentBuffer.Duplicate(), TypePlain, PlaintextClheaderValue);
                break;

            case "/json":
                byte[] json = Encoding.UTF8.GetBytes(NewMessage().ToJsonFormat());
                this.WriteResponse(ctx, Unpooled.WrappedBuffer(json), TypeJson, JsonClheaderValue);
                break;

            default:
                var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false);
                await ctx.WriteAndFlushAsync(response);

                await ctx.CloseAsync();

                break;
            }
        }
        /// <summary>
        /// 发送消息并清空缓冲区。
        /// </summary>
        /// <param name="message">消息内容。</param>
        /// <returns>一个任务。</returns>
        public async Task SendAndFlushAsync(TransportMessage message)
        {
            var buffer   = GetByteBuffer(message, out int contentLength);
            var response = WriteResponse(_context, buffer, TypeJson, AsciiString.Cached($"{ contentLength}"));

            await _context.WriteAndFlushAsync(response);

            await _context.CloseAsync();
        }
 /// <summary>
 /// 发送消息。
 /// </summary>
 /// <param name="message">消息内容。</param>
 /// <returns>一个任务。</returns>
 public async Task SendAsync(TransportMessage message)
 {
     if (!_context.Channel.Active)
     {
         if (OnChannelUnActived != null)
         {
             OnChannelUnActived(this, _context.Channel.RemoteAddress);
         }
         throw new CommunicationException($"{_context.Channel.RemoteAddress}服务提供者不健康,无法发送消息");
     }
     var buffer   = GetByteBuffer(message, out int contentLength);
     var response = WriteResponse(_context, buffer, TypeJson, AsciiString.Cached($"{contentLength}"));
     await _context.WriteAsync(response);
 }
Ejemplo n.º 7
0
        // Creates a new HTTP method with the specified name.  You will not need to
        // create a new method unless you are implementing a protocol derived from
        // HTTP, such as
        // http://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol and
        // http://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol
        //
        public HttpMethod(string name)
        {
            Contract.Requires(name != null);

            name = name.Trim();
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(nameof(name));
            }

            for (int i = 0; i < name.Length; i++)
            {
                char c = name[i];
                if (CharUtil.IsISOControl(c) || char.IsWhiteSpace(c))
                {
                    throw new ArgumentException($"Invalid character '{c}' in {nameof(name)}");
                }
            }

            this.name = AsciiString.Cached(name);
        }
Ejemplo n.º 8
0
        protected override void Encode(IChannelHandlerContext ctx, IResponseMessage msg, List <object> output)
        {
            var buf      = msg.ToBodyBuffer();
            var status   = HttpResponseStatus.ValueOf(Convert.ToInt32(msg.Headers.Get(Constants.ResponseStatusCode)));
            var response = new DefaultFullHttpResponse(HttpVersion.Http11, status, buf, false);

            HttpHeaders headers = response.Headers;

            headers.Set(HttpHeaderNames.Server, AsciiString.Cached(Options.Name));
            headers.Set(HttpHeaderNames.Date, this.date);
            headers.Set(HttpHeaderNames.ContentLength, AsciiString.Cached($"{msg.Headers.Get(Constants.Headers.ContentLength)}"));

            if (Convert.ToInt32(msg.Headers.Get(Constants.Headers.ContractId)) == (int)ContractType.HandShake)
            {
                headers.Set(HttpHeaderNames.ContentType, AsciiString.Cached("text/plain"));
            }
            else
            {
                headers.Set(HttpHeaderNames.ContentType, AsciiString.Cached(msg.Headers.Get(Constants.Headers.ContentType)));
            }
            output.Add(response);
        }
        public override void ChannelRead(IChannelHandlerContext ctx, object message)
        {
            if (message is IFullHttpRequest httpRequest)
            {
                var succeeded = false;
                if (httpRequest.Method == HttpMethod.Post && restfulRoute.Equals(httpRequest.Uri, StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        if (httpRequest.Content.HasArray)
                        {
                            String         jsonStr        = Encoding.UTF8.GetString(httpRequest.Content.Array, httpRequest.Content.ArrayOffset, httpRequest.Content.ReadableBytes);
                            SampleRequest  request        = JsonConvert.DeserializeObject <SampleRequest>(jsonStr);
                            SampleResponse sampleResponse = new SampleResponse()
                            {
                                Response = request.Request
                            };
                            var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(sampleResponse));
                            WriteResponse(ctx, Unpooled.WrappedBuffer(bytes), AsciiString.Cached("application/json"), new AsciiString(bytes.Length.ToString()));
                        }
                    }
                    catch (Exception)
                    {
                        ReturnInternalServerError(ctx);
                    }
                }

                if (!succeeded)
                {
                    ReturnBadRequest(ctx);
                }
            }
            else
            {
                ctx.FireChannelRead(message);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates a new HTTP method with the specified name.  You will not need to
        /// create a new method unless you are implementing a protocol derived from
        /// HTTP, such as
        /// http://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol and
        /// http://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol
        /// </summary>
        /// <param name="name"></param>
        public HttpMethod(string name)
        {
            if (name is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name);
            }

            name = name.Trim();
            if (string.IsNullOrEmpty(name))
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name);
            }

            for (int i = 0; i < name.Length; i++)
            {
                char c = name[i];
                if (CharUtil.IsISOControl(c) || char.IsWhiteSpace(c))
                {
                    ThrowHelper.ThrowArgumentException_InvalidMethodName(c, name);
                }
            }

            this.name = AsciiString.Cached(name);
        }
 public static async Task OnEnd(IChannelHandlerContext ctx, object message)
 {
     try
     {
         Channel channel = null;
         bool    success = upChannels.TryGetValue(ctx.Channel, out channel);
         if (success)
         {
             var         oldContext = channel;
             var         response   = new DefaultFullHttpResponse(DotNetty.Codecs.Http.HttpVersion.Http11, HttpResponseStatus.OK, Unpooled.Empty, false);
             HttpHeaders headers    = response.Headers;
             headers.Set(ContentTypeEntity, TypePlain);
             headers.Set(ServerEntity, ServerName);
             int StaticPlaintextLen = 0;
             headers.Set(ContentLengthEntity, AsciiString.Cached($"{StaticPlaintextLen}"));
             oldContext.request.WriteAndFlushAsync(message as IFullHttpResponse).ConfigureAwait(false);
             freeChannels.Enqueue(channel);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message + ex.StackTrace);
     }
 }
Ejemplo n.º 12
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, IFullHttpRequest msg)
        {
            if (msg.Method == HttpMethod.Post)
            {
                var decoder = new HttpPostRequestDecoder(msg);
                decoder.Offer(msg);
                string hookMethodName  = string.Empty;
                string hookMethodValue = string.Empty;
                decoder.GetBodyHttpDatas().ForEach(httpData =>
                {
                    var param = (IAttribute)httpData;
                    if (param.Name == HookMethodName)
                    {
                        hookMethodName = param.Value;
                    }
                    if (param.Name == HookMethodValue)
                    {
                        hookMethodValue = param.Value;
                    }
                });
                if (!string.IsNullOrEmpty(hookMethodName) && !string.IsNullOrEmpty(hookMethodValue))
                {
                    Console.WriteLine(hookMethodName + "---" + hookMethodValue);
                    switch (hookMethodName)
                    {
                    case "getAndroidId":
                        HookData.AndroidId = hookMethodValue;
                        break;

                    case "getMacAddr":
                        HookData.Mac = hookMethodValue;
                        break;

                    case "get_bssid_addr":
                        HookData.BSSID = hookMethodValue;
                        break;

                    case "get_qimei":
                        HookData.IMEI = hookMethodValue;
                        break;

                    case "get_IMSI":
                        HookData.IMSI = hookMethodValue;
                        break;

                    case "A1":
                        HookData.A1 = hookMethodValue;
                        break;

                    case "A2":
                        HookData.A2 = hookMethodValue;
                        break;

                    case "A3":
                        HookData.A3 = hookMethodValue;
                        break;

                    case "nick":
                        HookData.Nick = hookMethodValue;
                        break;

                    case "D2KEY":
                        HookData.D2KEY = hookMethodValue;
                        Common.Keys.AddLast(new DecryptionKey()
                        {
                            Key = hookMethodValue, KeyType = KeyType.D2_KEY
                        });
                        break;

                    case "tgtkey":
                        HookData.TGTKEY = hookMethodValue;
                        Common.Keys.AddLast(new DecryptionKey()
                        {
                            Key = hookMethodValue, KeyType = KeyType.RAND_TGT_KEY
                        });
                        break;

                    case "LoginPwd":
                        HookData.Pwd = hookMethodValue;
                        break;

                    default:
                        break;
                    }

                    if (hookMethodName == "set_g_share_key")
                    {
                        if (_keys.Count >= 2)
                        {
                            Common.Keys.AddLast(new DecryptionKey()
                            {
                                Key = hookMethodValue, KeyType = KeyType.SHARE_KEY, PublicKey = _keys.Take(), PrivateKey = _keys.Take()
                            });
                        }
                        else
                        {
                            Common.Keys.AddLast(new DecryptionKey()
                            {
                                Key = hookMethodValue, KeyType = KeyType.SHARE_KEY
                            });
                            Logger.Warn("set_g_share_key 队列剩余容量不足!");
                        }
                    }

                    if (hookMethodName == "set_c_pub_key" || hookMethodName == "set_c_pri_key")
                    {
                        _keys.Add(hookMethodValue);
                    }

                    if (hookMethodName == "Cryptor.encrypt" || hookMethodName == "Cryptor.decrypt")
                    {
                        Common.Keys.AddLast(new DecryptionKey()
                        {
                            Key = hookMethodValue, KeyType = KeyType.CACHED_SHAKEY
                        });
                    }

                    if (hookMethodName == "set_c_pub_key" || hookMethodName == "set_c_pri_key" ||
                        hookMethodName == "set_g_share_key" || hookMethodName == "GenECDHKeyEx" ||
                        hookMethodName == "SetSigInfo" || hookMethodName == "Cryptor.encrypt" ||
                        hookMethodName == "Cryptor.decrypt" || hookMethodName == "test" ||
                        hookMethodName == "LoginPwd" || hookMethodName == "calShareKeyByBouncycastle" ||
                        hookMethodName == "InitShareKeyByBouncycastle")
                    {
                        Tab.TabHttpServer.HttpServerLog("hookMethodName: {0} hookMethodValue: {1}", hookMethodName, hookMethodValue);
                    }
                }
            }

            byte[] content = Encoding.UTF8.GetBytes("http server is ok");
            WriteResponse(ctx, Unpooled.WrappedBuffer(content), TypePlain, AsciiString.Cached(content.Length.ToString()));
        }
 WebSocketVersion(string value)
 {
     this.value = AsciiString.Cached(value);
 }
Ejemplo n.º 14
0
 public static DateTime?ParseHttpDate(string txt) => ParseHttpDate(AsciiString.Cached(txt));
Ejemplo n.º 15
0
 public static DateTime?ParseHttpDate(string txt, int start, int end) => ParseHttpDate(AsciiString.Cached(txt), start, end);
Ejemplo n.º 16
0
 HttpScheme(int port, string name)
 {
     this.port = port;
     this.name = AsciiString.Cached(name);
 }
 HttpStatusClass(int min, int max, string defaultReasonPhrase)
 {
     this.min = min;
     this.max = max;
     this.defaultReasonPhrase = AsciiString.Cached(defaultReasonPhrase);
 }
Ejemplo n.º 18
0
 PseudoHeaderName(string value, bool requestOnly)
 {
     _value       = AsciiString.Cached(value);
     _requestOnly = requestOnly;
 }
Ejemplo n.º 19
0
 static HpackHeaderField NewHeaderField(string name, string value)
 {
     return(new HpackHeaderField(AsciiString.Cached(name), AsciiString.Cached(value)));
 }
Ejemplo n.º 20
0
 static HpackHeaderField NewEmptyHeaderField(string name)
 {
     return(new HpackHeaderField(AsciiString.Cached(name), AsciiString.Empty));
 }