public static byte[] GetData(string url) { Uri URLCall = new Uri(url); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.Headers.Add("Accept", "text/html,text/xml,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); Client.Headers.Add("Accept-Language", "en-us,en;q=0.5"); Client.Headers.Add("Accept-Encoding", "gzip"); Client.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7"); Client.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); byte[] result = Client.DownloadData(URLCall); Client.Dispose(); return(result); }
private static bool RetrieveJSON(string JSONUrl, string Function) { Log.Checking("JSON LIST: Retriving " + JSONUrl); try { Uri URLCall = new Uri(JSONUrl); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { OnlineListJson = Client.DownloadString(URLCall); if (URLCall.OriginalString.Contains(URLs.Main)) { UnitedSC = APIStatus.Online; } else if (URLCall.OriginalString.Contains(URLs.Static)) { CarbonSC = APIStatus.Online; } else if (URLCall.OriginalString.Contains(URLs.Static_Alt)) { CarbonTwoSC = APIStatus.Online; } Log.UrlCall("JSON LIST: Retrieved " + JSONUrl); } catch (WebException Error) { APIStatus API_Status = APIChecker.StatusCodes(JSONUrl, Error, (HttpWebResponse)Error.Response); if (URLCall.OriginalString.Contains(URLs.Main)) { UnitedSC = API_Status; } else if (URLCall.OriginalString.Contains(URLs.Static)) { CarbonSC = API_Status; } else if (URLCall.OriginalString.Contains(URLs.Static_Alt)) { CarbonTwoSC = API_Status; } return(false); } catch (Exception Error) { LogToFileAddons.OpenLog("JSON LIST", null, Error, null, true); if (URLCall.OriginalString.Contains(URLs.Main)) { UnitedSC = APIStatus.Unknown; } else if (URLCall.OriginalString.Contains(URLs.Static)) { CarbonSC = APIStatus.Unknown; } else if (URLCall.OriginalString.Contains(URLs.Static_Alt)) { CarbonTwoSC = APIStatus.Unknown; } return(false); } finally { if (Client != null) { Client.Dispose(); } } if (IsJSONValid.ValidJson(OnlineListJson)) { switch (Function) { case "SL": ServerListUpdater.CachedJSONList = OnlineListJson; break; case "CDNL": CDNListUpdater.CachedJSONList = OnlineListJson; break; default: break; } Log.Completed("JSON LIST: Valid " + JSONUrl); return(true); } else { Log.Completed("JSON LIST: Invalid " + JSONUrl); return(false); } } catch { return(false); } finally { if (OnlineListJson != null) { OnlineListJson = null; } } }
private void SetVisuals() { /*******************************/ /* Set Font / * /*******************************/ FontFamily DejaVuSans = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf"); FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf"); var MainFontSize = 9f * 96f / CreateGraphics().DpiY; if (UnixOS.Detected()) { MainFontSize = 9f; } Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); ServerListRenderer.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); Loading.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); BtnAddServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnRemoveServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnSelectServer.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); BtnClose.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); Version.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); /********************************/ /* Set Theme Colors & Images / * /********************************/ ForeColor = Theming.WinFormTextForeColor; BackColor = Theming.WinFormTBGForeColor; Loading.ForeColor = Theming.WinFormWarningTextForeColor; Version.ForeColor = Theming.WinFormTextForeColor; ServerListRenderer.ForeColor = Theming.WinFormSecondaryTextForeColor; BtnAddServer.ForeColor = Theming.BlueForeColorButton; BtnAddServer.BackColor = Theming.BlueBackColorButton; BtnAddServer.FlatAppearance.BorderColor = Theming.BlueBorderColorButton; BtnAddServer.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton; BtnRemoveServer.ForeColor = CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton; BtnRemoveServer.BackColor = CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton; BtnRemoveServer.FlatAppearance.BorderColor = CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton; BtnRemoveServer.FlatAppearance.MouseOverBackColor = CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton; BtnSelectServer.ForeColor = !CustomServersOnly ? Theming.BlueForeColorButton : Theming.GrayForeColorButton; BtnSelectServer.BackColor = !CustomServersOnly ? Theming.BlueBackColorButton : Theming.GrayBackColorButton; BtnSelectServer.FlatAppearance.BorderColor = !CustomServersOnly ? Theming.BlueBorderColorButton : Theming.GrayBorderColorButton; BtnSelectServer.FlatAppearance.MouseOverBackColor = !CustomServersOnly ? Theming.BlueMouseOverBackColorButton : Theming.GrayMouseOverBackColorButton; BtnClose.ForeColor = Theming.BlueForeColorButton; BtnClose.BackColor = Theming.BlueBackColorButton; BtnClose.FlatAppearance.BorderColor = Theming.BlueBorderColorButton; BtnClose.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton; /********************************/ /* Functions / * /********************************/ Name = (CustomServersOnly ? "Saved Custom Servers" : "Please Select a Server") + " - SBRW Launcher"; ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { if (!CustomServersOnly) { SelectedGameServerToRemember(); } }); BtnSelectServer.Click += new EventHandler(BtnSelectServer_Click); BtnRemoveServer.Click += new EventHandler(BtnRemoveServer_Click); Version.Text = "Version: v" + Application.ProductVersion; /* And one for keeping data about server, IP tbh */ ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add(""); ServerListRenderer.Columns[0].Width = 1; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[1].Width = 210; ServerListRenderer.Columns.Add("Country"); ServerListRenderer.Columns[2].Width = 100; ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Online"); ServerListRenderer.Columns[3].Width = 75; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Registered"); ServerListRenderer.Columns[4].Width = 85; ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Center; ServerListRenderer.Columns.Add("Ping"); ServerListRenderer.Columns[5].Width = 60; ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Center; foreach (ServerList substring in CustomServersOnly ? ServerListUpdater.NoCategoryList_CSO : ServerListUpdater.NoCategoryList) { try { ServersToPing.Enqueue(ID + "_|||_" + substring.IPAddress + "_|||_" + substring.Name); ServerListRenderer.Items.Add(new ListViewItem( new[] { ID.ToString(), substring.Name, "", "", "", "", "" } )); ServerListBook.Add(ID, substring); ID++; } catch { } } Shown += (x, y) => { Application.OpenForms[this.Name].Activate(); this.BringToFront(); new Thread(() => { while (ServersToPing.Count != 0) { string QueueContent = ServersToPing.Dequeue(); string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None); int serverid = Convert.ToInt32(QueueContent2[0]) - 1; string serverurl = QueueContent2[1] + "/GetServerInformation"; ServerName = QueueContent2[2]; string ServerJson = null; try { try { Uri URLCall = new Uri(serverurl); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { ServerJson = Client.DownloadString(serverurl); } catch { } finally { if (Client != null) { Client.Dispose(); } } } catch { } if (string.IsNullOrWhiteSpace(ServerJson)) { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; }, this); } else if (!IsJSONValid.ValidJson(ServerJson)) { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[3].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[4].Text = "-?-"; ServerListRenderer.Items[serverid].SubItems[5].Text = "-?-"; }, this); } else { ServerJsonData = JsonConvert.DeserializeObject <GetServerInformation>(ServerJson); ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = (!string.IsNullOrWhiteSpace(ServerJsonData.serverName)) ? ServerJsonData.serverName : ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = ServerListUpdater.CountryName(ServerJsonData.country.ToString()); ServerListRenderer.Items[serverid].SubItems[3].Text = ServerJsonData.onlineNumber.ToString(); ServerListRenderer.Items[serverid].SubItems[4].Text = ServerJsonData.numberOfRegistered.ToString(); }, this); Ping CheckMate = null; try { Uri StringToUri = new Uri(serverurl); ServicePointManager.FindServicePoint(StringToUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; CheckMate = new Ping(); CheckMate.PingCompleted += (sender3, e3) => { if (e3.Reply != null) { if (e3.Reply.Status == IPStatus.Success && ServerName != "Offline Built-In Server") { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = e3.Reply.RoundtripTime + "ms"; }, this); } else { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "!?"; }, this); } } else { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "N/A"; }, this); } ((AutoResetEvent)e3.UserState).Set(); }; CheckMate.SendAsync(StringToUri.Host, 5000, new byte[1], new PingOptions(30, true), new AutoResetEvent(false)); } catch { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[5].Text = "?"; }, this); } finally { if (CheckMate != null) { CheckMate.Dispose(); } } } } catch { ServerListRenderer.SafeInvokeAction(() => { ServerListRenderer.Items[serverid].SubItems[1].Text = ServerName; ServerListRenderer.Items[serverid].SubItems[2].Text = "---"; ServerListRenderer.Items[serverid].SubItems[3].Text = "---"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; }, this); } finally { if (ServerJson != null) { ServerJson = null; } if (ServerJsonData != null) { ServerJsonData = null; } if (ServerName != null) { ServerName = null; } GC.Collect(); } Application.DoEvents(); } Loading.SafeInvokeAction(() => { Loading.Text = string.Empty; }, this); }).Start(); }; }
private void OkButton_Click(object sender, EventArgs e) { try { if (File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)))) { File.Move( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)), Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON))); } else if (!File.Exists( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)))) { try { File.WriteAllText( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)), "[]"); } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } } } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } Error.Visible = false; this.Refresh(); if (IsNullOrWhiteSpace(ServerAddress.Text) || IsNullOrWhiteSpace(Strings.Encode(ServerName.Text))) { if (IsNullOrWhiteSpace(ServerAddress.Text)) { Error.Text = "Fix Empty IP"; DrawErrorAroundTextBox(ServerAddress); } else { Error.Text = "Fix Empty Name"; DrawErrorAroundTextBox(ServerName); } Error.Visible = true; return; } if (Error.Visible) { Error.Visible = false; } bool CorrectFormat = Uri.TryCreate(ServerAddress.Text, UriKind.Absolute, out Uri Result) && (Result.Scheme == Uri.UriSchemeHttp || Result.Scheme == Uri.UriSchemeHttps); string FormattedURL; if (!CorrectFormat) { DrawErrorAroundTextBox(ServerAddress); return; } else { FormattedURL = Result.ToString(); } ButtonControls(false); try { string ServerInfomationJSON = Empty; try { Uri StringToUri = new Uri(FormattedURL + "/GetServerInformation"); ServicePointManager.FindServicePoint(StringToUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { ServerInfomationJSON = Client.DownloadString(StringToUri); } catch (Exception Error) { string LogMessage = "Add Server Check Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { string LogMessage = "Add Server Check Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } if (IsNullOrWhiteSpace(ServerInfomationJSON)) { ButtonControls(true); return; } else if (!IsJSONValid.ValidJson(ServerInfomationJSON)) { Error.Text = "Unstable Connection"; DrawErrorAroundTextBox(ServerAddress); Error.Visible = true; ButtonControls(true); ServerInfomationJSON = null; return; } else { GetServerInformation ServerInformationData = null; try { ServerInformationData = JsonConvert.DeserializeObject <GetServerInformation>(ServerInfomationJSON); } catch (Exception Error) { string LogMessage = "Add Server Get Information Encountered an Error:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); } if (ServerInformationData == null) { ButtonControls(true); ServerInfomationJSON = null; return; } else { string ServerID = Empty; Uri newModNetUri = new Uri(FormattedURL + "/Modding/GetModInfo"); ServicePointManager.FindServicePoint(newModNetUri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { GetModInfo ServerGetInfo = JsonConvert.DeserializeObject <GetModInfo>(Client.DownloadString(newModNetUri)); ServerID = IsNullOrWhiteSpace(ServerGetInfo.serverID) ? Result.Host : ServerGetInfo.serverID; } catch (Exception Error) { LogToFileAddons.OpenLog("Add Server", null, Error, null, true); ServerID = Result.Host; } finally { if (Client != null) { Client.Dispose(); } } try { StreamReader sr = new StreamReader(Locations.LauncherCustomServers); String oldcontent = sr.ReadToEnd(); sr.Close(); if (IsNullOrWhiteSpace(oldcontent)) { oldcontent = "[]"; } var Servers = JsonConvert.DeserializeObject <List <ServerList> >(oldcontent); Servers.Add(new ServerList { Name = Strings.Encode(ServerName.Text), IPAddress = FormattedURL, IsSpecial = false, ID = ServerID, Category = IsNullOrWhiteSpace(Strings.Encode(ServerCategory.Text)) ? "Custom" : Strings.Encode(ServerCategory.Text) }); File.WriteAllText(Locations.LauncherCustomServers, JsonConvert.SerializeObject(Servers)); MessageBox.Show(null, "The New server will be added on the next start of the Launcher.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception Error) { string LogMessage = "Failed to Add New Server:"; LogToFileAddons.OpenLog("Add Server", LogMessage, Error, null, false); ButtonControls(true); return; } finally { if (ServerID != null) { ServerID = null; } if (ServerInfomationJSON != null) { ServerInfomationJSON = null; } } CancelButton_Click(sender, e); } } } catch { DrawErrorAroundTextBox(ServerAddress); ButtonControls(true); } }
private void RegisterButton_Click(object sender, EventArgs e) { Refresh(); List <string> registerErrors = new List <string>(); if (string.IsNullOrWhiteSpace(RegisterEmail.Text)) { registerErrors.Add("Please enter your e-mail."); RegisterEmailBorder.Image = Theming.BorderEmailError; } else if (!IsEmailValid.Validate(RegisterEmail.Text)) { registerErrors.Add("Please enter a valid e-mail address."); RegisterEmailBorder.Image = Theming.BorderEmailError; } if (string.IsNullOrWhiteSpace(RegisterTicket.Text) && _ticketRequired) { registerErrors.Add("Please enter your ticket."); RegisterTicketBorder.Image = Theming.BorderTicketError; } if (string.IsNullOrWhiteSpace(RegisterPassword.Text)) { registerErrors.Add("Please enter your password."); RegisterPasswordBorder.Image = Theming.BorderPasswordError; } if (string.IsNullOrWhiteSpace(RegisterConfirmPassword.Text)) { registerErrors.Add("Please confirm your password."); RegisterConfirmPasswordBorder.Image = Theming.BorderPasswordError; } if (RegisterConfirmPassword.Text != RegisterPassword.Text) { registerErrors.Add("Passwords don't match."); RegisterConfirmPasswordBorder.Image = Theming.BorderPasswordError; } if (!RegisterAgree.Checked) { registerErrors.Add("You have not agreed to the Terms of Service."); RegisterAgree.ForeColor = Theming.Error; } if (registerErrors.Count == 0) { bool allowReg = false; String Email; String Password; switch (Authentication.HashType(InformationCache.SelectedServerJSON.authHash ?? string.Empty)) { case AuthHash.H10: Email = RegisterEmail.Text.ToString(); Password = RegisterPassword.Text.ToString(); break; case AuthHash.H11: Email = RegisterEmail.Text.ToString(); Password = MDFive.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H12: Email = RegisterEmail.Text.ToString(); Password = SHA.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H13: Email = RegisterEmail.Text.ToString(); Password = SHATwoFiveSix.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H20: Email = MDFive.Hashes(RegisterEmail.Text.ToString()).ToLower(); Password = MDFive.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H21: Email = SHA.Hashes(RegisterEmail.Text.ToString()).ToLower(); Password = SHA.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; case AuthHash.H22: Email = SHATwoFiveSix.Hashes(RegisterEmail.Text.ToString()).ToLower(); Password = SHATwoFiveSix.Hashes(RegisterPassword.Text.ToString()).ToLower(); break; default: Log.Error("HASH TYPE: Unknown Hash Standard was Provided"); return; } try { string[] regex = new Regex(@"([0-9A-Z]{5})([0-9A-Z]{35})").Split(Password.ToUpper()); Uri URLCall = new Uri("https://api.pwnedpasswords.com/range/" + regex[1]); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } String serverReply = null; try { serverReply = Client.DownloadString(URLCall); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("Register", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (!string.IsNullOrWhiteSpace(serverReply)) { String verify = regex[2]; string[] hashes = serverReply.Split('\n'); foreach (string hash in hashes) { var splitChecks = hash.Split(':'); if (splitChecks[0] == verify) { var passwordCheckReply = MessageBox.Show(null, "Password used for registration has been breached " + Convert.ToInt32(splitChecks[1]) + " times, you should consider using a different one.\n\nAlternatively you can use the unsafe password anyway." + "\nWould you like to continue to use it?", "GameLauncher", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (passwordCheckReply == DialogResult.Yes) { allowReg = true; } else { allowReg = false; } } else { allowReg = true; } } } else { allowReg = true; } } catch { allowReg = true; } if (allowReg) { Tokens.Clear(); Tokens.IPAddress = InformationCache.SelectedServerData.IPAddress; Tokens.ServerName = ServerListUpdater.ServerName("Register"); Authentication.Client("Register", InformationCache.SelectedServerJSON.modernAuthSupport, Email, Password, _ticketRequired ? RegisterTicket.Text : null); if (!String.IsNullOrWhiteSpace(Tokens.Success)) { DialogResult Success = MessageBox.Show(null, Tokens.Success, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Warning); if (Success == DialogResult.OK) { Close(); } } else { MessageBox.Show(null, Tokens.Error, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { var message = "There were some errors while registering. Please fix them:\n\n"; foreach (var error in registerErrors) { message += "• " + error + "\n"; } MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/// <summary> /// Form Url or Post Request to the Server for Login and Registration /// </summary> /// <remarks>Non Secure: Uses regualar URL Request. Secure: Uses Post Request</remarks> /// <returns>Receives UserId and Auth Key for Login. Sends Email and Password to Server</returns> /// <param name="ConnectionProtocol">Connection Protocol: Check AuthProtocol</param> /// <param name="Method">Form Type: "Login" or "Register"</param> public static void Client(string Method, bool Modern_Auth, String Email, String Password, String Token) { try { if (!Modern_Auth) { Uri URLCall = new Uri((Method == "Login") ? Tokens.IPAddress + "/User/authenticateUser?email=" + Email + "&password="******"/User/createUser?email=" + Email + "&password="******"&inviteTicket=" + Token : "")); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); Client.Headers["X-HWID"] = HardwareID.FingerPrint.Value(); Client.Headers["X-HiddenHWID"] = HardwareID.FingerPrint.ValueAlt(); Client.Headers["X-UserAgent"] = "GameLauncherReborn " + Application.ProductVersion + " WinForms (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"; Client.Headers["X-GameLauncherHash"] = WebHelpers.Value(); Client.Headers["X-GameLauncherCertificate"] = CertificateStore.LauncherSerial; Client.Headers["X-DiscordID"] = DiscordLauncherPresence.UserID; } try { if (Method == "Login") { LoginResponse = Client.DownloadString(URLCall); } else { LoginResponse = Client.DownloadString(URLCall); } } catch { throw; } finally { if (Client != null) { Client.Dispose(); } } } else { string ServerUrl = Tokens.IPAddress + "/User/modernAuth"; if (Method == "Register") { ServerUrl = Tokens.IPAddress + "/User/modernRegister"; } Uri SendRequest = new Uri(ServerUrl); ServicePointManager.FindServicePoint(SendRequest).ConnectionLeaseTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(SendRequest); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; httpWebRequest.Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { String JSON; if (Method == "Login") { JSON = new JavaScriptSerializer().Serialize(new { Email, Password, upgrade = true }); } else { JSON = new JavaScriptSerializer().Serialize(new { Email, Password, Ticket = Token }); } streamWriter.Write(JSON); } ServerResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var sr = new StreamReader(ServerResponse.GetResponseStream())) { ServerErrorCode = (int)ServerResponse.StatusCode; LoginResponse = sr.ReadToEnd(); } } } catch (WebException Error) { LogToFileAddons.OpenLog("CLIENT [LOGIN/REGISTER]", null, Error, null, true); ServerResponse = (HttpWebResponse)Error.Response; if (ServerResponse == null) { ServerErrorCode = 500; LoginResponse = Modern_Auth ? "{\"error\":\"Failed to get reply from server. Please retry.\"}" : "<LoginStatusVO><UserId>0</UserId><Description>Failed to get reply from server. Please retry.</Description></LoginStatusVO>"; } else { using (var sr = new StreamReader(ServerResponse.GetResponseStream())) { ServerErrorCode = (int)ServerResponse.StatusCode; ServerErrorResponse = Modern_Auth ? "{\"error\":\"" + ServerResponse.StatusDescription + "\"}" : null; LoginResponse = sr.ReadToEnd(); } } } if (!Modern_Auth) { if (string.IsNullOrWhiteSpace(LoginResponse)) { Tokens.Error = "Server Seems to be Offline."; } else { XmlDocument sbrwXml = new XmlDocument(); var msgBoxInfo = string.Empty; bool XMLIsErrorFree = true; try { if (EnableInsiderDeveloper.Allowed()) { Log.Info("Authentication: Received XML -> " + LoginResponse); } sbrwXml.LoadXml(LoginResponse); if (EnableInsiderDeveloper.Allowed()) { Log.Info("Authentication: Loaded XML -> " + sbrwXml.OuterXml); } } catch (Exception Error) { LogToFileAddons.OpenLog("XML LOGIN", null, Error, null, true); XMLIsErrorFree = false; msgBoxInfo = "An error occured: " + Error.Message; } if (XMLIsErrorFree == true) { if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO", "NodeOnly") == "VAILD NODE - LAUNCHER") { if (XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Ban", "InnerText") != "EMPTY VALUE - LAUNCHER") { if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Description", "NodeOnly") == "VAILD NODE - LAUNCHER") { msgBoxInfo += XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText"); } else { msgBoxInfo = string.Format("You got banned on {0}.", Tokens.ServerName) + "\n"; if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Ban/Reason", "NodeOnly") != "INVALID NODE - LAUNCHER") { msgBoxInfo += "Reason: " + XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Ban/Reason", "InnerText") + "\n"; } else { msgBoxInfo += "Reason: Unknown \n"; } if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Ban/Expires", "NodeOnly") != "INVALID NODE - LAUNCHER") { msgBoxInfo += "Ban Expires: " + XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Ban/Expires", "InnerText"); } else { msgBoxInfo += "Banned Forever"; } } } else if (XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/UserId", "InnerText") == "0") { if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Description", "NodeOnly") != "ERROR NODE - LAUNCHER" && XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText") != "EMPTY VALUE - LAUNCHER") { if (XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText") == "LOGIN ERROR") { msgBoxInfo += "Invalid E-mail or Password"; } else { msgBoxInfo += XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Description", "InnerText"); } } else { msgBoxInfo += "ERROR " + ServerErrorCode + ": " + XMLServerCore.NodeReader(sbrwXml, "InnerText", "html/body", "InnerText"); } } if (string.IsNullOrWhiteSpace(msgBoxInfo) || msgBoxInfo == "SERVER FULL") { if (Method == "Login" && string.IsNullOrWhiteSpace(msgBoxInfo)) { Tokens.UserId = XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/UserId", "InnerText"); Tokens.LoginToken = XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/LoginToken", "InnerText"); if (XMLServerCore.NodeReader(sbrwXml, "NodeOnly", "LoginStatusVO/Warning", null) == "VAILD NODE - LAUNCHER") { Tokens.Warning = XMLServerCore.NodeReader(sbrwXml, "InnerText", "LoginStatusVO/Warning", "InnerText"); } } else if (Method == "Register") { string MessageSuccess; string MessageServerWelcome = string.Empty; if (!string.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.messageSrv)) { if (InformationCache.SelectedServerJSON.messageSrv.ToLower().Contains("welcome")) { MessageServerWelcome = InformationCache.SelectedServerJSON.messageSrv + "\n"; } else { MessageServerWelcome = "Welcome: " + InformationCache.SelectedServerJSON.messageSrv + "\n"; } } if (msgBoxInfo == "SERVER FULL") { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. However, server is actually full, " + "therefore you cannot play it right now.", Tokens.ServerName); } else { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. You can log in now.", Tokens.ServerName); } Tokens.Success = MessageSuccess; } else { Tokens.Error = msgBoxInfo; } } else { Tokens.Error = msgBoxInfo; } } else { Log.Error("Authentication: Unable to Read XML File Due to the Node 'LoginStatusVO' having an Error"); Tokens.Error = "Unable to Read XML File Due to the Node 'LoginStatusVO' having an Error\nERROR NODE - LAUNCHER"; } } else { Log.Error("Authentication: Unable to Read XML File -> " + msgBoxInfo); Tokens.Error = msgBoxInfo; } } } else { if (String.IsNullOrWhiteSpace(LoginResponse)) { Tokens.Error = "Server seems to be offline."; } else { ModernAuthObject ServerObjectResponse; try { ServerObjectResponse = JsonConvert.DeserializeObject <ModernAuthObject>(LoginResponse); } catch { ServerObjectResponse = JsonConvert.DeserializeObject <ModernAuthObject>(ServerErrorResponse); } if (String.IsNullOrWhiteSpace(ServerObjectResponse.Error) || ServerObjectResponse.Error == "SERVER FULL") { if (Method == "Login") { Tokens.UserId = ServerObjectResponse.UserId; Tokens.LoginToken = ServerObjectResponse.Token; if (!String.IsNullOrWhiteSpace(ServerObjectResponse.Warning)) { Tokens.Warning = ServerObjectResponse.Warning; } } else if (Method == "Register") { string MessageSuccess; string MessageServerWelcome = string.Empty; if (!string.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.messageSrv)) { if (InformationCache.SelectedServerJSON.messageSrv.ToLower().Contains("welcome")) { MessageServerWelcome = InformationCache.SelectedServerJSON.messageSrv + "\n"; } else { MessageServerWelcome = "Welcome: " + InformationCache.SelectedServerJSON.messageSrv + "\n"; } } if (ServerObjectResponse.Error == "SERVER FULL") { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. However, server is actually full, " + "therefore you cannot play it right now.", Tokens.ServerName); } else { MessageSuccess = string.Format(MessageServerWelcome + "Successfully registered on {0}. You can log in now.", Tokens.ServerName); } Tokens.Success = MessageSuccess; } } else { Tokens.Error = ServerObjectResponse.Error; } } } }
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs args) { try { if (WebCalls.Alternative()) { using (WebClient webClient = new WebClient()) { webClient.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadManager_DownloadDataCompleted); webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); while (true) { if (this._freeChunks <= 0) { Thread.Sleep(100); } else { lock (this._downloadQueue) { if (this._downloadQueue.Count == 0) { lock (this._workers) { this._workers.Remove((BackgroundWorker)sender); } DownloaderHandler._workerCount--; break; } } string value = null; lock (this._downloadQueue) { value = this._downloadQueue.Last.Value; this._downloadQueue.RemoveLast(); lock (this._freeChunksLock) { this._freeChunks--; } } lock (this._downloadList[value]) { if (this._downloadList[value].Status != DownloaderHandler.DownloadStatus.Canceled) { this._downloadList[value].Status = DownloaderHandler.DownloadStatus.Downloading; } } while (webClient.IsBusy) { Thread.Sleep(100); } webClient.DownloadDataAsync(new Uri(value), value); DownloaderHandler.DownloadStatus status = DownloaderHandler.DownloadStatus.Downloading; while (status == DownloaderHandler.DownloadStatus.Downloading) { status = this._downloadList[value].Status; if (status == DownloaderHandler.DownloadStatus.Canceled) { break; } Thread.Sleep(100); } if (status == DownloaderHandler.DownloadStatus.Canceled) { webClient.CancelAsync(); } lock (this._workers) { if (DownloaderHandler._workerCount > this._maxWorkers || !this._managerRunning) { this._workers.Remove((BackgroundWorker)sender); DownloaderHandler._workerCount--; break; } } } } } } else { using (WebClientWithTimeout webClient = new WebClientWithTimeout()) { webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.DownloadManager_DownloadDataCompleted); webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); while (true) { if (this._freeChunks <= 0) { Thread.Sleep(100); } else { lock (this._downloadQueue) { if (this._downloadQueue.Count == 0) { lock (this._workers) { this._workers.Remove((BackgroundWorker)sender); } DownloaderHandler._workerCount--; break; } } string value = null; lock (this._downloadQueue) { value = this._downloadQueue.Last.Value; this._downloadQueue.RemoveLast(); lock (this._freeChunksLock) { this._freeChunks--; } } lock (this._downloadList[value]) { if (this._downloadList[value].Status != DownloaderHandler.DownloadStatus.Canceled) { this._downloadList[value].Status = DownloaderHandler.DownloadStatus.Downloading; } } while (webClient.IsBusy) { Thread.Sleep(100); } webClient.DownloadDataAsync(new Uri(value), value); DownloaderHandler.DownloadStatus status = DownloaderHandler.DownloadStatus.Downloading; while (status == DownloaderHandler.DownloadStatus.Downloading) { status = this._downloadList[value].Status; if (status == DownloaderHandler.DownloadStatus.Canceled) { break; } Thread.Sleep(100); } if (status == DownloaderHandler.DownloadStatus.Canceled) { webClient.CancelAsync(); } lock (this._workers) { if (DownloaderHandler._workerCount > this._maxWorkers || !this._managerRunning) { this._workers.Remove((BackgroundWorker)sender); DownloaderHandler._workerCount--; break; } } } } } } } catch (Exception Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER [Background Work DH]", null, Error, null, true); Exception exception = Error; lock (this._workers) { this._workers.Remove((BackgroundWorker)sender); DownloaderHandler._workerCount--; } } }
private void CorruptedFilesFound() { DiscordLauncherPresence.Status("Verify Bad", null); /* START Show Redownloader Progress*/ StartScanner.SafeInvokeAction(() => StartScanner.Visible = false); StopScanner.SafeInvokeAction(() => StopScanner.Visible = true); VerifyHashText.SafeInvokeAction(() => VerifyHashText.Text = "Currently (re)downloading files\nThis part may take awhile\ndepending on your connection."); if (File.Exists("invalidfiles.dat") && File.ReadAllLines("invalidfiles.dat") != null) { DownloadProgressText.SafeInvokeAction(() => DownloadProgressText.Text = "\nPreparing to Download Files"); string[] files = File.ReadAllLines("invalidfiles.dat"); foreach (string text in files) { if (!ForceStopScan) { try { while (StillDownloading) { } if (!ForceStopScan) { currentCount = files.Count(); string text2 = FileSettingsSave.GameInstallation + text; string address = FinalCDNURL + "/unpacked" + text.Replace("\\", "/"); if (File.Exists(text2)) { try { LogVerify.Deleted("File: " + text2); File.Delete(text2); } catch (Exception Error) { LogVerify.Error("File: " + text2 + " Error: " + Error.Message); LogVerify.ErrorIC("File: " + text2 + " Error: " + Error.HResult); LogVerify.ErrorFR("File: " + text2 + " Error: " + Error.ToString()); } } try { if (!new FileInfo(text2).Directory.Exists) { new FileInfo(text2).Directory.Create(); } } catch (Exception Error) { LogToFileAddons.OpenLog("VERIFY HASH File Info", null, Error, null, true); } Uri URLCall = new Uri(address); int Timeout = (int)TimeSpan.FromMinutes(5).TotalMilliseconds; if (address.Contains("copspeechdat")) { Timeout = (int)TimeSpan.FromMinutes(30).TotalMilliseconds; } else if (address.Contains("nfs09mx.mus")) { Timeout = (int)TimeSpan.FromMinutes(15).TotalMilliseconds; } ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = Timeout; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.DownloadProgressChanged += (Systems, RecevingData) => { if (RecevingData.TotalBytesToReceive >= 1 && !ForceStopScan) { DownloadProgressText.SafeInvokeAction(() => DownloadProgressText.Text = "Downloading File [ " + redownloadedCount + " / " + currentCount + " ]:\n" + CurrentDownloadingFile + "\n" + TimeConversions.FormatFileSize(RecevingData.BytesReceived) + " of " + TimeConversions.FormatFileSize(RecevingData.TotalBytesToReceive)); } else if (ForceStopScan) { Client.CancelAsync(); } }; Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted); try { Client.DownloadFileAsync(URLCall, text2); CurrentDownloadingFile = text; StillDownloading = true; } catch (Exception Error) { if (!ForceStopScan) { redownloadErrorCount++; } LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } else { break; } } catch (Exception Error) { if (!ForceStopScan) { redownloadErrorCount++; } LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true); } finally { if (IsVerifyHashOpen) { Application.DoEvents(); GC.Collect(); } } } else { break; } } } }
public static void Check() { if (!UnixOS.Detected()) { Log.Checking("REDISTRIBUTABLE: Is Installed or Not"); DiscordLauncherPresence.Status("Start Up", "Checking Redistributable Package Visual Code 2015 to 2019"); if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x86)) { if (MessageBox.Show(Translations.Database("Redistributable_VC_32") + "\n\n" + Translations.Database("Redistributable_VC_P2") + "\n\n" + Translations.Database("Redistributable_VC_P3") + "\n\n" + Translations.Database("Redistributable_VC_P4"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { try { Uri URLCall = new Uri("https://aka.ms/vs/16/release/VC_redist.x86.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { Client.DownloadFile(URLCall, "VC_redist.x86.exe"); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE", null, Error, null, true); } if (File.Exists("VC_redist.x86.exe")) { try { var proc = Process.Start(new ProcessStartInfo { Verb = "runas", Arguments = "/quiet", FileName = "VC_redist.x86.exe" }); proc.WaitForExit((int)TimeSpan.FromMinutes(10).TotalMilliseconds); if (proc == null) { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P6"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (proc != null) { if (!proc.HasExited) { if (proc.Responding) { proc.CloseMainWindow(); } else { proc.Kill(); ErrorFree = false; } } if (proc.ExitCode != 0) { ErrorFree = false; Log.Error("REDISTRIBUTABLE INSTALLER [EXIT CODE]: " + proc.ExitCode.ToString() + " HEX: (0x" + proc.ExitCode.ToString("X") + ")"); MessageBox.Show(Translations.Database("Redistributable_VC_P7") + " " + proc.ExitCode.ToString() + " (0x" + proc.ExitCode.ToString("X") + ")" + "\n" + Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } proc.Close(); } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE x86 Process", null, Error, null, true); ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P9"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P10"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Log.Info("REDISTRIBUTABLE: 32-bit 2015-2019 VC++ Redistributable Package is Installed"); } if (Environment.Is64BitOperatingSystem) { if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x64)) { if (MessageBox.Show(Translations.Database("Redistributable_VC_64") + "\n\n" + Translations.Database("Redistributable_VC_P2") + "\n\n" + Translations.Database("Redistributable_VC_P3") + "\n\n" + Translations.Database("Redistributable_VC_P4"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { try { Uri URLCall = new Uri("https://aka.ms/vs/16/release/VC_redist.x64.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { Client.DownloadFile(URLCall, "VC_redist.x64.exe"); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE x64", null, Error, null, true); } if (File.Exists("VC_redist.x64.exe")) { try { var proc = Process.Start(new ProcessStartInfo { Verb = "runas", Arguments = "/quiet", FileName = "VC_redist.x64.exe" }); proc.WaitForExit((int)TimeSpan.FromMinutes(10).TotalMilliseconds); if (proc == null) { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P6"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (proc != null) { if (!proc.HasExited) { if (proc.Responding) { proc.CloseMainWindow(); } else { proc.Kill(); ErrorFree = false; } } if (proc.ExitCode != 0) { ErrorFree = false; Log.Error("REDISTRIBUTABLE INSTALLER [EXIT CODE]: " + proc.ExitCode.ToString() + " HEX: (0x" + proc.ExitCode.ToString("X") + ")"); MessageBox.Show(Translations.Database("Redistributable_VC_P7") + " " + proc.ExitCode.ToString() + " (0x" + proc.ExitCode.ToString("X") + ")" + "\n" + Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } proc.Close(); } } catch (Exception Error) { LogToFileAddons.OpenLog("REDISTRIBUTABLE x64 Process", null, Error, null, true); ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P9"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P10"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { ErrorFree = false; MessageBox.Show(Translations.Database("Redistributable_VC_P8"), Translations.Database("Redistributable_VC_P5"), MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Log.Info("REDISTRIBUTABLE: 64-bit 2015-2019 VC++ Redistributable Package is Installed"); } } Log.Completed("REDISTRIBUTABLE: Done"); } Log.Info("ID: Moved to Function"); /* (Start Process) */ HardwareID.FingerPrint.Get(); }
/* Check If Updater Exists or Requires an Update */ public static void Check() { Log.Checking("LAUNCHER UPDATER: Is Version Up to Date or not"); DiscordLauncherPresence.Status("Start Up", "Checking Launcher and Updater Release Information"); /* Update this text file if a new GameLauncherUpdater.exe has been delployed - DavidCarbon */ try { bool IsGithubOnline = false; Uri URLCall = new Uri(URLs.GitHub_Updater); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { VersionJSON = Client.DownloadString(URLCall); IsGithubOnline = true; } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } bool IsJsonValid = false; try { if (IsJSONValid.ValidJson(VersionJSON) && IsGithubOnline) { GitHubRelease GHAPI = JsonConvert.DeserializeObject <GitHubRelease>(VersionJSON); if (GHAPI.TagName != null) { Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GHAPI.TagName); LatestUpdaterBuildVersion = GHAPI.TagName; IsJsonValid = true; } Log.Info("LAUNCHER UPDATER: Latest Version -> " + LatestUpdaterBuildVersion); if (GHAPI != null) { GHAPI = null; } } else { Log.Warning("LAUNCHER UPDATER: Received Invalid JSON Data"); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER", null, Error, null, true); } if (!IsGithubOnline || !IsJsonValid) { Log.Info("LAUNCHER UPDATER: Fail Safe Latest Version -> " + LatestUpdaterBuildVersion); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER", null, Error, null, true); } finally { if (VersionJSON != null) { VersionJSON = null; } } /* Check if File needs to be Downloaded or Require an Update */ string UpdaterPath = Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameUpdater)); if (!File.Exists(UpdaterPath)) { Log.Info("LAUNCHER UPDATER: Starting GameLauncherUpdater downloader"); try { Uri URLCall = new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (File.Exists(UpdaterPath)) { try { if (new FileInfo(UpdaterPath).Length == 0) { File.Delete(UpdaterPath); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE Error #1]", null, Error, null, true); } } }; try { Client.DownloadFile(URLCall, UpdaterPath); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE DL #1]", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [!FileExists]", null, Error, null, true); } } else if (File.Exists(UpdaterPath)) { try { var LauncherUpdaterBuild = FileVersionInfo.GetVersionInfo(UpdaterPath); var LauncherUpdaterBuildNumber = LauncherUpdaterBuild.FileVersion; var UpdaterBuildNumberResult = LauncherUpdaterBuildNumber.CompareTo(LatestUpdaterBuildVersion); Log.Build("LAUNCHER UPDATER BUILD: GameLauncherUpdater " + LauncherUpdaterBuildNumber); if (UpdaterBuildNumberResult < 0) { Log.Info("LAUNCHER UPDATER: " + UpdaterBuildNumberResult + " Builds behind latest Updater!"); } else { Log.Info("LAUNCHER UPDATER: Latest GameLauncherUpdater!"); } if (UpdaterBuildNumberResult < 0) { Log.Info("LAUNCHER UPDATER: Downloading New " + Locations.NameUpdater); File.Delete(Locations.NameUpdater); Uri URLCall = new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (File.Exists(UpdaterPath)) { try { if (new FileInfo(UpdaterPath).Length == 0) { File.Delete(UpdaterPath); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE Error #2]", null, Error, null, true); } } }; try { Client.DownloadFile(URLCall, Locations.NameUpdater); } catch (WebException Error) { APIChecker.StatusCodes( "https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe", Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [EXE DL #2]", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATER [FileExists]", null, Error, null, true); } } Log.Completed("LAUNCHER UPDATER: Done"); Log.Info("LAUNCHER UPDATE: Moved to Function"); /* (Start Process) Check Latest Launcher Version */ LauncherUpdateCheck.Latest(); }
private void Verify(object parameters) { string[] array = (string[])parameters; string str = array[0].Trim(); string text = array[1].Trim(); if (!string.IsNullOrWhiteSpace(text)) { str = str + "/" + text; } string text2 = array[2].Trim(); bool flag = bool.Parse(array[3]); bool flag2 = bool.Parse(array[4]); bool flag3 = bool.Parse(array[5]); bool flag4 = false; try { XmlDocument indexFile = this.GetIndexFile(str + "/index.xml", false); if (indexFile == null) { ISynchronizeInvoke arg_B9_0 = this.mFE; Delegate arg_B9_1 = this.mDownloadFailed; object[] args = new object[1]; arg_B9_0.BeginInvoke(arg_B9_1, args); } else { long num = long.Parse(indexFile.SelectSingleNode("/index/header/length").InnerText); var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.Headers.Add("Accept", "text/html,text/xml,application/xhtml+xml,application/xml,application/*,*/*;q=0.9,*/*;q=0.8"); Client.Headers.Add("Accept-Language", "en-us,en;q=0.5"); Client.Headers.Add("Accept-Encoding", "gzip,deflate"); Client.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); XmlNodeList xmlNodeList = indexFile.SelectNodes("/index/fileinfo"); DownloaderHashReader.Instance.Clear(); DownloaderHashReader.Instance.Start(indexFile, text2, text + ".hsh", this.mHashThreads); long num2 = 0L; ulong num3 = 0uL; ulong num4 = 0uL; foreach (XmlNode xmlNode in xmlNodeList) { string text3 = xmlNode.SelectSingleNode("path").InnerText; string innerText = xmlNode.SelectSingleNode("file").InnerText; if (!string.IsNullOrWhiteSpace(text2)) { int num5 = text3.IndexOf("/"); if (num5 >= 0) { text3 = text3.Replace(text3.Substring(0, num5), text2); } else { text3 = text2; } } string text4 = text3 + "/" + innerText; int num6 = int.Parse(xmlNode.SelectSingleNode("length").InnerText); if (xmlNode.SelectSingleNode("hash") != null) { if (!DownloaderHashReader.Instance.HashesMatch(text4)) { num3 += ulong.Parse(xmlNode.SelectSingleNode("length").InnerText); ulong num7; if (xmlNode.SelectSingleNode("compressed") != null) { num7 = ulong.Parse(xmlNode.SelectSingleNode("compressed").InnerText); } else { num7 = ulong.Parse(xmlNode.SelectSingleNode("length").InnerText); } num4 += num7; if (flag) { this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { }); return; } flag4 = true; } } else { if (flag) { throw new DownloaderException("Without hash in the metadata I cannot verify the download"); } flag4 = true; } if (Downloader.mStopFlag) { ISynchronizeInvoke arg_367_0 = this.mFE; Delegate arg_367_1 = this.mDownloadFailed; object[] args2 = new object[1]; arg_367_0.BeginInvoke(arg_367_1, args2); return; } num2 += (long)num6; object[] args3 = new object[] { num, num2, 0, innerText, 0 }; this.mFE.BeginInvoke(this.mProgressUpdated, args3); } if (flag3) { DownloaderHashReader.Instance.WriteHashCache(text + ".hsh", true); } if (flag4) { this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { }); } else { this.mFE.BeginInvoke(this.mDownloadFinished, null); } } } catch (DownloaderException Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER", null, Error, null, true); this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { Error }); } catch (Exception Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER", null, Error, null, true); this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { Error }); } finally { if (flag2) { DownloaderHashReader.Instance.Clear(); } GC.Collect(); } }
private void Download(object parameters) { this.mDownloading = true; string[] array = (string[])parameters; string text = array[0]; string text2 = array[1]; if (!string.IsNullOrWhiteSpace(text2)) { text = text + "/" + text2; } string text3 = array[2]; bool flag = bool.Parse(array[3]); bool useCache = bool.Parse(array[4]); ulong num = ulong.Parse(array[5]); byte[] array2; XmlNodeList xmlNodeList; try { XmlDocument indexFile = this.GetIndexFile(text + "/index.xml", useCache); if (indexFile == null) { ISynchronizeInvoke arg_AE_0 = this.mFE; Delegate arg_AE_1 = this.mDownloadFailed; object[] args = new object[1]; arg_AE_0.BeginInvoke(arg_AE_1, args); } else { long num2 = long.Parse(indexFile.SelectSingleNode("/index/header/length").InnerText); long num3 = 0L; long num4; if (num == 0uL) { num4 = long.Parse(indexFile.SelectSingleNode("/index/header/compressed").InnerText); } else { num4 = (long)num; } long num5 = 0L; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.Headers.Add("Accept", "text/html,text/xml,application/xhtml+xml,application/xml,application/*,*/*;q=0.9,*/*;q=0.8"); Client.Headers.Add("Accept-Language", "en-us,en;q=0.5"); Client.Headers.Add("Accept-Encoding", "gzip,deflate"); Client.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); int num6 = 1; array2 = null; xmlNodeList = indexFile.SelectNodes("/index/fileinfo"); this.mDownloadManager.Initialize(indexFile, text); if (flag) { DownloaderHashReader.Instance.Clear(); DownloaderHashReader.Instance.Start(indexFile, text3, text2 + ".hsh", this.mHashThreads); } int num7 = 0; List <string> list = new List <string>(); int i = 0; bool flag2 = false; int num11; long fileschecked = 0; foreach (XmlNode xmlNode in xmlNodeList) { XmlNodeList xmlNodeList2 = xmlNode.SelectNodes("compressed"); int num8; if (xmlNodeList2.Count == 0) { num8 = int.Parse(xmlNode.SelectNodes("length")[0].InnerText); } else { num8 = int.Parse(xmlNodeList2[0].InnerText); } num7 = ((num8 > num7) ? num8 : num7); string text4 = xmlNode.SelectSingleNode("path").InnerText; if (!string.IsNullOrWhiteSpace(text3)) { int num9 = text4.IndexOf("/"); if (num9 >= 0) { text4 = text4.Replace(text4.Substring(0, num9), text3); } else { text4 = text3; } } string innerText = xmlNode.SelectSingleNode("file").InnerText; string fileName = text4 + "/" + innerText; int num10 = int.Parse(xmlNode.SelectSingleNode("section").InnerText); num11 = int.Parse(xmlNode.SelectSingleNode("offset").InnerText); if (flag) { if (list.Count == 0) { i = num10; } while (i <= num10) { list.Insert(0, string.Format("{0}/section{1}.dat", text, i)); i++; } } else if (!DownloaderHashReader.Instance.HashesMatch(fileName)) { if (i <= num10) { if (list.Count == 0) { i = num10; } while (i <= num10) { list.Insert(0, string.Format("{0}/section{1}.dat", text, i)); i++; } } flag2 = true; } else { if (flag2) { int num12 = num10; if (num11 == 0) { num12--; } while (i <= num12) { list.Insert(0, string.Format("{0}/section{1}.dat", text, i)); i++; } } if (i < num10) { i = num10; } flag2 = false; } } foreach (string current in list) { this.mDownloadManager.ScheduleFile(current); } list.Clear(); list = null; num11 = 0; this.mDownloadManager.Start(); byte[] array3 = new byte[num7]; byte[] array4 = new byte[13]; int num13 = 0; foreach (XmlNode xmlNode2 in xmlNodeList) { if (Downloader.mStopFlag) { break; } string text5 = xmlNode2.SelectSingleNode("path").InnerText; string innerText2 = xmlNode2.SelectSingleNode("file").InnerText; if (!string.IsNullOrWhiteSpace(text3)) { int num14 = text5.IndexOf("/"); if (num14 >= 0) { text5 = text5.Replace(text5.Substring(0, num14), text3); } else { text5 = text3; } } string text6 = text5 + "/" + innerText2; int num15 = int.Parse(xmlNode2.SelectSingleNode("length").InnerText); int num16 = 0; XmlNode xmlNode3 = xmlNode2.SelectSingleNode("compressed"); if (xmlNode2.SelectSingleNode("section") != null && num6 < int.Parse(xmlNode2.SelectSingleNode("section").InnerText)) { num6 = int.Parse(xmlNode2.SelectSingleNode("section").InnerText); } string text7 = null; if (xmlNode2.SelectSingleNode("hash") != null && DownloaderHashReader.Instance.HashesMatch(text6)) { num16 += num15; if (xmlNode3 != null) { if (num == 0uL) { num3 += (long)int.Parse(xmlNode3.InnerText); } num5 += (long)int.Parse(xmlNode3.InnerText); num11 += int.Parse(xmlNode3.InnerText); } else { if (num == 0uL) { num3 += (long)num15; } num5 += (long)num15; num11 += num15; } if (this.mProgressUpdated != null) { object[] args2 = new object[] { num2, num3, num4, text6, 0 }; this.mFE.Invoke(this.mProgressUpdated, args2); } int num17 = int.Parse(xmlNode2.SelectSingleNode("section").InnerText); if (num13 != num17) { for (int j = num13 + 1; j < num17; j++) { this.mDownloadManager.CancelDownload(string.Format("{0}/section{1}.dat", text, j)); } num13 = num17 - 1; } } else { Directory.CreateDirectory(text5); FileStream fileStream = File.Create(text6); int num18 = num15; if (xmlNode3 != null) { num18 = int.Parse(xmlNode3.InnerText); } int k = 0; bool flag3 = false; int num19 = 13; while (k < num18) { if (array2 == null || num11 >= array2.Length) { if (xmlNode2.SelectSingleNode("offset") != null && !flag3) { num11 = int.Parse(xmlNode2.SelectSingleNode("offset").InnerText); } else { num11 = 0; } text7 = string.Format("{0}/section{1}.dat", text, num6); for (int l = num13 + 1; l < num6; l++) { this.mDownloadManager.CancelDownload(string.Format("{0}/section{1}.dat", text, l)); } array2 = null; GC.Collect(); array2 = this.mDownloadManager.GetFile(text7); if (array2 == null) { if (this.mDownloadFailed != null) { if (!Downloader.mStopFlag) { this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { new Exception("DownloadManager returned a null buffer") }); } else { ISynchronizeInvoke arg_887_0 = this.mFE; Delegate arg_887_1 = this.mDownloadFailed; object[] args = new object[1]; arg_887_0.BeginInvoke(arg_887_1, args); } } return; } num13 = num6; num5 += (long)array2.Length; num6++; if (!this.mDownloadManager.GetStatus(string.Format("{0}/section{1}.dat", text, num6)).HasValue&& num5 < num4) { this.mDownloadManager.ScheduleFile(string.Format("{0}/section{1}.dat", text, num6)); } } else { if (num18 - k > array2.Length - num11) { text7 = string.Format("{0}/section{1}.dat", text, num6); this.mDownloadManager.ScheduleFile(text7); flag3 = true; } int num20 = Math.Min(array2.Length - num11, num18 - k); if (num19 != 0) { if (xmlNode3 != null) { int num21 = Math.Min(num19, num20); Buffer.BlockCopy(array2, num11, array4, 13 - num19, num21); Buffer.BlockCopy(array2, num11 + num21, array3, 0, num20 - num21); num19 -= num21; } else { Buffer.BlockCopy(array2, num11, array3, 0, num20); num19 = 0; } } else { Buffer.BlockCopy(array2, num11, array3, k - ((xmlNode3 != null) ? 13 : 0), num20); } num11 += num20; k += num20; num3 += (long)num20; } if (this.mProgressUpdated != null) { try { object[] args3 = new object[] { num2, num3, num4, text6, 0 }; this.mFE.BeginInvoke(this.mProgressUpdated, args3); } catch { } } } if (xmlNode3 != null) { if (!Downloader.IsLzma(array4)) { MessageBox.Show("Compression algorithm not recognized" + text7); throw new DownloaderException("Compression algorithm not recognized: " + text7); } fileStream.Close(); fileStream.Dispose(); IntPtr outPropsSize = new IntPtr(5); byte[] array5 = new byte[5]; for (int m = 0; m < 5; m++) { array5[m] = array4[m]; } long num22 = 0L; for (int n = 0; n < 8; n++) { num22 += (long)((long)array4[n + 5] << 8 * n); } if (num22 != (long)num15) { MessageBox.Show("Compression data length in header '" + num22 + "' != than in metadata '" + num15 + "'"); throw new DownloaderException("Compression data length in header '" + num22 + "' != than in metadata '" + num15 + "'"); } int num23 = num18; num18 -= 13; IntPtr intPtr = new IntPtr(num18); IntPtr value = new IntPtr(num22); int num24 = LZMA.LzmaUncompressBuf2File(text6, ref value, array3, ref intPtr, array5, outPropsSize); /* TODO: use total file lenght and extracted file length instead of files checked and total array size. */ fileschecked = +num3; try { object[] xxxxxx = new object[] { text6, fileschecked, num4 }; this.mFE.BeginInvoke(this.mShowExtract, xxxxxx); } catch { } if (num24 != 0) { MessageBox.Show("Decompression returned " + num24); throw new UncompressionException(num24, "Decompression returned " + num24); } if (value.ToInt32() != num15) { MessageBox.Show("Decompression returned different size '" + value.ToInt32() + "' than metadata '" + num15 + "'"); throw new DownloaderException("Decompression returned different size '" + value.ToInt32() + "' than metadata '" + num15 + "'"); } num16 += (int)value; } else { fileStream.Write(array3, 0, num15); num16 += num15; } if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } } if (!Downloader.mStopFlag) { DownloaderHashReader.Instance.WriteHashCache(text2 + ".hsh", false); } if (Downloader.mStopFlag) { if (this.mDownloadFailed != null) { ISynchronizeInvoke arg_D16_0 = this.mFE; Delegate arg_D16_1 = this.mDownloadFailed; object[] args = new object[1]; arg_D16_0.BeginInvoke(arg_D16_1, args); } } else if (this.mDownloadFinished != null) { this.mFE.BeginInvoke(this.mDownloadFinished, null); } } } catch (DownloaderException Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER", null, Error, null, true); if (this.mDownloadFailed != null) { try { this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { Error }); } catch { } } } catch (Exception Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER", null, Error, null, true); if (this.mDownloadFailed != null) { try { this.mFE.BeginInvoke(this.mDownloadFailed, new object[] { Error }); } catch { } } } finally { if (flag) { DownloaderHashReader.Instance.Clear(); } this.mDownloadManager.Clear(); GC.Collect(); this.mDownloading = false; } }
private XmlDocument GetIndexFile(string url, bool useCache) { XmlDocument result; try { if (useCache && Downloader.mIndexCached != null) { result = Downloader.mIndexCached; } else { Uri URLCall = new Uri(url); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient(); if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout(); } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } Client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.Downloader_DownloadFileCompleted); try { string tempFileName = Strings.Encode(Path.GetTempFileName()); Client.DownloadFileAsync(URLCall, tempFileName); while (Client.IsBusy) { if (Downloader.mStopFlag) { Client.CancelAsync(); result = null; return(result); } Thread.Sleep(100); } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(tempFileName); Downloader.mIndexCached = xmlDocument; result = xmlDocument; } catch (Exception Error) { LogToFileAddons.OpenLog("CDN Get Index File", null, Error, null, true); result = null; } finally { if (Client != null) { Client.Dispose(); } } } } catch (Exception Error) { LogToFileAddons.OpenLog("CDN DOWNLOADER", null, Error, null, true); result = null; } return(result); }
public static void Latest() { Log.Checking("LAUNCHER UPDATE: Is Version Up to Date or not"); DiscordLauncherPresence.Status("Start Up", "Checking Latest Launcher Release Information"); try { Uri URLCall = new Uri((EnableInsiderBetaTester.Allowed() || EnableInsiderDeveloper.Allowed()) ? URLs.GitHub_Launcher_Beta : URLs.GitHub_Launcher_Stable); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { VersionJSON = Client.DownloadString(URLCall); VisualsAPIChecker.GitHubAPI = true; } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATE [GITHUB]", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (IsJSONValid.ValidJson(VersionJSON) && VisualsAPIChecker.GitHubAPI) { LatestLauncherBuild = (EnableInsiderDeveloper.Allowed() || EnableInsiderBetaTester.Allowed()) ? JsonConvert.DeserializeObject <List <GitHubRelease> >(VersionJSON)[0].TagName : JsonConvert.DeserializeObject <GitHubRelease>(VersionJSON).TagName; Log.Info("LAUNCHER UPDATE: GitHub Latest Version -> " + LatestLauncherBuild); ValidJSONDownload = true; } else { Log.Error("LAUNCHER UPDATE: Failed to retrieve Latest Build information from GitHub"); ValidJSONDownload = false; } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATE [GITHUB]", null, Error, null, true); } Log.Completed("LAUNCHER UPDATE: Done"); if (!UpdateStatusResult()) { Log.Info("FIRST TIME RUN: Moved to Function"); /* Do First Time Run Checks */ FunctionStatus.FirstTimeRun(); } else { if (DiscordLauncherPresence.Running()) { DiscordLauncherPresence.Stop("Close"); } if (ServerProxy.Running()) { ServerProxy.Instance.Stop("Force Close"); } Application.Exit(); } }
/* Retrieve CA Information */ /// <summary> /// Retrieves the Root CA JSON file with the latest details of the Certificate /// </summary> /// <remarks>Sets the Certificate Details For Launcher Comparison</remarks> public static void Latest() { if (!UnixOS.Detected()) { Log.Checking("CERTIFICATE STORE: Is Installed or Not"); DiscordLauncherPresence.Status("Start Up", "Checking Root Certificate Authority"); try { Uri URLCall = new Uri("http://crl.carboncrew.org/RCA-Info.json"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { /* Download Up to Date Certificate Status */ RootCAJson = Client.DownloadString(URLCall); } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (IsJSONValid.ValidJson(RootCAJson)) { JsonRootCA API = JsonConvert.DeserializeObject <JsonRootCA>(RootCAJson); if (API.CN != null) { Log.Info("CERTIFICATE STORE: Setting Common Name -> " + API.CN); RootCACommonName = API.CN; } if (API.Subject != null) { Log.Info("CERTIFICATE STORE: Setting Subject Name -> " + API.Subject); RootCASubjectName = API.Subject; } if (API.Ids != null) { foreach (IdsModel entries in API.Ids) { if (entries.Serial != null) { Log.Info("CERTIFICATE STORE: Setting Serial Number -> " + entries.Serial); RootCASerial = entries.Serial; } } } if (API.File != null) { foreach (FileModel entries in API.File) { if (entries.Name != null) { Log.Info("CERTIFICATE STORE: Setting Root CA File Name -> " + entries.Name); RootCAFileName = entries.Name; } if (entries.Cer != null) { Log.Info("CERTIFICATE STORE: Setting Root CA File URL -> " + entries.Cer); RootCAFileURL = entries.Cer; } } } if (API != null) { API = null; } } else { Log.Warning("CERTIFICATE STORE: Received Invalid JSON Data"); } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } finally { if (RootCAJson != null) { RootCAJson = null; } } /* Install Custom Root Certificate (If Default Values aren't used) */ if (RootCASerial != "7449A8EB07C997A6") { try { X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); var certificatesThumbPrint = store.Certificates.Find(X509FindType.FindByThumbprint, RootCASerial, false); for (int i = 0; i < store.Certificates.Count; i++) { if (store.Certificates[i].SerialNumber == RootCASerial) { Log.Info("CERTIFICATE STORE: Found Root CA [" + store.Certificates[i].Subject + "]"); Log.Info("CERTIFICATE STORE: Serial Number [" + store.Certificates[i].SerialNumber + "]"); IsROOTCAInstalled = true; } else if (store.Certificates[i].SerialNumber != RootCASerial && store.Certificates[i].Subject == RootCASubjectName) { Log.Info("CERTIFICATE STORE: Removing OLD Root CA [" + store.Certificates[i].Subject + "]"); Log.Info("CERTIFICATE STORE: Serial Number [" + store.Certificates[i].SerialNumber + "]"); store.Remove(store.Certificates[i]); } } store.Close(); store.Dispose(); } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } string CertSaveLocation = Strings.Encode(Path.Combine(Locations.LauncherFolder, RootCAFileName + ".cer")); try { if (!IsROOTCAInstalled) { Uri URLCall = new Uri(RootCAFileURL); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { /* Download Up to Date Certificate Status */ Client.DownloadFile(URLCall, CertSaveLocation); } catch (WebException Error) { APIChecker.StatusCodes(RootCAFileURL, Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (File.Exists(CertSaveLocation)) { X509Store Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); Store.Open(OpenFlags.ReadWrite); X509Certificate2Collection collection = new X509Certificate2Collection(); X509Certificate2 cert = new X509Certificate2(CertSaveLocation); byte[] encodedCert = cert.GetRawCertData(); Log.Info("CERTIFICATE STORE: We are now installing [" + RootCACommonName + "] certificate into the Trusted Root Certificate store ..."); Store.Add(cert); Log.Info("CERTIFICATE STORE: Done! [" + RootCACommonName + "] certificate was installed successfully."); Store.Close(); Store.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } try { if (File.Exists(CertSaveLocation)) { Log.Info("CERTIFICATE STORE: Removed [" + RootCACommonName + "] certificate from launcher folder."); File.Delete(CertSaveLocation); } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true); } } else { Log.Warning("CERTIFICATE STORE: Default Information was detected. Not running additional Function Calls"); } Log.Completed("CERTIFICATE STORE: Done"); } Log.Checking("CERTIFICATE CHECK: Is Signed or Not"); try { X509Certificate certificate = null; try { Assembly assembly = Assembly.LoadFrom(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameLauncher))); Module module = assembly.GetModules().First(); certificate = module.GetSignerCertificate(); if (certificate != null) { LauncherSerial = certificate.GetSerialNumberString(); } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE CHECK", null, Error, null, true); } finally { if (certificate != null) { certificate.Dispose(); } } } catch (Exception Error) { LogToFileAddons.OpenLog("CERTIFICATE CHECK", null, Error, null, true); } Log.Completed("CERTIFICATE CHECK: Done"); Log.Info("VERIFIED: Moved to Function"); /* (Start Process) Check if Launcher Is Signed or Not */ IsExeVerified.Check(); }
public static void DisableChecks(bool CompletedEvent) { cheats_detected = Get_Cheat_Status(); if (cheats_detected != 0) { if (cheats_detected == 64 && !CompletedEvent) { /* You Know the Rules and So Do I */ } else { if (ServerProxy.Running()) { foreach (string report_url in URLs.AntiCheatFD) { if (Completed == 0) { Completed++; FunctionStatus.ExternalToolsWasUsed = true; } if (report_url.EndsWith("?")) { try { Uri sendReport = new Uri(report_url + "serverip=" + serverip + "&user_id=" + user_id + "&persona_name=" + persona_name + "&event_session=" + event_id + "&cheat_type=" + cheats_detected + "&hwid=" + HardwareID.FingerPrint.Value() + "&persona_id=" + persona_id + "&launcher_hash=" + WebHelpers.Value() + "&launcher_certificate=" + CertificateStore.LauncherSerial + "&hwid_fallback=" + HardwareID.FingerPrint.ValueAlt() + "&car_used=" + DiscordGamePresence.PersonaCarName + "&os_platform=" + InformationCache.OSName + "&event_status=" + CompletedEvent); ServicePointManager.FindServicePoint(sendReport).ConnectionLeaseTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " - (" + InsiderInfo.BuildNumberOnly() + ")"); } Client.DownloadStringCompleted += (Nice, Brock) => { Client.Dispose(); }; try { string NTVersion = WindowsProductVersion.GetWindowsBuildNumber() != 0 ? WindowsProductVersion.GetWindowsBuildNumber().ToString() : "Wine"; Client.Headers.Add("os-version", NTVersion); Client.DownloadStringAsync(sendReport); } catch { } } catch { } } else { try { Uri sendReport = new Uri(report_url); ServicePointManager.FindServicePoint(sendReport).ConnectionLeaseTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; var request = (HttpWebRequest)WebRequest.Create(sendReport); var postData = "serverip=" + serverip + "&user_id=" + user_id + "&persona_name=" + persona_name + "&event_session=" + event_id + "&cheat_type=" + cheats_detected + "&hwid=" + HardwareID.FingerPrint.Value() + "&persona_id=" + persona_id + "&launcher_hash=" + WebHelpers.Value() + "&launcher_certificate=" + CertificateStore.LauncherSerial + "&hwid_fallback=" + HardwareID.FingerPrint.ValueAlt() + "&car_used=" + DiscordGamePresence.PersonaCarName + "&os_platform=" + InformationCache.OSName + "&event_status=" + CompletedEvent; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; request.Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); String responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); } catch { } } } } else { if (Completed != URLs.AntiCheatSD.Length) { foreach (string report_url in URLs.AntiCheatSD) { Completed++; if (report_url.EndsWith("?")) { try { Uri sendReport = new Uri(report_url + "serverip=" + serverip + "&user_id=" + user_id + "&cheat_type=" + cheats_detected + "&hwid=" + HardwareID.FingerPrint.Value() + "&launcher_hash=" + WebHelpers.Value() + "&launcher_certificate=" + CertificateStore.LauncherSerial + "&hwid_fallback=" + HardwareID.FingerPrint.ValueAlt() + "&os_platform=" + InformationCache.OSName); ServicePointManager.FindServicePoint(sendReport).ConnectionLeaseTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " - (" + InsiderInfo.BuildNumberOnly() + ")"); } Client.DownloadStringCompleted += (Nice, Brock) => { Client.Dispose(); }; try { string NTVersion = WindowsProductVersion.GetWindowsBuildNumber() != 0 ? WindowsProductVersion.GetWindowsBuildNumber().ToString() : "Wine"; Client.Headers.Add("os-version", NTVersion); Client.DownloadStringAsync(sendReport); } catch { } } catch { } } } } } TimeConversions.MUFRTime(); } } detect_MULTIHACK = detect_FAST_POWERUPS = detect_SPEEDHACK = detect_SMOOTH_WALLS = detect_TANK_MODE = detect_WALLHACK = detect_DRIFTMOD = detect_PURSUITBOT = false; cheats_detected = 0; Secret.Abort(); }
private void StartGameScanner() { DiscordLauncherPresence.Status("Verify Scan", null); Log.Info("VERIFY HASH: Checking and Deleting '.orig' Files and Symbolic Folders"); ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Removing any '.orig' Files in Game Directory"); /* START Show Warning Text */ VerifyHashText.SafeInvokeAction(() => { VerifyHashText.ForeColor = Theming.WinFormWarningTextForeColor; VerifyHashText.Text = "Warning:\nIf '.orig' Files Exist\nIt will be Removed Permanently"; }); /* END Show Warning Text */ try { DirectoryInfo InstallationDirectory = new DirectoryInfo(FileSettingsSave.GameInstallation); foreach (DirectoryInfo FoldersWeFound in InstallationDirectory.GetDirectories()) { if (!ForceStopScan) { foreach (FileInfo FoundFile in InstallationDirectory.EnumerateFiles("*.orig", SearchOption.AllDirectories)) { if (!ForceStopScan) { try { FoundFile.Delete(); LogVerify.Deleted("File: " + FoundFile.Name); } catch (Exception Error) { DeletionError++; LogVerify.Error("File: " + FoundFile.Name + " Error: " + Error.Message); LogVerify.ErrorIC("File: " + FoundFile.Name + " Error: " + Error.HResult); LogVerify.ErrorFR("File: " + FoundFile.Name + " Error: " + Error.ToString()); } } else { break; } } foreach (FileInfo FoundFile in FoldersWeFound.EnumerateFiles("*.orig", SearchOption.AllDirectories)) { if (!ForceStopScan) { try { FoundFile.Delete(); LogVerify.Deleted("File: " + FoundFile.Name); } catch (Exception Error) { DeletionError++; LogVerify.Error("File: " + FoundFile.Name + " Error: " + Error.Message); LogVerify.ErrorIC("File: " + FoundFile.Name + " Error: " + Error.HResult); LogVerify.ErrorFR("File: " + FoundFile.Name + " Error: " + Error.ToString()); } } else { break; } } foreach (DirectoryInfo FoundDirectory in InstallationDirectory.EnumerateDirectories()) { if (!ForceStopScan) { if (ModNetHandler.IsSymbolic(FoundDirectory.FullName)) { if (Directory.Exists(FoundDirectory.FullName)) { try { Directory.Delete(FoundDirectory.FullName, true); LogVerify.Deleted("Folder: " + FoundDirectory.Name); } catch (Exception Error) { DeletionError++; LogVerify.Error("Folder: " + FoundDirectory.Name + " Error: " + Error.Message); LogVerify.ErrorIC("Folder: " + FoundDirectory.Name + " Error: " + Error.HResult); LogVerify.ErrorFR("Folder: " + FoundDirectory.Name + " Error: " + Error.ToString()); } } else if (File.Exists(FoundDirectory.FullName)) { try { File.Delete(FoundDirectory.FullName); LogVerify.Deleted("File: " + FoundDirectory.Name); } catch (Exception Error) { DeletionError++; LogVerify.Error("File: " + FoundDirectory.Name + " Error: " + Error.Message); LogVerify.ErrorIC("File: " + FoundDirectory.Name + " Error: " + Error.HResult); LogVerify.ErrorFR("File: " + FoundDirectory.Name + " Error: " + Error.ToString()); } } } } else { break; } } foreach (DirectoryInfo FoundDirectory in FoldersWeFound.EnumerateDirectories()) { if (!ForceStopScan) { if (ModNetHandler.IsSymbolic(FoundDirectory.FullName)) { if (Directory.Exists(FoundDirectory.FullName)) { try { Directory.Delete(FoundDirectory.FullName, true); LogVerify.Deleted("Folder: " + FoundDirectory.Name); } catch (Exception Error) { DeletionError++; LogVerify.Error("Folder: " + FoundDirectory.Name + " Error: " + Error.Message); LogVerify.ErrorIC("Folder: " + FoundDirectory.Name + " Error: " + Error.HResult); LogVerify.ErrorFR("Folder: " + FoundDirectory.Name + " Error: " + Error.ToString()); } } else if (File.Exists(FoundDirectory.FullName)) { try { File.Delete(FoundDirectory.FullName); LogVerify.Deleted("File: " + FoundDirectory.Name); } catch (Exception Error) { DeletionError++; LogVerify.Error("File: " + FoundDirectory.Name + " Error: " + Error.Message); LogVerify.ErrorIC("File: " + FoundDirectory.Name + " Error: " + Error.HResult); LogVerify.ErrorFR("File: " + FoundDirectory.Name + " Error: " + Error.ToString()); } } } } else { break; } } } else { break; } } if (Directory.Exists(Path.Combine(FileSettingsSave.GameInstallation, "scripts")) && !ForceStopScan) { DirectoryInfo ScriptsFolder = new DirectoryInfo(Path.Combine(FileSettingsSave.GameInstallation, "scripts")); if (ScriptsFolder.EnumerateFiles().Count() > 1) { if (MessageBox.Show("Verify Hash has found files in the Scripts folder.\n" + "If you have installed custom Scripts or have not installed any Scripts" + "\n\nClick Yes, to Allow Deletion of Files" + "\nClick No, to Skip Deletion of Files", "VerifyHash", MessageBoxButtons.YesNo) == DialogResult.Yes) { foreach (FileInfo FoundFile in ScriptsFolder.EnumerateFiles()) { if (FoundFile.Name != "LangPicker.ini") { try { File.Delete(FoundFile.FullName); LogVerify.Deleted("File: " + FoundFile.Name); } catch (Exception Error) { DeletionError++; LogVerify.Error("File: " + FoundFile.Name + " Error: " + Error.Message); LogVerify.ErrorIC("File: " + FoundFile.Name + " Error: " + Error.HResult); LogVerify.ErrorFR("File: " + FoundFile.Name + " Error: " + Error.ToString()); } } } } } } } catch (Exception Error) { LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true); } if (DeletionError != 0) { Log.Info("VERIFY HASH: Completed check for '.orig' Files and Symbolic Folders, BUT Encounterd a File or Folder Deletion Error. " + "Check Verify.log for More Details"); if (MessageBox.Show("Verify Hash has encountered File or Folder Deletion Errors.\n" + "Would you like to Open Verify.Log and Stop the Scanner?", "VerifyHash", MessageBoxButtons.YesNo) == DialogResult.Yes) { string LogFile = Strings.Encode(Locations.LogVerify); if (File.Exists(LogFile)) { Process.Start(LogFile); } StopScanner_Click(null, null); } } else { Log.Info("VERIFY HASH: Completed check for '.orig' Files and Symbolic Folders"); } if (!ForceStopScan) { try { FunctionStatus.IsVerifyHashDisabled = true; String[] getFilesToCheck = { }; if (File.Exists("checksums.dat") && EnableInsiderDeveloper.Allowed()) { /* Read Local checksums.dat */ getFilesToCheck = File.ReadAllLines("checksums.dat"); } else { /* Fetch and Read Remote checksums.dat */ ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Downloading Checksums File"); Uri URLCall = new Uri(FinalCDNURL + "/unpacked/checksums.dat"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } bool ErrorFree = true; try { getFilesToCheck = Client.DownloadString(URLCall).Split('\n'); } catch (Exception Error) { LogToFileAddons.OpenLog("VERIFY HASH CHECKSUMS", "Downloading of the Checksums File has Encountered an Error", Error, "Error", false); ErrorFree = false; } finally { if (Client != null) { Client.Dispose(); } } if (ErrorFree) { File.WriteAllLines("checksums.dat", getFilesToCheck); } else { StopScanner_Click(null, null); } } scannedHashes = new string[getFilesToCheck.Length][]; for (var i = 0; i < getFilesToCheck.Length; i++) { if (!ForceStopScan) { scannedHashes[i] = getFilesToCheck[i].Split(' '); } else { break; } } filesToScan = scannedHashes.Length; totalFilesScanned = 0; /* START Show Warning Text */ VerifyHashText.SafeInvokeAction(() => { VerifyHashText.ForeColor = Theming.WinFormWarningTextForeColor; VerifyHashText.Text = "Warning:\n Stopping the Scan before it is complete\nWill result in needing to start over!"; }); /* END Show Warning Text */ foreach (string[] file in scannedHashes) { if (!ForceStopScan) { String FileHash = file[0].Trim(); String FileName = file[1].Trim(); String RealPathToFile = FileSettingsSave.GameInstallation + FileName; if (!File.Exists(RealPathToFile)) { InvalidFileList.Add(FileName); LogVerify.Missing("File: " + FileName); } else { if (FileHash != SHA.Files(RealPathToFile).Trim()) { InvalidFileList.Add(FileName); LogVerify.Invalid("File: " + FileName); } else { LogVerify.Valid("File: " + FileName); } } totalFilesScanned++; ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Scanning Files: " + (totalFilesScanned * 100 / getFilesToCheck.Length) + "%"); ScanProgressBar.SafeInvokeAction(() => ScanProgressBar.Value = totalFilesScanned * 100 / getFilesToCheck.Length); } else { break; } } Log.Info("VERIFY HASH: Scan Completed"); if (!InvalidFileList.Any() || ForceStopScan) { StartScanner.SafeInvokeAction(() => StartScanner.Visible = false); StopScanner.SafeInvokeAction(() => StopScanner.Visible = false); ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = ForceStopScan ? "User Stopped Scan." : "Scan Complete. No Files Missing or Invalid!"); /* Hide the DownloadProgressBar as un-needed */ DownloadProgressBar.SafeInvokeAction(() => DownloadProgressBar.Visible = false); DownloadProgressText.SafeInvokeAction(() => DownloadProgressText.Visible = false); /* Update the player messaging that we're done */ VerifyHashText.SafeInvokeAction(() => { if (!ForceStopScan) { VerifyHashText.ForeColor = Theming.WinFormSuccessTextForeColor; } VerifyHashText.Text = ForceStopScan ? "Verify Hash Scan Process has been Terminated" : "Excellent News! There are ZERO\nmissing or invalid Gamefiles!"; }); Integrity(); GameScanner(false); } else { ScanProgressText.SafeInvokeAction(() => ScanProgressText.Text = "Found Invalid or Missing Files"); File.WriteAllLines("invalidfiles.dat", InvalidFileList); Log.Info("VERIFY HASH: Found Invalid or Missing Files and will Start File Downloader"); CorruptedFilesFound(); } } catch (Exception Error) { LogToFileAddons.OpenLog("VERIFY HASH", null, Error, null, true); } } }