public override bool Excute() { string clientName = BinaryUtils.ReadString(m_data); string authCode = BinaryUtils.ReadString(m_data); if (Global.ClientAuthList.Count == 0 || Global.ClientAuthList.Any(t => t.Match(clientName, authCode))) { bool isSuccess = true; P2PTcpItem item = new P2PTcpItem(); item.TcpClient = m_tcpClient; if (Global.TcpMap.ContainsKey(clientName)) { if (Global.TcpMap[clientName].TcpClient.IsDisConnected) { Global.TcpMap[clientName].TcpClient.Close(); Global.TcpMap[clientName] = item; } else { isSuccess = false; Send_0x0101 sendPacket = new Send_0x0101(m_tcpClient, false, $"ClientName:{clientName} 已被使用"); m_tcpClient.Client.Send(sendPacket.PackData()); m_tcpClient.Close(); try { Global.TcpMap[clientName].TcpClient.Client.Send(new Send_0x0052().PackData()); } catch (Exception) { Global.TcpMap.Remove(clientName); } } } else { Global.TcpMap.Add(clientName, item); } if (isSuccess) { m_tcpClient.ClientName = clientName; Send_0x0101 sendPacket = new Send_0x0101(m_tcpClient, true, $"客户端{clientName}认证通过"); m_tcpClient.Client.Send(sendPacket.PackData()); } } else { Send_0x0101 sendPacket = new Send_0x0101(m_tcpClient, false, $"客户端{clientName}认证失败"); m_tcpClient.Client.Send(sendPacket.PackData()); m_tcpClient.Close(); } return(true); }
/// <summary> /// 监听映射端口并转发数据(ip直接转发模式) /// </summary> /// <param name="readClient"></param> private void ListenPortMapTcpWithIp(P2PTcpClient readClient) { if (readClient.ToClient == null || !readClient.ToClient.Connected) { LogUtils.Warning($"【失败】IP数据转发:绑定的Tcp连接已断开."); readClient.Close(); return; } byte[] buffer = new byte[P2PGlobal.P2PSocketBufferSize]; NetworkStream readStream = readClient.GetStream(); NetworkStream toStream = readClient.ToClient.GetStream(); try { while (readClient.Connected) { int curReadLength = readStream.ReadSafe(buffer, 0, buffer.Length); if (curReadLength > 0) { if (readClient.ToClient != null) { toStream.Write(buffer, 0, curReadLength); } else { LogUtils.Warning($"【失败】IP数据转发:目标Tcp连接已释放."); readClient.Close(); break; } } else { LogUtils.Warning($"【失败】IP数据转发:Tcp连接已断开."); //如果tcp已关闭,需要关闭相关tcp try { readClient.ToClient?.Close(); } finally { } break; } } } finally { LogUtils.Warning($"【失败】IP数据转发:目标Tcp连接已断开."); readClient.Close(); } }
public override bool Excute() { try { string token = BinaryUtils.ReadString(m_data); int mapPort = BinaryUtils.ReadInt(m_data); string remoteEndPoint = BinaryUtils.ReadString(m_data);; if (Global.AllowPortList.Any(t => t.Match(mapPort, m_tcpClient.ClientName))) { P2PTcpClient portClient = new P2PTcpClient("127.0.0.1", mapPort); P2PTcpClient serverClient = new P2PTcpClient(Global.ServerAddress, Global.ServerPort); portClient.IsAuth = serverClient.IsAuth = true; portClient.ToClient = serverClient; serverClient.ToClient = portClient; Models.Send.Send_0x0211 sendPacket = new Models.Send.Send_0x0211(token); int length = serverClient.Client.Send(sendPacket.PackData()); LogUtils.Info($"命令:0x0211 内网穿透Tcp绑定:{portClient.RemoteEndPoint}->{serverClient.RemoteEndPoint}->{remoteEndPoint}"); Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <Models.Receive.Packet_0x0212>(portClient); }); Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <Models.Receive.Packet_ToPort>(serverClient); }); } else { LogUtils.Warning($"命令:0x0211 无权限,端口:{mapPort}"); m_tcpClient.Close(); } } catch (Exception ex) { LogUtils.Warning($"命令:0x0211 错误:{Environment.NewLine} {ex}"); } return(true); }
/// <summary> /// 匹配对应的Command命令 /// </summary> /// <param name="tcpClient"></param> /// <param name="packet"></param> /// <returns></returns> public static P2PCommand FindCommand(P2PTcpClient tcpClient, ReceivePacket packet) { P2PCommand command = null; if (Global.AllowAnonymous.Contains(packet.CommandType) || tcpClient.IsAuth) { if (Global.CommandDict.ContainsKey(packet.CommandType)) { Type type = Global.CommandDict[packet.CommandType]; command = Activator.CreateInstance(type, tcpClient, packet.GetBytes()) as P2PCommand; } else { LogUtils.Warning($"{tcpClient.RemoteEndPoint}请求了未知命令{packet.CommandType}"); } } else { tcpClient.Close(); if (tcpClient.ToClient != null && tcpClient.ToClient.Connected) { tcpClient.ToClient.Close(); } LogUtils.Warning($"拦截{tcpClient.RemoteEndPoint}未授权命令"); } return(command); }
private void ListenPortMapPortWithServerName(PortMapItem item) { //服务端口限制在1000以上 if (item.LocalPort > 1000) { try { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); listener.Start(); ConsoleUtils.WriteLine($"Server:端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { string token = tcpClient.Token; //获取目标tcp if (Global.TcpMap.ContainsKey(item.RemoteAddress) && Global.TcpMap[item.RemoteAddress].Connected) { //加入待连接集合 Global.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Models.Send.Port2PApplyRequest packet = new Models.Send.Port2PApplyRequest(token, item.RemotePort); Debug.WriteLine("[服务器]发送Port2P连接申请"); Global.TcpMap[item.RemoteAddress].Client.Send(packet.PackData()); Global.TaskFactory.StartNew(() => { Thread.Sleep(Global.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (Global.WaiteConnetctTcp.ContainsKey(token)) { Debug.WriteLine("[服务器]5秒无响应,关闭连接"); Global.WaiteConnetctTcp[token].Close(); Global.WaiteConnetctTcp.Remove(token); } }); } else { Debug.WriteLine($"[服务器][错误]端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}服务不在线."); tcpClient.Close(); } }); } }); } catch { ConsoleUtils.WriteLine($"Server:端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); throw new Exception($"端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); } } else { ConsoleUtils.WriteLine($"Server:端口必须大于1000,当前端口:{item.LocalPort}"); } }
public override bool Excute() { int tokenLength = m_data.ReadInt32(); string token = m_data.ReadBytes(tokenLength).ToStringUnicode(); int mapPort = m_data.ReadInt32(); if (Global.AllowPort.Contains(mapPort)) { P2PTcpClient portClient = new P2PTcpClient("127.0.0.1", mapPort); P2PTcpClient serverClient = new P2PTcpClient(Global.ServerAddress, Global.ServerPort); portClient.IsAuth = serverClient.IsAuth = true; portClient.ToClient = serverClient; serverClient.ToClient = portClient; Models.Send.P2PortApplyResponse sendPacket = new Models.Send.P2PortApplyResponse(token); int length = serverClient.Client.Send(sendPacket.PackData()); Debug.WriteLine($"Port2P请求有效,{portClient.LocalEndPoint}->{serverClient.LocalEndPoint}"); Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <Models.Recieve.Port2PPacket>(portClient); }); Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <Models.Recieve.P2PortPacket>(serverClient); }); } else { Debug.WriteLine("Port2P请求无效,关闭连接"); m_tcpClient.Close(); } return(true); }
public override bool Excute() { int step = m_data.ReadInt32(); switch (step) { case 2: { bool isDestClient = BinaryUtils.ReadBool(m_data); string token = BinaryUtils.ReadString(m_data); if (isDestClient) { CreateTcpFromDest(token); } else { CreateTcpFromSource(token); } } break; case 4: ListenPort(); break; case -1: { string message = BinaryUtils.ReadString(m_data); LogUtils.Warning($"【P2P】穿透失败,错误消息:{Environment.NewLine}{message}"); m_tcpClient.Close(); } break; } return(true); }
private void ListenPortMapPortWithServerName(PortMapItem item) { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); return; } ListenerList.Add(listener); LogUtils.Show($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { string token = tcpClient.Token; //获取目标tcp if (Global.TcpMap.ContainsKey(item.RemoteAddress) && Global.TcpMap[item.RemoteAddress].TcpClient.Connected) { //加入待连接集合 Global.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Models.Send.Send_0x0211 packet = new Models.Send.Send_0x0211(token, item.RemotePort); Global.TcpMap[item.RemoteAddress].TcpClient.Client.Send(packet.PackData()); Global.TaskFactory.StartNew(() => { Thread.Sleep(Global.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (Global.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Warning($"【失败】内网穿透:{Global.P2PTimeout}秒无响应,已超时."); Global.WaiteConnetctTcp[token].Close(); Global.WaiteConnetctTcp.Remove(token); } }); } else { LogUtils.Warning($"【失败】内网穿透:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} 客户端不在线!"); tcpClient.Close(); } }); } }); }
/// <summary> /// 监听映射端口并转发数据(ip直接转发模式) /// </summary> /// <param name="readClient"></param> private void ListenPortMapTcpWithIp(P2PTcpClient readClient) { if (readClient.ToClient == null || !readClient.ToClient.Connected) { Debug.WriteLine($"[错误]端口映射:目标tcp不存在"); readClient.Close(); return; } byte[] buffer = new byte[P2PGlobal.P2PSocketBufferSize]; NetworkStream readStream = readClient.GetStream(); NetworkStream toStream = readClient.ToClient.GetStream(); while (readClient.Connected) { int curReadLength = readStream.ReadSafe(buffer, 0, buffer.Length); if (curReadLength > 0) { if (readClient.ToClient != null && readClient.ToClient.Connected) { toStream.Write(buffer, 0, curReadLength); } else { Debug.WriteLine($"远程端口已关闭{readClient.Client.RemoteEndPoint}"); readClient.Close(); break; } } else { Debug.WriteLine($"从端口{readClient.LocalEndPoint}读取到0的数据"); //如果tcp已关闭,需要关闭相关tcp if (readClient.ToClient != null && readClient.ToClient.Connected) { readClient.ToClient.Close(); } break; } } }
private void ListenPortMapPortWithServerName(PortMapItem item) { try { TcpListener listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); listener.Start(); ListenerList.Add(listener); LogUtils.Show($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { string token = tcpClient.Token; //获取目标tcp if (Global.P2PServerTcp != null && Global.P2PServerTcp.Connected) { //加入待连接集合 Global.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Send_0x0201_Apply packet = new Send_0x0201_Apply(token, item.RemoteAddress, item.RemotePort); Global.P2PServerTcp.Client.Send(packet.PackData()); //LogUtils.Debug("P2P第一步:向服务器发送申请."); Global.TaskFactory.StartNew(() => { Thread.Sleep(Global.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (Global.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Warning($"【失败】内网穿透:{Global.P2PTimeout}秒无响应,已超时."); Global.WaiteConnetctTcp[token].Close(); Global.WaiteConnetctTcp.Remove(token); } }); } else { LogUtils.Warning($"【失败】内网穿透:未连接服务器!"); tcpClient.Close(); } }); } }); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); } }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { //服务端口限制在1000以上 if (item.LocalPort > 1000) { try { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); listener.Start(); ConsoleUtils.WriteLine($"Server:端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { try { P2PTcpClient ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; } catch { tcpClient.Close(); Debug.WriteLine($"端口{item.LocalPort}映射关闭,无法建立{item.RemoteAddress}:{item.RemotePort}tcp连接."); } if (tcpClient.Connected) { Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient); }); Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient.ToClient); }); } }); } }); } catch { ConsoleUtils.WriteLine($"Server:端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); throw new Exception($"端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); } } else { ConsoleUtils.WriteLine($"Server:端口必须大于1000,当前端口:{item.LocalPort}"); } }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); return; } ListenerList.Add(listener); LogUtils.Show($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { try { P2PTcpClient ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; } catch (Exception ex) { tcpClient.Close(); LogUtils.Error($"【失败】内网穿透:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); } if (tcpClient.Connected) { Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient); }); Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient.ToClient); }); } }); } }); }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { TcpListener listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"端口映射失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); } ListenerList.Add(listener); LogUtils.Show($"端口映射成功:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { P2PTcpClient ipClient = null; try { ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); } catch (Exception ex) { tcpClient.Close(); LogUtils.Error($"内网穿透失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex}"); } if (ipClient.Connected) { tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; Global.TaskFactory.StartNew(() => ListenPortMapTcpWithIp(tcpClient)); Global.TaskFactory.StartNew(() => ListenPortMapTcpWithIp(tcpClient.ToClient)); } }); } }); }
public override bool Excute() { int tokenLength = m_data.ReadInt32(); string token = m_data.ReadBytes(tokenLength).ToStringUnicode(); if (Global.WaiteConnetctTcp.ContainsKey(token)) { P2PTcpClient client = Global.WaiteConnetctTcp[token]; Global.WaiteConnetctTcp.Remove(token); client.IsAuth = m_tcpClient.IsAuth = true; client.ToClient = m_tcpClient; m_tcpClient.ToClient = client; Debug.WriteLine($"[服务器]转发{client.RemoteEndPoint}->{m_tcpClient.RemoteEndPoint}"); //监听client Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <Port2PPacket>(client); }); } else { m_tcpClient.Close(); throw new Exception("连接已关闭"); } return(true); }
public override bool Excute() { int tokenLength = m_data.ReadInt32(); string token = m_data.ReadBytes(tokenLength).ToStringUnicode(); if (Global.WaiteConnetctTcp.ContainsKey(token)) { P2PTcpClient client = Global.WaiteConnetctTcp[token]; Global.WaiteConnetctTcp.Remove(token); client.IsAuth = m_tcpClient.IsAuth = true; client.ToClient = m_tcpClient; m_tcpClient.ToClient = client; LogUtils.Debug($"命令:0x0211 已绑定内网穿透(2端)通道 {client.RemoteEndPoint}->{m_tcpClient.RemoteEndPoint}"); //监听client Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <Packet_0x0212>(client); }); } else { m_tcpClient.Close(); throw new Exception("绑定内网穿透(2端)通道失败,目标Tcp连接已断开"); } return(true); }
public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : ReceivePacket { try { Guid curGuid = Global.CurrentGuid; byte[] buffer = new byte[P2PGlobal.P2PSocketBufferSize]; NetworkStream tcpStream = tcpClient.GetStream(); ReceivePacket msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket; while (tcpClient.Connected && curGuid == Global.CurrentGuid) { int curReadLength = tcpStream.ReadSafe(buffer, 0, buffer.Length); if (curReadLength > 0) { byte[] refData = buffer.Take(curReadLength).ToArray(); while (msgReceive.ParseData(ref refData)) { LogUtils.Debug($"命令类型:{msgReceive.CommandType}"); //todo:执行command P2PCommand command = FindCommand(tcpClient, msgReceive); if (command != null) { command.Excute(); } //重置msgReceive msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket; if (refData.Length <= 0) { break; } } } else { try { if (Global.TcpMap.ContainsKey(tcpClient.ClientName)) { if (Global.TcpMap[tcpClient.ClientName].TcpClient == tcpClient) { Global.TcpMap.Remove(tcpClient.ClientName); } } tcpClient.Close(); } catch { } //如果tcp已关闭,需要关闭相关tcp if (tcpClient.ToClient != null && tcpClient.ToClient.Connected) { try { tcpClient.ToClient.Close(); } catch { } } LogUtils.Debug($"tcp连接{tcpClient.RemoteEndPoint}已断开"); break; } } } catch (Exception ex) { LogUtils.Error($"【错误】Global_Func.ListenTcp:{Environment.NewLine}{ex}"); } }