static QString getServiceName(DWORD processId)
{
    QString name;
    SC_HANDLE hSCM = OpenSCManager(nullptr, nullptr, SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT);
    if (! hSCM) {
        return name;
    }

    DWORD bufSize = 0;
    DWORD servCount = 0;
    EnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL,
                         nullptr, 0, &bufSize, &servCount, nullptr, nullptr);

    std::vector<BYTE> buffer(bufSize);
    EnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL,
                         buffer.data(), (DWORD)buffer.size(), &bufSize,
                         &servCount, nullptr, nullptr);

    auto services = reinterpret_cast<LPENUM_SERVICE_STATUS_PROCESS>(buffer.data());
    for (unsigned int i = 0; i < servCount; ++i) {
        ENUM_SERVICE_STATUS_PROCESS service = services[i];
        if (service.ServiceStatusProcess.dwProcessId == processId) {
            // This is your service.
            name = QString::fromUtf16((const ushort*)service.lpServiceName);
            break;
        }
    }
    CloseServiceHandle(hSCM);
    return name;
}
Ejemplo n.º 2
0
bool mod_service::getList(vector<KIWI_SERVICE_STATUS_PROCESS> * monVectorService, wstring * machineName) // machine non implémenté
{
	bool reussite = false;
	DWORD error = ERROR_SUCCESS;

	if(SC_HANDLE monManager = OpenSCManager(machineName ? machineName->c_str() : NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE))
	{
		DWORD tailleRequise = 0;
		DWORD nbServices = 0;
		DWORD resumeHandle = 0;
		
		if(!(EnumServicesStatusEx(monManager, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, NULL, 0, &tailleRequise, &nbServices, &resumeHandle, NULL) != 0) && GetLastError() == ERROR_MORE_DATA)
		{
			BYTE * servicesBuff = new BYTE[tailleRequise];
			ENUM_SERVICE_STATUS_PROCESS * mesServ = reinterpret_cast<ENUM_SERVICE_STATUS_PROCESS *>(servicesBuff);
			if(reussite = EnumServicesStatusEx(monManager, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, servicesBuff, tailleRequise, &tailleRequise, &nbServices, &resumeHandle, NULL) != 0)
			{
				for(DWORD i = 0; i < nbServices; i++)
				{
					KIWI_SERVICE_STATUS_PROCESS monService = {mesServ[i].lpServiceName, mesServ[i].lpDisplayName, mesServ[i].ServiceStatusProcess};
					monVectorService->push_back(monService);
				}
			}
			delete[] servicesBuff;
			error = GetLastError();
		}

		CloseServiceHandle(monManager);
		SetLastError(error);
	}
	return reussite;
}
Ejemplo n.º 3
0
QueryData genDrivers(QueryContext& context) {
  DWORD bytesNeeded = 0;
  DWORD serviceCount = 0;
  std::map<std::string, std::string> loadedDrivers;
  QueryData results;

  // Get All Loaded Drivers including ones managed by SCM
  enumLoadedDrivers(loadedDrivers);

  auto schScManager = OpenSCManager(nullptr, nullptr, GENERIC_READ);
  if (schScManager == nullptr) {
    TLOG << "EnumServiceStatusEx failed (" << GetLastError() << ")";
    return {};
  }

  EnumServicesStatusEx(schScManager,
                       SC_ENUM_PROCESS_INFO,
                       SERVICE_DRIVER,
                       SERVICE_STATE_ALL,
                       nullptr,
                       0,
                       &bytesNeeded,
                       &serviceCount,
                       nullptr,
                       nullptr);

  auto buf = static_cast<PVOID>(malloc(bytesNeeded));
  if (EnumServicesStatusEx(schScManager,
                           SC_ENUM_PROCESS_INFO,
                           SERVICE_DRIVER,
                           SERVICE_STATE_ALL,
                           (LPBYTE)buf,
                           bytesNeeded,
                           &bytesNeeded,
                           &serviceCount,
                           nullptr,
                           nullptr) != 0) {
    auto services = static_cast<ENUM_SERVICE_STATUS_PROCESS*>(buf);
    for (DWORD i = 0; i < serviceCount; ++i) {
      queryDrvInfo(schScManager, services[i], loadedDrivers, results);
    }
  } else {
    TLOG << "EnumServiceStatusEx failed (" << GetLastError() << ")";
  }

  free(buf);
  CloseServiceHandle(schScManager);

  for (const auto& element : loadedDrivers) {
    Row r;
    r["name"] = element.first;
    r["path"] = element.second;
    r["status"] = SQL_TEXT(kDrvStatus[4]);
    results.push_back(r);
  }

  return results;
}
Ejemplo n.º 4
0
bool ServiceUtil::is_exist(const tstring& name)
{
    bool bReturn = false;

    do 
    {
        scoped_scmgr_handle hSCMgr(GENERIC_READ);
        if (!hSCMgr.valid())
        {
            break;
        }

        DWORD dwNeededBytes = 0;
        DWORD dwReturnedSerivice = 0;
        DWORD dwResumeEntryNum = 0;
        if (EnumServicesStatusEx(hSCMgr.get(), SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_WIN32, 
            SERVICE_STATE_ALL, NULL, 0, &dwNeededBytes, &dwReturnedSerivice, &dwResumeEntryNum, NULL))
        {
            ErrorLog("EnumServicesStatusEx success while query needed bytes");
            break;
        }

        CLastErrorFormat e;
        if (ERROR_MORE_DATA != e.code())
        {
            ErrorLogLastErrEx(e, "EnumServicesStatusEx error code is not ERROR_MORE_DATA while query needed bytes");
            break;
        }

        boost::scoped_array<BYTE> lpData(new BYTE[dwNeededBytes]);
        memset(lpData.get(), 0, dwNeededBytes);
        if (!EnumServicesStatusEx(hSCMgr.get(), SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_WIN32, 
            SERVICE_STATE_ALL, lpData.get(), dwNeededBytes, &dwNeededBytes, &dwReturnedSerivice, &dwResumeEntryNum, NULL))
        {
            ErrorLogLastErr("EnumServicesStatusEx fail");
            break;
        }

        ENUM_SERVICE_STATUS_PROCESS *lpServiceStatus = reinterpret_cast<ENUM_SERVICE_STATUS_PROCESS *>(lpData.get());
        for (DWORD dwServiceIndex = 0; dwServiceIndex != dwReturnedSerivice; ++dwServiceIndex)
        {
            tstring cur_name = lpServiceStatus[dwServiceIndex].lpServiceName;
            if (boost::algorithm::iequals(cur_name, name))
            {
                bReturn = true;
                break;
            }
        }

    } while (false);

    return bReturn;
}
static QString enumerateService(DWORD processId)
{
    SC_HANDLE hSCM = OpenSCManager(NULL, NULL,
        SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT);

    if (hSCM == NULL) {
        return QString();
    }
    DWORD bufferSize = 0;
    DWORD requiredBufferSize = 0;
    DWORD totalServicesCount = 0;
    EnumServicesStatusEx(hSCM,
			 SC_ENUM_PROCESS_INFO,
			 SERVICE_WIN32,
			 SERVICE_STATE_ALL,
			 NULL,
			 bufferSize,
			 &requiredBufferSize,
			 &totalServicesCount,
			 NULL,
			 NULL);

    std::vector<BYTE> buffer(requiredBufferSize);
    EnumServicesStatusEx(hSCM,
			 SC_ENUM_PROCESS_INFO,
			 SERVICE_WIN32,
			 SERVICE_STATE_ALL,
			 buffer.data(),
			 (DWORD)buffer.size(),
			 &requiredBufferSize,
			 &totalServicesCount,
			 NULL,
			 NULL);

    QString name;
    LPENUM_SERVICE_STATUS_PROCESS services =
        reinterpret_cast<LPENUM_SERVICE_STATUS_PROCESS>(buffer.data());
    for (unsigned int i = 0; i < totalServicesCount; ++i) {
        ENUM_SERVICE_STATUS_PROCESS service = services[i];
        if (service.ServiceStatusProcess.dwProcessId == processId) {
            // This is your service.
            name = QString::fromUtf16((const ushort*)service.lpServiceName);
            break;
        }
    }

    CloseServiceHandle(hSCM);

    return name;
}
Ejemplo n.º 6
0
BOOL get_services(_In_ SC_HANDLE hServiceManager, _In_ DWORD serviceType, _Out_ ENUM_SERVICE_STATUS_PROCESS** servicesBuffer, _Out_ DWORD* serviceCount)
{
	DWORD serviceBufferSize = 1024 * sizeof(ENUM_SERVICE_STATUS_PROCESS);
	ENUM_SERVICE_STATUS_PROCESS* services = static_cast<ENUM_SERVICE_STATUS_PROCESS*>(malloc(serviceBufferSize));

	if (serviceCount) //assume failure
		*serviceCount = 0;

	if (services) {

		SecureZeroMemory(services, serviceBufferSize);

		DWORD remainderBufferSize = 0;
		DWORD resumeHandle = 0;
		if (EnumServicesStatusEx(hServiceManager, SC_ENUM_PROCESS_INFO, serviceType, SERVICE_STATE_ALL, (LPBYTE)services, serviceBufferSize, &remainderBufferSize, serviceCount, &resumeHandle, NULL) != 0)
		{
			// success and we enumerated all the services
			*servicesBuffer = services;
			return TRUE;
		}

		DWORD lastError = GetLastError();
		if (lastError == ERROR_MORE_DATA)
		{
			// we didn't get all the services, so we'll just re-enumerate all to make things easy
			serviceBufferSize += remainderBufferSize;

			ENUM_SERVICE_STATUS_PROCESS* tmp;

			tmp = static_cast<ENUM_SERVICE_STATUS_PROCESS*>(realloc(services, serviceBufferSize));
			if (tmp) {
				services = tmp;
				SecureZeroMemory(services, serviceBufferSize);
				if (EnumServicesStatusEx(hServiceManager, SC_ENUM_PROCESS_INFO, serviceType, SERVICE_STATE_ALL, (LPBYTE)services, serviceBufferSize, &remainderBufferSize, serviceCount, NULL, NULL) != 0)
				{
					*servicesBuffer = services;
					return TRUE;
				}
			}
		}
		else
		{
			printf("ERROR: %u\n", lastError);
		}
		
		free(services);

	}
	return FALSE;
}
Ejemplo n.º 7
0
int	SERVICES(AGENT_REQUEST *request, AGENT_RESULT *result)
{
	int				start_type, service_state, ret;
	char				*type, *state, *exclude, *buf = NULL, *utf8;
	SC_HANDLE			h_mgr;
	ENUM_SERVICE_STATUS_PROCESS	*ssp = NULL;
	DWORD				sz = 0, szn, i, services, resume_handle = 0;

	if (3 < request->nparam)
		return SYSINFO_RET_FAIL;

	type = get_rparam(request, 0);
	state = get_rparam(request, 1);
	exclude = get_rparam(request, 2);

	if (NULL == type || '\0' == *type || 0 == strcmp(type, "all"))	/* default parameter */
		start_type = ZBX_SRV_STARTTYPE_ALL;
	else if (0 == strcmp(type, "automatic"))
		start_type = ZBX_SRV_STARTTYPE_AUTOMATIC;
	else if (0 == strcmp(type, "manual"))
		start_type = ZBX_SRV_STARTTYPE_MANUAL;
	else if (0 == strcmp(type, "disabled"))
		start_type = ZBX_SRV_STARTTYPE_DISABLED;
	else
		return SYSINFO_RET_FAIL;

	if (NULL == state || '\0' == *state || 0 == strcmp(state, "all"))	/* default parameter */
		service_state = ZBX_SRV_STATE_ALL;
	else if (0 == strcmp(state, "stopped"))
		service_state = ZBX_SRV_STATE_STOPPED;
	else if (0 == strcmp(state, "started"))
		service_state = ZBX_SRV_STATE_STARTED;
	else if (0 == strcmp(state, "start_pending"))
		service_state = ZBX_SRV_STATE_START_PENDING;
	else if (0 == strcmp(state, "stop_pending"))
		service_state = ZBX_SRV_STATE_STOP_PENDING;
	else if (0 == strcmp(state, "running"))
		service_state = ZBX_SRV_STATE_RUNNING;
	else if (0 == strcmp(state, "continue_pending"))
		service_state = ZBX_SRV_STATE_CONTINUE_PENDING;
	else if (0 == strcmp(state, "pause_pending"))
		service_state = ZBX_SRV_STATE_PAUSE_PENDING;
	else if (0 == strcmp(state, "paused"))
		service_state = ZBX_SRV_STATE_PAUSED;
	else
		return SYSINFO_RET_FAIL;

	if (NULL == (h_mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
		return SYSINFO_RET_FAIL;

	while (0 != (ret = EnumServicesStatusEx(h_mgr, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL,
			(LPBYTE)ssp, sz, &szn, &services, &resume_handle, NULL)) || ERROR_MORE_DATA == GetLastError())
	{
		for (i = 0; i < services; i++)
		{
			SC_HANDLE	h_srv;

			if (NULL == (h_srv = OpenService(h_mgr, ssp[i].lpServiceName, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG)))
				continue;

			if (SUCCEED == check_service_starttype(h_srv, start_type))
			{
				if (SUCCEED == check_service_state(h_srv, service_state))
				{
					utf8 = zbx_unicode_to_utf8(ssp[i].lpServiceName);

					if (NULL == exclude || FAIL == str_in_list(exclude, utf8, ','))
						buf = zbx_strdcatf(buf, "%s\n", utf8);

					zbx_free(utf8);
				}
			}

			CloseServiceHandle(h_srv);
		}

		if (0 == szn)
			break;

		if (NULL == ssp)
		{
			sz = szn;
			ssp = (ENUM_SERVICE_STATUS_PROCESS *)zbx_malloc((void *)ssp, sz);
		}
	}

	zbx_free(ssp);

	CloseServiceHandle(h_mgr);

	if (NULL == buf)
		buf = zbx_strdup(buf, "0");

	SET_STR_RESULT(result, buf);

	return SYSINFO_RET_OK;
}
Ejemplo n.º 8
0
PVOID PhEnumServices(
    _In_ SC_HANDLE ScManagerHandle,
    _In_opt_ ULONG Type,
    _In_opt_ ULONG State,
    _Out_ PULONG Count
    )
{
    static ULONG initialBufferSize = 0x8000;
    LOGICAL result;
    PVOID buffer;
    ULONG bufferSize;
    ULONG returnLength;
    ULONG servicesReturned;

    if (!Type)
        Type = WindowsVersion >= WINDOWS_10 ? SERVICE_TYPE_ALL : (SERVICE_DRIVER | SERVICE_WIN32);
    if (!State)
        State = SERVICE_STATE_ALL;

    bufferSize = initialBufferSize;
    buffer = PhAllocate(bufferSize);

    if (!(result = EnumServicesStatusEx(
        ScManagerHandle,
        SC_ENUM_PROCESS_INFO,
        Type,
        State,
        buffer,
        bufferSize,
        &returnLength,
        &servicesReturned,
        NULL,
        NULL
        )))
    {
        if (GetLastError() == ERROR_MORE_DATA)
        {
            PhFree(buffer);
            bufferSize += returnLength;
            buffer = PhAllocate(bufferSize);

            result = EnumServicesStatusEx(
                ScManagerHandle,
                SC_ENUM_PROCESS_INFO,
                Type,
                State,
                buffer,
                bufferSize,
                &returnLength,
                &servicesReturned,
                NULL,
                NULL
                );
        }

        if (!result)
        {
            PhFree(buffer);
            return NULL;
        }
    }

    if (bufferSize <= 0x20000) initialBufferSize = bufferSize;
    *Count = servicesReturned;

    return buffer;
}
Ejemplo n.º 9
0
void
GetServices ( void )
{
    LV_ITEM item;
    WORD wCodePage;
    WORD wLangID;
    SC_HANDLE ScHandle;
    SC_HANDLE hService;
    DWORD BytesNeeded = 0;
    DWORD ResumeHandle = 0;
    DWORD NumServices = 0;
    DWORD dwHandle, dwLen;
    size_t Index;
    UINT BufLen;
    TCHAR szStatus[128];
    TCHAR* lpData;
    TCHAR* lpBuffer;
    TCHAR szStrFileInfo[80];
    TCHAR FileName[MAX_PATH];
    LPVOID pvData;

    LPSERVICE_FAILURE_ACTIONS pServiceFailureActions = NULL;
    LPQUERY_SERVICE_CONFIG pServiceConfig = NULL;
    ENUM_SERVICE_STATUS_PROCESS *pServiceStatus = NULL;

    ScHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE);
    if (ScHandle != NULL)
    {
        if (EnumServicesStatusEx(ScHandle, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, (LPBYTE)pServiceStatus, 0, &BytesNeeded, &NumServices, &ResumeHandle, 0) == 0)
        {
            /* Call function again if required size was returned */
            if (GetLastError() == ERROR_MORE_DATA)
            {
                /* reserve memory for service info array */
                pServiceStatus = HeapAlloc(GetProcessHeap(), 0, BytesNeeded);
                if (!pServiceStatus)
                {
                    CloseServiceHandle(ScHandle);
                    return;
                }

                /* fill array with service info */
                if (EnumServicesStatusEx(ScHandle, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, (LPBYTE)pServiceStatus, BytesNeeded, &BytesNeeded, &NumServices, &ResumeHandle, 0) == 0)
                {
                    HeapFree(GetProcessHeap(), 0, pServiceStatus);
                    CloseServiceHandle(ScHandle);
                    return;
                }
            }
            else /* exit on failure */
            {
                CloseServiceHandle(ScHandle);
                return;
            }
        }

        if (NumServices)
        {
            if (!pServiceStatus)
            {
                CloseServiceHandle(ScHandle);
                return;
            }

            for (Index = 0; Index < NumServices; Index++)
            {
                memset(&item, 0, sizeof(LV_ITEM));
                item.mask = LVIF_TEXT;
                item.iImage = 0;
                item.pszText = pServiceStatus[Index].lpDisplayName;
                item.iItem = ListView_GetItemCount(hServicesListCtrl);
                item.lParam = 0;
                item.iItem = ListView_InsertItem(hServicesListCtrl, &item);

                if (pServiceStatus[Index].ServiceStatusProcess.dwCurrentState == SERVICE_RUNNING)
                {
                    ListView_SetCheckState(hServicesListCtrl, item.iItem, TRUE);
                }

                BytesNeeded = 0;
                hService = OpenService(ScHandle, pServiceStatus[Index].lpServiceName, SC_MANAGER_CONNECT);
                if (hService != NULL)
                {
                    /* check if service is required by the system*/
                    if (!QueryServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, (LPBYTE)NULL, 0, &BytesNeeded))
                    {
                        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
                        {
                            pServiceFailureActions = HeapAlloc(GetProcessHeap(), 0, BytesNeeded);
                            if (pServiceFailureActions == NULL)
                            {
                                HeapFree(GetProcessHeap(), 0, pServiceStatus);
                                CloseServiceHandle(hService);
                                CloseServiceHandle(ScHandle);
                                return;
                            }

                            if (!QueryServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, (LPBYTE)pServiceFailureActions, BytesNeeded, &BytesNeeded))
                            {
                                HeapFree(GetProcessHeap(), 0, pServiceFailureActions);
                                HeapFree(GetProcessHeap(), 0, pServiceStatus);
                                CloseServiceHandle(hService);
                                CloseServiceHandle(ScHandle);
                                return;
                            }
                        }
                        else /* exit on failure */
                        {
                            HeapFree(GetProcessHeap(), 0, pServiceStatus);
                            CloseServiceHandle(hService);
                            CloseServiceHandle(ScHandle);
                            return;
                        }
                    }

                    if (pServiceFailureActions != NULL)
                    {
                        if (pServiceFailureActions->cActions && pServiceFailureActions->lpsaActions[0].Type == SC_ACTION_REBOOT)
                        {
                                LoadString(hInst, IDS_SERVICES_YES, szStatus, 128);
                                item.pszText = szStatus;
                                item.iSubItem = 1;
                                SendMessage(hServicesListCtrl, LVM_SETITEMTEXT, item.iItem, (LPARAM) &item);
                        }
                        HeapFree(GetProcessHeap(), 0, pServiceFailureActions);
                        pServiceFailureActions = NULL;
                    }

                    /* get vendor of service binary */
                    BytesNeeded = 0;
                    if (!QueryServiceConfig(hService, NULL, 0, &BytesNeeded))
                    {
                        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
                        {
                            pServiceConfig = HeapAlloc(GetProcessHeap(), 0, BytesNeeded);
                            if (pServiceConfig == NULL)
                            {
                                HeapFree(GetProcessHeap(), 0, pServiceStatus);
                                CloseServiceHandle(hService);
                                CloseServiceHandle(ScHandle);
                                return;
                            }
                            if (!QueryServiceConfig(hService, pServiceConfig, BytesNeeded, &BytesNeeded))
                            {
                                HeapFree(GetProcessHeap(), 0, pServiceConfig);
                                HeapFree(GetProcessHeap(), 0, pServiceStatus);
                                CloseServiceHandle(hService);
                                CloseServiceHandle(ScHandle);
                                return;
                            }
                        }
                        else /* exit on failure */
                        {
                            HeapFree(GetProcessHeap(), 0, pServiceStatus);
                            CloseServiceHandle(hService);
                            CloseServiceHandle(ScHandle);
                            return;
                        }
                    }

                    memset(&FileName, 0, MAX_PATH);
                    if (_tcscspn(pServiceConfig->lpBinaryPathName, _T("\"")))
                    {
                        _tcsncpy(FileName, pServiceConfig->lpBinaryPathName, _tcscspn(pServiceConfig->lpBinaryPathName, _T(" ")) );
                    }
                    else
                    {
                        _tcscpy(FileName, pServiceConfig->lpBinaryPathName);
                    }

                    HeapFree(GetProcessHeap(), 0, pServiceConfig);
                    pServiceConfig = NULL;

                    dwLen = GetFileVersionInfoSize(FileName, &dwHandle);
                    if (dwLen)
                    {
                        lpData = HeapAlloc(GetProcessHeap(), 0, dwLen);
                        if (lpData == NULL)
                        {
                            HeapFree(GetProcessHeap(), 0, pServiceStatus);
                            CloseServiceHandle(hService);
                            CloseServiceHandle(ScHandle);
                            return;
                        }
                        if (!GetFileVersionInfo (FileName, dwHandle, dwLen, lpData))
                        {
                            HeapFree(GetProcessHeap(), 0, lpData);
                            HeapFree(GetProcessHeap(), 0, pServiceStatus);
                            CloseServiceHandle(hService);
                            CloseServiceHandle(ScHandle);
                            return;
                        }

                        if (VerQueryValue(lpData, _T("\\VarFileInfo\\Translation"), &pvData, (PUINT) &BufLen))
                        {
                            wCodePage = LOWORD(*(DWORD*) pvData);
                            wLangID = HIWORD(*(DWORD*) pvData);
                            wsprintf(szStrFileInfo, _T("StringFileInfo\\%04X%04X\\CompanyName"), wCodePage, wLangID);
                        }

                        if (VerQueryValue (lpData, szStrFileInfo, (void**) &lpBuffer, (PUINT) &BufLen))
                        {
                            item.pszText = lpBuffer;
                            item.iSubItem = 2;
                            SendMessage(hServicesListCtrl, LVM_SETITEMTEXT, item.iItem, (LPARAM) &item);
                        }
                        HeapFree(GetProcessHeap(), 0, lpData);
                    }
                    else
                    {
                        LoadString(hInst, IDS_SERVICES_UNKNOWN, szStatus, 128);
                        item.pszText = szStatus;
                        item.iSubItem = 2;
                        SendMessage(hServicesListCtrl, LVM_SETITEMTEXT, item.iItem, (LPARAM) &item);
                    }
                    CloseServiceHandle(hService);
                }

                LoadString(hInst, ((pServiceStatus[Index].ServiceStatusProcess.dwCurrentState == SERVICE_STOPPED) ? IDS_SERVICES_STATUS_STOPPED : IDS_SERVICES_STATUS_RUNNING), szStatus, 128);
                item.pszText = szStatus;
                item.iSubItem = 3;
                SendMessage(hServicesListCtrl, LVM_SETITEMTEXT, item.iItem, (LPARAM) &item);

            }
        }

        HeapFree(GetProcessHeap(), 0, pServiceStatus);
        CloseServiceHandle(ScHandle);
    }

}
Ejemplo n.º 10
0
int	SERVICE_DISCOVERY(AGENT_REQUEST *request, AGENT_RESULT *result)
{
	ENUM_SERVICE_STATUS_PROCESS	*ssp = NULL;
	QUERY_SERVICE_CONFIG		*qsc = NULL;
	SERVICE_DESCRIPTION		*scd = NULL;
	SC_HANDLE			h_mgr;
	DWORD				sz = 0, szn, i, k, services, resume_handle = 0;
	char				*utf8;
	struct zbx_json			j;

	if (NULL == (h_mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot obtain system information."));
		return SYSINFO_RET_FAIL;
	}

	zbx_json_init(&j, ZBX_JSON_STAT_BUF_LEN);
	zbx_json_addarray(&j, ZBX_PROTO_TAG_DATA);

	while (0 != EnumServicesStatusEx(h_mgr, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL,
			(LPBYTE)ssp, sz, &szn, &services, &resume_handle, NULL) || ERROR_MORE_DATA == GetLastError())
	{
		for (i = 0; i < services; i++)
		{
			SC_HANDLE	h_srv;
			DWORD		current_state;

			if (NULL == (h_srv = OpenService(h_mgr, ssp[i].lpServiceName, SERVICE_QUERY_CONFIG)))
				continue;

			QueryServiceConfig(h_srv, NULL, 0, &sz);

			if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
			{
				zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain configuration of service \"%s\": %s",
						ssp[i].lpServiceName, strerror_from_system(GetLastError()));
				goto next;
			}

			qsc = (QUERY_SERVICE_CONFIG *)zbx_malloc(qsc, sz);

			if (0 == QueryServiceConfig(h_srv, qsc, sz, &sz))
			{
				zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain configuration of service \"%s\": %s",
						ssp[i].lpServiceName, strerror_from_system(GetLastError()));
				goto next;
			}

			QueryServiceConfig2(h_srv, SERVICE_CONFIG_DESCRIPTION, NULL, 0, &sz);

			if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
			{
				zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain description of service \"%s\": %s",
						ssp[i].lpServiceName, strerror_from_system(GetLastError()));
				goto next;
			}

			scd = (SERVICE_DESCRIPTION *)zbx_malloc(scd, sz);

			if (0 == QueryServiceConfig2(h_srv, SERVICE_CONFIG_DESCRIPTION, (LPBYTE)scd, sz, &sz))
			{
				zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain description of service \"%s\": %s",
						ssp[i].lpServiceName, strerror_from_system(GetLastError()));
				goto next;
			}

			zbx_json_addobject(&j, NULL);

			utf8 = zbx_unicode_to_utf8(ssp[i].lpServiceName);
			zbx_json_addstring(&j, "{#SERVICE.NAME}", utf8, ZBX_JSON_TYPE_STRING);
			zbx_free(utf8);

			utf8 = zbx_unicode_to_utf8(ssp[i].lpDisplayName);
			zbx_json_addstring(&j, "{#SERVICE.DISPLAYNAME}", utf8, ZBX_JSON_TYPE_STRING);
			zbx_free(utf8);

			if (NULL != scd->lpDescription)
			{
				utf8 = zbx_unicode_to_utf8(scd->lpDescription);
				zbx_json_addstring(&j, "{#SERVICE.DESCRIPTION}", utf8, ZBX_JSON_TYPE_STRING);
				zbx_free(utf8);
			}
			else
				zbx_json_addstring(&j, "{#SERVICE.DESCRIPTION}", "", ZBX_JSON_TYPE_STRING);

			current_state = ssp[i].ServiceStatusProcess.dwCurrentState;
			for (k = 0; k < ARRSIZE(service_states) && current_state != service_states[k]; k++)
				;

			zbx_json_adduint64(&j, "{#SERVICE.STATE}", k);
			zbx_json_addstring(&j, "{#SERVICE.STATENAME}", get_state_string(current_state),
					ZBX_JSON_TYPE_STRING);

			utf8 = zbx_unicode_to_utf8(qsc->lpBinaryPathName);
			zbx_json_addstring(&j, "{#SERVICE.PATH}", utf8, ZBX_JSON_TYPE_STRING);
			zbx_free(utf8);

			utf8 = zbx_unicode_to_utf8(qsc->lpServiceStartName);
			zbx_json_addstring(&j, "{#SERVICE.USER}", utf8, ZBX_JSON_TYPE_STRING);
			zbx_free(utf8);

			if (SERVICE_AUTO_START == qsc->dwStartType)
			{
				if (SUCCEED == check_delayed_start(h_srv))
				{
					zbx_json_adduint64(&j, "{#SERVICE.STARTUP}", 1);
					zbx_json_addstring(&j, "{#SERVICE.STARTUPNAME}", "automatic delayed",
							ZBX_JSON_TYPE_STRING);
				}
				else
				{
					zbx_json_adduint64(&j, "{#SERVICE.STARTUP}", 0);
					zbx_json_addstring(&j, "{#SERVICE.STARTUPNAME}", "automatic",
							ZBX_JSON_TYPE_STRING);
				}
			}
			else
			{
				for (k = 2; k < ARRSIZE(start_types) &&	qsc->dwStartType != start_types[k]; k++)
					;

				zbx_json_adduint64(&j, "{#SERVICE.STARTUP}", k);
				zbx_json_addstring(&j, "{#SERVICE.STARTUPNAME}", get_startup_string(qsc->dwStartType),
						ZBX_JSON_TYPE_STRING);
			}

			zbx_json_close(&j);
