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
|
//
// ServerApplication.cpp
//
// Library: Util
// Package: Application
// Module: ServerApplication
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/OptionException.h"
#include "Poco/FileStream.h"
#include "Poco/Exception.h"
#if !defined(POCO_VXWORKS)
#include "Poco/Process.h"
#include "Poco/NamedEvent.h"
#endif
#include "Poco/NumberFormatter.h"
#include "Poco/Logger.h"
#include "Poco/String.h"
#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS)
#include "Poco/TemporaryFile.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/stat.h>
#include <fstream>
#elif defined(POCO_OS_FAMILY_WINDOWS)
#if !defined(_WIN32_WCE)
#include "Poco/Util/WinService.h"
#include "Poco/Util/WinRegistryKey.h"
#endif
#include "Poco/UnWindows.h"
#include <cstring>
#endif
#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING)
#include "Poco/UnicodeConverter.h"
#endif
using Poco::NumberFormatter;
using Poco::Exception;
using Poco::SystemException;
namespace Poco {
namespace Util {
#if defined(POCO_OS_FAMILY_WINDOWS)
Poco::NamedEvent ServerApplication::_terminate(Poco::ProcessImpl::terminationEventName(Poco::Process::id()));
#if !defined(_WIN32_WCE)
Poco::Event ServerApplication::_terminated;
SERVICE_STATUS ServerApplication::_serviceStatus;
SERVICE_STATUS_HANDLE ServerApplication::_serviceStatusHandle = 0;
#endif
#endif
#if defined(POCO_VXWORKS) || POCO_OS == POCO_OS_ANDROID
Poco::Event ServerApplication::_terminate;
#endif
ServerApplication::ServerApplication()
{
#if defined(POCO_OS_FAMILY_WINDOWS)
#if !defined(_WIN32_WCE)
_action = SRV_RUN;
std::memset(&_serviceStatus, 0, sizeof(_serviceStatus));
#endif
#endif
}
ServerApplication::~ServerApplication()
{
}
bool ServerApplication::isInteractive() const
{
bool runsInBackground = config().getBool("application.runAsDaemon", false) || config().getBool("application.runAsService", false);
return !runsInBackground;
}
int ServerApplication::run()
{
return Application::run();
}
void ServerApplication::terminate()
{
#if defined(POCO_OS_FAMILY_WINDOWS)
_terminate.set();
#elif defined(POCO_VXWORKS) || POCO_OS == POCO_OS_ANDROID
_terminate.set();
#else
Poco::Process::requestTermination(Process::id());
#endif
}
#if defined(POCO_OS_FAMILY_WINDOWS)
#if !defined(_WIN32_WCE)
//
// Windows specific code
//
BOOL ServerApplication::ConsoleCtrlHandler(DWORD ctrlType)
{
switch (ctrlType)
{
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
terminate();
return _terminated.tryWait(10000) ? TRUE : FALSE;
default:
return FALSE;
}
}
void ServerApplication::ServiceControlHandler(DWORD control)
{
switch (control)
{
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
terminate();
_serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
break;
case SERVICE_CONTROL_INTERROGATE:
break;
}
SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
}
#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING)
void ServerApplication::ServiceMain(DWORD argc, LPWSTR* argv)
#else
void ServerApplication::ServiceMain(DWORD argc, LPTSTR* argv)
#endif
{
ServerApplication& app = static_cast<ServerApplication&>(Application::instance());
app.config().setBool("application.runAsService", true);
#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING)
_serviceStatusHandle = RegisterServiceCtrlHandlerW(L"", ServiceControlHandler);
#else
_serviceStatusHandle = RegisterServiceCtrlHandlerA("", ServiceControlHandler);
#endif
if (!_serviceStatusHandle)
throw SystemException("cannot register service control handler");
_serviceStatus.dwServiceType = SERVICE_WIN32;
_serviceStatus.dwCurrentState = SERVICE_START_PENDING;
_serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
_serviceStatus.dwWin32ExitCode = 0;
_serviceStatus.dwServiceSpecificExitCode = 0;
_serviceStatus.dwCheckPoint = 0;
_serviceStatus.dwWaitHint = 0;
SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
try
{
#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING)
std::vector<std::string> args;
for (DWORD i = 0; i < argc; ++i)
{
std::string arg;
Poco::UnicodeConverter::toUTF8(argv[i], arg);
args.push_back(arg);
}
app.init(args);
#else
app.init(argc, argv);
#endif
_serviceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
int rc = app.run();
_serviceStatus.dwWin32ExitCode = rc ? ERROR_SERVICE_SPECIFIC_ERROR : 0;
_serviceStatus.dwServiceSpecificExitCode = rc;
}
catch (Exception& exc)
{
app.logger().log(exc);
_serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
_serviceStatus.dwServiceSpecificExitCode = EXIT_CONFIG;
}
catch (...)
{
app.logger().error("fatal error - aborting");
_serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
_serviceStatus.dwServiceSpecificExitCode = EXIT_SOFTWARE;
}
_serviceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(_serviceStatusHandle, &_serviceStatus);
}
void ServerApplication::waitForTerminationRequest()
{
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
_terminate.wait();
_terminated.set();
}
int ServerApplication::run(int argc, char** argv)
{
if (!hasConsole() && isService())
{
return 0;
}
else
{
int rc = EXIT_OK;
try
{
init(argc, argv);
switch (_action)
{
case SRV_REGISTER:
registerService();
rc = EXIT_OK;
break;
case SRV_UNREGISTER:
unregisterService();
rc = EXIT_OK;
break;
default:
rc = run();
}
}
catch (Exception& exc)
{
logger().log(exc);
rc = EXIT_SOFTWARE;
}
return rc;
}
}
int ServerApplication::run(const std::vector<std::string>& args)
{
if (!hasConsole() && isService())
{
return 0;
}
else
{
int rc = EXIT_OK;
try
{
init(args);
switch (_action)
{
case SRV_REGISTER:
registerService();
rc = EXIT_OK;
break;
case SRV_UNREGISTER:
unregisterService();
rc = EXIT_OK;
break;
default:
rc = run();
}
}
catch (Exception& exc)
{
logger().log(exc);
rc = EXIT_SOFTWARE;
}
return rc;
}
}
#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING)
int ServerApplication::run(int argc, wchar_t** argv)
{
if (!hasConsole() && isService())
{
return 0;
}
else
{
int rc = EXIT_OK;
try
{
init(argc, argv);
switch (_action)
{
case SRV_REGISTER:
registerService();
rc = EXIT_OK;
break;
case SRV_UNREGISTER:
unregisterService();
rc = EXIT_OK;
break;
default:
rc = run();
}
}
catch (Exception& exc)
{
logger().log(exc);
rc = EXIT_SOFTWARE;
}
return rc;
}
}
#endif
bool ServerApplication::isService()
{
#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING)
SERVICE_TABLE_ENTRYW svcDispatchTable[2];
svcDispatchTable[0].lpServiceName = L"";
svcDispatchTable[0].lpServiceProc = ServiceMain;
svcDispatchTable[1].lpServiceName = NULL;
svcDispatchTable[1].lpServiceProc = NULL;
return StartServiceCtrlDispatcherW(svcDispatchTable) != 0;
#else
SERVICE_TABLE_ENTRY svcDispatchTable[2];
svcDispatchTable[0].lpServiceName = "";
svcDispatchTable[0].lpServiceProc = ServiceMain;
svcDispatchTable[1].lpServiceName = NULL;
svcDispatchTable[1].lpServiceProc = NULL;
return StartServiceCtrlDispatcherA(svcDispatchTable) != 0;
#endif
}
bool ServerApplication::hasConsole()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
return hStdOut != INVALID_HANDLE_VALUE && hStdOut != NULL;
}
void ServerApplication::registerService()
{
std::string name = config().getString("application.baseName");
std::string path = config().getString("application.path");
WinService service(name);
if (_displayName.empty())
service.registerService(path);
else
service.registerService(path, _displayName);
if (_startup == "auto")
service.setStartup(WinService::SVC_AUTO_START);
else if (_startup == "manual")
service.setStartup(WinService::SVC_MANUAL_START);
if (!_description.empty())
service.setDescription(_description);
logger().information("The application has been successfully registered as a service.");
}
void ServerApplication::unregisterService()
{
std::string name = config().getString("application.baseName");
WinService service(name);
service.unregisterService();
logger().information("The service has been successfully unregistered.");
}
void ServerApplication::defineOptions(OptionSet& options)
{
Application::defineOptions(options);
options.addOption(
Option("registerService", "", "Register the application as a service.")
.required(false)
.repeatable(false)
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleRegisterService)));
options.addOption(
Option("unregisterService", "", "Unregister the application as a service.")
.required(false)
.repeatable(false)
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleUnregisterService)));
options.addOption(
Option("displayName", "", "Specify a display name for the service (only with /registerService).")
.required(false)
.repeatable(false)
.argument("name")
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDisplayName)));
options.addOption(
Option("description", "", "Specify a description for the service (only with /registerService).")
.required(false)
.repeatable(false)
.argument("text")
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDescription)));
options.addOption(
Option("startup", "", "Specify the startup mode for the service (only with /registerService).")
.required(false)
.repeatable(false)
.argument("automatic|manual")
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleStartup)));
}
void ServerApplication::handleRegisterService(const std::string& /*name*/, const std::string& /*value*/)
{
_action = SRV_REGISTER;
}
void ServerApplication::handleUnregisterService(const std::string& /*name*/, const std::string& /*value*/)
{
_action = SRV_UNREGISTER;
}
void ServerApplication::handleDisplayName(const std::string& /*name*/, const std::string& value)
{
_displayName = value;
}
void ServerApplication::handleDescription(const std::string& /*name*/, const std::string& value)
{
_description = value;
}
void ServerApplication::handleStartup(const std::string& /*name*/, const std::string& value)
{
if (Poco::icompare(value, 4, std::string("auto")) == 0)
_startup = "auto";
else if (Poco::icompare(value, std::string("manual")) == 0)
_startup = "manual";
else
throw InvalidArgumentException("argument to startup option must be 'auto[matic]' or 'manual'");
}
#else // _WIN32_WCE
void ServerApplication::waitForTerminationRequest()
{
_terminate.wait();
}
int ServerApplication::run(int argc, char** argv)
{
try
{
init(argc, argv);
}
catch (Exception& exc)
{
logger().log(exc);
return EXIT_CONFIG;
}
return run();
}
int ServerApplication::run(const std::vector<std::string>& args)
{
try
{
init(args);
}
catch (Exception& exc)
{
logger().log(exc);
return EXIT_CONFIG;
}
return run();
}
#if defined(POCO_WIN32_UTF8) && !defined(POCO_NO_WSTRING)
int ServerApplication::run(int argc, wchar_t** argv)
{
try
{
init(argc, argv);
}
catch (Exception& exc)
{
logger().log(exc);
return EXIT_CONFIG;
}
return run();
}
#endif
#endif // _WIN32_WCE
#elif defined(POCO_VXWORKS)
//
// VxWorks specific code
//
void ServerApplication::waitForTerminationRequest()
{
_terminate.wait();
}
int ServerApplication::run(int argc, char** argv)
{
try
{
init(argc, argv);
}
catch (Exception& exc)
{
logger().log(exc);
return EXIT_CONFIG;
}
return run();
}
int ServerApplication::run(const std::vector<std::string>& args)
{
try
{
init(args);
}
catch (Exception& exc)
{
logger().log(exc);
return EXIT_CONFIG;
}
return run();
}
void ServerApplication::defineOptions(OptionSet& options)
{
Application::defineOptions(options);
}
#elif defined(POCO_OS_FAMILY_UNIX)
//
// Unix specific code
//
void ServerApplication::waitForTerminationRequest()
{
#if POCO_OS != POCO_OS_ANDROID
sigset_t sset;
sigemptyset(&sset);
if (!std::getenv("POCO_ENABLE_DEBUGGER"))
{
sigaddset(&sset, SIGINT);
}
sigaddset(&sset, SIGQUIT);
sigaddset(&sset, SIGTERM);
sigprocmask(SIG_BLOCK, &sset, NULL);
int sig;
sigwait(&sset, &sig);
#else // POCO_OS != POCO_OS_ANDROID
_terminate.wait();
#endif
}
int ServerApplication::run(int argc, char** argv)
{
bool runAsDaemon = isDaemon(argc, argv);
if (runAsDaemon)
{
beDaemon();
}
try
{
init(argc, argv);
if (runAsDaemon)
{
int rc = chdir("/");
if (rc != 0) return EXIT_OSERR;
}
}
catch (Exception& exc)
{
logger().log(exc);
return EXIT_CONFIG;
}
return run();
}
int ServerApplication::run(const std::vector<std::string>& args)
{
bool runAsDaemon = false;
for (std::vector<std::string>::const_iterator it = args.begin(); it != args.end(); ++it)
{
if (*it == "--daemon")
{
runAsDaemon = true;
break;
}
}
if (runAsDaemon)
{
beDaemon();
}
try
{
init(args);
if (runAsDaemon)
{
int rc = chdir("/");
if (rc != 0) return EXIT_OSERR;
}
}
catch (Exception& exc)
{
logger().log(exc);
return EXIT_CONFIG;
}
return run();
}
bool ServerApplication::isDaemon(int argc, char** argv)
{
std::string option("--daemon");
for (int i = 1; i < argc; ++i)
{
if (option == argv[i])
return true;
}
return false;
}
void ServerApplication::beDaemon()
{
#if !defined(POCO_NO_FORK_EXEC)
pid_t pid;
if ((pid = fork()) < 0)
throw SystemException("cannot fork daemon process");
else if (pid != 0)
exit(0);
setsid();
umask(027);
// attach stdin, stdout, stderr to /dev/null
// instead of just closing them. This avoids
// issues with third party/legacy code writing
// stuff to stdout/stderr.
FILE* fin = freopen("/dev/null", "r+", stdin);
if (!fin) throw Poco::OpenFileException("Cannot attach stdin to /dev/null");
FILE* fout = freopen("/dev/null", "r+", stdout);
if (!fout) throw Poco::OpenFileException("Cannot attach stdout to /dev/null");
FILE* ferr = freopen("/dev/null", "r+", stderr);
if (!ferr) throw Poco::OpenFileException("Cannot attach stderr to /dev/null");
#else
throw Poco::NotImplementedException("platform does not allow fork/exec");
#endif
}
void ServerApplication::defineOptions(OptionSet& options)
{
Application::defineOptions(options);
options.addOption(
Option("daemon", "", "Run application as a daemon.")
.required(false)
.repeatable(false)
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleDaemon)));
options.addOption(
Option("umask", "", "Set the daemon's umask (octal, e.g. 027).")
.required(false)
.repeatable(false)
.argument("mask")
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handleUMask)));
options.addOption(
Option("pidfile", "", "Write the process ID of the application to given file.")
.required(false)
.repeatable(false)
.argument("path")
.callback(OptionCallback<ServerApplication>(this, &ServerApplication::handlePidFile)));
}
void ServerApplication::handleDaemon(const std::string& name, const std::string& value)
{
config().setBool("application.runAsDaemon", true);
}
void ServerApplication::handleUMask(const std::string& name, const std::string& value)
{
int mask = 0;
for (std::string::const_iterator it = value.begin(); it != value.end(); ++it)
{
mask *= 8;
if (*it >= '0' && *it <= '7')
mask += *it - '0';
else
throw Poco::InvalidArgumentException("umask contains non-octal characters", value);
}
umask(mask);
}
void ServerApplication::handlePidFile(const std::string& name, const std::string& value)
{
Poco::FileOutputStream ostr(value);
if (ostr.good())
ostr << Poco::Process::id() << std::endl;
else
throw Poco::CreateFileException("Cannot write PID to file", value);
Poco::TemporaryFile::registerForDeletion(value);
}
#endif
} } // namespace Poco::Util
|