Debian Codegraph @

psutil/arch/windows/services.c

raw
1 /*
2 * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 #include <Python.h>
8 #include <windows.h>
9 #include <Winsvc.h>
10
11 #include "../../arch/all/init.h"
12
13
14 // ==================================================================
15 // utils
16 // ==================================================================
17
18
19 SC_HANDLE
20 psutil_get_service_handler(
21 const wchar_t *service_name,
22 DWORD scm_access,
23 DWORD access)
24 {
25 SC_HANDLE sc = NULL;
26 SC_HANDLE hService = NULL;
27
28 sc = OpenSCManagerW(NULL, NULL, scm_access);
29 if (sc == NULL) {
30 psutil_PyErr_SetFromOSErrnoWithSyscall("OpenSCManagerW");
31 return NULL;
32 }
33
34 hService = OpenServiceW(sc, service_name, access);
35 if (hService == NULL) {
36 psutil_PyErr_SetFromOSErrnoWithSyscall("OpenServiceW");
37 CloseServiceHandle(sc);
38 return NULL;
39 }
40
41 CloseServiceHandle(sc);
42 return hService;
43 }
44
45
46 // helper: parse args, convert to wchar, and open service
47 // returns NULL on error. On success, fills *service_name_out.
48 static SC_HANDLE
49 psutil_get_service_from_args(
50 PyObject *args,
51 DWORD scm_access,
52 DWORD access,
53 wchar_t **service_name_out)
54 {
55 PyObject *py_service_name = NULL;
56 wchar_t *service_name = NULL;
57 Py_ssize_t wlen;
58 SC_HANDLE hService = NULL;
59
60 if (!PyArg_ParseTuple(args, "U", &py_service_name)) {
61 return NULL;
62 }
63
64 service_name = PyUnicode_AsWideCharString(py_service_name, &wlen);
65 if (service_name == NULL) {
66 return NULL;
67 }
68
69 hService = psutil_get_service_handler(service_name, scm_access, access);
70 if (hService == NULL) {
71 PyMem_Free(service_name);
72 return NULL;
73 }
74
75 *service_name_out = service_name;
76 return hService;
77 }
78
79
80
81 // XXX - expose these as constants?
82 static const char *
83 get_startup_string(DWORD startup) {
84 switch (startup) {
85 case SERVICE_AUTO_START:
86 return "automatic";
87 case SERVICE_DEMAND_START:
88 return "manual";
89 case SERVICE_DISABLED:
90 return "disabled";
91 /*
92 // drivers only (since we use EnumServicesStatusEx() with
93 // SERVICE_WIN32)
94 case SERVICE_BOOT_START:
95 return "boot-start";
96 case SERVICE_SYSTEM_START:
97 return "system-start";
98 */
99 default:
100 return "unknown";
101 }
102 }
103
104
105 // XXX - expose these as constants?
106 static const char *
107 get_state_string(DWORD state) {
108 switch (state) {
109 case SERVICE_RUNNING:
110 return "running";
111 case SERVICE_PAUSED:
112 return "paused";
113 case SERVICE_START_PENDING:
114 return "start_pending";
115 case SERVICE_PAUSE_PENDING:
116 return "pause_pending";
117 case SERVICE_CONTINUE_PENDING:
118 return "continue_pending";
119 case SERVICE_STOP_PENDING:
120 return "stop_pending";
121 case SERVICE_STOPPED:
122 return "stopped";
123 default:
124 return "unknown";
125 }
126 }
127
128
129 // ==================================================================
130 // APIs
131 // ==================================================================
132
133 /*
134 * Enumerate all services.
135 */
136 PyObject *
137 psutil_winservice_enumerate(PyObject *self, PyObject *args) {
138 ENUM_SERVICE_STATUS_PROCESSW *lpService = NULL;
139 BOOL ok;
140 SC_HANDLE sc = NULL;
141 DWORD bytesNeeded = 0;
142 DWORD srvCount;
143 DWORD resumeHandle = 0;
144 DWORD dwBytes = 0;
145 DWORD i;
146 PyObject *py_retlist = PyList_New(0);
147 PyObject *py_tuple = NULL;
148 PyObject *py_name = NULL;
149 PyObject *py_display_name = NULL;
150
151 if (py_retlist == NULL)
152 return NULL;
153
154 sc = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE);
155 if (sc == NULL) {
156 psutil_PyErr_SetFromOSErrnoWithSyscall("OpenSCManager");
157 return NULL;
158 }
159
160 for (;;) {
161 ok = EnumServicesStatusExW(
162 sc,
163 SC_ENUM_PROCESS_INFO,
164 SERVICE_WIN32, // XXX - extend this to include drivers etc.?
165 SERVICE_STATE_ALL,
166 (LPBYTE)lpService,
167 dwBytes,
168 &bytesNeeded,
169 &srvCount,
170 &resumeHandle,
171 NULL);
172 if (ok || (GetLastError() != ERROR_MORE_DATA))
173 break;
174 if (lpService)
175 free(lpService);
176 dwBytes = bytesNeeded;
177 lpService = (ENUM_SERVICE_STATUS_PROCESSW*)malloc(dwBytes);
178 }
179
180 for (i = 0; i < srvCount; i++) {
181 // Get unicode name / display name.
182 py_name = NULL;
183 py_name = PyUnicode_FromWideChar(
184 lpService[i].lpServiceName, wcslen(lpService[i].lpServiceName));
185 if (py_name == NULL)
186 goto error;
187
188 py_display_name = NULL;
189 py_display_name = PyUnicode_FromWideChar(
190 lpService[i].lpDisplayName, wcslen(lpService[i].lpDisplayName));
191 if (py_display_name == NULL)
192 goto error;
193
194 // Construct the result.
195 py_tuple = Py_BuildValue("(OO)", py_name, py_display_name);
196 if (py_tuple == NULL)
197 goto error;
198 if (PyList_Append(py_retlist, py_tuple))
199 goto error;
200 Py_DECREF(py_display_name);
201 Py_DECREF(py_name);
202 Py_DECREF(py_tuple);
203 }
204
205 // Free resources.
206 CloseServiceHandle(sc);
207 free(lpService);
208 return py_retlist;
209
210 error:
211 Py_DECREF(py_name);
212 Py_XDECREF(py_display_name);
213 Py_XDECREF(py_tuple);
214 Py_DECREF(py_retlist);
215 if (sc != NULL)
216 CloseServiceHandle(sc);
217 if (lpService != NULL)
218 free(lpService);
219 return NULL;
220 }
221
222
223 /*
224 * Get service config information. Returns:
225 * - display_name
226 * - binpath
227 * - username
228 * - startup_type
229 */
230 PyObject *
231 psutil_winservice_query_config(PyObject *self, PyObject *args) {
232 wchar_t *service_name = NULL;
233 SC_HANDLE hService = NULL;
234 BOOL ok;
235 DWORD bytesNeeded = 0;
236 QUERY_SERVICE_CONFIGW *qsc = NULL;
237 PyObject *py_tuple = NULL;
238 PyObject *py_unicode_display_name = NULL;
239 PyObject *py_unicode_binpath = NULL;
240 PyObject *py_unicode_username = NULL;
241
242 hService = psutil_get_service_from_args(
243 args,
244 SC_MANAGER_ENUMERATE_SERVICE,
245 SERVICE_QUERY_CONFIG,
246 &service_name
247 );
248 if (hService == NULL)
249 return NULL;
250
251 // First call to QueryServiceConfigW() is necessary to get the
252 // right size.
253 bytesNeeded = 0;
254 QueryServiceConfigW(hService, NULL, 0, &bytesNeeded);
255 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
256 psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfigW");
257 goto error;
258 }
259
260 qsc = (QUERY_SERVICE_CONFIGW *)malloc(bytesNeeded);
261 if (qsc == NULL) {
262 PyErr_NoMemory();
263 goto error;
264 }
265
266 ok = QueryServiceConfigW(hService, qsc, bytesNeeded, &bytesNeeded);
267 if (!ok) {
268 psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfigW");
269 goto error;
270 }
271
272 // Get unicode display name.
273 py_unicode_display_name = PyUnicode_FromWideChar(
274 qsc->lpDisplayName, wcslen(qsc->lpDisplayName));
275 if (py_unicode_display_name == NULL)
276 goto error;
277
278 // Get unicode bin path.
279 py_unicode_binpath = PyUnicode_FromWideChar(
280 qsc->lpBinaryPathName, wcslen(qsc->lpBinaryPathName));
281 if (py_unicode_binpath == NULL)
282 goto error;
283
284 // Get unicode username.
285 py_unicode_username = PyUnicode_FromWideChar(
286 qsc->lpServiceStartName, wcslen(qsc->lpServiceStartName));
287 if (py_unicode_username == NULL)
288 goto error;
289
290 // Construct result tuple.
291 py_tuple = Py_BuildValue(
292 "(OOOs)",
293 py_unicode_display_name,
294 py_unicode_binpath,
295 py_unicode_username,
296 get_startup_string(qsc->dwStartType) // startup
297 );
298 if (py_tuple == NULL)
299 goto error;
300
301 // Free resources.
302 Py_DECREF(py_unicode_display_name);
303 Py_DECREF(py_unicode_binpath);
304 Py_DECREF(py_unicode_username);
305 free(qsc);
306 CloseServiceHandle(hService);
307 PyMem_Free(service_name);
308 return py_tuple;
309
310 error:
311 Py_XDECREF(py_unicode_display_name);
312 Py_XDECREF(py_unicode_binpath);
313 Py_XDECREF(py_unicode_username);
314 Py_XDECREF(py_tuple);
315 if (hService)
316 CloseServiceHandle(hService);
317 if (qsc)
318 free(qsc);
319 if (service_name)
320 PyMem_Free(service_name);
321 return NULL;
322 }
323
324
325 /*
326 * Get service status information. Returns:
327 * - status
328 * - pid
329 */
330 PyObject *
331 psutil_winservice_query_status(PyObject *self, PyObject *args) {
332 wchar_t *service_name = NULL;
333 SC_HANDLE hService = NULL;
334 BOOL ok;
335 DWORD bytesNeeded = 0;
336 SERVICE_STATUS_PROCESS *ssp = NULL;
337 PyObject *py_tuple = NULL;
338
339 hService = psutil_get_service_from_args(
340 args,
341 SC_MANAGER_ENUMERATE_SERVICE,
342 SERVICE_QUERY_STATUS,
343 &service_name
344 );
345 if (hService == NULL)
346 return NULL;
347
348 // First call to QueryServiceStatusEx() is necessary to get the
349 // right size.
350 QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, NULL, 0,
351 &bytesNeeded);
352 if (GetLastError() == ERROR_MUI_FILE_NOT_FOUND) {
353 // Also services.msc fails in the same manner, so we return an
354 // empty string.
355 CloseServiceHandle(hService);
356 PyMem_Free(service_name);
357 return Py_BuildValue("s", "");
358 }
359 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
360 psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceStatusEx");
361 goto error;
362 }
363
364 ssp = (SERVICE_STATUS_PROCESS *)HeapAlloc(GetProcessHeap(), 0, bytesNeeded);
365 if (ssp == NULL) {
366 PyErr_NoMemory();
367 goto error;
368 }
369
370 // Actual call.
371 ok = QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)ssp,
372 bytesNeeded, &bytesNeeded);
373 if (!ok) {
374 psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceStatusEx");
375 goto error;
376 }
377
378 py_tuple = Py_BuildValue(
379 "(sk)",
380 get_state_string(ssp->dwCurrentState),
381 ssp->dwProcessId
382 );
383 if (py_tuple == NULL)
384 goto error;
385
386 CloseServiceHandle(hService);
387 HeapFree(GetProcessHeap(), 0, ssp);
388 PyMem_Free(service_name);
389 return py_tuple;
390
391 error:
392 Py_XDECREF(py_tuple);
393 if (hService)
394 CloseServiceHandle(hService);
395 if (ssp)
396 HeapFree(GetProcessHeap(), 0, ssp);
397 if (service_name)
398 PyMem_Free(service_name);
399 return NULL;
400 }
401
402 PyObject *
403 psutil_winservice_query_descr(PyObject *self, PyObject *args) {
404 BOOL ok;
405 DWORD bytesNeeded = 0;
406 SC_HANDLE hService = NULL;
407 SERVICE_DESCRIPTIONW *scd = NULL;
408 wchar_t *service_name = NULL;
409 PyObject *py_retstr = NULL;
410
411 hService = psutil_get_service_from_args(
412 args,
413 SC_MANAGER_ENUMERATE_SERVICE,
414 SERVICE_QUERY_CONFIG,
415 &service_name
416 );
417 if (hService == NULL)
418 return NULL;
419
420 QueryServiceConfig2W(hService, SERVICE_CONFIG_DESCRIPTION, NULL, 0, &bytesNeeded);
421
422 if ((GetLastError() == ERROR_NOT_FOUND) ||
423 (GetLastError() == ERROR_MUI_FILE_NOT_FOUND))
424 {
425 // E.g. services.msc fails in this manner, so we return an
426 // empty string.
427 psutil_debug("set empty string for NOT_FOUND service description");
428 CloseServiceHandle(hService);
429 PyMem_Free(service_name);
430 return Py_BuildValue("s", "");
431 }
432
433 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
434 psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfig2W");
435 goto error;
436 }
437
438 scd = (SERVICE_DESCRIPTIONW *)malloc(bytesNeeded);
439 if (scd == NULL) {
440 PyErr_NoMemory();
441 goto error;
442 }
443
444 ok = QueryServiceConfig2W(hService, SERVICE_CONFIG_DESCRIPTION,
445 (LPBYTE)scd, bytesNeeded, &bytesNeeded);
446 if (!ok) {
447 psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfig2W");
448 goto error;
449 }
450
451 if (scd->lpDescription == NULL) {
452 py_retstr = Py_BuildValue("s", "");
453 }
454 else {
455 py_retstr = PyUnicode_FromWideChar(
456 scd->lpDescription, wcslen(scd->lpDescription));
457 }
458
459 if (!py_retstr)
460 goto error;
461
462 free(scd);
463 CloseServiceHandle(hService);
464 PyMem_Free(service_name);
465 return py_retstr;
466
467 error:
468 if (hService)
469 CloseServiceHandle(hService);
470 if (scd)
471 free(scd);
472 if (service_name)
473 PyMem_Free(service_name);
474 return NULL;
475 }
476
477
478 /*
479 * Start service.
480 * XXX - note: this is exposed but not used.
481 */
482 PyObject *
483 psutil_winservice_start(PyObject *self, PyObject *args) {
484 BOOL ok;
485 SC_HANDLE hService = NULL;
486 wchar_t *service_name = NULL;
487
488 hService = psutil_get_service_from_args(
489 args,
490 SC_MANAGER_ALL_ACCESS,
491 SERVICE_START,
492 &service_name
493 );
494 if (hService == NULL)
495 return NULL;
496
497 ok = StartService(hService, 0, NULL);
498 if (!ok) {
499 psutil_PyErr_SetFromOSErrnoWithSyscall("StartService");
500 goto error;
501 }
502
503 CloseServiceHandle(hService);
504 PyMem_Free(service_name);
505 Py_RETURN_NONE;
506
507 error:
508 if (hService)
509 CloseServiceHandle(hService);
510 if (service_name)
511 PyMem_Free(service_name);
512 return NULL;
513 }
514
515
516 /*
517 * Stop service.
518 * XXX - note: this is exposed but not used.
519 */
520 PyObject *
521 psutil_winservice_stop(PyObject *self, PyObject *args) {
522 wchar_t *service_name = NULL;
523 BOOL ok;
524 SC_HANDLE hService = NULL;
525 SERVICE_STATUS ssp;
526
527 hService = psutil_get_service_from_args(
528 args,
529 SC_MANAGER_ALL_ACCESS,
530 SERVICE_STOP,
531 &service_name
532 );
533 if (hService == NULL)
534 return NULL;
535
536 // Note: this can hang for 30 secs.
537 Py_BEGIN_ALLOW_THREADS
538 ok = ControlService(hService, SERVICE_CONTROL_STOP, &ssp);
539 Py_END_ALLOW_THREADS
540 if (!ok) {
541 psutil_PyErr_SetFromOSErrnoWithSyscall("ControlService");
542 goto error;
543 }
544
545 CloseServiceHandle(hService);
546 PyMem_Free(service_name);
547 Py_RETURN_NONE;
548
549 error:
550 if (hService)
551 CloseServiceHandle(hService);
552 if (service_name)
553 PyMem_Free(service_name);
554 return NULL;
555 }