コード例 #1
0
        /// <summary>
        /// Checks utility credentials Looks in cache, tries windows cache, and then prompts.
        /// Returns CommandResults.Successful always unless exception.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="force">if set to <c>true</c> [force].</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns>CommandResults.</returns>
        private CommandResults CheckResourceCredentialsUtility(string path, bool force,
                                                               NetworkCredential credentials = null)
        {
            try
            {
                if (CredentialsList.ContainsKey(path) && !force)
                {
                    CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtility:returning cached authentication status");
                    return(CommandResults.Successful);
                }
                else if (CredentialsList.ContainsKey(path))
                {
                    CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtility:removing cached authentication");

                    CredentialsList.Remove(path);
                }

                if (string.IsNullOrEmpty(credentials.UserName) && string.IsNullOrEmpty(credentials.Password) && CanPromptForCredentials())
                {
                    credentials = Credentials.PromptForCredentials(credentials.UserName, credentials.Password, path);
                }

                CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtility:adding cached authentication:" + path);

                return(AddToCredentialList(credentials, path));
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("DEBUG:CheckResourceCredentialsUtiltiy:Exception:" + e.ToString());
                return(AddToCredentialList(credentials, path, false, CommandResults.Fail));
            }
        }
コード例 #2
0
        /// <summary>
        /// Returns cached ResourceCredential or generates new empty one
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>ResourceCredential.</returns>
        public ResourceCredential GetCredentials(string path)
        {
            string pathKey = path;
            Uri    uri;

            try
            {
                if (Uri.TryCreate(path, UriKind.Absolute, out uri))
                {
                    pathKey = uri.Host;
                }

                if (CredentialsList.ContainsKey(pathKey))
                {
                    return(CredentialsList[pathKey]);
                }
                else
                {
                    return(new ResourceCredential());
                }
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("DEBUG:GetCredentials:Exception:" + e.ToString());
                return(new ResourceCredential());
            }
        }
コード例 #3
0
ファイル: FTP.cs プロジェクト: citrix/CDFMonitor
        // The EndGetResponseCallback method
        // completes a call to BeginGetResponse.
        /// <summary>
        /// Ends the get response callback.
        /// </summary>
        /// <param name="ar">The ar.</param>
        private void EndGetResponseCallback(IAsyncResult ar)
        {
            Status = "AsyncFTP:getting response.";
            CDFMonitor.LogOutputHandler(Status);
            var            state    = (FtpState)ar.AsyncState;
            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;

                // Signal the main application thread that the operation is complete.
                state.OperationComplete.Set();
            }

            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                //Console.WriteLine("Error getting response.");
                Status = "AsyncFTP:Error getting response.";
                CDFMonitor.LogOutputHandler(Status);
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
コード例 #4
0
        /// <summary>
        /// Verifies the trace file output.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="repair">if set to <c>true</c> [repair].</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool VerifyTraceFileOutput(ref string file, bool repair)
        {
            bool retval = true;

            if (_config.Activity == Configuration.ActivityType.TraceToEtl)
            {
                if (string.IsNullOrEmpty(file))
                {
                    CDFMonitor.LogOutputHandler(string.Format("Fail:Trace File Output does not exist but should for this activity type (etl):{0}", _config.AppSettings.Activity));
                    return(false);
                }
            }

            if (_config.Activity == Configuration.ActivityType.TraceToCsv ||
                _config.Activity == Configuration.ActivityType.RegexParseToCsv)
            {
                if (string.IsNullOrEmpty(file))
                {
                    if (repair)
                    {
                        CDFMonitor.LogOutputHandler(string.Format("Fail:Trace File Output is not configured but should for this activity:{0}", _config.Activity));
                        return(false);
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler(string.Format("Warning:Trace File Output is not configured for this activity:{0}", _config.Activity));
                    }
                }
            }

            if (_config.Activity == Configuration.ActivityType.TraceToEtl)
            {
                // fix extension regardless of repair
                if (Path.GetExtension(file).ToLower() != ".etl")
                {
                    CDFMonitor.LogOutputHandler(string.Format("Trace File Output does does not have correct extension. fixing:{0}", file));
                    file = Regex.Replace(file, Path.GetExtension(file), ".etl", RegexOptions.IgnoreCase);
                }
            }
            else
            {
                // fix extension regardless of repair
                if (Path.GetExtension(file).ToLower() == ".etl")
                {
                    CDFMonitor.LogOutputHandler(string.Format("Trace File Output does does not have correct extension. fixing:{0}", file));
                    file = Regex.Replace(file, Path.GetExtension(file), ".csv", RegexOptions.IgnoreCase);
                }
            }

            if ((string.IsNullOrEmpty(file) && repair) ||
                (!string.IsNullOrEmpty(file) &&
                 !FileManager.CheckPath(file, true)))
            {
                retval = false;
            }

            retval &= AllLogsUnique();

            return(retval);
        }