next:
			zbx_free(scd);
			zbx_free(qsc);

			CloseServiceHandle(h_srv);
		}

		if (0 == szn)
			break;

		if (NULL == ssp)
		{
			sz = szn;
			ssp = (ENUM_SERVICE_STATUS_PROCESS *)zbx_malloc(ssp, sz);
		}
	}

	zbx_free(ssp);

	CloseServiceHandle(h_mgr);

	zbx_json_close(&j);

	SET_STR_RESULT(result, zbx_strdup(NULL, j.buffer));

	zbx_json_free(&j);

	return SYSINFO_RET_OK;
}
Ejemplo n.º 11
0
BOOL
GetServiceList(PMAIN_WND_INFO Info,
               DWORD *NumServices)
{
    SC_HANDLE ScHandle;
    BOOL bRet = FALSE;

    DWORD BytesNeeded = 0;
    DWORD ResumeHandle = 0;

    *NumServices = 0;

    if (Info->pAllServices != NULL)
    {
        HeapFree(ProcessHeap,
                     0,
                     Info->pAllServices);
        Info->pAllServices = NULL;
    }

    ScHandle = OpenSCManagerW(NULL,
                              NULL,
                              SC_MANAGER_ENUMERATE_SERVICE);
    if (ScHandle != NULL)
    {
        if (!EnumServicesStatusEx(ScHandle,
                                  SC_ENUM_PROCESS_INFO,
                                  SERVICE_WIN32,
                                  SERVICE_STATE_ALL,
                                  NULL,
                                  0,
                                  &BytesNeeded,
                                  NumServices,
                                  &ResumeHandle,
                                  0))
        {
            /* Call function again if required size was returned */
            if (GetLastError() == ERROR_MORE_DATA)
            {
                /* reserve memory for service info array */
                Info->pAllServices = (ENUM_SERVICE_STATUS_PROCESS *) HeapAlloc(ProcessHeap,
                                                                         0,
                                                                         BytesNeeded);
                if (Info->pAllServices)
                {
                    /* fill array with service info */
                    if (EnumServicesStatusEx(ScHandle,
                                             SC_ENUM_PROCESS_INFO,
                                             SERVICE_WIN32,
                                             SERVICE_STATE_ALL,
                                             (LPBYTE)Info->pAllServices,
                                             BytesNeeded,
                                             &BytesNeeded,
                                             NumServices,
                                             &ResumeHandle,
                                             0))
                    {
                        bRet = TRUE;
                    }
                }
            }
        }
    }

    if (ScHandle)
        CloseServiceHandle(ScHandle);

    if (!bRet && Info->pAllServices)
    {
        HeapFree(ProcessHeap,
                 0,
                 Info->pAllServices);
    }

    return bRet;
}
Ejemplo n.º 12
0
void CServices::GetServiceInfo()
{
	SC_HANDLE sc = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	if(sc==NULL)
		return;

	SC_HANDLE hSCCervice;

	DWORD ret=0;
	DWORD size=0;
	DWORD dwError=0;
	LPENUM_SERVICE_STATUS_PROCESS st;
	LPQUERY_SERVICE_CONFIG lpsc;
	CServices::PSERVICEINFO pServiceInfo;
	/*得到所需要的大小*/
	if(!EnumServicesStatusEx(sc,SC_ENUM_PROCESS_INFO, SERVICE_WIN32,SERVICE_STATE_ALL, NULL,0,&size,&ret, NULL, NULL))
	{		
		st = (LPENUM_SERVICE_STATUS_PROCESS)LocalAlloc(LPTR,(SIZE_T)size);
		EnumServicesStatusEx(sc,SC_ENUM_PROCESS_INFO,SERVICE_WIN32,SERVICE_STATE_ALL, (LPBYTE)st,size,&size,&ret,NULL, NULL);
	}
	pServiceInfo = (CServices::PSERVICEINFO)LocalAlloc(LPTR,(SIZE_T)(ret * sizeof(SERVICEINFO)));
	CServices::PSERVICEINFO pTemp = pServiceInfo;
	/*得到每一个服务的有关信息*/
	for (int i=0; i<ret; i++)
	{
		hSCCervice = OpenService(sc, st[i].lpServiceName, SERVICE_QUERY_CONFIG);
		if(hSCCervice == NULL)
		{
			CloseServiceHandle(sc);
			return;
		}
		/*得到服务信息所需大小*/
		if(!QueryServiceConfig(hSCCervice, NULL, 0, &size))
		{
			dwError = GetLastError();
			if(ERROR_INSUFFICIENT_BUFFER == dwError)
			{
				lpsc = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR,(SIZE_T)size);
				QueryServiceConfig(hSCCervice, lpsc, size, &size);
			}else{
				goto cleanup;
			}
		}
		pTemp->ServiceStatus = st[i];
		/*所属组为exe文件路径中"-k "之后的字符*/
		WCHAR *p = wcsstr(lpsc->lpBinaryPathName, TEXT("-k"));
		/*没有则说明不属于任何组*/
		if(NULL == p)
		{
			wcscpy(pTemp->OrderGroup, TEXT("N/A"));
		}
		else
		{
			wcscpy(pTemp->OrderGroup, p+3);
		}
		
		pTemp++;
	}	

	RefreshSevice(pServiceInfo, ret);

