-
Notifications
You must be signed in to change notification settings - Fork 851
Expand file tree
/
Copy pathPythonService.cpp
More file actions
1452 lines (1347 loc) · 54.3 KB
/
PythonService.cpp
File metadata and controls
1452 lines (1347 loc) · 54.3 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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MODULE: PythonService.exe
//
// PURPOSE: An executable that hosts Python services.
// This source file is used to compile 2 discrete targets:
// * servicemanager.pyd - A Python extension that contains
// all the functionality.
// * PythonService.exe - This simply loads servicemanager.pyd, and
// calls a public function. Note that PythonService.exe may one
// day die - it is now possible for python.exe to directly host
// services.
//
// @doc
// We use DCOM constants and possible CoInitializeEx.
#define _WIN32_DCOM
#include "PyWinTypes.h"
#include "direct.h"
#include "objbase.h"
#include "tchar.h"
#ifdef PYSERVICE_BUILD_DLL
#define PYSERVICE_EXPORT extern "C" __declspec(dllexport)
#else
#define PYSERVICE_EXPORT extern "C" __declspec(dllimport)
#endif
PYSERVICE_EXPORT BOOL PythonService_Initialize(const TCHAR *evtsrc_name, const TCHAR *evtsrc_file);
PYSERVICE_EXPORT void PythonService_Finalize();
PYSERVICE_EXPORT BOOL PythonService_PrepareToHostSingle(PyObject *);
PYSERVICE_EXPORT BOOL PythonService_PrepareToHostMultiple(const TCHAR *service_name, PyObject *klass);
PYSERVICE_EXPORT BOOL PythonService_StartServiceCtrlDispatcher();
PYSERVICE_EXPORT int PythonService_main(int argc, TCHAR **argv);
TCHAR g_szEventSourceName[MAX_PATH] = _T("Python Service");
TCHAR g_szEventSourceFileName[MAX_PATH] = _T("");
BOOL g_bRegisteredEventSource = FALSE;
BOOL bServiceDebug = FALSE;
BOOL bServiceRunning = FALSE;
// Globals
HINSTANCE g_hdll = 0; // remains zero in the exe stub.
static void ReportAPIError(DWORD msgCode, DWORD errCode = 0);
static void ReportPythonError(DWORD);
static BOOL ReportError(DWORD, LPCTSTR *inserts = NULL, WORD errorType = EVENTLOG_ERROR_TYPE);
static void CheckRegisterEventSourceFile();
#include "PythonServiceMessages.h"
// Useful for debugging problems that only show themselves when run under the SCM
#define LOG_TRACE_MESSAGE(msg) \
{ \
LPTSTR lpszStrings[] = {_T(msg), NULL}; \
ReportError(MSG_IR1, (LPCTSTR *)lpszStrings, EVENTLOG_INFORMATION_TYPE); \
}
#ifdef PYSERVICE_BUILD_DLL // The bulk of this file is only used when building the core DLL.
#define MAX_SERVICES 10
typedef struct {
PyObject *klass; // The Python class we instantiate as the service.
SERVICE_STATUS_HANDLE sshStatusHandle; // the handle for this service.
PyObject *obServiceCtrlHandler; // The Python control handler for the service.
BOOL bUseEx; // does this handler expect the extra args?
} PY_SERVICE_TABLE_ENTRY;
// Globals
// Will be set to one of SERVICE_WIN32_OWN_PROCESS etc flags.
DWORD g_serviceProcessFlags = 0;
// The global SCM dispatch table. A trailing NULL indicates to the SCM
// how many are used, so we allocate one extra for this sentinel
static SERVICE_TABLE_ENTRY DispatchTable[MAX_SERVICES + 1] = {{NULL, NULL}};
// A parallel array of Python information for the service.
static PY_SERVICE_TABLE_ENTRY PythonServiceTable[MAX_SERVICES];
#define RESOURCE_SERVICE_NAME 1016 // resource ID in the EXE of the service name
// internal function prototypes
VOID WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv);
BOOL WINAPI DebugControlHandler(DWORD dwCtrlType);
DWORD WINAPI service_ctrl_ex(DWORD, DWORD, LPVOID, LPVOID);
VOID WINAPI service_ctrl(DWORD);
static PY_SERVICE_TABLE_ENTRY *FindPythonServiceEntry(LPCTSTR svcName);
static PyObject *LoadPythonServiceClass(TCHAR *svcInitString);
static PyObject *LoadPythonServiceInstance(PyObject *, DWORD dwArgc, LPTSTR *lpszArgv);
static BOOL LocatePythonServiceClassString(TCHAR *svcName, TCHAR *buf, int cchBuf);
// Some handy service statuses we can use without filling at runtime.
SERVICE_STATUS neverStartedStatus = {SERVICE_WIN32_OWN_PROCESS,
SERVICE_STOPPED,
0, // dwControlsAccepted,
ERROR_SERVICE_SPECIFIC_ERROR, // dwWin32ExitCode;
1, // dwServiceSpecificExitCode;
0, // dwCheckPoint;
0};
SERVICE_STATUS errorStatus = {SERVICE_WIN32_OWN_PROCESS,
SERVICE_STOP_PENDING,
0, // dwControlsAccepted,
ERROR_SERVICE_SPECIFIC_ERROR, // dwWin32ExitCode;
1, // dwServiceSpecificExitCode;
0, // dwCheckPoint;
5000};
SERVICE_STATUS startingStatus = {SERVICE_WIN32_OWN_PROCESS,
SERVICE_START_PENDING,
0, // dwControlsAccepted,
0, // dwWin32ExitCode;
0, // dwServiceSpecificExitCode;
0, // dwCheckPoint;
5000};
SERVICE_STATUS stoppedStatus = {SERVICE_WIN32_OWN_PROCESS,
SERVICE_STOPPED,
0, // dwControlsAccepted,
0, // dwWin32ExitCode;
0, // dwServiceSpecificExitCode;
0, // dwCheckPoint;
0};
SERVICE_STATUS stoppedErrorStatus = {SERVICE_WIN32_OWN_PROCESS,
SERVICE_STOPPED,
0, // dwControlsAccepted
ERROR_SERVICE_SPECIFIC_ERROR, // dwWin32ExitCode
0x20000001, // dwServiceSpecificExitCode
0, // dwCheckPoint
0};
// The Service Control Manager/Event Log seems to interpret dwServiceSpecificExitCode as a Win32 Error code
// (https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes)
// So stoppedErrorStatus has dwServiceSpecificExitCode with bit 29 set to indicate an application-defined error code.
///////////////////////////////////////////////////////////////////////
//
//
// ** The builtin Python module - referenced as 'servicemanager' by
// ** Python code
//
//
///////////////////////////////////////////////////////////////////////
static PyObject *servicemanager_startup_error;
static PyObject *DoLogMessage(WORD errorType, PyObject *obMsg)
{
WCHAR *msg;
if (!PyWinObject_AsWCHAR(obMsg, &msg))
return NULL;
DWORD errorCode = errorType == EVENTLOG_ERROR_TYPE ? PYS_E_GENERIC_ERROR : PYS_E_GENERIC_WARNING;
LPCTSTR inserts[] = {msg, NULL};
BOOL ok;
Py_BEGIN_ALLOW_THREADS;
ok = ReportError(errorCode, inserts, errorType);
Py_END_ALLOW_THREADS;
PyWinObject_FreeWCHAR(msg); // free msg before potentially raising error
if (!ok)
return PyWin_SetAPIError("RegisterEventSource/ReportEvent");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |servicemanager|LogMsg|Logs a specific message
static PyObject *PyLogMsg(PyObject *self, PyObject *args)
{
PyObject *obStrings;
WORD errorType;
DWORD code;
LPCTSTR *pStrings = NULL;
PyObject *rc = NULL;
Py_ssize_t numStrings = 0;
BOOL ok = FALSE;
// @pyparm int|errorType||
// @pyparm int|eventId||
// @pyparm (string, )|inserts|None|
if (!PyArg_ParseTuple(args, "il|O:LogMsg", &errorType, &code, &obStrings))
return NULL;
if (obStrings == Py_None) {
pStrings = NULL;
}
else if (PySequence_Check(obStrings)) {
numStrings = PySequence_Length(obStrings);
pStrings = new LPCTSTR[numStrings + 1];
if (pStrings == NULL) {
PyErr_SetString(PyExc_MemoryError, "Allocating string arrays");
goto cleanup;
}
memset(pStrings, 0, sizeof(TCHAR *) * (numStrings + 1)); // this also terminates array!
for (Py_ssize_t i = 0; i < numStrings; i++) {
PyObject *obString = PySequence_GetItem(obStrings, i);
if (obString == NULL) {
goto cleanup;
}
BOOL ok = PyWinObject_AsTCHAR(obString, (LPTSTR *)(pStrings + i));
Py_XDECREF(obString);
if (!ok)
goto cleanup;
}
}
else {
PyErr_SetString(PyExc_TypeError, "strings must be None or a sequence");
goto cleanup;
}
Py_BEGIN_ALLOW_THREADS ok = ReportError(code, pStrings, errorType);
Py_END_ALLOW_THREADS if (ok)
{
Py_INCREF(Py_None);
rc = Py_None;
}
else PyWin_SetAPIError("RegisterEventSource/ReportEvent");
cleanup:
if (pStrings) {
for (int i = 0; i < numStrings; i++) PyWinObject_FreeTCHAR((LPTSTR)pStrings[i]);
delete[] pStrings;
}
return rc;
}
// @pymethod |servicemanager|LogInfoMsg|Logs a generic informational message to the event log
static PyObject *PyLogInfoMsg(PyObject *self, PyObject *args)
{
PyObject *obMsg;
// @pyparm string|msg||The message to write.
if (!PyArg_ParseTuple(args, "O:LogInfoMsg", &obMsg))
return NULL;
return DoLogMessage(EVENTLOG_INFORMATION_TYPE, obMsg);
}
// @pymethod |servicemanager|LogWarningMsg|Logs a generic warning message to the event log
static PyObject *PyLogWarningMsg(PyObject *self, PyObject *args)
{
PyObject *obMsg;
// @pyparm string|msg||The message to write.
if (!PyArg_ParseTuple(args, "O:LogWarningMsg", &obMsg))
return NULL;
return DoLogMessage(EVENTLOG_WARNING_TYPE, obMsg);
}
// @pymethod |servicemanager|LogErrorMsg|Logs a generic error message to the event log
static PyObject *PyLogErrorMsg(PyObject *self, PyObject *args)
{
// @pyparm string|msg||The message to write.
PyObject *obMsg;
if (!PyArg_ParseTuple(args, "O:LogErrorMsg", &obMsg))
return NULL;
return DoLogMessage(EVENTLOG_ERROR_TYPE, obMsg);
}
// @pymethod |servicemanager|SetEventSourceName|Sets the event source name
// for event log entries written by the service.
static PyObject *PySetEventSourceName(PyObject *self, PyObject *args)
{
PyObject *obName;
// @pyparm string|sourceName||The event source name
// @pyparm bool|registerNow|False|If True, the event source name in the
// registry will be updated immediately.
// If False, the name will be registered the first time an event log entry
// is written via any pythonservice methods (or possibly never if no record
// if written).
// <nl>Note that in some cases, the service itself will not have permission
// to write the event source in the registry. Therefore, it would be
// prudent for your installation program to call this function with
// registerNow=True, to ensure your services can write useful entries.
int registerNow = 0;
if (!PyArg_ParseTuple(args, "O|i:SetEventSourceName", &obName, ®isterNow))
return NULL;
TCHAR *msg;
if (!PyWinObject_AsTCHAR(obName, &msg))
return NULL;
_tcsncpy(g_szEventSourceName, msg, sizeof g_szEventSourceName / sizeof(TCHAR));
PyWinObject_FreeTCHAR(msg);
g_bRegisteredEventSource = FALSE; // so this name re-registered.
if (registerNow)
CheckRegisterEventSourceFile();
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod int/None|servicemanager|RegisterServiceCtrlHandler|Registers the Python service control handler function.
static PyObject *PyRegisterServiceCtrlHandler(PyObject *self, PyObject *args)
{
PyObject *nameOb, *obCallback;
BOOL bUseEx = FALSE;
// @pyparm string|serviceName||The name of the service. This is provided in args[0] of the service class
// __init__ method.
// @pyparm object|callback||The Python function that performs as the control function. This will be called with an
// integer status argument.
// @pyparm bool|extra_args|False|Is this callback expecting the additional 2 args passed by HandlerEx?
if (!PyArg_ParseTuple(args, "OO|i", &nameOb, &obCallback, &bUseEx))
return NULL;
if (!PyCallable_Check(obCallback)) {
PyErr_SetString(PyExc_TypeError, "Second argument must be a callable object");
return NULL;
}
WCHAR *szName;
if (!PyWinObject_AsWCHAR(nameOb, &szName))
return NULL;
PY_SERVICE_TABLE_ENTRY *pe = FindPythonServiceEntry(szName);
if (pe == NULL) {
PyErr_SetString(PyExc_ValueError, "The service name is not hosted by this process");
PyWinObject_FreeWCHAR(szName);
return NULL;
}
Py_XDECREF(pe->obServiceCtrlHandler);
pe->obServiceCtrlHandler = obCallback;
pe->bUseEx = bUseEx;
Py_INCREF(obCallback);
if (bServiceDebug) { // If debugging, get out now, and give None back.
Py_INCREF(Py_None);
return Py_None;
}
pe->sshStatusHandle = RegisterServiceCtrlHandlerExW(szName, service_ctrl_ex, pe);
PyWinObject_FreeWCHAR(szName);
PyObject *rc;
if (pe->sshStatusHandle == 0) {
Py_DECREF(obCallback);
obCallback = NULL;
rc = PyWin_SetAPIError("RegisterServiceCtrlHandlerEx");
}
else {
rc = PyWinLong_FromHANDLE(pe->sshStatusHandle);
}
return rc;
// @rdesc If the service manager is in debug mode, this returns None, indicating
// there is no service control manager handle, otherwise the handle to the Win32 service manager.
}
// @pymethod |servicemanager|CoInitializeEx|Initialize OLE with additional options.
static PyObject *PyCoInitializeEx(PyObject *self, PyObject *args)
{
DWORD flags;
if (!PyArg_ParseTuple(args, "l:CoInitializeEx", &flags))
return NULL;
HRESULT hr = CoInitializeEx(NULL, flags);
return PyLong_FromLong(hr);
}
// @pymethod |servicemanager|CoUninitialize|Unitialize OLE
static PyObject *PyCoUninitialize(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":CoUninitialize"))
return NULL;
CoUninitialize();
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod True/False|servicemanager|Debugging|Indicates if the service is running in debug mode
// and optionally toggles the debug flag.
static PyObject *PyDebugging(PyObject *self, PyObject *args)
{
// @pyparm int|newVal|-1|If not -1, a new value for the debugging flag.
// The result is the value of the flag before it is changed.
int newVal = (int)-1;
if (!PyArg_ParseTuple(args, "|i:Debugging", &newVal))
return NULL;
PyObject *rc = bServiceDebug ? Py_True : Py_False;
Py_INCREF(rc);
if (newVal != (int)-1)
bServiceDebug = newVal;
return rc;
}
// @pymethod True/False|servicemanager|RunningAsService|Indicates if the code is
// being executed as a service.
static PyObject *PyRunningAsService(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":RunningAsService"))
return NULL;
PyObject *rc = bServiceRunning ? Py_True : Py_False;
Py_INCREF(rc);
return rc;
}
// @pymethod int|servicemanager|PumpWaitingMessages|Pumps all waiting messages.
// @rdesc Returns 1 if a WM_QUIT message was received, else 0
static PyObject *PyPumpWaitingMessages(PyObject *self, PyObject *args)
{
MSG msg;
long result = 0;
// Read all of the messages in this next loop,
// removing each message as we read it.
Py_BEGIN_ALLOW_THREADS while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// If it's a quit message, we're out of here.
if (msg.message == WM_QUIT) {
result = 1;
break;
}
// Otherwise, dispatch the message.
DispatchMessage(&msg);
} // End of PeekMessage while loop
Py_END_ALLOW_THREADS return PyLong_FromLong(result);
}
static PyObject *PyStartServiceCtrlDispatcher(PyObject *self)
{
BOOL ok;
Py_BEGIN_ALLOW_THREADS ok = PythonService_StartServiceCtrlDispatcher();
Py_END_ALLOW_THREADS if (!ok) return PyWin_SetAPIError("StartServiceCtrlDispatcher");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |servicemanager|Initialize|Initialize the module for hosting a service. This is generally called
// automatically
static PyObject *PyServiceInitialize(PyObject *self, PyObject *args)
{
PyObject *nameOb = Py_None, *fileOb = Py_None;
// @pyparm string|eventSourceName|None|The event source name
// @pyparm string|eventSourceFile|None|The name of the file
// (generally a DLL) with the event source messages.
if (!PyArg_ParseTuple(args, "|OO", &nameOb, &fileOb))
return NULL;
TCHAR *name, *file;
if (!PyWinObject_AsTCHAR(nameOb, &name, TRUE))
return NULL;
if (!PyWinObject_AsTCHAR(fileOb, &file, TRUE)) {
PyWinObject_FreeTCHAR(name);
return NULL;
}
PythonService_Initialize(name, file);
PyWinObject_FreeTCHAR(name);
PyWinObject_FreeTCHAR(file);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |servicemanager|Finalize|
static PyObject *PyServiceFinalize(PyObject *self)
{
PythonService_Finalize();
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |servicemanager|PrepareToHostSingle|Prepare for hosting a single service in this EXE
static PyObject *PyPrepareToHostSingle(PyObject *self, PyObject *args)
{
PyObject *klass = Py_None;
// @pyparm object|klass|None|The Python class to host. If not specified, the
// service name is looked up in the registry and the specified class instantiated.
if (!PyArg_ParseTuple(args, "|O", &klass))
return NULL;
BOOL ok = PythonService_PrepareToHostSingle(klass);
if (!ok) {
PyErr_SetString(servicemanager_startup_error, "PrepareToHostSingle failed!");
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |servicemanager|PrepareToHostMultiple|Prepare for hosting a multiple services in this EXE
static PyObject *PyPrepareToHostMultiple(PyObject *self, PyObject *args)
{
PyObject *klass, *obSvcName;
// @pyparm string|service_name||The name of the service hosted by the class
// @pyparm object|klass||The Python class to host.
if (!PyArg_ParseTuple(args, "OO", &obSvcName, &klass))
return NULL;
TCHAR *name;
if (!PyWinObject_AsTCHAR(obSvcName, &name, FALSE))
return NULL;
BOOL ok = PythonService_PrepareToHostMultiple(name, klass);
if (!ok) {
PyErr_SetString(servicemanager_startup_error, "PrepareToHostMultiple failed!");
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @module servicemanager|A module that interfaces with the Windows Service Control Manager. While this
// module can be imported by regular Python programs, it is only useful when used by a Python program
// hosting a service - and even then is generally used automatically by the Python Service framework.
// See the pipeTestService sample for an example of using this module.
// <nl>The module <o win32service> and <o win32serviceutil> provide other facilities for controlling
// and managing services.
static struct PyMethodDef servicemanager_functions[] = {
{"CoInitializeEx", PyCoInitializeEx, 1}, // @pymeth CoInitializeEx|
{"CoUninitialize", PyCoUninitialize, 1}, // @pymeth CoUninitialize|
{"RegisterServiceCtrlHandler", PyRegisterServiceCtrlHandler,
1}, // @pymeth RegisterServiceCtrlHandler|Registers a function to retrieve service control notification messages.
{"LogMsg", PyLogMsg, 1}, // @pymeth LogMsg|Write an specific message to the log.
{"LogInfoMsg", PyLogInfoMsg, 1}, // @pymeth LogInfoMsg|Write an informational message to the log.
{"LogErrorMsg", PyLogErrorMsg, 1}, // @pymeth LogErrorMsg|Write an error message to the log.
{"LogWarningMsg", PyLogWarningMsg, 1}, // @pymeth LogWarningMsg|Logs a generic warning message to the event log
{"PumpWaitingMessages", PyPumpWaitingMessages,
1}, // @pymeth PumpWaitingMessages|Pumps waiting window messages for the service.
{"Debugging", PyDebugging, 1}, // @pymeth Debugging|Indicates if the service is running in debug mode.
{"StartServiceCtrlDispatcher", (PyCFunction)PyStartServiceCtrlDispatcher,
METH_NOARGS}, // @pymeth StartServiceCtrlDispatcher|Starts the service by calling the win32
// StartServiceCtrlDispatcher function.
{"Initialize", PyServiceInitialize, 1}, // @pymeth Initialize|
{"Finalize", (PyCFunction)PyServiceFinalize, METH_NOARGS}, // @pymeth Finalize|
{"PrepareToHostSingle", PyPrepareToHostSingle, 1}, // @pymeth PrepareToHostSingle|
{"PrepareToHostMultiple", PyPrepareToHostMultiple, 1}, // @pymeth PrepareToHostMultiple|
{"RunningAsService", PyRunningAsService,
1}, // @pymeth RunningAsService|Indicates if the code is running as a service.
{"SetEventSourceName", PySetEventSourceName,
1}, // @pymeth SetEventSourceName|Sets the event source name for event log entries written by the service.
{NULL}};
#define ADD_CONSTANT(tok) \
if (PyModule_AddIntConstant(module, #tok, tok) == -1) \
PYWIN_MODULE_INIT_RETURN_ERROR;
PYWIN_MODULE_INIT_FUNC(servicemanager)
{
PYWIN_MODULE_INIT_PREPARE(servicemanager, servicemanager_functions,
"A module that interfaces with the Windows Service Control Manager.");
servicemanager_startup_error = PyErr_NewException("servicemanager.startup_error", NULL, NULL);
if (servicemanager_startup_error == NULL)
PYWIN_MODULE_INIT_RETURN_ERROR;
PyDict_SetItemString(dict, "startup_error", servicemanager_startup_error);
ADD_CONSTANT(COINIT_MULTITHREADED);
ADD_CONSTANT(COINIT_APARTMENTTHREADED);
ADD_CONSTANT(COINIT_DISABLE_OLE1DDE);
ADD_CONSTANT(COINIT_SPEED_OVER_MEMORY);
ADD_CONSTANT(PYS_SERVICE_STARTING);
ADD_CONSTANT(PYS_SERVICE_STARTED);
ADD_CONSTANT(PYS_SERVICE_STOPPING);
ADD_CONSTANT(PYS_SERVICE_STOPPED);
ADD_CONSTANT(EVENTLOG_ERROR_TYPE);
ADD_CONSTANT(EVENTLOG_INFORMATION_TYPE);
ADD_CONSTANT(EVENTLOG_WARNING_TYPE);
ADD_CONSTANT(EVENTLOG_AUDIT_SUCCESS);
ADD_CONSTANT(EVENTLOG_AUDIT_FAILURE);
PYWIN_MODULE_INIT_RETURN_SUCCESS;
}
static char *NarrowString(WCHAR *s)
{
int cchNarrow = WideCharToMultiByte(CP_ACP, 0, s, -1, NULL, 0, NULL, NULL);
char *ret = (char *)malloc(cchNarrow);
if (ret)
WideCharToMultiByte(CP_ACP, 0, s, -1, ret, cchNarrow, NULL, NULL);
return ret;
}
// Couple of helpers for the service manager
static void PyService_InitPython()
{
// XXX - this assumes GIL held, so no races possible
static BOOL have_init = FALSE;
if (have_init)
return;
have_init = TRUE;
// Often for a service, __argv[0] will be just "ExeName", rather
// than "c:\path\to\ExeName.exe"
// This, however, shouldn't be a problem, as Python itself
// knows how to get the .EXE name when it needs.
int pyargc;
WCHAR **pyargv = CommandLineToArgvW(GetCommandLineW(), &pyargc);
if (pyargv)
Py_SetProgramName(pyargv[0]);
#ifdef BUILD_FREEZE
PyInitFrozenExtensions();
#endif
Py_Initialize();
#ifdef BUILD_FREEZE
PyWinFreeze_ExeInit();
#endif
// Notes about argv: When debugging a service, the argv is currently
// the *full* args, including the "-debug servicename" args. This
// isn't ideal, but has been this way for a few builds, and a good
// fix isn't clear - should 'servicename' be presented in argv, even
// though it never is when running as a real service?
if (pyargv)
PySys_SetArgv(pyargc, pyargv);
PyInit_servicemanager();
LocalFree(pyargv);
}
/*************************************************************************
*
*
* Our Python Service "public API" - allows clients to use our DLL
* in almost any possible way
*
*
*************************************************************************/
// FUNCTION: PythonService_Initialize
//
// PURPOSE: Initialize the DLL
//
// PARAMETERS:
// evtsrc_name - The event source name, as it appears in the event log (and
// as used to obtain the eventsource handle.
// evtsrc_file - The name of the file registered with the event viewer for this
// source.
// Both params can be NULL, meaning defaults are used.
//
// RETURN VALUE:
// TRUE if we registered OK.
BOOL PythonService_Initialize(const TCHAR *evtsrc_name, const TCHAR *evtsrc_file)
{
if (evtsrc_name && *evtsrc_name)
_tcsncpy(g_szEventSourceName, evtsrc_name, sizeof g_szEventSourceName / sizeof(TCHAR));
if (evtsrc_file && *evtsrc_file)
_tcsncpy(g_szEventSourceFileName, evtsrc_file, sizeof g_szEventSourceFileName / sizeof(TCHAR));
return TRUE;
}
// FUNCTION: PythonService_Finalize
//
// PURPOSE: Finalize our service hosting framework
void PythonService_Finalize()
{
UINT i;
for (i = 0; i < MAX_SERVICES; i++) {
if (DispatchTable[i].lpServiceName == NULL)
break;
Py_XDECREF(PythonServiceTable[i].klass);
PythonServiceTable[i].klass = NULL;
}
}
// FUNCTION: PythonService_PrepareToHostSingle
//
// PURPOSE: Prepare this EXE for hosting a single service. The service name
// need not be given - the service named passed by Windows as the
// service starts is used.
//
// PARAMETERS:
// klass - The Python class which implements this service. Note this may be NULL,
// which means we will lookup and instantiate the class using the service
// name that Windows starts us with
//
// RETURN VALUE:
// FALSE if we have exceeded the maximum number of services in this executable,
// or if this service name has already been prepared.
//
// COMMENTS:
// Theoretically could be called multiple times, once for each service hosted
// by this process - however, some code will need tweaking to get it working
// correctly for more than one service.
BOOL PythonService_PrepareToHostSingle(PyObject *klass)
{
if (g_serviceProcessFlags == 0)
g_serviceProcessFlags = SERVICE_WIN32_OWN_PROCESS;
else if (g_serviceProcessFlags != SERVICE_WIN32_OWN_PROCESS)
return FALSE;
DispatchTable[0].lpServiceName = _tcsdup(_T(""));
DispatchTable[0].lpServiceProc = service_main;
PythonServiceTable[0].klass = klass;
Py_XINCREF(klass);
PythonServiceTable[0].sshStatusHandle = 0;
PythonServiceTable[0].obServiceCtrlHandler = NULL;
PythonServiceTable[0].bUseEx = 0;
return TRUE;
}
// FUNCTION: PythonService_PrepareToHostMultiple
//
// PURPOSE: Prepare this EXE for hosting the nominated Python service.
//
// PARAMETERS:
// service_name - name of the service.
// klass - The Python class which implements this service.
//
// RETURN VALUE:
// FALSE if we have exceeded the maximum number of services in this executable,
// if the exe is already setup to host an "own process" service, or if this
// service name has already been prepared.
//
// COMMENTS:
// Should be called multiple times, once for each service hosted
// by this process - however, some code will need tweaking to get it working
// correctly for more than one service.
BOOL PythonService_PrepareToHostMultiple(const TCHAR *service_name, PyObject *klass)
{
if (g_serviceProcessFlags == 0)
g_serviceProcessFlags = SERVICE_WIN32_SHARE_PROCESS;
else if (g_serviceProcessFlags != SERVICE_WIN32_SHARE_PROCESS)
return FALSE;
UINT i;
for (i = 0; i < MAX_SERVICES; i++) {
if (DispatchTable[i].lpServiceName == NULL)
break;
if (_tcscmp(service_name, DispatchTable[i].lpServiceName) == 0)
return FALSE;
}
if (i >= MAX_SERVICES)
return FALSE;
DispatchTable[i].lpServiceName = _tcsdup(service_name);
DispatchTable[i].lpServiceProc = service_main;
PythonServiceTable[i].klass = klass;
Py_INCREF(klass);
PythonServiceTable[i].sshStatusHandle = 0;
PythonServiceTable[i].obServiceCtrlHandler = NULL;
PythonServiceTable[i].bUseEx = 0;
return TRUE;
}
// FUNCTION: PythonService_StartServiceCtrlDispatcher
//
// PURPOSE: Calls the Windows StartServiceCtrlDispatcher with
// the DispatchTable setup by previous calls to PrepareToHost
// functions.
//
// RETURN VALUE:
// As per the API. Call GetLastError() to work out why.
BOOL PythonService_StartServiceCtrlDispatcher() { return StartServiceCtrlDispatcher(DispatchTable); }
/*************************************************************************
*
*
* Service Implementation - the main service entry point, and our magic
* of delegating to Python.
*
*
*************************************************************************/
// Find a previously registered SERVICE_TABLE_ENTRY for the named service,
// or NULL if not found.
PY_SERVICE_TABLE_ENTRY *FindPythonServiceEntry(LPCTSTR svcName)
{
PY_SERVICE_TABLE_ENTRY *ppy = PythonServiceTable;
if (g_serviceProcessFlags == SERVICE_WIN32_OWN_PROCESS)
return ppy;
SERVICE_TABLE_ENTRY *ps = DispatchTable;
while (ps->lpServiceName) {
if (_tcscmp(ps->lpServiceName, svcName) == 0)
break;
ppy++;
ps++;
}
if (ps->lpServiceName)
return ppy;
return NULL;
}
//
// FUNCTION: service_main
//
// PURPOSE: To perform actual initialization and execution of the service
//
// PARAMETERS:
// dwArgc - number of command line arguments
// lpszArgv - array of command line arguments
//
// RETURN VALUE:
// none
//
// COMMENTS:
// This routine is called by the Service Control Manager. It loads
// the "SvcRun" function from the class instance and calls it.
void WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv)
{
PyObject *instance = NULL;
PyObject *start = NULL;
// set this to true if the final SERVICE_STOPPED status reported
// should be with a non-zero error code.
bool stopWithError = false;
bServiceRunning = TRUE;
if (bServiceDebug)
SetConsoleCtrlHandler(DebugControlHandler, TRUE);
// NOTE: If possible, we want to always call RegisterServiceCtrlHandlerEx,
// even in error situations. Otherwise Windows will get a little upset
// and turn us into a zombie. Grabbing the service handle and reporting
// an error condition works correctly, whereas exiting doesn't.
// Note also that in the usual, non-error case,
// RegisterServiceCtrlHandlerEx is actually called via the Python code
// (servicemanager.RegisterServiceCtrlHandler), not via us.
CEnterLeavePython _celp;
PY_SERVICE_TABLE_ENTRY *pe;
if (g_serviceProcessFlags == SERVICE_WIN32_OWN_PROCESS) {
pe = PythonServiceTable;
if (!pe->klass) {
TCHAR svcInitBuf[256];
LocatePythonServiceClassString(lpszArgv[0], svcInitBuf, sizeof(svcInitBuf) / sizeof(svcInitBuf[0]));
pe->klass = LoadPythonServiceClass(svcInitBuf);
}
}
else
pe = FindPythonServiceEntry(lpszArgv[0]);
if (!pe) {
LPTSTR lpszStrings[] = {lpszArgv[0], NULL};
ReportError(E_PYS_NO_SERVICE, (LPCTSTR *)lpszStrings);
// This is still yucky and will send us zombie. It should never happen
// and needs too much of a reorg to fix.
goto cleanup;
}
assert(pe->sshStatusHandle == 0); // should have no scm handle yet.
if (pe->klass) // avoid an extra redundant log message.
instance = LoadPythonServiceInstance(pe->klass, dwArgc, lpszArgv);
// If Python has not yet registered the service control handler, then
// we are in serious trouble - it is likely the service will enter a
// zombie state, where it won't do anything, but you can not start
// another. Therefore, we still create register the handler, thereby
// getting a handle, so we can immediately tell Windows the service
// is rooted (that is a technical term!)
if (!bServiceDebug && pe->sshStatusHandle == 0) {
// If we don't have a pe->sshStatusHandle(), then the Python code
// failed to register itself with the SCM.
// If we have an instance, it means that instance simply neglected
// to do the right thing - report that as an error.
if (instance)
ReportPythonError(E_PYS_NOT_CONTROL_HANDLER);
// else no instance - an error has already been reported.
if (!bServiceDebug) {
pe->sshStatusHandle = RegisterServiceCtrlHandlerExW(lpszArgv[0], service_ctrl_ex, pe);
}
}
// No instance - we can't start.
if (!instance) {
if (pe->sshStatusHandle) {
SetServiceStatus(pe->sshStatusHandle, &neverStartedStatus);
pe->sshStatusHandle = 0; // reset so we don't attempt to set 'stopped'
}
goto cleanup;
}
if (!bServiceDebug)
if (!SetServiceStatus(pe->sshStatusHandle, &startingStatus))
ReportAPIError(PYS_E_API_CANT_SET_PENDING);
start = PyObject_GetAttrString(instance, "SvcRun");
if (start == NULL)
ReportPythonError(E_PYS_NO_RUN_METHOD);
else {
// Call the Python service entry point - when this returns, the
// service has stopped!
PyObject *result = PyObject_CallObject(start, NULL);
if (result == NULL) {
// SvcRun() raised an Exception so we stop with an error code.
stopWithError = true;
ReportPythonError(E_PYS_START_FAILED);
}
else {
Py_DECREF(result);
}
}
// We are all done.
cleanup:
// try to report the stopped status to the service control manager.
Py_XDECREF(start);
Py_XDECREF(instance);
if (pe && pe->sshStatusHandle) { // Won't be true if debugging.
if (!SetServiceStatus(pe->sshStatusHandle, (stopWithError ? &stoppedErrorStatus : &stoppedStatus)))
ReportAPIError(PYS_E_API_CANT_SET_STOPPED);
}
return;
}
// The service control handler - receives async notifications from the
// SCM, and delegates to the Python instance. One of service_ctrl
// or service_ctrl_ex are used as entry points depending on whether
// we are running on NT or 2K/XP.
DWORD WINAPI dispatchServiceCtrl(DWORD dwCtrlCode, DWORD dwEventType, LPVOID eventData, PY_SERVICE_TABLE_ENTRY *pse)
{
if (pse->obServiceCtrlHandler == NULL) { // Python is in error.
if (!bServiceDebug)
SetServiceStatus(pse->sshStatusHandle, &errorStatus);
return ERROR_CALL_NOT_IMPLEMENTED;
}
// Ensure we have a context for our thread.
DWORD dwResult;
CEnterLeavePython celp;
PyObject *args;
if (pse->bUseEx) {
PyObject *sub;
switch (dwCtrlCode) {
case SERVICE_CONTROL_DEVICEEVENT:
sub = PyWinObject_FromPARAM((LPARAM)eventData);
break;
case SERVICE_CONTROL_POWEREVENT: {
if (dwEventType == PBT_POWERSETTINGCHANGE) {
POWERBROADCAST_SETTING *pbs = (POWERBROADCAST_SETTING *)eventData;
sub = Py_BuildValue("NN", PyWinObject_FromIID(pbs->PowerSetting),
PyBytes_FromStringAndSize((char *)pbs->Data, pbs->DataLength));
}
else {
sub = Py_None;
Py_INCREF(Py_None);
}
break;
}
case SERVICE_CONTROL_SESSIONCHANGE: {
WTSSESSION_NOTIFICATION *sn = (WTSSESSION_NOTIFICATION *)eventData;
sub = Py_BuildValue("(i)", sn->dwSessionId);
break;
}
default:
sub = Py_None;
Py_INCREF(sub);
break;
}
args = Py_BuildValue("(llN)", dwCtrlCode, dwEventType, sub);
}
else {
args = Py_BuildValue("(l)", dwCtrlCode);
}
PyObject *result = PyObject_CallObject(pse->obServiceCtrlHandler, args);
Py_XDECREF(args);
if (result == NULL) {
ReportPythonError(PYS_E_SERVICE_CONTROL_FAILED);
dwResult = ERROR_CALL_NOT_IMPLEMENTED; // correct code?
}
else if (result == Py_None)
dwResult = NOERROR;
else {
dwResult = PyLong_AsUnsignedLongMask(result);
if (dwResult == -1 && PyErr_Occurred()) {
ReportPythonError(PYS_E_SERVICE_CONTROL_FAILED);
dwResult = ERROR_SERVICE_SPECIFIC_ERROR;
}
}
Py_XDECREF(result);
return dwResult;
}
DWORD WINAPI service_ctrl_ex(DWORD dwCtrlCode, // requested control code
DWORD dwEventType, // event type
LPVOID lpEventData, // event data
LPVOID lpContext // user-defined context data
)
{
PY_SERVICE_TABLE_ENTRY *pse = (PY_SERVICE_TABLE_ENTRY *)lpContext;
return dispatchServiceCtrl(dwCtrlCode, dwEventType, lpEventData, pse);
}
VOID WINAPI service_ctrl(DWORD dwCtrlCode // requested control code
)
{
dispatchServiceCtrl(dwCtrlCode, 0, NULL, &PythonServiceTable[0]);
}
// When debugging, a console event handler that simulates a service
// stop control.
BOOL WINAPI DebugControlHandler(DWORD dwCtrlType)
{
switch (dwCtrlType) {
case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate
case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode
{
_tprintf(TEXT("Stopping debug service.\n"));
// simulate a stop even to each service
PY_SERVICE_TABLE_ENTRY *ppy = PythonServiceTable;
SERVICE_TABLE_ENTRY *ps = DispatchTable;
while (ps->lpServiceName) {
service_ctrl_ex(SERVICE_CONTROL_STOP, 0, NULL, ppy);
ppy++;
ps++;
}
return TRUE;
break;
}
}
return FALSE;
}
/*************************************************************************
*
*
* Generic Service Host implementation - handles command-line args,
* uses the registry to work out what Python classes to load, etc.
* This section could be split into the EXE.
*
*
*************************************************************************/
//
// FUNCTION: PythonService_main
//
// PURPOSE: entrypoint for our generic PythonService host
//
// PARAMETERS:
// argc - number of command line arguments
// argv - array of command line arguments
//
// RETURN VALUE:
// none
//
// COMMENTS:
// main() either performs the command line task, or
// call StartServiceCtrlDispatcher to register the
// main service thread. When the this call returns,
// the service has stopped, so exit.
//
int PythonService_main(int argc, TCHAR **argv)
{
// Note that we don't know the service name we are hosting yet!