コード例 #5
0
ファイル: EtwTraceConsumer.cs プロジェクト: citrix/CDFMonitor
        /// <summary>
        /// Starts reading the ETW session events.
        /// </summary>
        /// <param name="state">The state.</param>
        public void ProcessTrace(object state)
        {
            Debug.Assert(_handle[0] != 0 && NativeMethods.IsValidHandle(_handle[0]),
                         "_handle[0] != 0 && NativeMethods.IsValidHandle(_handle[0])");

            long startFileTime = 0;
            long stopFileTime  = 0;
            uint ret           = 0;

            // Sometimes processtrace will return early presumably due to network issues or latency so keep retrying
            while (_running && _processTraceRetry > 0 && _handle[0] != 0)
            {
                if (_bufferCallback.LogfileHeader.BuffersWritten > 0 &&
                    (_onBufferReadCount == _bufferCallback.BuffersRead))
                {
                    break;
                }

                startFileTime = _bufferCallback.LogfileHeader.StartTime;
                CDFMonitor.LogOutputHandler(string.Format("ProcessTrace (re)starting ProcessTrace:{0}:{1}", startFileTime, _sessionName));
                ret = NativeMethods.ProcessTrace(_handle, _handle.Length, ref startFileTime, ref stopFileTime);
                _processTraceRetry--;

                if (CDFMonitor.CloseCurrentSessionEvent.WaitOne(1000))
                {
                    return;
                }
            }

            // Only call CloseTrace after ProcessTrace completes
            CloseTrace();
            CDFMonitor.LogOutputHandler("ProcessTrace return: " + ret);
        }
コード例 #6
0
        /// <summary>
        /// Runs the process.
        /// </summary>
        /// <param name="remoteCommand">The remote command.</param>
        /// <returns>System.Int32.</returns>
        public int RunProcess(string remoteCommand)
        {
            try
            {
                CDFMonitor.LogOutputHandler("Runprocess:enter:" + remoteCommand);

                var objectGetOptions          = new ObjectGetOptions();
                var managementPath            = new ManagementPath("Win32_Process");
                var processClass              = new ManagementClass(_manScope, managementPath, objectGetOptions);
                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
                inParams["CommandLine"] = remoteCommand;
                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                CDFMonitor.LogOutputHandler("DEBUG:RunProcess:Creation of the process returned: " +
                                            outParams["returnValue"]);
                CDFMonitor.LogOutputHandler("DEBUG:RunProcess:Process ID: " + outParams["processId"]);

                return(Convert.ToInt32(outParams["processId"]));
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("Fail:Runprocess:exception:" + e.ToString());
                return(0);
            }
        }