cleanup:
	CloseServiceHandle(sc);
	CloseServiceHandle(hSCCervice);
}
Ejemplo n.º 13
0
/*
* supCreateSCMSnapshot
*
* Purpose:
*
* Collects SCM information for drivers description.
*
* Returned buffer must be freed with supFreeScmSnapshot after usage.
*
*/
PVOID supCreateSCMSnapshot(
	PSIZE_T lpNumberOfEntries
	)
{
	BOOL cond = FALSE, bResult = FALSE;
	SC_HANDLE schSCManager;
	DWORD dwBytesNeeded, dwServicesReturned, dwSize, dwSlack;
	PVOID Services = NULL;

	if (lpNumberOfEntries) {
		*lpNumberOfEntries = 0;
	}

	do {
		schSCManager = OpenSCManager(NULL,
			NULL,
			SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE
			);

		if (schSCManager == NULL) {
			break;
		}

		// query required memory size for snapshot
		dwBytesNeeded = 0;
		dwServicesReturned = 0;

		dwSize = 0x1000;
		Services = VirtualAlloc(NULL, dwSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
		if (Services == NULL) {
			break;
		}
		
		bResult = EnumServicesStatusEx(schSCManager, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER, 
			SERVICE_STATE_ALL, Services, dwSize, &dwBytesNeeded, &dwServicesReturned, NULL, NULL);	
		if (bResult == FALSE) {

			if (GetLastError() == ERROR_MORE_DATA) {
				// allocate memory block with page aligned size
				VirtualFree(Services, 0, MEM_RELEASE);
				dwSize = dwBytesNeeded + sizeof(ENUM_SERVICE_STATUS_PROCESS);
				dwSlack = dwSize % 0x1000;
				if (dwSlack > 0) dwSize = dwSize + 0x1000 - dwSlack;

				Services = VirtualAlloc(NULL, dwSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
				if (Services == NULL) {
					break;
				}

				if (!EnumServicesStatusEx(schSCManager, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER, 
					SERVICE_STATE_ALL, Services, dwSize, &dwBytesNeeded, &dwServicesReturned, NULL, NULL)) 
				{
					VirtualFree(Services, 0, MEM_RELEASE);
					Services = NULL;
					break;
				}
			} //ERROR_MORE_DATA
		} //bResult == FALSE;

		// also return actual number of services
		if (lpNumberOfEntries) {
			*lpNumberOfEntries = dwServicesReturned;
		}

		CloseServiceHandle(schSCManager);
	} while (cond);

	return Services;
}
Ejemplo n.º 14
0
static BOOL
EnumServices(ENUM_SERVICE_STATUS_PROCESS **pServiceStatus,
             DWORD ServiceType,
             DWORD ServiceState)
{
    SC_HANDLE hSCManager;
    DWORD BufSize = 0;
    DWORD BytesNeeded = 0;
    DWORD ResumeHandle = 0;
    DWORD NumServices = 0;
    DWORD Ret;

    hSCManager = OpenSCManager(NULL,
                               NULL,
                               SC_MANAGER_ENUMERATE_SERVICE);
    if (hSCManager == NULL)
    {
        ReportLastError();
        return FALSE;
    }

    Ret = EnumServicesStatusEx(hSCManager,
                               SC_ENUM_PROCESS_INFO,
                               ServiceType,
                               ServiceState,
                               (LPBYTE)*pServiceStatus,
                               BufSize,
                               &BytesNeeded,
                               &NumServices,
                               &ResumeHandle,
                               0);

    if ((Ret == 0) && (GetLastError() == ERROR_MORE_DATA))
    {
        *pServiceStatus = (ENUM_SERVICE_STATUS_PROCESS *)
                          HeapAlloc(GetProcessHeap(),
                                    0,
                                    BytesNeeded);
        if (*pServiceStatus != NULL)
        {
            if (EnumServicesStatusEx(hSCManager,
                                     SC_ENUM_PROCESS_INFO,
                                     ServiceType,
                                     ServiceState,
                                     (LPBYTE)*pServiceStatus,
                                     BytesNeeded,
                                     &BytesNeeded,
                                     &NumServices,
                                     &ResumeHandle,
                                     0))
            {
                CloseServiceHandle(hSCManager);
                return NumServices;
            }
        }
    }

    ReportLastError();
    if (*pServiceStatus)
        HeapFree(GetProcessHeap(), 0, *pServiceStatus);

    CloseServiceHandle(hSCManager);

    return NumServices;
}
Ejemplo n.º 15
0
/*
 * Enumerate all services.
 */
PyObject *
psutil_winservice_enumerate(PyObject *self, PyObject *args) {
    ENUM_SERVICE_STATUS_PROCESS *lpService = NULL;
    BOOL ok;
    SC_HANDLE sc = NULL;
    DWORD bytesNeeded = 0;
    DWORD srvCount;
    DWORD resumeHandle = 0;
    DWORD dwBytes = 0;
    DWORD i;
    PyObject *py_retlist = PyList_New(0);
    PyObject *py_tuple = NULL;
    PyObject *py_unicode_display_name = NULL;

    if (py_retlist == NULL)
        return NULL;

    sc = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE);
    if (sc == NULL) {
        PyErr_SetFromWindowsErr(0);
        return NULL;
    }

    for (;;) {
        ok = EnumServicesStatusEx(
            sc,
            SC_ENUM_PROCESS_INFO,
            SERVICE_WIN32,  // XXX - extend this to include drivers etc.?
            SERVICE_STATE_ALL,
            (LPBYTE)lpService,
            dwBytes,
            &bytesNeeded,
            &srvCount,
            &resumeHandle,
            NULL);
        if (ok || (GetLastError() != ERROR_MORE_DATA))
            break;
        if (lpService)
            free(lpService);
        dwBytes = bytesNeeded;
        lpService = (ENUM_SERVICE_STATUS_PROCESS*)malloc(dwBytes);
    }

    for (i = 0; i < srvCount; i++) {
        // Get unicode display name.
        py_unicode_display_name = NULL;
        py_unicode_display_name = PyUnicode_Decode(
            lpService[i].lpDisplayName,
            _tcslen(lpService[i].lpDisplayName),
            Py_FileSystemDefaultEncoding,
            "replace");
        if (py_unicode_display_name == NULL)
            goto error;

        // Construct the result.
        py_tuple = Py_BuildValue(
            "(sO)",
            lpService[i].lpServiceName,  // name
            py_unicode_display_name  // display_name
        );
        if (py_tuple == NULL)
            goto error;
        if (PyList_Append(py_retlist, py_tuple))
            goto error;
        Py_DECREF(py_unicode_display_name);
        Py_DECREF(py_tuple);
    }

    // Free resources.
    CloseServiceHandle(sc);
    free(lpService);
    return py_retlist;

error:
    Py_XDECREF(py_unicode_display_name);
    Py_XDECREF(py_tuple);
    Py_DECREF(py_retlist);
    if (sc != NULL)
        CloseServiceHandle(sc);
    if (lpService != NULL)
        free(lpService);
    return NULL;
}