Ejemplo n.º 1
0
 public void ProcessData(NatSession session, NatRequestInfo requestInfo, HttpModel httpModel)
 {
     try
     {
         switch (requestInfo.Body.Action)
         {
         case (int)HttpAction.Response:
         {
             var context = ContextDict.FirstOrDefault(c => c.Key == httpModel.SessionId).Value;
             if (context == null)
             {
                 HandleLog.WriteLine($"未找到上下文context,SessionId={httpModel.SessionId}");
                 return;
             }
             using var stream = context.Response.OutputStream;
             if (httpModel.Content?.Length > 0)
             {
                 //解压
                 var byteData = DataHelper.Decompress(httpModel.Content);
                 var res      = byteData.ToUTF8String();
                 foreach (var item in httpModel.Headers)
                 {
                     context.Response.AddHeader(item.Key, item.Value);
                 }
                 context.Response.StatusCode      = httpModel.StatusCode;
                 context.Response.ContentType     = httpModel.ContentType;
                 context.Response.ContentLength64 = byteData.Length;
                 //把处理信息返回到客户端
                 stream.WriteAsync(byteData, 0, byteData.Length).ContinueWith((t) =>
                     {
                         var timeSpan  = (DateTime.Now - httpModel.RequestTime);
                         var totalSize = byteData.Length * 1.00 / 1024;
                         var speed     = Math.Round(totalSize / timeSpan.TotalSeconds, 1);
                         HandleLog.WriteLine($"{session.Client.user_name} {session.Client.name} {context.Request.HttpMethod} {context.Request.Url.AbsoluteUri} {httpModel.StatusCode} {httpModel.StatusMessage} {Math.Round(totalSize, 1)}KB {timeSpan.TotalMilliseconds}ms {speed}KB/s");
                         ContextDict.Remove(httpModel.SessionId);
                     });
             }
         }
         break;
         }
     }
     catch (Exception ex)
     {
         HandleLog.WriteLine($"HttpServer ProcessData穿透处理异常,{ex}");
     }
 }
Ejemplo n.º 2
0
        public void ProcessData(NatSession session, NatRequestInfo requestInfo, HttpModel httpModel)
        {
            try
            {
                switch (requestInfo.Body.Action)
                {
                case (int)HttpAction.Response:
                {
                    var context = GetSingle(c => c.SessionId == httpModel.SessionId);
                    if (context == null)
                    {
                        HandleLog.WriteLine($"未找到上下文context,SessionId={httpModel.SessionId}");
                        return;
                    }
                    HttpResponse httpResponse = new HttpResponse()
                    {
                        HttpVersion   = httpModel.HttpVersion,
                        Headers       = httpModel.Headers,
                        Status        = httpModel.StatusCode,
                        StatusMessage = httpModel.StatusMessage
                    };
                    if (httpModel.Content?.Length > 0)
                    {
                        //解压
                        var byteData = DataHelper.Decompress(httpModel.Content);
                        httpResponse.ContentType = httpModel.ContentType;
                        httpResponse.Body        = byteData;
                    }
                    //把处理信息返回到客户端
                    context.Send(httpResponse.Write());

                    var timeSpan  = (DateTime.Now - httpModel.RequestTime);
                    var totalSize = (httpResponse.Body?.Length ?? 0) * 1.00 / 1024;
                    var map       = session.MapList.Find(c => c.remote_endpoint == httpModel.Host);
                    HandleLog.WriteLine($"{session.Client.user_name} {session.Client.name} {map?.name} {httpModel.Method} {httpModel.Path} {httpModel.StatusCode} {httpModel.StatusMessage} {Math.Round(totalSize, 1)}KB {timeSpan.TotalMilliseconds}ms");
                }
                break;
                }
            }
            catch (Exception ex)
            {
                HandleLog.WriteLine($"HttpsServer ProcessData穿透处理异常,{ex}");
            }
        }
