/// <summary> /// 从配置文件中加载配置 /// </summary> /// <returns></returns> public BaseConfig LoadFromFile() { IFileManager fileManager = EasyInject.Get <IFileManager>(); AppConfig config = LoadFromString(fileManager.ReadAll(IFileManager.Config)) as AppConfig; return(config); }
/// <summary> /// 匹配对应的Command命令 /// </summary> /// <param name="tcpClient"></param> /// <param name="packet"></param> /// <returns></returns> public static P2PCommand FindCommand(P2PTcpClient tcpClient, ReceivePacket packet) { P2PCommand command = null; AppCenter appCenter = EasyInject.Get <AppCenter>(); if (appCenter.AllowAnonymous.Contains(packet.CommandType) || tcpClient.IsAuth) { if (appCenter.CommandDict.ContainsKey(packet.CommandType)) { Type type = appCenter.CommandDict[packet.CommandType]; command = Activator.CreateInstance(type, tcpClient, packet.Data.Select(t => t).ToArray()) as P2PCommand; } else { LogUtils.Warning($"{tcpClient.RemoteEndPoint}请求了未知命令{packet.CommandType}"); } } else { tcpClient?.SafeClose(); tcpClient.ToClient?.SafeClose(); LogUtils.Warning($"拦截{tcpClient.RemoteEndPoint}未授权命令"); } return(command); }
public void Start(string pipeName = "") { pipeServer = new w_pipe.PipeServer(); pipeServer.StartListen(pipeName); EasyInject.Get <ILogger>().OnWriteLog += PipeServer_OnWriteLog; //订阅“命令”消息 pipeServer.RegisterHandler <string>("ExcuteCmd", ReadCallBack); //订阅“获取监听端口”消息 pipeServer.RegisterHandler <string>("GetListenPorts", (_, pipe) => { string ret = ""; for (int i = 0; i < appCenter.Config.PortMapList.Count; i++) { PortMapItem item = appCenter.Config.PortMapList[i]; if (i != appCenter.Config.PortMapList.Count - 1) { ret += item.LocalPort + ","; } else { ret += item.LocalPort; } } //发送“监听端口”信息 w_pipe.PipeServer.SendMsg(pipe, "GetListenPorts_R", ret); }); //订阅“获取版本”消息 pipeServer.RegisterHandler <string>("GetVersionInfo", (_, pipe) => { //发送“版本信息” w_pipe.PipeServer.SendMsg(pipe, "GetVersionInfo_R", EasyInject.Get <AppCenter>().SoftVerSion); }); }
public void TestGlobal_CommandList() { CoreModule coreModule = new CoreModule(); coreModule.InitCommandList(); Assert.AreNotEqual(EasyInject.Get <AppCenter>().CommandDict.Count, 0); }
protected virtual void InitInterface() { appCenter = EasyInject.Get <AppCenter>(); tcpCenter = EasyInject.Get <TcpCenter>(); configManager = EasyInject.Get <IConfig>(); P2PClient = EasyInject.Get <P2PClient>(); }
public override bool Excute() { LogUtils.Trace($"开始处理消息:0x0201"); int step = BinaryUtils.ReadInt(m_data); //是否第一步创建 if (step == 1) { //token,servername,port string token = BinaryUtils.ReadString(m_data); string clientName = BinaryUtils.ReadString(m_data); int clientPort = BinaryUtils.ReadInt(m_data); int p2pType = BinaryUtils.ReadInt(m_data); if (p2pTypeDict.ContainsKey(token)) { p2pTypeDict[token] = p2pType; } else { p2pTypeDict.Add(token, p2pType); } P2PStart_ServerTransfer(token, clientName, clientPort, p2pType); } else if (step == 3) { string clientName = BinaryUtils.ReadString(m_data); m_tcpClient.ClientName = clientName; string token = BinaryUtils.ReadString(m_data); if (clientCenter.WaiteConnetctTcp.ContainsKey(token)) { if (p2pTypeDict.ContainsKey(token) && p2pTypeDict[token] >= 1) { P2PBind_DirectConnect(token); } else { P2PBind_ServerTransfer(token); } p2pTypeDict.Remove(token); } else { clientCenter.WaiteConnetctTcp.Add(token, m_tcpClient); LogUtils.Debug($"正在等待隧道连接绑定 token:{token}."); EasyInject.Get <AppCenter>().StartNewTask(() => { Thread.Sleep(appCenter.Config.P2PWaitConnectTime); if (clientCenter.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Debug($"等待隧道连接绑定已超时 token:{token}."); EasyOp.Do(() => m_tcpClient.SafeClose()); clientCenter.WaiteConnetctTcp.Remove(token); p2pTypeDict.Remove(token); } }); } } return(true); }
protected void InitRegister() { EasyInject.Put <AppCenter, AppCenter>().Singleton(); EasyInject.Put <IFileManager, FileManager>().Common(); EasyInject.Put <ILogger, Logger>().Singleton(); EasyInject.Put <IServerConfig, ConfigManager>().Singleton(); EasyInject.Put <ClientCenter, ClientCenter>().Singleton(); }
public Send_0x0103() : base(P2PCommandType.Login0x0103) { AppConfig appConfig = EasyInject.Get <AppCenter>().Config; // allowport BinaryUtils.Write(Data, appConfig.AllowPortList); // 客户端黑名单 BinaryUtils.Write(Data, appConfig.BlackClients); }
protected void InitSelf() { appCenter = EasyInject.Get <AppCenter>(); tcpCenter = EasyInject.Get <TcpCenter>(); configManager = EasyInject.Get <IConfig>(); P2PClient = EasyInject.Get <P2PClient>(); pipeServer = EasyInject.Get <IPipeServer>(); pipeServer.Start(); }
public Send_0x0101() : base(P2PCommandType.Login0x0101) { AppCenter appCenter = EasyInject.Get <AppCenter>(); // 客户端名称 BinaryUtils.Write(Data, appCenter.Config.ClientName); // 授权码 BinaryUtils.Write(Data, appCenter.Config.AuthCode); }
public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : ReceivePacket { RelationTcp_Server relationSt = new RelationTcp_Server(); relationSt.buffer = new byte[P2PGlobal.P2PSocketBufferSize]; relationSt.readTcp = tcpClient; relationSt.msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket; relationSt.guid = EasyInject.Get <AppCenter>().CurrentGuid; relationSt.readTcp.GetStream().BeginRead(relationSt.buffer, 0, relationSt.buffer.Length, ReadTcp_Server, relationSt); }
protected void InitRegister() { EasyInject.Put <AppCenter, AppCenter>().Singleton(); EasyInject.Put <TcpCenter, TcpCenter>().Singleton(); EasyInject.Put <IFileManager, FileManager>().Common(); EasyInject.Put <ILogger, Logger>().Singleton(); EasyInject.Put <IConfig, ConfigManager>().Singleton(); EasyInject.Put <IPipeServer, PipeServer>().Singleton(); EasyInject.Put <P2PClient, P2PClient>().Singleton(); }
public Send_0x0201_Bind(string token) : base(P2PCommandType.P2P0x0201) { AppConfig appConfig = EasyInject.Get <AppCenter>().Config; // P2P标志 BinaryUtils.Write(Data, (int)3); // 客户端名称 BinaryUtils.Write(Data, appConfig.ClientName); // P2P穿透唯一标志 BinaryUtils.Write(Data, token); }
public void SafeClose() { if (this.Connected) { EasyInject.Get <ILogger>().WriteLine(new LogInfo() { LogLevel = Enums.LogLevel.Trace, Msg = $"关闭tcp连接{this.RemoteEndPoint}" }); this.GetStream().Close(3000); this.Close(); } }
/// <summary> /// 循环集合覆盖写入配置文件 /// </summary> /// <param name="list">要写入的内容集合</param> private void ForeachWrite(List <string> list) { IFileManager fileManager = EasyInject.Get <IFileManager>(); fileManager.ForeachWrite(IFileManager.Config, func => { foreach (string lineStr in list) { func(lineStr); } }, false); }
public string RegisterMacAddress(string mac) { Random random = new Random(); string name = random.Next(303030, 909090).ToString(); while (MacAddressMap.ContainsKey(name)) { name = random.Next(303030, 909090).ToString(); } MacAddressMap.Add(mac, name); EasyInject.Get <IServerConfig>().SaveMacAddress(this); return(name); }
protected virtual void InitRegister() { //应用中心,用于存放配置、全局变量等信息 EasyInject.Put <AppCenter, AppCenter>().Singleton(); //Tcp管理,用于保存当前tcp连接和端口监听实例 EasyInject.Put <TcpCenter, TcpCenter>().Singleton(); //文件IO接口,不同系统的文件读写方式有区别,可重载此接口实现定制 EasyInject.Put <IFileManager, FileManager>().Common(); //日志接口,用于日志写入 EasyInject.Put <ILogger, Logger>().Singleton(); //配置管理,用于读写配置文件 EasyInject.Put <IConfig, ConfigManager>().Singleton(); //内网穿透客户端实例 EasyInject.Put <P2PClient, P2PClient>().Singleton(); }
/// <summary> /// 保存mac地址映射 /// </summary> /// <param name="configIn">传入的配置实例</param> public void SaveMacAddress(BaseConfig configIn) { AppConfig config = configIn as AppConfig; lock (macLock) { IFileManager fileManager = EasyInject.Get <IFileManager>(); Dictionary <string, string> macMap = config.MacAddressMap; fileManager.ForeachWrite(FileManager.MacAdress, func => { foreach (string mac in macMap.Keys) { func($"{mac} {macMap[mac]}"); } }, false); } }
/// <summary> /// 加载mac地址映射 /// </summary> /// <param name="config">传入的配置实例</param> /// <returns></returns> private AppConfig LoadMacAddress(AppConfig config) { IFileManager fileManager = EasyInject.Get <IFileManager>(); if (fileManager.IsExist(FileManager.MacAdress)) { fileManager.ReadLine(FileManager.MacAdress, lineData => { string lineStr = lineData.Trim(); string[] oneData = lineStr.Split(' ').Where(t => !string.IsNullOrWhiteSpace(t)).ToArray(); if (oneData.Length == 2) { config.MacAddressMap.Add(oneData[0], oneData[1]); } }); } return(config); }
public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : ReceivePacket { RelationTcp_Server relationSt = new RelationTcp_Server(); relationSt.buffer = new byte[P2PGlobal.P2PSocketBufferSize]; relationSt.readTcp = tcpClient; relationSt.msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket; relationSt.guid = EasyInject.Get <AppCenter>().CurrentGuid; relationSt.readTcp.GetStream().BeginRead(relationSt.buffer, 0, relationSt.buffer.Length, ReadTcp_Server, relationSt); //如果20秒仍未授权,则关闭 TimerUtils.Instance.AddJob(() => { if (!tcpClient.IsAuth) { EasyOp.Do(() => tcpClient?.SafeClose()); } }, 20000); }
protected virtual void DoWriteLine() { bool isError = false; do { try { IFileManager fileInst = EasyInject.Get <IFileManager>(); if (!fileInst.IsExist(IFileManager.Log)) { fileInst.Create(IFileManager.Log); } fileInst.ForeachWrite(IFileManager.Log, BatchWrite); } catch { isError = true; Thread.Sleep(2000); } } while (isError); m_curTask = null; }
protected void InitSelf() { appCenter = EasyInject.Get <AppCenter>(); configManager = EasyInject.Get <IServerConfig>(); P2PServer = new P2PServer(); }
private void Form1_Load(object sender, EventArgs e) { LogTextBox.AppendText("\r\n"); LogTextBox.AppendText("************************************************************************\r\n"); LogTextBox.AppendText("* P2P内网穿透桌面客户端 作者:ZeroDeng *\r\n"); LogTextBox.AppendText("* 需要更专业的配置请自行手动修改配置文件 *\r\n"); LogTextBox.AppendText("* 感谢内核作者:wireboy *\r\n"); LogTextBox.AppendText("* 有好的建议或者意见请移步github提交issues *\r\n"); LogTextBox.AppendText("* 客户端github地址:https://github.com/ZeroDeng01/P2PSocket.Client.WFM *\r\n"); LogTextBox.AppendText("************************************************************************\r\n"); LogTextBox.AppendText("\r\n"); if (Config.IsExistConfig()) { //加载服务端地址 ServerAddressTextBox.Text = ini.IniReadValue("Common", "ServerAddress"); //加载客户端名称 string clientName = ini.IniReadValue("Common", "ClientName"); if (clientName.Trim().Length > 0) { ClientNameTextBox.Text = clientName; } else { clientName = BitConverter.ToUInt32(Guid.NewGuid().ToByteArray(), 8).ToString(); ClientNameTextBox.Text = clientName; ini.IniWriteValue("Common", "ClientName", clientName); } //加载被控端口 string allowPortStr = ini.IniReadValue("Common", "AllowPort"); if (!"".Equals(allowPortStr)) { if (allowPortStr.IndexOf(',') != -1) { allowPorts = new BindingList <string>(allowPortStr.Split(',').ToList()); } else { allowPorts.Add(allowPortStr); } } AllowPortListBox.DataSource = allowPorts; //初始化日志回调 EasyInject.Get <ILogger>().OnWriteLog += PipeServer_OnWriteLog; //初始启动P2PSocket clientModule.Start(); AppConfig config = new AppConfig(); List <string> portmap = ini.GetPortMapItems(); if (portmap != null) { foreach (string s in portmap) { portMapItems.Add(s); } PortMapItemListBox.DataSource = portMapItems; } } else { Log("配置文件缺失,正在创建"); if (!Directory.Exists(Config.RuntimePath)) //不存在文件夹,创建 { Directory.CreateDirectory(Config.RuntimePath); //创建新的文件夹 } FileStream fs = File.Create(Config.ConfigFile); //创建文件 fs.Close(); Log("配置文件创建完毕"); Form1_Load(sender, e); } }
/// <summary> /// 管道数据读取回调方法 /// </summary> /// <param name="ar"></param> protected override void ReadCallBack(IAsyncResult ar) { PipeSt st = ar.AsyncState as PipeSt; int length = st.pipe.EndRead(ar); if (length > 0) { st.pipe.BeginRead(st.buffer, 0, st.buffer.Length, ReadCallBack, st); string strData = Encoding.Unicode.GetString(st.buffer.Take(length).ToArray()); string[] strSplit = strData.Split(' ').Where(t => !string.IsNullOrWhiteSpace(t)).ToArray(); AppCenter appCenter = EasyInject.Get <AppCenter>(); if (strSplit[0] == "ls") { string msg = "当前监听端口:"; appCenter.Config.PortMapList.ForEach(t => { msg += t.LocalPort + " "; }); WriteLine(st.pipe, msg); } else if (strSplit[0] == "v") { WriteLine(st.pipe, $"当前版本 { EasyInject.Get<AppCenter>().SoftVerSion}"); } else if (strSplit[0] == "use") { IConfig configManager = EasyInject.Get <IConfig>(); EasyOp.Do(() => { PortMapItem obj = configManager.ParseToObject("[PortMapItem]", strSplit[1]) as PortMapItem; if (obj != null) { //设置配置文件更新时间,避免出发重加载配置文件逻辑 appCenter.LastUpdateConfig = DateTime.Now; //添加/修改指定项到配置文件 configManager.SaveItem(obj); P2PClient client = EasyInject.Get <P2PClient>(); //监听/修改端口映射 if (client.UsePortMapItem(obj)) { appCenter.Config.PortMapList.Add(obj); WriteLine(st.pipe, "添加/修改端口映射成功!"); LogUtils.Info($"管道命令:添加/修改端口映射 {obj.LocalPort}->{obj.RemoteAddress}:{obj.RemotePort}"); } else { WriteLine(st.pipe, "添加/修改端口映射失败,请参考wiki中的端口映射配置项!"); } } else { WriteLine(st.pipe, "添加/修改端口映射失败,请参考wiki中的端口映射配置项!"); } }, e => { WriteLine(st.pipe, $"添加/修改端口映射异常:{e}"); }); } else if (strSplit[0] == "del") { int localPort; if (int.TryParse(strSplit[1], out localPort)) { EasyOp.Do(() => { //设置配置文件更新时间,避免出发重加载配置文件逻辑 appCenter.LastUpdateConfig = DateTime.Now; P2PClient client = EasyInject.Get <P2PClient>(); //停止监听端口 client.UnUsePortMapItem(localPort); IConfig configManager = EasyInject.Get <IConfig>(); //移除配置文件中指定项 configManager.RemoveItem(new PortMapItem() { LocalPort = localPort }); WriteLine(st.pipe, "移除端口映射成功!"); LogUtils.Info($"管道命令:移除端口映射 {localPort}"); }, e => { WriteLine(st.pipe, $"移除端口映射异常:{e}"); }); } else { WriteLine(st.pipe, "移除端口映射失败!"); } } else if (strSplit[0] == "log") { if (strSplit.Length == 2 && strSplit[1] == "-s") { LogItem pipeSt = logItems.FirstOrDefault(t => t.item == st.pipe); logItems.Remove(pipeSt); WriteLine(st.pipe, "停止记录日志"); } else { LogLevel level = appCenter.Config.LogLevel; if (strSplit.Length == 2) { switch (strSplit[1].ToLower()) { case "debug": level = LogLevel.Debug; break; case "error": level = LogLevel.Error; break; case "info": level = LogLevel.Info; break; case "none": level = LogLevel.None; break; case "warning": level = LogLevel.Warning; break; case "trace": level = LogLevel.Trace; break; } } if (!logItems.Any(t => t.item == st.pipe)) { LogItem item = new LogItem(); item.item = st.pipe; item.level = level; logItems.Add(item); WriteLine(st.pipe, $"开始记录日志,级别:{level}"); } else { LogItem pipeSt = logItems.FirstOrDefault(t => t.item == st.pipe); pipeSt.level = level; WriteLine(st.pipe, $"设置日志级别:{level}"); } } } else if (strSplit[0] == "h") { string msg = ""; using (MemoryStream ms = new MemoryStream()) { StreamWriter writer = new StreamWriter(ms); writer.WriteLine("1.开始日志打印: log [Debug/Info/Warning/Trace]"); writer.WriteLine("2.结束日志打印: log -s"); writer.WriteLine("3.获取监听端口: ls"); writer.WriteLine("4.获取当前版本: v"); writer.WriteLine("5.添加/修改端口映射: use 映射配置 (例:\"use 12345->[ClientA]:3389\")"); writer.WriteLine("6.删除指定端口映射: del 端口号 (例:\"del 3388\")"); writer.Close(); msg = Encoding.UTF8.GetString(ms.ToArray()); } WriteLine(st.pipe, msg); } else { WriteLine(st.pipe, "暂不支持此命令,输入\"h\"查看帮助"); } } }
/// <summary> /// 读取配置文件内容 /// </summary> /// <param name="doReadFunc">实际读取内容的方法</param> private void ReadToEnd(Action <StreamReader> doReadFunc) { IFileManager fileManager = EasyInject.Get <IFileManager>(); ReadToEnd(fileManager.ReadAll(IFileManager.Config), doReadFunc); }
/// <summary> /// 从配置文件中加载配置 /// </summary> /// <returns></returns> public BaseConfig LoadFromFile() { IFileManager fileManager = EasyInject.Get <IFileManager>(); return(LoadFromString(fileManager.ReadAll(IFileManager.Config))); }
public ConfigManager() { appCenter = EasyInject.Get <AppCenter>(); }
public PipeServer() { EasyInject.Get <ILogger>().OnWriteLog += PipeServer_OnWriteLog; }
private static void ReadTcp_Server(IAsyncResult ar) { RelationTcp_Server relation = (RelationTcp_Server)ar.AsyncState; if (relation.guid == EasyInject.Get <AppCenter>().CurrentGuid) { if (relation.readTcp.Connected && relation.readTcp.GetStream().CanRead) { int length = 0; EasyOp.Do(() => { length = relation.readTcp.GetStream().EndRead(ar); }, () => { if (length > 0) { byte[] refData = relation.buffer.Take(length).ToArray(); while (relation.msgReceive.ParseData(ref refData)) { // 执行command using (P2PCommand command = FindCommand(relation.readTcp, relation.msgReceive)) { //LogUtils.Trace($"命令类型:{relation.msgReceive.CommandType}"); if (command != null) { bool isSuccess = false; EasyOp.Do(() => { isSuccess = command.Excute(); }, e => { LogUtils.Error($"执行命令{relation.msgReceive.CommandType}时发生异常:{e}"); }); if (!isSuccess) { EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); return; } } else { EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); return; } } //重置msgReceive relation.msgReceive.Reset(); if (refData.Length <= 0) { break; } } if (relation.readTcp.Connected) { EasyOp.Do(() => { relation.readTcp.GetStream().BeginRead(relation.buffer, 0, relation.buffer.Length, ReadTcp_Server, relation); }, ex => { LogUtils.Debug($"Tcp连接已被断开 {relation.readTcp.RemoteEndPoint}"); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); }); } } else { EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); } }, ex => { LogUtils.Debug($"Tcp连接已被断开 {relation.readTcp.RemoteEndPoint}"); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); }); } } else { LogUtils.Debug($"主动断开{relation.readTcp.RemoteEndPoint}连接"); EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); } //if (TcpCenter.Instance.ConnectedTcpList.Contains(relation.readTcp)) // TcpCenter.Instance.ConnectedTcpList.Remove(relation.readTcp); }
public P2PClient() { appCenter = EasyInject.Get <AppCenter>(); tcpCenter = EasyInject.Get <TcpCenter>(); }