/
ServiceBase.cs
965 lines (862 loc) · 37.1 KB
/
ServiceBase.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using static Interop.Advapi32;
namespace System.ServiceProcess
{
/// <summary>
/// <para>Provides a base class for a service that will exist as part of a service application. <see cref='System.ServiceProcess.ServiceBase'/>
/// must be derived when creating a new service class.</para>
/// </summary>
public class ServiceBase : Component
{
private SERVICE_STATUS _status;
private IntPtr _statusHandle;
private ServiceControlCallbackEx? _commandCallbackEx;
private ServiceMainCallback? _mainCallback;
private ManualResetEvent? _startCompletedSignal;
private ExceptionDispatchInfo? _startFailedException;
private int _acceptedCommands;
private string _serviceName;
private bool _nameFrozen; // set to true once we've started running and ServiceName can't be changed any more.
private bool _commandPropsFrozen; // set to true once we've use the Can... properties.
private bool _disposed;
private bool _initialized;
private object _stopLock = new object();
private EventLog? _eventLog;
/// <summary>
/// Indicates the maximum size for a service name.
/// </summary>
public const int MaxNameLength = 80;
/// <summary>
/// Creates a new instance of the <see cref='System.ServiceProcess.ServiceBase()'/> class.
/// </summary>
public ServiceBase()
{
_acceptedCommands = AcceptOptions.ACCEPT_STOP;
ServiceName = string.Empty;
AutoLog = true;
}
/// <summary>
/// When this method is called from OnStart, OnStop, OnPause or OnContinue,
/// the specified wait hint is passed to the
/// Service Control Manager to avoid having the service marked as not responding.
/// </summary>
/// <param name="milliseconds"></param>
public unsafe void RequestAdditionalTime(int milliseconds)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
if (_status.currentState != ServiceControlStatus.STATE_CONTINUE_PENDING &&
_status.currentState != ServiceControlStatus.STATE_START_PENDING &&
_status.currentState != ServiceControlStatus.STATE_STOP_PENDING &&
_status.currentState != ServiceControlStatus.STATE_PAUSE_PENDING)
{
throw new InvalidOperationException(SR.NotInPendingState);
}
_status.waitHint = milliseconds;
_status.checkPoint++;
SetServiceStatus(_statusHandle, pStatus);
}
}
#if NETCOREAPP
/// <summary>
/// When this method is called from OnStart, OnStop, OnPause or OnContinue,
/// the specified wait hint is passed to the
/// Service Control Manager to avoid having the service marked as not responding.
/// </summary>
/// <param name="time">The requested additional time</param>
public void RequestAdditionalTime(TimeSpan time) => RequestAdditionalTime(ToIntMilliseconds(time));
private static int ToIntMilliseconds(TimeSpan time)
{
long totalMilliseconds = (long)time.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(time));
}
return (int)totalMilliseconds;
}
#endif
/// <summary>
/// Indicates whether to report Start, Stop, Pause, and Continue commands in the event.
/// </summary>
[DefaultValue(true)]
public bool AutoLog { get; set; }
/// <summary>
/// The termination code for the service. Set this to a non-zero value before
/// stopping to indicate an error to the Service Control Manager.
/// </summary>
public int ExitCode
{
get
{
return _status.win32ExitCode;
}
set
{
_status.win32ExitCode = value;
}
}
/// <summary>
/// Indicates whether the service can be handle notifications on
/// computer power status changes.
/// </summary>
[DefaultValue(false)]
public bool CanHandlePowerEvent
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_POWEREVENT) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_POWEREVENT;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_POWEREVENT;
}
}
}
/// <summary>
/// Indicates whether the service can handle Terminal Server session change events.
/// </summary>
[DefaultValue(false)]
public bool CanHandleSessionChangeEvent
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_SESSIONCHANGE) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_SESSIONCHANGE;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_SESSIONCHANGE;
}
}
}
/// <summary>
/// Indicates whether the service can be paused and resumed.
/// </summary>
[DefaultValue(false)]
public bool CanPauseAndContinue
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_PAUSE_CONTINUE) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_PAUSE_CONTINUE;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_PAUSE_CONTINUE;
}
}
}
/// <summary>
/// Indicates whether the service should be notified when the system is shutting down.
/// </summary>
[DefaultValue(false)]
public bool CanShutdown
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_SHUTDOWN) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_SHUTDOWN;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_SHUTDOWN;
}
}
}
/// <summary>
/// Indicates whether the service can be stopped once it has started.
/// </summary>
[DefaultValue(true)]
public bool CanStop
{
get
{
return (_acceptedCommands & AcceptOptions.ACCEPT_STOP) != 0;
}
set
{
if (_commandPropsFrozen)
throw new InvalidOperationException(SR.CannotChangeProperties);
if (value)
{
_acceptedCommands |= AcceptOptions.ACCEPT_STOP;
}
else
{
_acceptedCommands &= ~AcceptOptions.ACCEPT_STOP;
}
}
}
/// <summary>
/// can be used to write notification of service command calls, such as Start and Stop, to the Application event log. This property is read-only.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual EventLog EventLog =>
_eventLog ??= new EventLog("Application")
{
Source = ServiceName
};
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected IntPtr ServiceHandle
{
get
{
return _statusHandle;
}
}
/// <summary>
/// Indicates the short name used to identify the service to the system.
/// </summary>
public string ServiceName
{
get
{
return _serviceName;
}
[MemberNotNull(nameof(_serviceName))]
set
{
if (_nameFrozen)
throw new InvalidOperationException(SR.CannotChangeName);
// For component properties, "" is a special case.
if (value != "" && !ValidServiceName(value))
throw new ArgumentException(SR.Format(SR.ServiceName, value, ServiceBase.MaxNameLength.ToString(CultureInfo.CurrentCulture)));
_serviceName = value;
}
}
internal static bool ValidServiceName(string serviceName) =>
!string.IsNullOrEmpty(serviceName) &&
serviceName.Length <= ServiceBase.MaxNameLength && // not too long
serviceName.AsSpan().IndexOfAny('\\', '/') < 0; // no slashes or backslash allowed
/// <summary>
/// <para>Disposes of the resources (other than memory ) used by
/// the <see cref='System.ServiceProcess.ServiceBase'/>.</para>
/// This is called from <see cref="Run(ServiceBase[])"/> when all
/// services in the process have entered the SERVICE_STOPPED state.
/// </summary>
protected override void Dispose(bool disposing)
{
_nameFrozen = false;
_commandPropsFrozen = false;
_disposed = true;
base.Dispose(disposing);
}
/// <summary>
/// <para> When implemented in a
/// derived class,
/// executes when a Continue command is sent to the service
/// by the
/// Service Control Manager. Specifies the actions to take when a
/// service resumes normal functioning after being paused.</para>
/// </summary>
protected virtual void OnContinue()
{
}
/// <summary>
/// <para> When implemented in a
/// derived class, executes when a Pause command is sent
/// to
/// the service by the Service Control Manager. Specifies the
/// actions to take when a service pauses.</para>
/// </summary>
protected virtual void OnPause()
{
}
/// <summary>
/// <para>
/// When implemented in a derived class, executes when the computer's
/// power status has changed.
/// </para>
/// </summary>
protected virtual bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return true;
}
/// <summary>
/// <para>When implemented in a derived class,
/// executes when a Terminal Server session change event is received.</para>
/// </summary>
protected virtual void OnSessionChange(SessionChangeDescription changeDescription)
{
}
/// <summary>
/// <para>When implemented in a derived class,
/// executes when the system is shutting down.
/// Specifies what should
/// happen just prior
/// to the system shutting down.</para>
/// </summary>
protected virtual void OnShutdown()
{
}
/// <summary>
/// <para> When implemented in a
/// derived class, executes when a Start command is sent
/// to the service by the Service
/// Control Manager. Specifies the actions to take when the service starts.</para>
/// <note type="rnotes">
/// Tech review note:
/// except that the SCM does not allow passing arguments, so this overload will
/// never be called by the SCM in the current version. Question: Is this true even
/// when the string array is empty? What should we say, then. Can
/// a ServiceBase derived class only be called programmatically? Will
/// OnStart never be called if you use the SCM to start the service? What about
/// services that start automatically at boot-up?
/// </note>
/// </summary>
protected virtual void OnStart(string[] args)
{
}
/// <summary>
/// <para> When implemented in a
/// derived class, executes when a Stop command is sent to the
/// service by the Service Control Manager. Specifies the actions to take when a
/// service stops
/// running.</para>
/// </summary>
protected virtual void OnStop()
{
}
private unsafe void DeferredContinue()
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
try
{
OnContinue();
WriteLogEntry(SR.ContinueSuccessful);
_status.currentState = ServiceControlStatus.STATE_RUNNING;
}
catch (Exception e)
{
_status.currentState = ServiceControlStatus.STATE_PAUSED;
WriteLogEntry(SR.Format(SR.ContinueFailed, e), EventLogEntryType.Error);
// We re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
finally
{
SetServiceStatus(_statusHandle, pStatus);
}
}
}
private void DeferredCustomCommand(int command)
{
try
{
OnCustomCommand(command);
WriteLogEntry(SR.CommandSuccessful);
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.CommandFailed, e), EventLogEntryType.Error);
// We should re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
}
private unsafe void DeferredPause()
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
try
{
OnPause();
WriteLogEntry(SR.PauseSuccessful);
_status.currentState = ServiceControlStatus.STATE_PAUSED;
}
catch (Exception e)
{
_status.currentState = ServiceControlStatus.STATE_RUNNING;
WriteLogEntry(SR.Format(SR.PauseFailed, e), EventLogEntryType.Error);
// We re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
finally
{
SetServiceStatus(_statusHandle, pStatus);
}
}
}
private void DeferredPowerEvent(int eventType)
{
// Note: The eventData pointer might point to an invalid location
// This might happen because, between the time the eventData ptr was
// captured and the time this deferred code runs, the ptr might have
// already been freed.
try
{
OnPowerEvent((PowerBroadcastStatus)eventType);
WriteLogEntry(SR.PowerEventOK);
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.PowerEventFailed, e), EventLogEntryType.Error);
// We rethrow the exception so that advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
}
private void DeferredSessionChange(int eventType, int sessionId)
{
try
{
OnSessionChange(new SessionChangeDescription((SessionChangeReason)eventType, sessionId));
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.SessionChangeFailed, e), EventLogEntryType.Error);
// We rethrow the exception so that advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
throw;
}
}
// We mustn't call OnStop directly from the command callback, as this will
// tie up the command thread for the duration of the OnStop, which can be lengthy.
// This is a problem when multiple services are hosted in a single process.
private unsafe void DeferredStop()
{
lock (_stopLock)
{
// never call SetServiceStatus again after STATE_STOPPED is set.
if (_status.currentState != ServiceControlStatus.STATE_STOPPED)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
int previousState = _status.currentState;
_status.checkPoint = 0;
_status.waitHint = 0;
_status.currentState = ServiceControlStatus.STATE_STOP_PENDING;
SetServiceStatus(_statusHandle, pStatus);
try
{
OnStop();
WriteLogEntry(SR.StopSuccessful);
_status.currentState = ServiceControlStatus.STATE_STOPPED;
SetServiceStatus(_statusHandle, pStatus);
}
catch (Exception e)
{
_status.currentState = previousState;
SetServiceStatus(_statusHandle, pStatus);
WriteLogEntry(SR.Format(SR.StopFailed, e), EventLogEntryType.Error);
throw;
}
}
}
}
}
private unsafe void DeferredShutdown()
{
try
{
OnShutdown();
WriteLogEntry(SR.ShutdownOK);
lock (_stopLock)
{
if (_status.currentState == ServiceControlStatus.STATE_PAUSED || _status.currentState == ServiceControlStatus.STATE_RUNNING)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
_status.checkPoint = 0;
_status.waitHint = 0;
_status.currentState = ServiceControlStatus.STATE_STOPPED;
SetServiceStatus(_statusHandle, pStatus);
}
}
}
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.ShutdownFailed, e), EventLogEntryType.Error);
throw;
}
}
/// <summary>
/// <para>When implemented in a derived class, <see cref='System.ServiceProcess.ServiceBase.OnCustomCommand'/>
/// executes when a custom command is passed to the service. Specifies the actions to take when
/// a command with the specified parameter value occurs.</para>
/// </summary>
protected virtual void OnCustomCommand(int command)
{
}
/// <summary>
/// <para>Provides the main entry point for an executable that
/// contains multiple associated services. Loads the specified services into memory so they can be
/// started.</para>
/// </summary>
public static unsafe void Run(ServiceBase[] services)
{
if (services == null || services.Length == 0)
throw new ArgumentException(SR.NoServices);
IntPtr entriesPointer = Marshal.AllocHGlobal(checked((services.Length + 1) * sizeof(SERVICE_TABLE_ENTRY)));
Span<SERVICE_TABLE_ENTRY> entries = new Span<SERVICE_TABLE_ENTRY>((void*)entriesPointer, services.Length + 1);
entries.Clear();
try
{
bool multipleServices = services.Length > 1;
// The members of the last entry in the table must have NULL values to designate the end of the table.
// Leave the last element in the entries span to be zeroed out.
for (int index = 0; index < services.Length; ++index)
{
ServiceBase service = services[index];
service.Initialize(multipleServices);
// This method allocates on unmanaged heap; Make sure that the contents are freed after use.
entries[index] = service.GetEntry();
}
// While the service is running, this function will never return. It will return when the service
// is stopped.
// After it returns, SCM might terminate the process at any time
// (so subsequent code is not guaranteed to run).
bool res = StartServiceCtrlDispatcher(entriesPointer);
foreach (ServiceBase service in services)
{
// Propagate exceptions throw during OnStart.
// Note that this same exception is also thrown from ServiceMainCallback
// (so SCM can see it as well).
service._startFailedException?.Throw();
}
string errorMessage = string.Empty;
if (!res)
{
errorMessage = new Win32Exception().Message;
Console.WriteLine(SR.CantStartFromCommandLine);
}
foreach (ServiceBase service in services)
{
service.Dispose();
if (!res)
{
service.WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), EventLogEntryType.Error);
}
}
}
finally
{
// Free the pointer to the name of the service on the unmanaged heap.
for (int i = 0; i < entries.Length; i++)
{
Marshal.FreeHGlobal(entries[i].name);
}
// Free the unmanaged array containing the entries.
Marshal.FreeHGlobal(entriesPointer);
}
}
/// <summary>
/// <para>Provides the main
/// entry point for an executable that contains a single
/// service. Loads the service into memory so it can be
/// started.</para>
/// </summary>
public static void Run(ServiceBase service)
{
if (service == null)
throw new ArgumentException(SR.NoServices);
Run(new ServiceBase[] { service });
}
public void Stop()
{
DeferredStop();
}
private void Initialize(bool multipleServices)
{
if (!_initialized)
{
//Cannot register the service with NT service manager if the object has been disposed, since finalization has been suppressed.
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!multipleServices)
{
_status.serviceType = ServiceTypeOptions.SERVICE_WIN32_OWN_PROCESS;
}
else
{
_status.serviceType = ServiceTypeOptions.SERVICE_WIN32_SHARE_PROCESS;
}
_status.currentState = ServiceControlStatus.STATE_START_PENDING;
_status.controlsAccepted = 0;
_status.win32ExitCode = 0;
_status.serviceSpecificExitCode = 0;
_status.checkPoint = 0;
_status.waitHint = 0;
_mainCallback = ServiceMainCallback;
_commandCallbackEx = this.ServiceCommandCallbackEx;
_initialized = true;
}
}
// Make sure that the name field is freed after use. We allocate a new string to avoid holding one central handle,
// which may lead to dangling pointer if Dispose is called in other thread.
private SERVICE_TABLE_ENTRY GetEntry()
{
_nameFrozen = true;
return new SERVICE_TABLE_ENTRY()
{
callback = Marshal.GetFunctionPointerForDelegate(_mainCallback!),
name = Marshal.StringToHGlobalUni(_serviceName)
};
}
private int ServiceCommandCallbackEx(int command, int eventType, IntPtr eventData, IntPtr eventContext)
{
switch (command)
{
case ControlOptions.CONTROL_POWEREVENT:
{
ThreadPool.QueueUserWorkItem(_ => DeferredPowerEvent(eventType));
break;
}
case ControlOptions.CONTROL_SESSIONCHANGE:
{
// The eventData pointer can be released between now and when the DeferredDelegate gets called.
// So we capture the session id at this point
WTSSESSION_NOTIFICATION sessionNotification = new WTSSESSION_NOTIFICATION();
Marshal.PtrToStructure(eventData, sessionNotification);
ThreadPool.QueueUserWorkItem(_ => DeferredSessionChange(eventType, sessionNotification.sessionId));
break;
}
default:
{
ServiceCommandCallback(command);
break;
}
}
return 0;
}
/// <summary>
/// Command Handler callback is called by NT .
/// Need to take specific action in response to each
/// command message. There is usually no need to override this method.
/// Instead, override OnStart, OnStop, OnCustomCommand, etc.
/// </summary>
/// <internalonly/>
private unsafe void ServiceCommandCallback(int command)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
if (command == ControlOptions.CONTROL_INTERROGATE)
SetServiceStatus(_statusHandle, pStatus);
else if (_status.currentState != ServiceControlStatus.STATE_CONTINUE_PENDING &&
_status.currentState != ServiceControlStatus.STATE_START_PENDING &&
_status.currentState != ServiceControlStatus.STATE_STOP_PENDING &&
_status.currentState != ServiceControlStatus.STATE_PAUSE_PENDING)
{
switch (command)
{
case ControlOptions.CONTROL_CONTINUE:
if (_status.currentState == ServiceControlStatus.STATE_PAUSED)
{
_status.currentState = ServiceControlStatus.STATE_CONTINUE_PENDING;
SetServiceStatus(_statusHandle, pStatus);
ThreadPool.QueueUserWorkItem(_ => DeferredContinue());
}
break;
case ControlOptions.CONTROL_PAUSE:
if (_status.currentState == ServiceControlStatus.STATE_RUNNING)
{
_status.currentState = ServiceControlStatus.STATE_PAUSE_PENDING;
SetServiceStatus(_statusHandle, pStatus);
ThreadPool.QueueUserWorkItem(_ => DeferredPause());
}
break;
case ControlOptions.CONTROL_STOP:
int previousState = _status.currentState;
//
// Can't perform all of the service shutdown logic from within the command callback.
// This is because there is a single ScDispatcherLoop for the entire process. Instead, we queue up an
// asynchronous call to "DeferredStop", and return immediately. This is crucial for the multiple service
// per process scenario, such as the new managed service host model.
//
if (_status.currentState == ServiceControlStatus.STATE_PAUSED || _status.currentState == ServiceControlStatus.STATE_RUNNING)
{
_status.currentState = ServiceControlStatus.STATE_STOP_PENDING;
SetServiceStatus(_statusHandle, pStatus);
// Set our copy of the state back to the previous so that the deferred stop routine
// can also save the previous state.
_status.currentState = previousState;
ThreadPool.QueueUserWorkItem(_ => DeferredStop());
}
break;
case ControlOptions.CONTROL_SHUTDOWN:
//
// Same goes for shutdown -- this needs to be very responsive, so we can't have one service tying up the
// dispatcher loop.
//
ThreadPool.QueueUserWorkItem(_ => DeferredShutdown());
break;
default:
ThreadPool.QueueUserWorkItem(_ => DeferredCustomCommand(command));
break;
}
}
}
}
// Need to execute the start method on a thread pool thread.
// Most applications will start asynchronous operations in the
// OnStart method. If such a method is executed in MainCallback
// thread, the async operations might get canceled immediately.
private void ServiceQueuedMainCallback(object state)
{
string[] args = (string[])state;
try
{
OnStart(args);
WriteLogEntry(SR.StartSuccessful);
_status.checkPoint = 0;
_status.waitHint = 0;
_status.currentState = ServiceControlStatus.STATE_RUNNING;
}
catch (Exception e)
{
WriteLogEntry(SR.Format(SR.StartFailed, e), EventLogEntryType.Error);
_status.currentState = ServiceControlStatus.STATE_STOPPED;
// We capture the exception so that it can be propagated
// from ServiceBase.Run.
// We also use the presence of this exception to inform SCM
// that the service failed to start successfully.
_startFailedException = ExceptionDispatchInfo.Capture(e);
}
_startCompletedSignal!.Set();
}
/// <summary>
/// ServiceMain callback is called by NT .
/// It is expected that we register the command handler,
/// and start the service at this point.
/// </summary>
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
public unsafe void ServiceMainCallback(int argCount, IntPtr argPointer)
{
fixed (SERVICE_STATUS* pStatus = &_status)
{
string[]? args = null;
if (argCount > 0)
{
char** argsAsPtr = (char**)argPointer;
// The first arg is always the service name. We don't want to pass that in,
// but we can use it to set the service name on ourselves if we don't already know it.
if (string.IsNullOrEmpty(_serviceName))
{
_serviceName = Marshal.PtrToStringUni((IntPtr)(*argsAsPtr))!;
}
args = new string[argCount - 1];
for (int index = 0; index < args.Length; ++index)
{
// we increment the pointer first so we skip over the first argument.
argsAsPtr++;
args[index] = Marshal.PtrToStringUni((IntPtr)(*argsAsPtr))!;
}
}
// If we are being hosted, then Run will not have been called, since the EXE's Main entrypoint is not called.
if (!_initialized)
{
Initialize(true);
}
_statusHandle = RegisterServiceCtrlHandlerEx(ServiceName, _commandCallbackEx, (IntPtr)0);
_nameFrozen = true;
if (_statusHandle == (IntPtr)0)
{
string errorMessage = new Win32Exception().Message;
WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), EventLogEntryType.Error);
}
_status.controlsAccepted = _acceptedCommands;
_commandPropsFrozen = true;
if ((_status.controlsAccepted & AcceptOptions.ACCEPT_STOP) != 0)
{
_status.controlsAccepted |= AcceptOptions.ACCEPT_SHUTDOWN;
}
_status.currentState = ServiceControlStatus.STATE_START_PENDING;
bool statusOK = SetServiceStatus(_statusHandle, pStatus);
if (!statusOK)
{
return;
}
// Need to execute the start method on a thread pool thread.
// Most applications will start asynchronous operations in the
// OnStart method. If such a method is executed in the current
// thread, the async operations might get canceled immediately
// since NT will terminate this thread right after this function
// finishes.
_startCompletedSignal = new ManualResetEvent(false);
_startFailedException = null;
ThreadPool.QueueUserWorkItem(new WaitCallback(this.ServiceQueuedMainCallback!), args);
_startCompletedSignal.WaitOne();
if (_startFailedException != null)
{
// Inform SCM that the service could not be started successfully.
// (Unless the service has already provided another failure exit code)
if (_status.win32ExitCode == 0)
{
_status.win32ExitCode = ServiceControlStatus.ERROR_EXCEPTION_IN_SERVICE;
}
}
statusOK = SetServiceStatus(_statusHandle, pStatus);
if (!statusOK)
{
string errorMessage = new Win32Exception().Message;
WriteLogEntry(SR.Format(SR.StartFailed, errorMessage), EventLogEntryType.Error);
lock (_stopLock)
{
if (_status.currentState != ServiceControlStatus.STATE_STOPPED)
{
_status.currentState = ServiceControlStatus.STATE_STOPPED;
SetServiceStatus(_statusHandle, pStatus);
}
}
}
}
}
private void WriteLogEntry(string message, EventLogEntryType type = EventLogEntryType.Information)
{
// EventLog failures shouldn't affect the service operation
try
{
if (AutoLog)
{
EventLog.WriteEntry(message, type);
}
}
catch
{
// Do nothing. Not having the event log is bad, but not starting the service as a result is worse.
}
}
}
}