コード例 #7
0
        /// <summary>
        /// WMI ctor
        /// </summary>
        /// <param name="remoteMachine">The remote machine.</param>
        /// <param name="rootpath">The rootpath.</param>
        /// <param name="creds">The creds.</param>
        public WMI(string remoteMachine, string rootpath = null, ResourceCredential creds = null)
        {
            try
            {
                // ResourceCredential tempcreds = creds ?? new ResourceCredential();
                ResourceCredential tempcreds = creds.Clone() ?? new ResourceCredential();

                _remoteMachine = remoteMachine;

                if (string.IsNullOrEmpty(rootpath))
                {
                    rootpath = @"\\{0}\ROOT\CIMV2";
                }

                SecureString securePassword = null;
                if (!string.IsNullOrEmpty(tempcreds.UserName) && !string.IsNullOrEmpty(tempcreds.Password) &&
                    CDFMonitor.Instance.Config.AppSettings.UseCredentials)
                {
                    unsafe
                    {
                        // Instantiate a new secure string.
                        fixed(char *pChars = tempcreds.Password.ToCharArray())
                        {
                            securePassword = new SecureString(pChars, tempcreds.Password.Length);
                        }
                    }
                }
                else
                {
                    tempcreds.UserName = null;
                    tempcreds.Password = null;
                    tempcreds.Domain   = null;
                }

                CDFMonitor.LogOutputHandler(string.Format("WMI using credentials: user:{0} domain:{1}", tempcreds.UserName, tempcreds.Domain));

                var options =
                    new ConnectionOptions("MS_409",
                                          string.IsNullOrEmpty(tempcreds.UserName) ? null : tempcreds.UserName,
                                          securePassword,
                                          string.IsNullOrEmpty(tempcreds.Domain)
                                              ? null
                                              : "ntlmdomain:" + tempcreds.Domain,
                                          ImpersonationLevel.Impersonate,
                                          AuthenticationLevel.Default,
                                          true,
                                          null,
                                          new TimeSpan(0, 0, 0, 0, CONNECT_TIMEOUT));

                _manScope = new ManagementScope(String.Format(rootpath, _remoteMachine), options);
                _manScope.Connect();
                Status = true;
                CDFMonitor.LogOutputHandler("DEBUG:WMI initialization: " + Status);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("WMI exception: " + e.ToString());
                Status = false;
            }
        }
コード例 #8
0
        /// <summary>
        /// Connects the unc path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns>System.Int32.</returns>
        private int ConnectUncPath(string path, NetworkCredential credentials)
        {
            CDFMonitor.LogOutputHandler("DEBUG:ConnectUncPath:enter:" + path);
            string userName = credentials.UserName;

            if (!string.IsNullOrEmpty(credentials.Domain))
            {
                userName = string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
            }

            if (GetPathType(path) != ResourceType.Unc)
            {
                return(-1);
            }

            DeterminePathObjType objectType = DeterminePathObj(path);

            if (objectType == DeterminePathObjType.File)
            {
                path = Path.GetDirectoryName(FileManager.GetFullPath(path));
                CDFMonitor.LogOutputHandler("DEBUG:ConnectUncPath:new path:" + path);
            }

            int ret = WindowsNetworking.ConnectToRemote(path,
                                                        userName,
                                                        credentials.Password, false);

            CDFMonitor.LogOutputHandler(string.Format("DEBUG:ConnectToRemote:return:{0}:{1}", path, ret == 0 ? true : false));
            return(ret);
        }
コード例 #9
0
 /// <summary>
 /// Kills the process.
 /// </summary>
 /// <param name="processName">Name of the process.</param>
 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
 public bool KillProcess(string processName)
 {
     try
     {
         CDFMonitor.LogOutputHandler("DEBUG:KillProcess:enter:" + processName);
         var msQuery = new SelectQuery("SELECT * FROM Win32_Process "
                                       + "Where Name = '" + processName + "'"
                                       + "AND Handle != '" + Process.GetCurrentProcess().Id + "'");
         var searchProcedure = new ManagementObjectSearcher(_manScope, msQuery);
         foreach (ManagementObject item in searchProcedure.Get())
         {
             try
             {
                 item.InvokeMethod("Terminate", null);
             }
             catch (SystemException e)
             {
                 CDFMonitor.LogOutputHandler("DEBUG:KillProcess:exception:" + e.ToString());
                 return(false);
             }
         }
         return(true);
     }
     catch (Exception e)
     {
         CDFMonitor.LogOutputHandler("Fail:KillProcess:exception:" + e.ToString());
         return(false);
     }
 }
コード例 #10
0
        /// <summary>
        /// Gets the SYSTEMROOT.
        /// </summary>
        /// <returns>System.String.</returns>
        public string GetSYSTEMROOT()
        {
            try
            {
                string retval                   = string.Empty;
                var    objectGetOptions         = new ObjectGetOptions();
                var    managementPath           = new ManagementPath("Win32_OperatingSystem");
                var    processClass             = new ManagementClass(_manScope, managementPath, objectGetOptions);
                ManagementObjectCollection objs = processClass.GetInstances();
                foreach (ManagementObject obj in objs)
                {
                    retval = obj["WindowsDirectory"].ToString();
                    break;
                }
                objs.Dispose();
                CDFMonitor.LogOutputHandler("DEBUG:GetSYSTEMROOT returned: " + retval);

                return(retval);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("GetSYSTEMROOT exception: " + e.ToString());
                return(string.Empty);
            }
        }