Ejemplo n.º 3
0
        private static void Received(NatSession session, NatRequestInfo requestInfo)
        {
            Task.Run(() =>
            {
                try
                {
                    //HandleLog.WriteLine($"NAT服务收到数据:{requestInfo.Raw.ToHexWithSpace()},正文内容: {requestInfo.Body.ToJson()}");
                    switch (requestInfo.Body.Type)
                    {
                    case (byte)JsonType.NAT:
                        {
                            NATServer.ProcessData(session, requestInfo);
                            break;
                        }

                    case (byte)JsonType.HTTP:
                        {
                            var httpModel = requestInfo.Body.Data.FromJson <HttpModel>();
                            var server    = HttpsServerList.Find(c => c.ServerId == httpModel.ServerId);
                            server?.ProcessData(session, requestInfo, httpModel);
                            break;
                        }

                    case (byte)JsonType.TCP:
                        {
                            var tcpModel = requestInfo.Body.Data.FromJson <TcpModel>();
                            var server   = TcpServerList.Find(c => c.ServerId == tcpModel.ServerId);
                            server?.ProcessData(session, requestInfo, tcpModel);
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    HandleLog.WriteLine($"穿透传输连接【{session.Remote},{session.Client?.name}】响应请求异常:{ex}");
                }
            });
        }
Ejemplo n.º 4
0
        private static void NATServer_NewRequestReceived(NatAppSession session, NatRequestInfo requestInfo)
        {
            Task.Run(() =>
            {
                try
                {
                    //HandleLog.WriteLine($"NAT服务收到数据:{requestInfo.Hex}");
                    if (requestInfo.Mode == 0x1)//nat
                    {
                        switch (requestInfo.FunCode)
                        {
                        case 0x1:
                            {
                                //注册包
                                var secret    = requestInfo.BodyRaw;
                                using var bll = new ClientBll();
                                var client    = bll.GetOne(secret).Data;
                                if (client == null)
                                {
                                    HandleLog.WriteLine($"主机【{session.RemoteEndPoint}】密钥不正确!!");
                                    session.SendMsg("主机密钥不正确,请确认是否填写正确!");
                                    return;
                                }
                                var checkSessions = NATServer.GetSessions(c => c.Client?.secret == secret).ToList();
                                if (checkSessions.Any())
                                {
                                    checkSessions.ForEach(c =>
                                    {
                                        session.SendMsg($"您的密钥已被主机{client.name},{session.RemoteEndPoint}使用,已强制下线!!");
                                        Thread.Sleep(500);
                                        c.Close();
                                    });
                                }
                                session.Client = client;

                                using var mapBll = new MapBll();
                                session.MapList  = mapBll.GetMapList(secret).Data ?? new List <Map>();
                                //原样返回回复客户端注册成功
                                session.Send(requestInfo.Data);
                                Task.Run(() =>
                                {
                                    //更新在线状态
                                    using var bll = new ClientBll();
                                    var updateRst = bll.UpdateOnlineStatus(new Client()
                                    {
                                        secret = session.Client.secret, is_online = true, last_heart_time = DateTime.Now
                                    });
                                    HandleLog.WriteLine($"更新主机【{session.Client.name}】在线状态结果:{updateRst.Message}", false);
                                });
                            }
                            break;

                        case 0x2:
                            {
                                //心跳包
                                var secret = requestInfo.BodyRaw;
                                HandleLog.WriteLine($"收到连接{session.RemoteEndPoint}的心跳包,密钥为:{secret},当前映射个数:{session.MapList.Count}", false);
                                Task.Run(() =>
                                {
                                    //更新在线状态
                                    using var bll = new ClientBll();
                                    var updateRst = bll.UpdateOnlineStatus(new Client()
                                    {
                                        secret = session.Client.secret, is_online = true, last_heart_time = DateTime.Now
                                    });
                                    HandleLog.WriteLine($"更新主机【{session.Client.name}】在线状态结果:{updateRst.Message}", false);
                                });
                            }
                            break;
                        }
                    }
                    else if (requestInfo.Mode == 0x2)//http
                    {
                        var packJson = JsonHelper.Instance.Deserialize <PackJson>(requestInfo.BodyRaw);
                        switch (requestInfo.FunCode)
                        {
                        case 0x1:
                            {
                                //02 01 数据长度(4) 正文数据(n)   ---http响应包
                                int count = 0;
                                mark:
                                var webSession = HttpServerList.SelectMany(c => c.GetAllSessions()).Where(c => c.UserId.ToLower() == packJson.UserId.ToLower()).FirstOrDefault();
                                if (webSession == null)
                                {
                                    count++;
                                    Thread.Sleep(500);
                                    if (count < 5)
                                    {
                                        goto mark;
                                    }
                                    HandleLog.WriteLine($"webSession【{packJson.UserId}】不存在");
                                    return;
                                }
                                //先讲16进制字符串转为byte数组  再gzip解压
                                var response = DataHelper.Decompress(packJson.Content);
                                var res      = webSession.TrySend(response, 0, response.Length);
                                HandleLog.WriteLine($"{packJson.ResponseInfo} {Math.Ceiling((DateTime.Now - webSession.RequestTime).Value.TotalMilliseconds)}ms");
                            }
                            break;
                        }
                    }
                    else if (requestInfo.Mode == 0x3)//tcp
                    {
                        var packJson = JsonHelper.Instance.Deserialize <PackJson>(requestInfo.BodyRaw);
                        switch (requestInfo.FunCode)
                        {
                        case 0x2:
                            {
                                //响应请求
                                int count = 0;
                                mark:
                                var tcpSession = TcpServerList.SelectMany(c => c.GetAllSessions()).Where(c => c.UserId.ToLower() == packJson.UserId.ToLower()).FirstOrDefault();
                                if (tcpSession == null)
                                {
                                    count++;
                                    Thread.Sleep(500);
                                    if (count < 5)
                                    {
                                        goto mark;
                                    }
                                    HandleLog.WriteLine($"tcpSession【{packJson.UserId}】不存在");
                                    return;
                                }
                                //先讲16进制字符串转为byte数组  再gzip解压
                                var response = DataHelper.Decompress(packJson.Content);
                                tcpSession.Send(response, 0, response.Length);
                                HandleLog.WriteLine($"----> {tcpSession.PackJson.UserId} 发送报文{response.Length}字节");
                            }
                            break;

                        case 0x3:
                            {
                                //响应请求
                                var tcpSession = TcpServerList.SelectMany(c => c.GetAllSessions()).Where(c => c.UserId.ToLower() == packJson.UserId.ToLower()).FirstOrDefault();
                                if (tcpSession != null)
                                {
                                    tcpSession.Close();
                                    HandleLog.WriteLine($"连接【{tcpSession.PackJson.UserId},{tcpSession.RemoteEndPoint}】关闭成功");
                                }
                            }
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    HandleLog.WriteLine($"穿透传输连接【{session.RemoteEndPoint},{session.Client?.name}】响应请求异常:{ex}");
                }
            });
        }
Ejemplo n.º 5
0
        public void ProcessData(NatSession session, NatRequestInfo requestInfo, HttpModel httpModel)
        {
            try
            {
                switch (requestInfo.Body.Action)
                {
                case (int)HttpAction.Response:
                {
                    var context = GetSingle(c => c.SessionId == httpModel.SessionId);
                    if (context == null)
                    {
                        HandleLog.WriteLine($"未找到上下文context,SessionId={httpModel.SessionId}");
                        return;
                    }
                    HttpResponse httpResponse = new HttpResponse()
                    {
                        HttpVersion   = httpModel.HttpVersion,
                        Headers       = httpModel.Headers,
                        Status        = httpModel.StatusCode,
                        StatusMessage = httpModel.StatusMessage
                    };
                    if (httpModel.Content?.Length > 0)
                    {
                        //解压
                        var byteData = DataHelper.Decompress(httpModel.Content);
                        httpResponse.ContentType = httpModel.ContentType;
                        httpResponse.Body        = byteData;
                    }
                    //把处理信息返回到客户端
                    context.Send(httpResponse.Write());
                    var response_time = DateTime.Now;
                    var timeSpan      = (response_time - httpModel.RequestTime);
                    var totalSize     = (httpResponse.Body?.Length ?? 0) * 1.00 / 1024;
                    var map           = session.MapList.Find(c => c.remote_endpoint == httpModel.Host);
                    HandleLog.WriteLine($"{session.Client.user_name} {session.Client.name} {map?.name} {httpModel.Method} {httpModel.Path} {httpModel.StatusCode} {httpModel.StatusMessage} {Math.Round(totalSize, 1)}KB {timeSpan.TotalMilliseconds}ms");

                    var request = new Request
                    {
                        request_url      = $"{map.protocol}://{map.remote_endpoint}{httpModel.Path}",
                        request_method   = httpModel.Method,
                        client_ip        = session.Remote,
                        user_id          = session.Client.user_id,
                        request_time     = httpModel.RequestTime,
                        response_time    = response_time,
                        handle_time      = Convert.ToInt64(timeSpan.TotalMilliseconds),   //ms
                        create_time      = DateTime.Now,
                        requet_content   = context.RequestInfo.Body == null ? null : Encoding.UTF8.GetString(context.RequestInfo.Body),
                        response_content = httpResponse.Body.Length <= 1024 ? Encoding.UTF8.GetString(httpResponse.Body) : "",
                        status_code      = httpModel.StatusCode,
                        status_message   = httpModel.StatusMessage,
                        total_size       = httpResponse.Body?.Length ?? 0,
                        speed            = Math.Round(totalSize / (timeSpan.TotalMilliseconds / 1000), 2),//KB/s
                        map_id           = map.id
                    };
                    lock (RequestQueue)
                        RequestQueue.Enqueue(request);
                }
                break;
                }
            }
            catch (Exception ex)
            {
                HandleLog.WriteLine($"HttpsServer ProcessData穿透处理异常,{ex}");
            }
        }
Ejemplo n.º 6
0
        private static void NATServer_NewRequestReceived(NatAppSession session, NatRequestInfo requestInfo)
        {
            try
            {
                //HandleLog.WriteLine($"NAT服务收到数据:{requestInfo.Hex}");
                switch (requestInfo.FunCode)
                {
                case 0x1:
                {
                    //注册包
                    var secret = requestInfo.BodyRaw;
                    using var bll = new ClientBll();
                    var client = bll.GetOne(secret).Data;
                    if (client == null)
                    {
                        HandleLog.WriteLine($"主机【{session.RemoteEndPoint}】密钥不正确!!");
                        session.SendMsg("主机密钥不正确,请确认是否填写正确!");
                        return;
                    }
                    var checkSession = NATServer.GetSessions(c => c.Client?.secret == secret).FirstOrDefault();
                    if (checkSession != null)
                    {
                        session.SendMsg($"密钥{secret}已被主机:{checkSession.Client.name},{checkSession.RemoteEndPoint}使用!");
                        return;
                    }
                    session.Client = client;

                    using var mapBll = new MapBll();
                    session.MapList  = mapBll.GetMapList(secret).Data ?? new List <Map>();
                    //原样返回回复客户端注册成功
                    session.Send(requestInfo.Data);
                    Task.Run(() =>
                        {
                            //更新在线状态
                            using var bll = new ClientBll();
                            var updateRst = bll.UpdateOnlineStatus(new Client()
                            {
                                secret = session.Client.secret, is_online = true, last_heart_time = DateTime.Now
                            });
                            HandleLog.WriteLine($"更新主机【{session.Client.name}】在线状态结果:{updateRst.Message}", false);
                        });
                }
                break;

                case 0x2:
                {
                    //心跳包
                    var secret = requestInfo.BodyRaw;
                    HandleLog.WriteLine($"收到连接{session.RemoteEndPoint}的心跳包,密钥为:{secret},当前映射个数:{session.MapList.Count}", false);
                    Task.Run(() =>
                        {
                            //更新在线状态
                            using var bll = new ClientBll();
                            var updateRst = bll.UpdateOnlineStatus(new Client()
                            {
                                secret = session.Client.secret, is_online = true, last_heart_time = DateTime.Now
                            });
                            HandleLog.WriteLine($"更新主机【{session.Client.name}】在线状态结果:{updateRst.Message}", false);
                        });
                }
                break;

                case 0x3:
                {
                    //响应请求
                    var packJson = JsonHelper.Instance.Deserialize <PackJson>(requestInfo.BodyRaw);
                    int count    = 0;
mark:
                    var webSession = HttpServer.GetSessions(c => c.UserId.ToLower() == packJson.UserId.ToLower()).FirstOrDefault();
                    if (webSession == null)
                    {
                        count++;
                        Thread.Sleep(500);
                        if (count < 5)
                        {
                            goto mark;
                        }
                        HandleLog.WriteLine($"webSession【{packJson.UserId}】不存在");
                        return;
                    }
                    //先讲16进制字符串转为byte数组  再gzip解压
                    var response    = DataHelper.Decompress(packJson.Content);
                    var rawResponse = Encoding.UTF8.GetString(response);
                    var res         = webSession.TrySend(response, 0, response.Length);
                    HandleLog.WriteLine($"{packJson.ResponseInfo} {Math.Ceiling((DateTime.Now - webSession.RequestTime).Value.TotalMilliseconds)}ms");
                    //webSession?.Close();
                }
                break;
                }
            }
            catch (Exception ex)
            {
                HandleLog.WriteLine($"webSession响应请求异常:{ex}");
            }
        }