public UpdateSystem(IPolicyConfiguration configuration, IPCServer server, string platformId) { m_platformPaths = PlatformTypes.New <IPathProvider>(); m_systemServices = PlatformTypes.New <ISystemServices>(); m_ipcServer = server; m_policyConfiguration = configuration; m_platformId = platformId; var bitVersionUri = string.Empty; if (Environment.Is64BitProcess) { bitVersionUri = "/update/cv4w-x64/update.xml"; } else { bitVersionUri = "/update/cv4w-x86/update.xml"; } var appUpdateInfoUrl = string.Format("{0}{1}", WebServiceUtil.Default.ServiceProviderApiPath, bitVersionUri); m_updater = new AppcastUpdater(new Uri(appUpdateInfoUrl)); m_logger = LoggerUtil.GetAppWideLogger(); }
/// <summary> /// Constructs a new named pipe server for IPC, with a channel name derived from the class /// namespace and the current machine's digital fingerprint. /// </summary> public IPCServer() { m_logger = LoggerUtil.GetAppWideLogger(); var channel = string.Format("{0}.{1}", nameof(Citadel.IPC), FingerprintService.Default.Value2).ToLower(); m_server = PlatformTypes.New <IPipeServer>(channel); //m_server = new NamedPipeServer<BaseMessage>(channel, security); m_server.ClientConnected += OnClientConnected; m_server.ClientDisconnected += OnClientDisconnected; m_server.ClientMessage += OnClientMessage; m_server.Error += M_server_Error; // Server is no longer started by constructor. We start the IPCServer after everything else has been set up by the FilterServiceProvider. m_ipcQueue = new IPCMessageTracker(this); m_callbacks.Add(typeof(AddSelfModerationEntryMessage), (msg) => { AddSelfModerationEntry?.Invoke(msg as AddSelfModerationEntryMessage); }); m_callbacks.Add(typeof(IpcMessage), (msg) => { // The new IPC message Request/Send API handles HandleIpcMessage(msg); }); }
public void Save() { lock (appSettingsLock) { string json = null; try { json = JsonConvert.SerializeObject(this); } catch (Exception ex) { LoggerUtil.GetAppWideLogger().Error(ex, "Failed to convert object to JSON."); return; } try { IPathProvider paths = PlatformTypes.New <IPathProvider>(); string settingsPath = paths.GetPath(@"app.settings"); using (StreamWriter writer = new StreamWriter(File.Open(settingsPath, FileMode.Create))) { writer.Write(json); } } catch (Exception ex) { LoggerUtil.GetAppWideLogger().Error(ex, "Failed to save app settings."); } } }
public IPCClient(bool autoReconnect = false) { logger = LoggerUtil.GetAppWideLogger(); ipcQueue = new IPCMessageTracker(this); var channel = string.Format("{0}.{1}", nameof(Citadel.IPC), FingerprintService.Default.Value2).ToLower(); client = PlatformTypes.New <IPipeClient>(channel, autoReconnect); // new NamedPipeClient<BaseMessage>(channel); logger.Info("Process {0} creating client", Process.GetCurrentProcess().Id); client.Connected += OnConnected; client.Disconnected += OnDisconnected; client.ServerMessage += OnServerMessage; client.AutoReconnect = autoReconnect; client.Error += clientError; client.Start(); m_callbacks.Add(typeof(IpcMessage), (msg) => { HandleIpcMessage(msg as IpcMessage); }); }
public SocketPipeServer() { paths = PlatformTypes.New <IPathProvider>(); logger = LoggerUtil.GetAppWideLogger(); isStopped = false; connectedClients = new List <ClientRepresentation>(); }
/// <summary> /// Private ctor since we're cheezy and use a singleton. /// </summary> private NetworkStatus() { m_nListUtil = PlatformTypes.New <INetworkInfo>(); m_nListUtil.ConnectionStateChanged += () => { ConnectionStateChanged?.Invoke(); }; }
public CaptivePortalHelper() { try { m_wifiManager = PlatformTypes.New <IWifiManager>(); } catch (Exception ex) { LoggerUtil.GetAppWideLogger().Error(ex, "Failed to initialize WIFI Manager."); } }
private void OnExtension(CommonFilterServiceProvider provider) { IPCServer server = provider.IPCServer; IPathProvider paths = PlatformTypes.New <IPathProvider>(); Task.Run(async() => { ConnectivityCheck.Accessible accessible = ConnectivityCheck.Accessible.Yes; try { List <ConflictReason> conflicts = ConflictDetection.SearchConflictReason(); server.Send <List <ConflictReason> >(IpcCall.ConflictsDetected, conflicts); IFilterAgent agent = PlatformTypes.New <IFilterAgent>(); accessible = agent.CheckConnectivity(); } catch (Exception ex) { m_logger.Error(ex, "Failed to check connectivity."); } try { WindowsDiverter diverter = new WindowsDiverter(14301, 14301, 14301, 14301); diverter.ConfirmDenyFirewallAccess = this.OnAppFirewallCheck; diverter.Start(1, () => { m_logger.Info("Diverter was started successfully."); IFilterAgent agent = PlatformTypes.New <IFilterAgent>(); ConnectivityCheck.Accessible afterDiverter = agent.CheckConnectivity(); if (accessible == ConnectivityCheck.Accessible.Yes && afterDiverter != ConnectivityCheck.Accessible.Yes) { server.Send <bool>(IpcCall.InternetAccessible, false); } else { server.Send <bool>(IpcCall.InternetAccessible, true); } }); } catch (Exception ex) { m_logger.Error($"Error occurred while starting the diverter."); LoggerUtil.RecursivelyLogException(m_logger, ex); } }); }
static DefaultPolicyConfiguration() { #if LOCAL_POLICY_CONFIGURATION serverConfigFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "CloudVeil", "server-cfg.json"); serverListDataFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "CloudVeil", "server-a.dat"); #endif s_paths = PlatformTypes.New <IPathProvider>(); configFilePath = Path.Combine(s_paths.ApplicationDataFolder, "cfg.json"); listDataFilePath = Path.Combine(s_paths.ApplicationDataFolder, "a.dat"); // Setup json serialization settings. s_configSerializerSettings = new JsonSerializerSettings(); s_configSerializerSettings.NullValueHandling = NullValueHandling.Ignore; }
public void InitializeIcon(List <StatusIconMenuItem> menuItems) { if (trayIcon != null) { trayIcon.Visible = false; trayIcon.Dispose(); trayIcon = null; } trayIcon = new System.Windows.Forms.NotifyIcon(); guiServices = PlatformTypes.New <IGuiServices>(); var iconPackUri = new Uri("pack://application:,,,/Resources/appicon.ico"); var resourceStream = System.Windows.Application.GetResourceStream(iconPackUri); trayIcon.Icon = new System.Drawing.Icon(resourceStream.Stream); trayIcon.DoubleClick += delegate(object sender, EventArgs args) { guiServices.BringAppToFront(); }; trayIcon.BalloonTipClosed += delegate(object sender, EventArgs args) { trayIcon.Visible = true; }; var windowsMenuItems = new List <System.Windows.Forms.MenuItem>(); foreach (var item in menuItems) { if (item.IsSeparator) { windowsMenuItems.Add(new MenuItem("-")); } else { windowsMenuItems.Add(new MenuItem(item.ItemName, item.OnTriggered)); } } trayIcon.ContextMenu = new ContextMenu(windowsMenuItems.ToArray()); trayIcon.Visible = true; }
public IProxyServer StartProxyServer(ProxyConfiguration config) { CommonProxyServer server = new CommonProxyServer(); var paths = PlatformTypes.New <IPathProvider>(); string certPath = paths.GetPath(@"rootCertificate.pem"); string keyPath = paths.GetPath(@"rootPrivateKey.pem"); BCCertificateMaker certMaker = new BCCertificateMaker(); AsymmetricCipherKeyPair pair = BCCertificateMaker.CreateKeyPair(2048); using (StreamWriter writer = new StreamWriter(new FileStream(keyPath, FileMode.Create, FileAccess.Write))) { BCCertificateMaker.ExportPrivateKey(pair.Private, writer); } X509Certificate2 cert = certMaker.MakeCertificate(config.AuthorityName, true, null, pair); using (StreamWriter writer = new StreamWriter(new FileStream(certPath, FileMode.Create, FileAccess.Write))) { BCCertificateMaker.ExportDotNetCertificate(cert, writer); } trustRootCertificate(cert); rootCert = cert; server.Init(14300, 14301, certPath, keyPath); server.BeforeRequest += config.BeforeRequest; server.BeforeResponse += config.BeforeResponse; server.Blacklisted += config.Blacklisted; server.Whitelisted += config.Whitelisted; server.Start(); OnStartProxy?.Invoke(this, new EventArgs()); return(server); }
public static AppSettings Load() { lock (appSettingsLock) { IPathProvider paths = PlatformTypes.New <IPathProvider>(); string settingsPath = paths.GetPath(@"app.settings"); if (!File.Exists(settingsPath)) { return(new AppSettings()); } using (StreamReader reader = File.OpenText(settingsPath)) { string json = reader.ReadToEnd(); AppSettings loaded = JsonConvert.DeserializeObject <AppSettings>(json); return(loaded ?? new AppSettings()); } } }
private void beginInstallUpdateExe(ApplicationUpdate update, bool restartApplication = true) { if (!File.Exists(update.UpdateFileLocalPath)) { throw new Exception("Target update installer does not exist at the expected location."); } var systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System); var email = PlatformTypes.New <IAuthenticationStorage>().UserEmail; var fingerPrint = FingerprintService.Default.Value; var userId = email + ":" + fingerPrint; string filename, args; if (restartApplication) { string executingProcess = Process.GetCurrentProcess().MainModule.FileName; filename = update.UpdateFileLocalPath; args = $"\"{filename}\" /upgrade /passive /waitforexit /userid={userId}"; // The /waitforexit argument makes sure FilterServiceProvider.exe is stopped before displaying its UI. } else { filename = update.UpdateFileLocalPath; args = $"\"{filename}\" /upgrade /passive /waitforexit /userid={userId}"; } try { logger.Info("Starting update process " + filename + " " + args); if (!ProcessCreation.CreateElevatedProcessInCurrentSession(filename, args)) { logger.Error($"Failed to create elevated process with {System.Runtime.InteropServices.Marshal.GetLastWin32Error()}"); } } catch (Exception ex) { logger.Error(ex); } }
public ApplicationUpdate(DateTime datePublished, string title, string htmlBody, Version currentVersion, Version updateVersion, Uri downloadLink, UpdateKind kind, string updaterArguments, bool isRestartRequired) { paths = PlatformTypes.New <IPathProvider>(); DatePublished = datePublished; Title = title = title != null ? title : string.Empty; HtmlBody = htmlBody = htmlBody != null ? htmlBody : string.Empty; CurrentVersion = currentVersion; UpdateVersion = updateVersion; DownloadLink = downloadLink; Kind = kind; UpdaterArguments = updaterArguments != null ? updaterArguments : string.Empty; IsRestartRequired = isRestartRequired; var targetDir = Path.Combine(paths.ApplicationDataFolder, "updates"); if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } // XXX TODO - Problems on non-windows plats? Do we care? UpdateFileLocalPath = Path.Combine(targetDir, Path.GetFileName(DownloadLink.LocalPath)); }
/// <summary> /// Begins the external installation after a N second delay specified. /// </summary> /// <param name="secondDelay"> /// The number of seconds to wait before starting the actual update. /// </param> /// <exception cref="Exception"> /// If the file designated at UpdateFileLocalPath does not exist at the time of this call, /// this method will throw. /// </exception> public void BeginInstallUpdate(bool restartApplication = true) => PlatformTypes.New <IFilterUpdater>().BeginInstallUpdate(this, restartApplication);
/// <summary> /// Request a generic resource from the service server(s). /// </summary> /// <param name="route"> /// The API route to make the request to. /// </param> /// <param name="responseReceived"> /// Gets set to false if no response was received, otherwise false. /// </param> /// <param name="noLogging"> /// Whether or not to log errors. Since HttpWebRequest brilliant throws exceptions for /// non-success HTTP status codes, it's nice to be able to control whether or not your /// request should have errors logged. /// </param> /// <returns> /// A non-null byte array on success. Null byte array on failure. /// </returns> public byte[] RequestResource(string resourceUri, out HttpStatusCode code, out bool responseReceived, ResourceOptions options = null, ServiceResource resource = ServiceResource.Custom) { if (options == null) { options = new ResourceOptions(); // Instantiate a resource options object with default options. } responseReceived = true; Dictionary <string, object> parameters = new Dictionary <string, object>(); try { // Try to send the device name as well. Helps distinguish between clients under the // same account. string deviceName = string.Empty; try { deviceName = Environment.MachineName; } catch { deviceName = "Unknown"; } var accessToken = WebServiceUtil.Default.AuthToken; //m_logger.Info("RequestResource1: accessToken=" + accessToken); IVersionProvider versionProvider = PlatformTypes.New <IVersionProvider>(); string version = versionProvider.GetApplicationVersion().ToString(3); // Build out post data with username and identifier. parameters.Add("identifier", FingerprintService.Default.Value); parameters.Add("device_id", deviceName); string postString = null; //string postString = string.Format("&identifier={0}&device_id={1}", FingerprintService.Default.Value, Uri.EscapeDataString(deviceName)); if (options.Parameters != null) { foreach (var parameter in options.Parameters) { parameters.Add(parameter.Key, parameter.Value); } } if (resource == ServiceResource.UserDataSumCheck || resource == ServiceResource.UserConfigSumCheck) { m_logger.Info("Sending version {0} to server", version); parameters.Add("app_version", version); } switch (options.ContentType) { case "application/x-www-form-urlencoded": postString = string.Join("&", parameters.Select(kv => $"{kv.Key}={kv.Value}")); break; case "application/json": postString = Newtonsoft.Json.JsonConvert.SerializeObject(parameters); break; } if (options.Method == "GET" || options.Method == "DELETE") { resourceUri += "?" + postString; if (postString.Contains("app_version")) { m_logger.Info("Sending postString as {0}", resourceUri); } } var request = GetApiBaseRequest(resourceUri, options); m_logger.Debug("WebServiceUtil.Request {0}", request.RequestUri); if (StringExtensions.Valid(accessToken)) { request.Headers.Add("Authorization", string.Format("Bearer {0}", accessToken)); } else if (resource != ServiceResource.RetrieveToken) { m_logger.Info("RequestResource1: Authorization failed."); AuthTokenRejected?.Invoke(); code = HttpStatusCode.Unauthorized; return(null); } if (options.Method != "GET" && options.Method != "DELETE") { if (postString.Contains("app_version")) { m_logger.Info("Sending {0} to server as {1}", postString, options.Method); } var formData = System.Text.Encoding.UTF8.GetBytes(postString); request.ContentLength = formData.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(formData, 0, formData.Length); requestStream.Close(); } } m_logger.Info("RequestResource: uri={0}", request.RequestUri); // Now that our login form data has been POST'ed, get a response. using (var response = (HttpWebResponse)request.GetResponse()) { // Get the response code as an int so we can range check it. var intCode = (int)response.StatusCode; code = (HttpStatusCode)intCode; try { // Check if response code is considered a success code. if (intCode >= 200 && intCode <= 299) { using (var memoryStream = new MemoryStream()) { response.GetResponseStream().CopyTo(memoryStream); // We do this just in case we get something like a 204. The idea here // is that if we return a non-null, the call was a success. var responseBody = memoryStream.ToArray(); if (responseBody == null || intCode == 204) { return(null); } return(responseBody); } } else { m_logger.Info("When requesting resource, got unexpected response code of {0}.", code); } } finally { response.Close(); request.Abort(); } } } catch (WebException e) { // KF - Set this to 0 for default. 0's a pretty good indicator of no internet. code = 0; try { using (WebResponse response = e.Response) { if (response == null) { responseReceived = false; } HttpWebResponse httpResponse = (HttpWebResponse)response; m_logger.Error("Error code: {0}", httpResponse.StatusCode); int intCode = (int)httpResponse.StatusCode; code = (HttpStatusCode)intCode; // Auth failure means re-log EXCEPT when requesting deactivation. if ((intCode == 401 || intCode == 403) && resource != ServiceResource.DeactivationRequest) { WebServiceUtil.Default.AuthToken = string.Empty; m_logger.Info("RequestResource2: Authorization failed."); AuthTokenRejected?.Invoke(); } else if (intCode > 399 && intCode <= 499 && resource != ServiceResource.DeactivationRequest) { m_logger.Info("Error occurred in RequestResource: {0}", intCode); } using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data)) { string text = reader.ReadToEnd(); m_logger.Error(text); } } } catch { } if (!options.NoLogging) { m_logger.Error(e.Message); m_logger.Error(e.StackTrace); } } catch (Exception e) { // XXX TODO - Good default? code = HttpStatusCode.InternalServerError; if (!options.NoLogging) { while (e != null) { m_logger.Error(e.Message); m_logger.Error(e.StackTrace); e = e.InnerException; } } } return(null); }
private WebServiceUtil() { m_logger = LoggerUtil.GetAppWideLogger(); m_authStorage = PlatformTypes.New <IAuthenticationStorage>(); }
public SocketPipeClient() { paths = PlatformTypes.New <IPathProvider>(); logger = LoggerUtil.GetAppWideLogger(); }
internal DnsEnforcement(IPolicyConfiguration configuration, NLog.Logger logger) { m_logger = logger; m_policyConfiguration = configuration; m_platformDns = PlatformTypes.New <IPlatformDns>(); }
public void Callback(DeactivationCommand deactivationCmd) { logger.Info("Deactivation command is: {0}", deactivationCmd.ToString()); if (deactivationCmd == DeactivationCommand.Granted) { IAntitampering antitampering = PlatformTypes.New <IAntitampering>(); if (antitampering.IsProcessProtected) { antitampering.DisableProcessProtection(); } logger.Info("Deactivation request granted on client."); // Init the shutdown of this application. Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); // TODO: Implement IPlatformApplicationServices if the above turns out to be a BUG. //Application.Current.Shutdown(ExitCodes.ShutdownWithoutSafeguards); } else { logger.Info("Deactivation request denied on client."); Device.BeginInvokeOnMainThread(async() => { string message = null; string title = null; switch (deactivationCmd) { case DeactivationCommand.Requested: message = "Your deactivation request has been received, but approval is still pending."; title = "Request Received"; break; case DeactivationCommand.Denied: // A little bit of tact will keep the mob and their pitchforks // from slaughtering us. message = "Your deactivation request has been received, but approval is still pending."; title = "Request Received"; //message = "Your deactivation request has been denied."; //title = "Request Denied"; break; case DeactivationCommand.Granted: message = "Your request was granted."; title = "Request Granted"; break; case DeactivationCommand.NoResponse: message = "Your deactivation request did not reach the server. Check your internet connection and try again."; title = "No Response Received"; break; } if ((Application.Current as App).NavPage.CurrentPage is MainPage) { await((Application.Current as App).NavPage.CurrentPage as MainPage).DisplayAlert(title, message, "OK"); } }); } }
/// <summary> /// Queries the service provider for updated filtering rules. /// </summary> /// <param name="cfgStream">Added this parameter so that we could test the default policy configuration.</param> public bool LoadConfiguration(Stream cfgStream) { try { // Load our configuration file and load configured lists, etc. if (cfgStream != null) { string cfgJson = string.Empty; using (TextReader textReader = new StreamReader(cfgStream)) { cfgJson = textReader.ReadToEnd(); } if (!StringExtensions.Valid(cfgJson)) { m_logger.Error("Could not find valid JSON config for filter."); return(false); } try { LoadConfigFromJson(cfgJson, s_configSerializerSettings); m_logger.Info("Configuration loaded from JSON."); } catch (Exception deserializationError) { m_logger.Error("Failed to deserialize JSON config."); LoggerUtil.RecursivelyLogException(m_logger, deserializationError); return(false); } if (Configuration.UpdateFrequency.Minutes <= 0 || Configuration.UpdateFrequency == Timeout.InfiniteTimeSpan) { // Just to ensure that we enforce a minimum value here. Configuration.UpdateFrequency = TimeSpan.FromMinutes(5); } loadAppList(BlacklistedApplications, Configuration.BlacklistedApplications, BlacklistedApplicationGlobs); loadAppList(WhitelistedApplications, Configuration.WhitelistedApplications, WhitelistedApplicationGlobs); TimeRestrictions = new TimeRestrictionModel[7]; for (int i = 0; i < 7; i++) { DayOfWeek day = (DayOfWeek)i; string configDay = day.ToString().ToLowerInvariant(); TimeRestrictionModel restriction = null; Configuration.TimeRestrictions?.TryGetValue(configDay, out restriction); TimeRestrictions[i] = restriction; } AreAnyTimeRestrictionsEnabled = TimeRestrictions.Any(r => r?.RestrictionsEnabled == true); if (Configuration.CannotTerminate) { // Turn on process protection if requested. PlatformTypes.New <IAntitampering>().EnableProcessProtection(); } else { PlatformTypes.New <IAntitampering>().DisableProcessProtection(); } // Don't do list loading in the same function as configuration loading, because those are now indeed two separate functions. } } catch (Exception e) { LoggerUtil.RecursivelyLogException(m_logger, e); return(false); } return(true); }
public static void Main(string[] args) { var sentry = SentrySdk.Init(o => { o.Dsn = new Dsn(CloudVeil.CompileSecrets.SentryDsn); o.BeforeBreadcrumb = (breadcrumb) => { if (breadcrumb.Message.Contains("Request")) { return(null); } else { return(breadcrumb); } }; }); LoggerUtil.LoggerName = "CitadelGUI"; bool startMinimized = false; foreach (string arg in args) { if (arg.IndexOf("StartMinimized") != -1) { startMinimized = true; break; } } try { if (Process.GetCurrentProcess().SessionId <= 0) { try { LoggerUtil.GetAppWideLogger().Error("GUI client started in session 0 isolation. Exiting. This should not happen."); Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } catch (Exception e) { // XXX TODO - We can't really log here unless we do a direct to-file write. Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } } Citadel.Core.Windows.Platform.Init(); PlatformTypes.Register <IGuiServices>((arr) => new WindowsGuiServices()); PlatformTypes.Register <ITrayIconController>((arr) => new WindowsTrayIconController()); } catch { // Lets assume that if we can't even read our session ID, that we're in session 0. Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } var guiChecks = PlatformTypes.New <IGUIChecks>(); try { RunGuiChecks(startMinimized); } catch (Exception e) { // The only way we got here is if the server isn't running, in which case we can do // nothing because its beyond our domain. LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e); return; } try { MainLogger = LoggerUtil.GetAppWideLogger(); } catch { } try { var app = new CitadelApp(); app.InitializeComponent(); app.Run(); // Always release mutex. guiChecks.UnpublishRunningApp(); } catch (Exception e) { try { SentrySdk.CaptureException(e); MainLogger = LoggerUtil.GetAppWideLogger(); LoggerUtil.RecursivelyLogException(MainLogger, e); } catch (Exception be) { // XXX TODO - We can't really log here unless we do a direct to-file write. } } sentry.Dispose(); // No matter what, always ensure that critical flags are removed from our process before exiting. CriticalKernelProcessUtility.SetMyProcessAsNonKernelCritical(); }
public ConsoleLogWriter(string prefix = "console") : base() { m_pathsProvider = PlatformTypes.New <IPathProvider>(); this.prefix = prefix; }
private static void RunGuiChecks(bool startMinimized) { guiChecks = PlatformTypes.New <IGUIChecks>(); // First, lets check to see if the user started the GUI in an isolated session. try { if (guiChecks.IsInIsolatedSession()) { LoggerUtil.GetAppWideLogger().Error("GUI client start in an isolated session. This should not happen."); Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } } catch { Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } try { bool createdNew = false; if (guiChecks.PublishRunningApp()) { createdNew = true; } /**/ if (!createdNew) { try { if (!startMinimized) { guiChecks.DisplayExistingUI(); } } catch (Exception e) { LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e); } // In case we have some out of sync state where the app is running at a higher // privilege level than us, the app won't get our messages. So, let's attempt an // IPC named pipe to deliver the message as well. try { // Something about instantiating an IPCClient here is making it all blow up in my face. using (var ipcClient = IPCClient.InitDefault()) { if (!startMinimized) { ipcClient.RequestPrimaryClientShowUI(); } // Wait plenty of time before dispose to allow delivery of the message. Task.Delay(500).Wait(); } } catch (Exception e) { // The only way we got here is if the server isn't running, in which case we // can do nothing because its beyond our domain. LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e); } LoggerUtil.GetAppWideLogger().Info("Shutting down process since one is already open."); // Close this instance. Environment.Exit((int)ExitCodes.ShutdownProcessAlreadyOpen); return; } } catch (Exception e) { // The only way we got here is if the server isn't running, in which case we can do // nothing because its beyond our domain. LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e); return; } }
public MacGUIChecks() { logger = LoggerUtil.GetAppWideLogger(); paths = PlatformTypes.New <IPathProvider>(); }