/// <summary> /// PING /// </summary> /// <param name="addr">要PING的地址</param> /// <returns></returns> public static Status Ping(string addr) { try { Ping ping = new Ping(); PingReply reply = ping.Send(addr); if (reply != null) { switch (reply.Status) { case IPStatus.Success: return(Status.Success); case IPStatus.TimedOut: return(Status.Timeout); default: return(Status.Fail); } } return(Status.Expection); } catch (Exception e) { Log4Net.WriteLog(e.Message, e); return(Status.Expection); } }
/// <summary> /// 下载文件 /// </summary> /// <param name="url">链接</param> /// <param name="path">本地文件</param> /// <returns></returns> public static bool DownloadFile(string url, string path) { int index = url.IndexOf("/", 10); //懒的用其他的了,这是第三个/的出现的位置 RestClient client = new RestClient(url.Substring(0, index)); RestRequest request = new RestRequest(url.Substring(index, url.Length - index)); client.Timeout = 20 * 1000; try { byte[] result = client.DownloadData(request); if (result.Length < 1024) { Log4Net.WriteLog($"下载失败: 太少数据({result.Length}b)"); return(false); } using (FileStream stream = new FileStream(path, FileMode.Create)) { stream.Write(result, 0, result.Length); } Log4Net.WriteLog($"下载成功({path})"); } catch (Exception e) { Log4Net.WriteLog("下载失败: " + e.Message, e); return(false); } return(true); }
public bool Start() { try { INetConnection dialer = GetDialerConnection(); INetConnection wifi = GetAPConnection(); if (dialer == null || wifi == null) { return(false); } INetSharingConfiguration wconf = nsm.INetSharingConfigurationForINetConnection[wifi]; Disable_ICS_WMI(false); if (wconf.SharingEnabled) { wconf.DisableSharing(); } wconf.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PRIVATE); INetSharingConfiguration dconf = nsm.INetSharingConfigurationForINetConnection[dialer]; Disable_ICS_WMI(true); if (dconf.SharingEnabled) { dconf.DisableSharing(); } // System.AccessViolationException??? dconf.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PUBLIC); } catch (Exception e) { Log4Net.WriteLog("Enable sharing wifi failed", e); return(false); } return(true); }
/// <summary> /// 修复VPN /// </summary> public static void Fix() { if (!IsElevated) { Log4Net.WriteLog(nameof(Fix), new InvalidOperationException("没有足够权限")); MessageBox.Show( "需要管理员权限以修复VPN(请重启并允许UAC)", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string gateway = FindGateway(); string IF = FindInterface(); string args = $"add {DialerConfig.AuthIP} mask 255.255.255.255 0.0.0.0 metric 5 IF {IF}"; ProcessStartInfo psi = new ProcessStartInfo { FileName = "route", Arguments = args, CreateNoWindow = true }; Process proc = Process.Start(psi); proc?.WaitForExit(); int metric = CheckMetric(); if (metric > 128) { MessageBox.Show( $"VPN跃点数过大,可能修复失败,如失败请断线重试(metric={metric})", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public static void Load() { Handle = LoadLibrary(fileName); if (Handle == IntPtr.Zero) { Log4Net.WriteLog($"加载DLL失败({Marshal.GetLastWin32Error()})"); } else { try { get_version = Marshal.GetDelegateForFunctionPointer <get_version_t>(GetProcAddress(Handle, nameof(get_version))); auth = Marshal.GetDelegateForFunctionPointer <auth_t>(GetProcAddress(Handle, nameof(auth))); exit_auth = Marshal.GetDelegateForFunctionPointer <auth_t>(GetProcAddress(Handle, nameof(exit_auth))); set_enable_crypt = Marshal.GetDelegateForFunctionPointer <set_enable_crypt_t>(GetProcAddress(Handle, nameof(set_enable_crypt))); set_remote_ip = Marshal.GetDelegateForFunctionPointer <set_str_t>(GetProcAddress(Handle, nameof(set_remote_ip))); set_keep_alive1_flag = Marshal.GetDelegateForFunctionPointer <set_str_t>(GetProcAddress(Handle, nameof(set_keep_alive1_flag))); set_log_file = Marshal.GetDelegateForFunctionPointer <set_str_t>(GetProcAddress(Handle, nameof(set_log_file))); } catch (Exception e) { Log4Net.WriteLog("加载DLL函数失败", e); } } }
/// <summary> /// 停止检测 /// </summary> public static void StopCheckUpdateTimer() { try { if (UpdateTimer != null) { UpdateTimer.Change(-1, -1); UpdateTimer.Dispose(); UpdateTimer = null; } } catch (Exception e) { Log4Net.WriteLog(e.Message, e); } }
/// <summary> /// 停止ping检测 /// </summary> public static void StopCheck() { if (cancleToken != null) { try { cancleToken.Cancel(); cancleToken = null; } catch (Exception e) { Log4Net.WriteLog(e.Message, e); } } Log4Net.WriteLog("ping thread exit successfully."); }
public static void TryUpdate() { string RemoteFileUrl = Updater.CheckUpdate("GDUT-Drcom/Drcom-Dialer", NoExtName + ".exe", Version.GetVersion()); if (RemoteFileUrl == "") { Log4Net.WriteLog("无需更新"); return; } if (RemoteFileUrl != null) { if (Updater.DownloadFile(RemoteFileUrl, NewName)) { Log4Net.WriteLog($"成功更新主程序"); Binder.BaseBinder.ShowBalloonTip( 3000, "应用更新", "程序更新成功,将在下次启动生效", System.Windows.Forms.ToolTipIcon.Info); return; } } RemoteFileUrl = Updater.CheckUpdate("https://tools.bigkeer.cn/", "drcom/dialer.json", "bigkeer", NoExtName + ".exe", Version.GetVersion()); if (RemoteFileUrl == "") { Log4Net.WriteLog("无需更新"); return; } if (RemoteFileUrl != null) { if (Updater.DownloadFile(RemoteFileUrl, NewName)) { Log4Net.WriteLog($"成功更新主程序"); Binder.BaseBinder.ShowBalloonTip( 3000, "应用更新", "程序更新成功,将在下次启动生效", System.Windows.Forms.ToolTipIcon.Info); return; } } }
/// <summary> /// 账户信息相关功能 /// </summary> public static void AccountInfo() { AccInfo = GetAccountInfomation(); if (AccInfo != null && AccInfo.Status == "success") { if (DialerConfig.isNotifyWhenExpire) { DateTime overDate = AccInfo.OverDate; TimeSpan left = overDate.Subtract(DateTime.Today); if (left.TotalDays <= 7) { Binder.BaseBinder.ShowBalloonTip( 5000, "提示", "校园网账户将于" + overDate.ToString("yyyy-MM-dd") + "过期,请尽快充值", System.Windows.Forms.ToolTipIcon.Warning); } } if (DialerConfig.zone == DialerConfig.Campus.Unknown) { if (AccInfo.Service.Contains("大学城")) { DialerConfig.zone = DialerConfig.Campus.HEMC; } else if (AccInfo.Service.Contains("东风路")) { DialerConfig.zone = DialerConfig.Campus.DongfengRd; } else if (AccInfo.Service.Contains("龙洞")) { DialerConfig.zone = DialerConfig.Campus.LongDong; } else if (AccInfo.Service.Contains("番禺")) { DialerConfig.zone = DialerConfig.Campus.Panyu; } else { Log4Net.WriteLog("无法匹配的校区字符串:" + AccInfo.Service); } } } }
/// <summary> /// 使用指定的Mirror检测更新 /// </summary> /// <param name="mirrorHost">Mirror主机</param> /// <param name="mirrorUrl">RestfulAPI的URL</param> /// <param name="mirrorName">Mirror名称</param> /// <param name="fileName">文件名</param> /// <param name="currentVersion">当前版本</param> /// <returns>URL。无需更新返回空,出错返回null</returns> public static String CheckUpdate(string mirrorHost, string mirrorUrl, string mirrorName, string fileName, string currentVersion) { var client = new RestClient(mirrorHost); var request = new RestRequest(mirrorUrl); var response = client.Execute(request); Log4Net.WriteLog($"[{fileName}]正在从{mirrorName}检测更新"); try { if (!string.IsNullOrEmpty(response?.Content) && (response.StatusCode == HttpStatusCode.OK)) { JsonObject json = SimpleJson.DeserializeObject(response.Content) as JsonObject; string remoteVersion = json["tag_name"] as string; Log4Net.WriteLog($"远端版本:{remoteVersion}"); // 无需更新 if (!CompareVersion(currentVersion, remoteVersion)) { return(""); } // 需要更新 foreach (JsonObject asset in json["assets"] as JsonArray) { if (asset["name"] as string == fileName) { return(asset["browser_download_url"] as string); } } } else { Log4Net.WriteLog($"{mirrorName}源获取失败"); } } catch (Exception e)//更新网络数据不是想要的 { Log4Net.WriteLog($"{mirrorName}源获取失败", e); } return(null); }
/// <summary> /// 等会再检测 /// </summary> public static void LaterCheckUpdate() { try { if (UpdateTimer == null) { UpdateTimer = new Timer(new TimerCallback((state) => { StopCheckUpdateTimer(); if (Binder.BaseBinder.IsConnected) { TryUpdate(); } }), null, 1000 * 60 * 10, 1000 * 60 * 10);//10min } } catch (Exception e) { Log4Net.WriteLog(e.Message, e); } }
/// <summary> /// 循环检测 /// </summary> public static void LoopCheck() { try { if (cancleToken != null) { cancleToken.Cancel(); } } catch (Exception e) { Log4Net.WriteLog(e.Message, e); } cancleToken = new CancellationTokenSource(); pingThread = new Task(() => { Check(DialerConfig.AuthIP); }, cancleToken.Token); pingThread.Start(); }
/// <summary> /// 比较两个版本以确定是否需要升级 /// </summary> /// <param name="baseVer">本地版本</param> /// <param name="remoteVer">远端版本</param> /// <returns></returns> public static bool CompareVersion(string baseVer, string remoteVer) { try { string[] bv = baseVer.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string[] rv = remoteVer.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); bool revert = bv.Length >= rv.Length; string[] v1, v2; if (revert) { v1 = rv; v2 = bv; } else { v1 = bv; v2 = rv; } for (int i = 0; i < v1.Length; i++) { int digit1, digit2; digit1 = int.Parse(v1[i]); digit2 = int.Parse(v2[i]); if (digit1 != digit2) { return((digit2 > digit1) ^ revert); //revert变量决定结果翻转 } } // 当remote长度大于base时返回true return(!revert); } catch (Exception e) { Log4Net.WriteLog(e.Message, e); return(true); } }
/// <summary> /// 改变自启动状态 /// </summary> /// <param name="setOrUnset">设置/取消</param> /// <returns></returns> public static bool SetStartup(bool setOrUnset) { RegistryKey regPath = Registry.CurrentUser; string path = Application.ExecutablePath; RegistryKey regKey = regPath.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); try { //RegistryKey 为空 if (setOrUnset) { regKey?.SetValue(Application.ProductName, path); } else { regKey?.DeleteValue(Application.ProductName); } //if (setOrUnset) //{ // regKey.SetValue(Application.ProductName, path); //} //else //{ // regKey.DeleteValue(Application.ProductName); //} return(true); } //catch (NullReferenceException) //{ // // //} catch (Exception e) { Log4Net.WriteLog(e.Message, e); return(false); } }
/// <summary> /// 检测更新 /// </summary> /// <returns></returns> public static Updater.UpdateState TryUpdate() { string localVersion = GDUT_Drcom.Version; Log4Net.WriteLog($"开始更新{DllName},当前心跳包版本({localVersion})"); try { string RemoteFileUrl = Updater.CheckUpdate("https://tools.bigkeer.cn/", "drcom/heartbeat.json", "bigkeer", DllName, GDUT_Drcom.Version); if (RemoteFileUrl == "") { Log4Net.WriteLog("无需更新"); return(Updater.UpdateState.UpToDate); } if (RemoteFileUrl != null) { GDUT_Drcom.Unload(); if (Updater.DownloadFile(RemoteFileUrl, DllName)) { GDUT_Drcom.Load(); return(Updater.UpdateState.Updated); } else { GDUT_Drcom.Load(); } } RemoteFileUrl = Updater.CheckUpdate("chenhaowen01/gdut-drcom", DllName, GDUT_Drcom.Version); if (RemoteFileUrl == "") { Log4Net.WriteLog("无需更新"); return(Updater.UpdateState.UpToDate); } if (RemoteFileUrl != null) { GDUT_Drcom.Unload(); if (Updater.DownloadFile(RemoteFileUrl, DllName)) { GDUT_Drcom.Load(); return(Updater.UpdateState.Updated); } else { GDUT_Drcom.Load(); return(Updater.UpdateState.Failed); } } return(Updater.UpdateState.Failed); } catch (Exception e) { Log4Net.WriteLog(e.Message, e); return(Updater.UpdateState.Failed); } }
/// <summary> /// 发送运行统计 /// </summary> public static void SendAnalyze() { RestClient client = new RestClient("https://api2.bmob.cn"); //填充用户信息 AnalyzeData data = new AnalyzeData(); if (!DialerConfig.isFeedback) { data.Username = "******"; } else { MD5 md5 = new MD5CryptoServiceProvider(); byte[] mdResult = md5.ComputeHash(Encoding.Default.GetBytes(DialerConfig.username)); data.Username = ToHexString(mdResult, mdResult.Length); } data.CampusZone = (int)DialerConfig.zone; data.Version = Version.GetVersion(); try { //发送/更新用户信息 if (DialerConfig.guid == "") { RestRequest request = new RestRequest("/1/classes/analyze", Method.POST); //post request.AddHeader("X-Bmob-Application-Id", "6402f2d047a6728395bc8df1f918b340"); request.AddHeader("X-Bmob-REST-API-Key", "a0069d330057d662b7a1af4245e8f882"); request.AddJsonBody(data); IRestResponse <ObjId> objId = client.Execute <ObjId>(request); if (objId.ResponseStatus == ResponseStatus.Completed) { DialerConfig.guid = objId.Data.objectId; DialerConfig.SaveConfig(); } } else { //update RestRequest request = new RestRequest($"/1/classes/analyze/{DialerConfig.guid}", Method.PUT); request.AddHeader("X-Bmob-Application-Id", "6402f2d047a6728395bc8df1f918b340"); request.AddHeader("X-Bmob-REST-API-Key", "a0069d330057d662b7a1af4245e8f882"); request.AddHeader("Content-Type", "application/json"); request.AddJsonBody(data); IRestResponse <ObjId> response = client.Execute <ObjId>(request); if (response.ResponseStatus == ResponseStatus.Completed) { if (response.Data.code == 101) { DialerConfig.guid = ""; DialerConfig.SaveConfig(); SendAnalyze(); } } } } catch (Exception e) { Log4Net.WriteLog(e.Message, e); } }
/// <summary> /// 获取账户信息 /// </summary> /// <returns></returns> public static AccountInfomation GetAccountInfomation() { try { AccountInfomation acci = new AccountInfomation(); if (DialerConfig.username == "" || DialerConfig.password == "") { acci.Status = "用户名或密码为空"; return(acci); } //构造Cookie RestClient client = new RestClient("http://222.200.98.8:1800"); client.CookieContainer = new System.Net.CookieContainer(); client.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"; //获取认证码 RestRequest indexRequest = new RestRequest("/Self/nav_login"); IRestResponse indexResponse = client.Execute(indexRequest); Match match = Regex.Match(indexResponse.Content, @"var checkcode=""([0-9]*)"""); string code = match.Groups[1].Value; //拉取验证码 client.Execute(new RestRequest("Self/RandomCodeAction.action")); //构造认证包 RestRequest authRequest = new RestRequest("/Self/LoginAction.action", Method.POST); authRequest.AddParameter("account", DialerConfig.username); MD5 md5 = new MD5CryptoServiceProvider(); byte[] mdResult = md5.ComputeHash(Encoding.Default.GetBytes(DialerConfig.password)); authRequest.AddParameter("password", BmobAnalyze.ToHexString(mdResult, mdResult.Length)); authRequest.AddParameter("code", ""); authRequest.AddParameter("checkcode", code); authRequest.AddParameter("Submit", "登录"); //认证 IRestResponse authResponse = client.Execute(authRequest); if (authResponse.Content.Contains("登录密码不正确")) { acci.Status = "用户名或密码不正确"; return(acci); } if (authResponse.Content.Contains("账号为空请正确填写")) { acci.Status = "未知的登录错误"; return(acci); } //获取账户信息 RestRequest infoRequest = new RestRequest("Self/refreshaccount"); IRestResponse <accountInfomation> infoResponse = client.Execute <accountInfomation>(infoRequest); //转换数据格式 if (infoResponse.Data == null) { acci.Status = "未知的获取错误"; return(acci); } acci.Status = infoResponse.Data.date; acci.Username = infoResponse.Data.note.welcome; acci.Service = infoResponse.Data.note.service; acci.LeftMoney = infoResponse.Data.note.leftmoeny; match = Regex.Match(infoResponse.Data.note.overdate, @"([0-9]*)-([0-9]*)-([0-9]*)"); DateTime overDate = new DateTime( int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value)); acci.OverDate = overDate; return(acci); } catch (Exception e) { Log4Net.WriteLog(e.Message, e); AccountInfomation acci = new AccountInfomation(); acci.Status = "内部错误"; return(acci); } }