-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathservice.cpp
More file actions
65 lines (53 loc) · 1.86 KB
/
service.cpp
File metadata and controls
65 lines (53 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "service.hpp"
bool service::RegisterAndStart(const std::wstring& driver_path, std::wstring driver_name) {
SC_HANDLE scm_handle = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE);
if (!scm_handle) {
return false;
}
// Create the service
SC_HANDLE service_handle = CreateServiceW(
scm_handle,
driver_name.c_str(),
driver_name.c_str(),
SERVICE_START | SERVICE_STOP | DELETE, // Desired access
SERVICE_KERNEL_DRIVER, // Service type (for drivers)
SERVICE_DEMAND_START, // Start type (manual start)
SERVICE_ERROR_NORMAL,
driver_path.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr
);
if (!service_handle) {
if (GetLastError() == ERROR_SERVICE_EXISTS) {
service_handle = OpenServiceW(scm_handle, driver_name.c_str(), SERVICE_START);
}
if (!service_handle) {
CloseServiceHandle(scm_handle);
return false;
}
}
// Start the service
bool result = StartServiceW(service_handle, 0, nullptr);
// Cleanup
CloseServiceHandle(service_handle);
CloseServiceHandle(scm_handle);
return result;
}
bool service::StopAndRemove(const std::wstring& driver_name) {
SC_HANDLE scm_handle = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
if (!scm_handle) {
return false;
}
SC_HANDLE service_handle = OpenServiceW(scm_handle, driver_name.c_str(), SERVICE_STOP | DELETE);
if (!service_handle) {
CloseServiceHandle(scm_handle);
return false;
}
SERVICE_STATUS service_status = {};
if (ControlService(service_handle, SERVICE_CONTROL_STOP, &service_status)) {
Sleep(1000);
}
bool result = DeleteService(service_handle);
CloseServiceHandle(service_handle);
CloseServiceHandle(scm_handle);
return result;
}