コード例 #11
0
        /// <summary>
        /// Binds the client socket.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="serverPort">The server port.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        private UdpClient BindClientSocket(string serverName, int serverPort)
        {
            UdpClient udpClient = new UdpClient();
            IPAddress serverIpAddress;

            try
            {
                if (WriterEnabled)
                {
                    IPAddress address;
                    if (IPAddress.TryParse(serverName, out address))
                    {
                        serverIpAddress = address;
                    }
                    else
                    {
                        serverIpAddress = Dns.GetHostAddresses(serverName)[0];
                    }

                    CDFMonitor.LogOutputHandler(string.Format("BindClientSocket:binding to:{0}:{1}", serverIpAddress, serverPort));
                    udpClient.Connect(new IPEndPoint(serverIpAddress, serverPort));
                }

                return(udpClient);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("BindClientSocket:exception:" + e.ToString());
                return(null);
            }
        }
コード例 #12
0
        /// <summary>
        /// Reads a package zip file containing specified content and resource files.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool ExtractPackage(string packageName, string outputFolder, bool force = false)
        {
            CDFMonitor.LogOutputHandler("ReadPackage:processing package:" + packageName);

            try
            {
                if (!FileManager.FileExists(packageName))
                {
                    return(false);
                }

                // create subfolder for package files based on package name
                outputFolder = string.Format("{0}\\{1}", outputFolder, Path.GetFileNameWithoutExtension(packageName));

                if (FileManager.CheckPath(outputFolder))
                {
                    if (force)
                    {
                        FileManager.DeleteFolder(outputFolder);
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler("ReadPackage:output folder exists and no force. returning:" + packageName);
                        return(false);
                    }
                }

                if (!FileManager.CheckPath(outputFolder, true))
                {
                    return(false);
                }

                // Read the Package
                using (ZipPackage package = (ZipPackage)ZipPackage.Open(packageName, FileMode.Open))
                {
                    CDFMonitor.LogOutputHandler("ReadPackage:package open. retrieving parts");
                    foreach (PackagePart pP in package.GetParts())
                    {
                        DecompressStream(pP.GetStream(FileMode.Open, FileAccess.Read),
                                         string.Format("{0}\\{1}", outputFolder, pP.Uri.ToString().TrimStart('/')));
                    }
                }

                if (Directory.GetFiles(outputFolder).Length > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Status = e.ToString();
                CDFMonitor.LogOutputHandler("ReadPackage:exception:" + Status);
                return(false);
            }
        }
コード例 #13
0
ファイル: EtwTraceConsumer.cs プロジェクト: citrix/CDFMonitor
 /// <summary>
 /// ctor.
 /// </summary>
 /// <param name="sessionName">Name of the session.</param>
 public EtwTraceConsumer(string sessionName)
 {
     Debug.Assert(!String.IsNullOrEmpty(sessionName), "!String.IsNullOrEmpty(sessionName)");
     CDFMonitor.LogOutputHandler("DEBUG:EtwTraceConsumer.ctor: new trace:" + sessionName);
     _sessionName = sessionName;
     _eventTraceBufferCallback = OnBufferRead;
     _eventCallback            = OnTraceEvent;
 }
コード例 #14
0
ファイル: ServiceInstaller.cs プロジェクト: citrix/CDFMonitor
        /// <summary>
        /// Stars the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the windows service</param>
        private static void StartService(IntPtr hService)
        {
            CDFMonitor.LogOutputHandler("StartService entry.");
            var status = new SERVICE_STATUS();

            StartService(hService, 0, 0);
            WaitForServiceStatus(hService, ServiceState.Starting, ServiceState.Run);
        }
コード例 #15
0
        /// <summary>
        /// Reads the registry modules.
        /// </summary>
        /// <param name="registryPath">The registry path.</param>
        /// <returns>Dictionary{System.StringSystem.String}.</returns>
        public Dictionary <string, string> ReadRegistryModules(string registryPath)
        {
            var  registryValues = new Dictionary <string, string>();
            bool hasAccess      = false;
            ManagementBaseObject outVals;

            try
            {
                CDFMonitor.LogOutputHandler("ReadRegistry:enter:" + registryPath);

                var objectGetOptions          = new ObjectGetOptions();
                var managementPath            = new ManagementPath("StdRegProv");
                var processClass              = new ManagementClass(_manScope, managementPath, objectGetOptions);
                ManagementBaseObject inParams = processClass.GetMethodParameters("CheckAccess");

                // Add the input parameters.
                // HKLM
                inParams["hDefKey"]     = 2147483650;
                inParams["sSubKeyName"] = registryPath;

                // Enumerate subkeys
                inParams["uRequired"] = 8;

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams = processClass.InvokeMethod("CheckAccess", inParams, null);

                hasAccess = (bool)outParams["bGranted"];

                CDFMonitor.LogOutputHandler("bGranted: " + hasAccess);
                CDFMonitor.LogOutputHandler("ReturnValue: " + outParams["ReturnValue"]);

                if (hasAccess)
                {
                    // Read key
                    outVals = processClass.InvokeMethod("EnumKey", inParams, null);
                    var subkeys = (string[])outVals["sNames"];

                    inParams               = processClass.GetMethodParameters("GetStringValue");
                    inParams["hDefKey"]    = 0x80000002; // 2147483650;
                    inParams["sValueName"] = "GUID";

                    foreach (string key in subkeys)
                    {
                        inParams["sSubKeyName"] = registryPath + "\\" + key;
                        outVals = processClass.InvokeMethod("GetStringValue", inParams, null);
                        registryValues.Add((string)outVals["sValue"], key);
                    }
                }

                return(registryValues);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("Fail:ReadRegistry:exception:" + e.ToString());
                return(registryValues);
            }
        }
コード例 #16
0
        /// <summary>
        /// Waits for given service to be in desired state up to TIME_OUT. Returns
        /// ReturnValue.Success if successful.
        /// </summary>
        /// <param name="svcName">service name to wait on</param>
        /// <param name="serviceState">desired state</param>
        /// <returns>ReturnValue.</returns>
        private ReturnValue WaitForServiceState(string svcName, ServiceState serviceState)
        {
            CDFMonitor.LogOutputHandler("WaitForServiceState:enter");
            ReturnValue  retval            = ReturnValue.UnknownFailure;
            DateTime     timeout           = DateTime.Now.Add(new TimeSpan(0, 0, 0, 0, TIME_OUT));
            ServiceState intermediateState = ServiceState.Unknown;
            ServiceState currentState      = ServiceState.Unknown;

            switch (serviceState)
            {
            case ServiceState.Running:
                intermediateState = ServiceState.StartPending;
                break;

            case ServiceState.Stopped:
                intermediateState = ServiceState.StopPending;
                break;

            case ServiceState.Paused:
                intermediateState = ServiceState.PausePending;
                break;

            default:
                break;
            }

            while (DateTime.Now < timeout)
            {
                if ((currentState = GetServiceState(svcName)) == serviceState)
                {
                    CDFMonitor.LogOutputHandler("WaitForServiceState:exit:success");

                    // even though service may be stopped we need to wait
                    if (serviceState == ServiceState.Stopped && CDFMonitor.CloseCurrentSessionEvent.WaitOne(1000))
                    {
                        return(ReturnValue.False);
                    }

                    return(ReturnValue.Success);
                }

                if (currentState != intermediateState)
                {
                    CDFMonitor.LogOutputHandler("WaitForServiceState:invalid intermediate state:exit:fail");
                    return(ReturnValue.False);
                }

                if (CDFMonitor.CloseCurrentSessionEvent.WaitOne(1000))
                {
                    CDFMonitor.LogOutputHandler("WaitForServiceState:exit:fail");
                    return(ReturnValue.False);
                }
            }

            return(retval);
        }
コード例 #17
0
        /// <summary>
        /// Uns the deploy.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool UnDeploy()
        {
            bool   retVal      = true;
            string destination = string.Empty;

            int i = 0;

            do
            {
                i++;

                foreach (string machine in new List <string>(RemoteList.Keys))
                {
                    if (RemoteList[machine] == RemoteStatus.UnDeployed)
                    {
                        CDFMonitor.LogOutputHandler(string.Format("UnDeploy: skipping machine {0} because of cached state: {1}", machine, RemoteList[machine]));
                        continue;
                    }

                    CDFMonitor.LogOutputHandler("UnDeploy: processing machine:" + machine + " state:" +
                                                RemoteList[machine].ToString());
                    WMIServicesManager wmi;
                    destination = "\\\\" + machine + "\\admin$\\cdfmonitor";
                    int pid = 0;

                    if (Ping(machine) &&
                        (wmi = new WMIServicesManager(machine, _creds)) != null &&
                        wmi.Status &&
                        (wmi.IsServiceInstalled(Resources.ServiceName) == WMIServicesManager.ReturnValue.True &&
                         wmi.StopService(Resources.ServiceName) == WMIServicesManager.ReturnValue.Success &&
                         wmi.UninstallService(Resources.ServiceName) == WMIServicesManager.ReturnValue.Success)
                        | (FileManager.CheckPath(destination, true)
                           &&
                           ((pid = wmi.RunProcess(string.Format("{0}\\cdfmonitor\\cdfmonitor.exe /clean", wmi.GetSYSTEMROOT()))) != 0
                            & wmi.CheckProcess(_processName, pid, true) == 0) &&
                           FileManager.DeleteFolder(destination, false)))
                    {
                        RemoteList[machine] = RemoteStatus.UnDeployed;
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler("Fail:UnDeploy: unsuccessful.");
                        RemoteList[machine] = RemoteStatus.Error;
                        retVal = false;
                    }

                    if (!CheckProgress(false, machine, i))
                    {
                        return(retVal);
                    }
                }
            }while ((RemoteList.Count(v => v.Value == RemoteStatus.UnDeployed)) != RemoteList.Count && CheckProgress(true, string.Empty, i));

            return(retVal);
        }
コード例 #18
0
        /// <summary>
        /// Manages the ProcessList
        /// </summary>
        /// <param name="processID"></param>
        private void ManageProcessList()
        {
            // clean up any tombstoned records
            cacheLock.EnterUpgradeableReadLock();
            try
            {
                foreach (ProcessList process in new List <ProcessList>(_processList))
                {
                    if (process.StopTime != DateTime.MinValue && DateTime.Now.Subtract(process.StopTime).Minutes > MAX_TOMBSTONE_MINUTES)
                    {
                        cacheLock.EnterWriteLock();
                        try
                        {
                            _processList.Remove(process);
                            CDFMonitor.LogOutputHandler(
                                string.Format("ManageProcessList: removing process:{0}.exe({1})", process.ProcessName, process.Id), JobOutputType.Etw);
                        }
                        catch (Exception ex1)
                        {
                            CDFMonitor.LogOutputHandler("DEBUG:ProcessListMonitor:ManageProcessList:remove stale Exception:{0}" + ex1.ToString());
                        }
                        finally
                        {
                            cacheLock.ExitWriteLock();
                        }
                    }
                }

                // make sure list doesnt get too big by cleaning cache of stale entries
                if (_processList.Count > MAX_PROCESS_LIST_COUNT)
                {
                    cacheLock.EnterWriteLock();
                    try
                    {
                        _processList.RemoveAll(p => p.StopTime != DateTime.MinValue);
                    }
                    catch (Exception ex2)
                    {
                        CDFMonitor.LogOutputHandler("DEBUG:ProcessListMonitor:ManageProcessList:Over max count Exception:{0}" + ex2.ToString());
                    }
                    finally
                    {
                        cacheLock.ExitWriteLock();
                    }
                }
            }
            catch (Exception ex)
            {
                CDFMonitor.LogOutputHandler("DEBUG:ProcessListMonitor:ManageProcessList:Exception:{0}" + ex.ToString());
            }
            finally
            {
                cacheLock.ExitUpgradeableReadLock();
            }
        }
コード例 #19
0
        /// <summary>
        /// determines by given path what resource type is being used if CDFMonitor is passed it
        /// will simply store credentials for utility
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>ResourceType</returns>
        public ResourceType GetPathType(string path)
        {
            try
            {
                if (path == Resources.SessionName)
                {
                    return(ResourceType.Utility);
                }

                if (string.IsNullOrEmpty(path))
                {
                    return(ResourceType.Unknown);
                }

                //path = FileManager.GetFullPath(path);

                Uri uri;
                if (Uri.TryCreate(path, UriKind.Absolute, out uri))
                {
                    // 130915
                    if (uri.IsUnc)
                    {
                        return(ResourceType.Unc);
                    }
                    else if (uri.IsLoopback)
                    {
                        return(ResourceType.Local);
                    }
                    else
                    {
                        return(ResourceType.Url);
                    }
                }

                string fullpath = FileManager.GetFullPath(path);

                if (fullpath.StartsWith(@"\\\\"))
                {
                    return(ResourceType.Unc);
                }

                if (File.Exists(fullpath) ||
                    Directory.Exists(fullpath))
                {
                    return(ResourceType.Local);
                }

                return(ResourceType.Unknown);
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler("DEBUG:GetPathType:Exception" + e.ToString());
                return(ResourceType.Error);
            }
        }
コード例 #20
0
        /// <summary>
        /// UDPs the reader.
        /// </summary>
        private void UdpReader()
        {
            UdpClient udpServer = new UdpClient();

            try
            {
                IPAddress  ip;
                IPEndPoint endPoint;

                // check if local ip and if so assign listener get local IP addresses
                IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

                // test if any host IP is a loopback IP or is equal to any local IP
                IPAddress.TryParse(_settings.UdpServer, out ip);
                if (ip == null || (!IPAddress.IsLoopback(ip) && !localIPs.Contains(ip)))
                {
                    endPoint = new IPEndPoint(IPAddress.Any, _settings.UdpServerPort);
                    CDFMonitor.LogOutputHandler("Listening for UDP broadcast with any ip.");
                }
                else
                {
                    endPoint = new IPEndPoint(ip, _settings.UdpServerPort);
                    CDFMonitor.LogOutputHandler("Listening for UDP broadcast with specified ip:" + ip.ToString());
                }

                udpServer = new UdpClient(endPoint);

                while (ListenerEnabled)
                {
                    UdpState udpState = new UdpState();
                    udpState.groupEP  = endPoint;
                    udpState.listener = udpServer;

                    udpServer.BeginReceive(new AsyncCallback(ReceiveCallback), udpState);

                    while (!_listenerCallback.WaitOne(100))
                    {
                        if (CDFMonitor.CloseCurrentSessionEvent.WaitOne(0) | !ListenerEnabled)
                        {
                            return;
                        }
                    }
                }

                return;
            }
            catch (Exception e)
            {
                CDFMonitor.LogOutputHandler(string.Format("UdpListener:exception:{0}", e.ToString()));
            }
            finally
            {
                udpServer.Close();
            }
        }
コード例 #21
0
ファイル: ServiceInstaller.cs プロジェクト: citrix/CDFMonitor
        /// <summary>
        /// Opens the service manager
        /// </summary>
        /// <param name="Rights">The service manager rights</param>
        /// <returns>the handle to the service manager</returns>
        private static IntPtr OpenSCManager(ServiceManagerRights Rights)
        {
            IntPtr scman = OpenSCManager(null, null, Rights);

            if (scman == IntPtr.Zero)
            {
                CDFMonitor.LogOutputHandler("Could not connect to service control manager.");
                return(IntPtr.Zero);
            }
            return(scman);
        }
コード例 #22
0
ファイル: ServiceInstaller.cs プロジェクト: citrix/CDFMonitor
        /// <summary>
        /// Gets the service state by using the handle of the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the service</param>
        /// <returns>The <code>ServiceState</code> of the service</returns>
        private static ServiceState GetServiceStatus(IntPtr hService)
        {
            var ssStatus = new SERVICE_STATUS();

            if (QueryServiceStatus(hService, ssStatus) == 0)
            {
                CDFMonitor.LogOutputHandler("Failed to query service status.");
                return(ServiceState.Unknown);
            }
            return(ssStatus.dwCurrentState);
        }
コード例 #23
0
        /// <summary>
        /// Stops the remote.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool StopRemote()
        {
            bool   retVal      = true;
            string destination = string.Empty;

            int i = 0;

            do
            {
                i++;

                foreach (string machine in new List <string>(RemoteList.Keys))
                {
                    if (RemoteList[machine] == RemoteStatus.Stopped)
                    {
                        CDFMonitor.LogOutputHandler(string.Format("StopRemote: skipping machine {0} because of cached state: {1}", machine, RemoteList[machine]));
                        continue;
                    }

                    CDFMonitor.LogOutputHandler("StopRemote: processing machine:" + machine + " state:" +
                                                RemoteList[machine].ToString());
                    WMIServicesManager wmi;

                    if (Ping(machine) &&
                        (wmi = new WMIServicesManager(machine, _creds)) != null &&
                        wmi.Status &&
                        (wmi.IsServiceInstalled(Resources.ServiceName) == WMIServicesManager.ReturnValue.True &&
                         wmi.StopService(Resources.ServiceName) == WMIServicesManager.ReturnValue.Success))
                    {
                        if (wmi.GetServiceState(Resources.ServiceName) == WMIServicesManager.ServiceState.Stopped)
                        {
                            RemoteList[machine] = RemoteStatus.Stopped;
                        }
                        else
                        {
                            RemoteList[machine] = RemoteStatus.Error;
                        }
                    }
                    else
                    {
                        CDFMonitor.LogOutputHandler("Fail:StopRemote: unsuccessful.");
                        RemoteList[machine] = RemoteStatus.Error;
                        retVal = false;
                    }

                    if (!CheckProgress(false, machine, i))
                    {
                        return(retVal);
                    }
                }
            }while ((RemoteList.Count(v => v.Value == RemoteStatus.Stopped) != RemoteList.Count) && CheckProgress(true, string.Empty, i));

            return(retVal);
        }
コード例 #24
0
        /// <summary>
        /// Disables WMI Process Creation and Deletion Callbacks
        /// </summary>
        public void Disable()
        {
            if (_enabled)
            {
                DisableProcessListThread();
                CDFMonitor.LogOutputHandler(string.Format("ProcessListMonitor: disabled: interrupt counter:{0} list size:{1}", _interruptCounter, _processList.Count));
                _enabled = false;
            }

            _processList.Clear();
        }
コード例 #25
0
        /// <summary>
        /// Stops the listener.
        /// </summary>
        public void StopListener()
        {
            CDFMonitor.LogOutputHandler("DEBUG:UDP.StopListener:enter");
            if (ListenerEnabled)
            {
                CDFMonitor.LogOutputHandler("DEBUG:UDP.StopListener:stopping");
                ListenerEnabled = false;
            }

            CDFMonitor.LogOutputHandler("DEBUG:UDP.StopListener:exit");
        }
コード例 #26
0
        /// <summary>
        /// Checks the unc path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="create">if set to <c>true</c> [create].</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        public bool CheckUncPath(string path, bool create = false)
        {
            CommandResults rc = CheckResourceCredentials(path, false);

            if (rc != ResourceManagement.CommandResults.Successful &&
                rc != ResourceManagement.CommandResults.InvalidPath)
            {
                CDFMonitor.LogOutputHandler("CheckUncPath:Fail no access to share:" + path);
                return(false);
            }
            return(CheckUncPath(path, GetCredentials(path), create));
        }
コード例 #27
0
 public static bool DeleteCredentials(string name)
 {
     try
     {
         return(CredDelete(name, CRED_TYPE.GENERIC, 0));
     }
     catch (Exception e)
     {
         CDFMonitor.LogOutputHandler("DEBUG:DeleteCredentials:exception" + e.ToString());
         return(false);
     }
 }
コード例 #28
0
        /// <summary>
        /// Starts the listener.
        /// </summary>
        public void StartListener()
        {
            CDFMonitor.LogOutputHandler("DEBUG:UDP.StartListener:enter");
            if (!ListenerEnabled)
            {
                CDFMonitor.LogOutputHandler("DEBUG:UDP.StartListener:starting");
                ListenerEnabled = true;
                UdpReader();
            }

            CDFMonitor.LogOutputHandler("DEBUG:UDP.StartListener:exit");
        }
コード例 #29
0
 /// <summary>
 /// Disconnects the unc path.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
 public bool DisconnectUncPath(string path)
 {
     try
     {
         return(WindowsNetworking.DisconnectRemote(path) == 0);
     }
     catch (Exception e)
     {
         CDFMonitor.LogOutputHandler("DEBUG:DisconnectUncPath:Exception:" + e.ToString());
         return(false);
     }
 }
コード例 #30
0
        /// <summary>
        /// Copies data from a path stream to a target stream.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The source stream to copyQ to.</param>
        private void CopyStream(Stream source, Stream target)
        {
            CDFMonitor.LogOutputHandler("Debug:CopyStream:enter");
            byte[] buf       = new byte[0x1000];
            int    bytesRead = 0;

            while ((bytesRead = source.Read(buf, 0, buf.Length)) > 0)
            {
                target.Write(buf, 0, bytesRead);
            }
            CDFMonitor.LogOutputHandler("Debug:CopyStream:exit");
        }