forked from poweradminllc/PAExec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServiceImpl.cpp
332 lines (290 loc) · 8.8 KB
/
ServiceImpl.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// ServiceImpl.cpp: Implementation for remote service
//
// Copyright (c) Power Admin LLC, 2012 - 2013
//
// This code is provided "as is", with absolutely no warranty expressed
// or implied. Any use is at your own risk.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "PAExec.h"
#include <process.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
__time64_t gLastClientContact = 0;
bool gbStop = false;
SERVICE_STATUS_HANDLE ghService = NULL;
SERVICE_STATUS gServiceStatus = {0};
static bool gbDevOnlyDebug = false;
bool gbInService = false;
extern volatile long gInProcessRequests;
void __cdecl StopServiceAsync(void*)
{
while(false == gbStop)
{
Sleep(5000);
if(0 == gInProcessRequests)
{
//wait 2 more seconds to see if it's still at zero to hope we didn't just catch it in between requests
Sleep(2000);
if(0 == gInProcessRequests)
{
Log(L"PAExec service stopping (async)", false);
gbStop = true; //signals to other places in app to stop too
if(NULL != ghService)
{
gServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(ghService, &gServiceStatus);
}
}
}
}
}
void WINAPI ServiceControlHandler(DWORD dwControl)
{
switch(dwControl)
{
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
if(0 == gInProcessRequests)
{
gbStop = true;
_ASSERT(NULL != ghService);
if(NULL != ghService)
{
Log(L"PAExec service stopping", false);
gServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(ghService, &gServiceStatus);
}
}
else
{
Log(L"PAExec received request to stop, but still have active requests. Will stop later.", false);
_beginthread(StopServiceAsync, 0, 0);
}
break;
}
}
#define BUFF_SIZE_HINT 16384
UINT WINAPI PipeClientThreadProc(void* p)
{
HANDLE hPipe = (HANDLE)p;
bool bBail = false;
while(true)
{
RemMsg request, response;
BYTE buff[BUFF_SIZE_HINT] = {0};
// Read client requests from the pipe.
bool bFirstRead = true;
BOOL fSuccess = FALSE;
DWORD gle = 0;
do
{
DWORD cbRead = 0;
// Read from the pipe.
fSuccess = ReadFile(
hPipe, // pipe handle
buff, // buffer to receive reply
sizeof(buff), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped
if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
{
gle = GetLastError();
Log(L"Error reading request from pipe -- stopping service", gle);
bBail = true;
break;
}
if(bFirstRead)
{
if(cbRead < sizeof(WORD))
{
gle = GetLastError();
Log(L"Received too little data in request -- stopping service", gle);
bBail = true;
break;
}
request.SetFromReceivedData(buff, cbRead);
bFirstRead = false;
}
else
request.m_payload.insert(request.m_payload.end(), buff, buff + cbRead);
} while (!fSuccess); // repeat loop if ERROR_MORE_DATA
if(bBail)
break;
HandleMsg(request, response, hPipe);
DWORD totalLen = 0;
const BYTE* pDataToSend = response.GetDataToSend(totalLen);
DWORD cbWritten = 0;
// Send a message to the pipe server.
fSuccess = WriteFile(
hPipe, // pipe handle
pDataToSend, // message
totalLen, // message length
&cbWritten,// bytes written
NULL); // not overlapped
if (!fSuccess || (cbWritten != totalLen))
{
gle = GetLastError();
Log(L"Error sending data back -- stopping service.", gle);
bBail = true;
break;
}
}
// Flush the pipe to allow the client to read the pipe's contents
// before disconnecting. Then disconnect the pipe, and close the
// handle to this pipe instance.
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
if(bBail)
ServiceControlHandler(SERVICE_CONTROL_STOP);
return 0;
}
VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
gbODS = true; //service always logs to DbgView at first
Log(L"PAExec ServiceMain starting.", false);
gServiceStatus.dwCurrentState = SERVICE_START_PENDING;
gServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
gServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; //when this is set, the service name isn't validated since there is only one service running in the process
if(false == gbDevOnlyDebug)
{
ghService = RegisterServiceCtrlHandler(L"PAExec", ServiceControlHandler);
if(0 == ghService)
{
Log(L"RegisterServiceCtrlHandler failed in PAExec", GetLastError());
return;
}
gServiceStatus.dwCurrentState = SERVICE_RUNNING;
BOOL b = SetServiceStatus(ghService, &gServiceStatus);
if(FALSE == b)
Log(L"Failed to signal PAExec running.", GetLastError());
}
Log(L"PAExec service running.", false);
gLastClientContact = _time64(NULL);
//Pipe server
//the name of the pipe will be the name of the executable, which is based on the caller, so it should always be unique
wchar_t path[_MAX_PATH * 2] = {0};
GetModuleFileName(NULL, path, ARRAYSIZE(path));
wchar_t* pC = wcsrchr(path, L'\\');
if(NULL != pC)
pC++; //get past backslash
CString pipename;
pipename.Format(L"\\\\.\\pipe\\%s", pC);
// The main loop creates an instance of the named pipe and
// then waits for a client to connect to it. When the client
// connects, a thread is created to handle communications
// with that client, and the loop is repeated.
while(false == gbStop)
{
HANDLE hPipe = CreateNamedPipe(
pipename, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
BUFF_SIZE_HINT, // output buffer size
BUFF_SIZE_HINT, // input buffer size
0, // client time-out
NULL); // default security attribute
if (BAD_HANDLE(hPipe))
{
CString msg;
msg.Format(L"PAExec failed to create pipe %s.", pipename);
Log(msg, GetLastError());
gbStop = true;
continue;
}
else
{
CString msg;
msg.Format(L"PAExec created pipe %s.", pipename);
Log(msg, false);
}
// Wait for the client to connect; if it succeeds,
// the function returns a nonzero value. If the function
// returns zero, GetLastError returns ERROR_PIPE_CONNECTED.
BOOL fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (fConnected)
{
// Create a thread for this client.
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, PipeClientThreadProc, hPipe, 0, NULL);
if (hThread == NULL)
{
gbStop = true;
continue;
}
else
CloseHandle(hThread);
}
else
// The client could not connect, so close the pipe.
CloseHandle(hPipe);
}
Log(L"PAExec exiting loop.", false);
if(false == gbDevOnlyDebug)
{
gServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(ghService, &gServiceStatus);
}
}
DWORD StartLocalService(CCmdLineParser& cmdParser)
{
gbDevOnlyDebug = cmdParser.HasKey(L"dbg");
gbInService = true;
SERVICE_TABLE_ENTRY st[] =
{
{ L"PAExec", ServiceMain }, //If the service is installed with the SERVICE_WIN32_OWN_PROCESS service type, this member is ignored, but cannot be NULL. This member can be an empty string ("").
{ NULL, NULL }
};
if(false == gbDevOnlyDebug)
{
if (!::StartServiceCtrlDispatcher(st))
{
gbODS = true;
Log(L"PAExec failed to start ServiceCtrlDispatcher.", GetLastError());
return GetLastError();
}
}
else
{
_ASSERT(0);
ServiceMain(0, NULL);
}
//for some reason (probably because the service didn't or couldn't stop when requested, and then couldn't be deleted), we're seeing cases where the service definition
//still hangs around (ie a long list of PAExec-xx-yy in services.msc), so here we'll take an additional step and try to delete ourself
SC_HANDLE sch = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
if(NULL != sch)
{
DWORD myPID = GetCurrentProcessId();
BYTE buffer[63 * 1024] = {0};
DWORD ignored;
DWORD serviceCount = 0;
DWORD resume = 0;
if(EnumServicesStatusEx(sch, SC_ENUM_PROCESS_INFO, SERVICE_WIN32_OWN_PROCESS, SERVICE_STATE_ALL, buffer, sizeof(buffer), &ignored, &serviceCount, &resume, NULL))
{
ENUM_SERVICE_STATUS_PROCESS* pStruct = (ENUM_SERVICE_STATUS_PROCESS*)buffer;
for(DWORD i = 0; i < serviceCount; i++)
{
if(pStruct[i].ServiceStatusProcess.dwProcessId == myPID)
{
SC_HANDLE hSvc = OpenService(sch, pStruct[i].lpServiceName, SC_MANAGER_ALL_ACCESS);
if(NULL != hSvc)
{
//service should be marked as stopped if we are down here
::DeleteService(hSvc);
CloseServiceHandle(hSvc);
}
break;
}
}
}
CloseServiceHandle(sch);
}
return 0;
}