Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

[r7651]: main / trunk / rexxapi / server / platform / windows / APIService.cpp Maximize Restore History

Download this file

APIService.cpp    1034 lines (907 with data), 32.8 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
/*----------------------------------------------------------------------------*/
/* */
/* Copyright (c) 1995, 2004 IBM Corporation. All rights reserved. */
/* Copyright (c) 2005-2009 Rexx Language Association. All rights reserved. */
/* */
/* This program and the accompanying materials are made available under */
/* the terms of the Common Public License v1.0 which accompanies this */
/* distribution. A copy is also available at the following address: */
/* http://www.ibm.com/developerworks/oss/CPLv1.0.htm */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the distribution. */
/* */
/* Neither the name of Rexx Language Association nor the names */
/* of its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */
/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
/* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, */
/* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY */
/* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */
/* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/*----------------------------------------------------------------------------*/
#include <aclapi.h>
#include "APIServer.hpp"
#include "stdio.h"
#define SERVICENAME "RXAPI"
#define SERVICEDESCRIPTION "%s Service for Open Object Rexx version %d.%d.%d"
#define SYNTAX_HELP "Syntax: rxapi opt [/s]\n\n" \
"Where opt is exactly one of:\n" \
"/i :\tinstall as Service.\n" \
"/u :\tuninstall as Service.\n" \
"/v :\tshow Version number\n\n" \
"The /s (silent) is optional and prevents any messages from displaying."
#define APP_LOG_KEYNAME "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\"
typedef enum {installed_state, running_state, disabled_state, uninstalled_state} ServiceStateType;
typedef enum {Windows_NT, Windows_2K} WindowsVersionType;
// Prototypes
void setServiceDACL(SC_HANDLE hService);
// Globals for Service
static SERVICE_STATUS_HANDLE m_hServiceStatus;
static SERVICE_STATUS m_Status;
static SERVICE_DESCRIPTION Info;
/* - - - - Useful debugging help, if'd out under normal circumstances- - - - -*/
#if 0
#include <shlobj.h>
#include <shlwapi.h>
TCHAR fileBuf[MAX_PATH];
static const char *fileName = NULL;
void __cdecl DebugMsg(const char* pszFormat, ...)
{
FILE *stream;
va_list arglist;
char buf[1024];
sprintf(buf, "[%s](%lu)(%lu){%d}: ", SERVICENAME, GetCurrentThreadId(),GetCurrentProcessId(),
m_Status.dwCurrentState);
va_start(arglist, pszFormat);
vsprintf(&buf[strlen(buf)], pszFormat, arglist);
va_end(arglist);
strcat(buf, "\n");
if ( fileName == NULL )
{
SHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS | CSIDL_FLAG_CREATE, NULL, 0, fileBuf);
PathAppend(fileBuf, "apiService.log");
fileName = fileBuf;
}
stream = fopen(fileName, "a+");
if ( stream )
{
fwrite(buf, 1, strlen(buf), stream);
fclose(stream);
}
}
#endif
/* - - End debugging help - - - - - - - - - - - - - - - - - - - - - - - - - - */
APIServer apiServer; // the real server instance
// A couple of helper functions.
inline void showMessage(const char *msg, unsigned int icon)
{
MessageBox(NULL, msg, SERVICENAME, MB_OK | icon);
}
#define WINDOWS_95_98_ME VER_PLATFORM_WIN32_WINDOWS
bool isAtLeastVersion(WindowsVersionType type)
{
OSVERSIONINFO version_info;
bool answer = false;
version_info.dwOSVersionInfoSize = sizeof(version_info);
GetVersionEx(&version_info);
switch ( type )
{
case Windows_NT :
answer = version_info.dwPlatformId != WINDOWS_95_98_ME;
break;
case Windows_2K :
answer = version_info.dwMajorVersion >= 5;
break;
default :
break;
}
return answer;
}
/**
* Starts up the API server and has it listen for messages.
*
* Run() is either called from ServiceMain() in which case the API server will
* be running in a Service process. If rxapi is not installed as a service, or
* for some reason the service can not be started, then Run() is called from
* WinMain() and the API server runs in a standard process.
*
* @param asService If true, Run() was called from ServiceMain(), otherwise
* Run() was called from WinMain().
*/
void Run (bool asService)
{
try
{
apiServer.initServer(); // start up the server
apiServer.listenForConnections(); // go into the message loop
}
catch (ServiceException *)
{
}
apiServer.terminateServer(); // shut everything down
}
/**
* The following functions handle the Service control requests.
*/
// Called when the service is first initialized
bool OnInit()
{
return true;
}
// Called when the service control manager wants to stop the service
void OnStop()
{
apiServer.terminateServer(); // terminate the server.
}
// called when the service is interrogated
void OnInterrogate()
{
}
// called when the service is paused
void OnPause()
{
}
// called when the service is continued
void OnContinue()
{
}
// called when the service is shut down
void OnShutdown()
{
}
// called when the service gets a user control message
BOOL OnUserControl(DWORD dwOpcode)
{
return FALSE; // say not handled
}
/**
* Updates the Service Control Manager with our current state.
*
* @param dwState The current state.
*/
void SetStatus(DWORD dwState)
{
m_Status.dwCurrentState = dwState;
SetServiceStatus(m_hServiceStatus, &m_Status);
}
/**
* The handler function registered with the Service Control dispatcher. The
* dispatcher uses this function to send service control messages to the service
* process.
*
* @param dwOpcode The control message.
*/
static void __cdecl Handler(DWORD dwOpcode)
{
switch (dwOpcode) {
case SERVICE_CONTROL_STOP: // 1
SetStatus(SERVICE_STOP_PENDING);
OnStop();
break;
case SERVICE_CONTROL_PAUSE: // 2
OnPause();
break;
case SERVICE_CONTROL_CONTINUE: // 3
OnContinue();
break;
case SERVICE_CONTROL_INTERROGATE: // 4
OnInterrogate();
break;
case SERVICE_CONTROL_SHUTDOWN: // 5
OnShutdown();
break;
default:
break;
}
// Report current status
SetServiceStatus(m_hServiceStatus, &m_Status);
}
bool Initialize()
{
bool result;
// Inform the Service Control Manager that we are about to start.
SetStatus(SERVICE_START_PENDING);
// Perform the actual initialization
result = OnInit();
// Inform the Service Control Manager of our final state.
m_Status.dwWin32ExitCode = GetLastError();
m_Status.dwCheckPoint = 0;
m_Status.dwWaitHint = 0;
if ( ! result )
{
SetStatus(SERVICE_STOPPED);
return false;
}
SetStatus(SERVICE_RUNNING);
return true;
}
/**
* After the service control dislpatcher receives a start request, (see
* startTheService(),) it creates a new thread and invokes this function on that
* thread to do the actual work of the service.
*
* @param dwArgc Count of args (not used by rxapi)
* @param lpszArgv Args (not used by rxapi)
*/
static void WINAPI ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
// Register the handler. The Service Control Manager will call back to this
// function to issue control requests.
m_Status.dwCurrentState = SERVICE_START_PENDING;
m_hServiceStatus = RegisterServiceCtrlHandler(SERVICENAME, (LPHANDLER_FUNCTION)Handler);
if ( m_hServiceStatus == (SERVICE_STATUS_HANDLE)NULL )
{
return;
}
// Start the initialisation
if ( Initialize() )
{
// Do the actual work. When the Run function returns, the service has
// stopped.
m_Status.dwWin32ExitCode = 0;
m_Status.dwCheckPoint = 0;
m_Status.dwWaitHint = 0;
Run(true);
}
// Tell the service control manager we have stopped
SetStatus(SERVICE_STOPPED);
}
/**
* Connects the main thread of this service process to the Service Control
* Manager. When this function succeeds, it will not return until the rxapi
* Service is stopped.
*
* @return A return of true indicates that rxapi was successfully started as a
* service process and has run to completion. A return of false
* indicates the rxapi service process was not started.
*
* @note When rxapi is installed as a service, it can not run as a service
* process unless it is started through the Service Control Manager. If
* rxapi is started through the command line or by CreateProcess(),
* StartServiceCtrlDispatcher() will return
* ERROR_FAILED_SERVICE_CONTROLLER_CONNECT and the service process will
* not have run.
*/
bool startTheService(void)
{
SERVICE_TABLE_ENTRY st[] =
{
{
(LPTSTR)SERVICENAME,
ServiceMain
},
{
NULL, NULL
}
};
m_Status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_Status.dwCurrentState = SERVICE_STOPPED;
m_Status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
m_Status.dwWin32ExitCode = 0;
m_Status.dwServiceSpecificExitCode = 0;
m_Status.dwCheckPoint = 0;
m_Status.dwWaitHint = 0;
return StartServiceCtrlDispatcher(st) != 0;
}
/**
* If rxapi is currently running as a Service process, then stop it.
*
* @param hService Opened handle to the service. The handle must have been
* opened with SERVICE_QUERY_STATUS and SERVICE_STOP access
* rights.
*
* @param timeOut Time to wait, in miliseconds for a pending stop to clear.
*
* @return True if the service is stopped, false if not sure that the service
* is stopped.
*/
bool stopTheService(SC_HANDLE hService, DWORD timeOut)
{
SERVICE_STATUS_PROCESS ssp;
DWORD startTicks = GetTickCount();
DWORD waitTime = timeOut / 20;
DWORD needed;
bool success = false;
// See if the service is already stopped.
if ( ! QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &needed) )
{
goto finished;
}
if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
success = true;
goto finished;
}
// When a service has a stop pending, we'll wait for it.
while ( ssp.dwCurrentState == SERVICE_STOP_PENDING )
{
Sleep(waitTime);
if ( ! QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &needed) )
{
goto finished;
}
if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
success = true;
goto finished;
}
if ( GetTickCount() - startTicks > timeOut )
{
goto finished;
}
}
// Send a stop code through the Sevice Control Manager to the service
SERVICE_STATUS ss;
if ( ! ControlService(hService, SERVICE_CONTROL_STOP, &ss) )
{
goto finished;
}
// Wait for the service to stop
while ( ssp.dwCurrentState != SERVICE_STOPPED )
{
Sleep(waitTime);
if ( ! QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &needed) )
{
break;
}
if ( ss.dwCurrentState == SERVICE_STOPPED )
{
success = true;
break;
}
if ( GetTickCount() - startTicks > timeOut )
{
break;
}
}
finished:
return success;
}
void setServiceDACL(SC_HANDLE hService)
{
EXPLICIT_ACCESS ea;
SECURITY_DESCRIPTOR sd;
PSECURITY_DESCRIPTOR psd = NULL;
PACL pacl = NULL;
PACL pNewAcl = NULL;
BOOL bDaclPresent = FALSE;
BOOL bDaclDefaulted = FALSE;
DWORD dwError = 0;
DWORD needed = 0;
// Get the current security descriptor for the service. First query with a
// size of 0 to get the needed size.
if ( ! QueryServiceObjectSecurity(hService, DACL_SECURITY_INFORMATION, &psd, 0, &needed) )
{
if ( GetLastError() == ERROR_INSUFFICIENT_BUFFER )
{
DWORD size = needed;
psd = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, size);
if (psd == NULL)
{
goto cleanup;
}
if ( ! QueryServiceObjectSecurity( hService, DACL_SECURITY_INFORMATION, psd, size, &needed) )
{
goto cleanup;
}
}
else
{
goto cleanup;
}
}
// Get the current DACL from the security descriptor.
if ( ! GetSecurityDescriptorDacl(psd, &bDaclPresent, &pacl, &bDaclDefaulted) )
{
goto cleanup;
}
// Build the ACE.
BuildExplicitAccessWithName(&ea, TEXT("Users"), SERVICE_START | SERVICE_STOP | GENERIC_READ, SET_ACCESS, NO_INHERITANCE);
dwError = SetEntriesInAcl(1, (PEXPLICIT_ACCESS)&ea, pacl, &pNewAcl);
if ( dwError != ERROR_SUCCESS )
{
goto cleanup;
}
// Initialize a new security descriptor.
if ( ! InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) )
{
goto cleanup;
}
// Set the new DACL in the security descriptor.
if ( ! SetSecurityDescriptorDacl(&sd, TRUE, pNewAcl, FALSE) )
{
goto cleanup;
}
// Set the new security descriptor for the service object.
SetServiceObjectSecurity(hService, DACL_SECURITY_INFORMATION, &sd);
cleanup:
if( pNewAcl != NULL )
{
LocalFree((HLOCAL)pNewAcl);
}
if( psd != NULL )
{
LocalFree((LPVOID)psd);
}
}
/**
* Install rxapi as a Windows service and add the registry entries to allow
* logging through the Event Log service.
*
* @return True if the service was installed, otherwise false.
*/
bool Install()
{
char szFilePath[_MAX_PATH];
SC_HANDLE hService = NULL;
char szKey[_MAX_PATH];
HKEY hKey = NULL;
DWORD dwData;
bool success = false;
// Open the Service Control Manager
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT);
if ( hSCM == NULL )
{
goto cleanup;
}
// Get the executable file path. The docs for Services say that if the path
// contains spaces it must be quoted.
// Use szKey as a temp buffer.
GetModuleFileName(NULL, szKey, sizeof(szKey));
if ( strstr(szKey, " ") == 0 )
{
strcpy(szFilePath, szKey);
}
else
{
_snprintf(szFilePath, sizeof(szFilePath), "\"%s\"", szKey);
}
// Create the service
hService = CreateService(hSCM, SERVICENAME, SERVICENAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szFilePath, NULL, NULL, NULL, NULL,
NULL);
if ( hService == NULL )
{
goto cleanup;
}
// At this point, the service is installed, so success is set to true. The
// rest of the stuff is icing on the cake so to speak. If something fails,
// it might be nice to notify someone, but we shouldn't say the service
// install failed, because it hasn't.
success = true;
// ChangeServiceConfig2() needs W2K or later.
if ( isAtLeastVersion(Windows_2K) )
{
// Use szKey as a temporary buffer
sprintf(szKey, SERVICEDESCRIPTION, SERVICENAME, ORX_VER, ORX_REL, ORX_MOD);
Info.lpDescription = szKey;
ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &Info);
}
// Set the discretionary ACL for the service.
setServiceDACL(hService);
// Add the registry entries to support logging messages. The source name is
// added as a subkey under the Application key in the EventLog service
// portion of the registry.
strcpy(szKey, APP_LOG_KEYNAME);
strcat(szKey, SERVICENAME);
if ( RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey) == ERROR_SUCCESS )
{
// Set the value of 'EventMessageFile' to the Event ID message-file name.
RegSetValueEx(hKey, "EventMessageFile", 0, REG_EXPAND_SZ, (CONST BYTE*)szFilePath,
(DWORD)strlen(szFilePath) + 1);
// Set the value of 'TypesSupported' to the supported types.
dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (CONST BYTE*)&dwData, sizeof(DWORD));
RegCloseKey(hKey);
}
cleanup:
if ( hService != NULL )
{
CloseServiceHandle(hService);
}
if ( hSCM != NULL )
{
CloseServiceHandle(hSCM);
}
return success;
}
/**
* Deletes rxapi as a service and cleans up the registry entries that were made
* when rxapi was installed as a service.
*
* @return true on success, othewise false.
*/
bool Uninstall()
{
bool success = false;
// Open the Service Control Manager
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if ( hSCM != NULL )
{
SC_HANDLE hService = OpenService(hSCM, SERVICENAME, DELETE | SERVICE_QUERY_STATUS | SERVICE_STOP);
if ( hService != NULL )
{
// First stop the service if it is running, which allows the Service
// Control Manger to clean up the database immediately. If we fail
// to stop the service we just ignore it. The database will be
// cleaned up at the next reboot. (Or sooner if the rxapi process is
// killed.)
stopTheService(hService, 1000);
if ( DeleteService(hService) )
{
success = true;
}
CloseServiceHandle(hService);
}
CloseServiceHandle(hSCM);
}
// Remove the Event Log service entries in the registry for rxapi. These
// entries are added during the Service installation function. Any errors
// are just ignored.
if ( success )
{
HKEY hKey = NULL;
if ( RegOpenKeyEx(HKEY_LOCAL_MACHINE, APP_LOG_KEYNAME, 0, DELETE, &hKey) == ERROR_SUCCESS )
{
if ( RegDeleteKey(hKey, SERVICENAME) == ERROR_SUCCESS )
{
RegCloseKey(hKey);
}
}
}
return success;
}
/**
* Determines if the service is currently running.
*
* If the current state is START PENDING will wait until the service is running
* or times out.
*
* @param hService Handle to the opened service. Note that the handle has to
* have been opened with SERVICE_QUERY_STATUS so that we can
* use QueryServiceStatusEx().
*
* @return True if the service is running, false otherwise.
*/
bool serviceIsRunning(SC_HANDLE hService)
{
SERVICE_STATUS_PROCESS ssp;
DWORD needed;
BOOL success = QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS), &needed);
if ( success )
{
if ( ssp.dwCurrentState == SERVICE_RUNNING || ssp.dwCurrentState == SERVICE_STOPPED ||
ssp.dwCurrentState == SERVICE_STOP_PENDING )
{
return ssp.dwCurrentState == SERVICE_RUNNING;
}
if ( ssp.dwCurrentState == SERVICE_START_PENDING )
{
// Save the tick count and initial checkpoint.
uint32_t startTicks = GetTickCount();
uint32_t oldCheck = ssp.dwCheckPoint;
uint32_t waitTime;
// Check the status until the service is no longer start pending.
// rxapi is not pausable, so PAUSED or PAUSED_PENDING should not be
// possible.
while ( ssp.dwCurrentState == SERVICE_START_PENDING )
{
// Do not wait longer than the wait hint, which for rxapi will
// be 2000 milliseconds.
//
// Microsoft suggests that a good interval is one tenth the wait
// hint, but not less than 1 second and no more than 10 seconds.
// rxapi usually starts in less than 200 milliseconds.
waitTime = ssp.dwWaitHint / 10;
if( waitTime < 200 )
{
waitTime = 200;
}
else if ( waitTime > 10000 )
{
waitTime = 10000;
}
Sleep(waitTime);
BOOL success = QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS), &needed);
if ( ! success || ssp.dwCurrentState == SERVICE_RUNNING )
{
break;
}
if ( ssp.dwCheckPoint > oldCheck )
{
// The service is making progress, so continue.
startTicks = GetTickCount();
oldCheck = ssp.dwCheckPoint;
}
else
{
if( (GetTickCount() - startTicks) > ssp.dwWaitHint )
{
// The wait hint interval has expired and we are still
// not started, so quit.
break;
}
}
}
return ssp.dwCurrentState == SERVICE_RUNNING;
}
}
return false;
}
/**
* Determines if: rxapi is installed as a service and is already running, is
* installed as a service but not running, installed but the service is
* currently disabled, or not installed as a service.
*
* @return One of the 4 service state enums.
*/
ServiceStateType getServiceState(void)
{
ServiceStateType state = uninstalled_state;
// Open the Service Control Manager
SC_HANDLE hSCM = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT);
if ( hSCM )
{
// Try to open the service, if this fails, rxapi is not installed as a
// service.
SC_HANDLE hService = OpenService(hSCM, SERVICENAME, SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS);
if ( hService )
{
// The service is definitely installed, we'll mark it as disabled
// until we know for sure it is not disabled.
state = disabled_state;
LPQUERY_SERVICE_CONFIG pqsc = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, 4096);
if ( pqsc )
{
DWORD needed;
if ( QueryServiceConfig(hService, pqsc, 4096, &needed) )
{
if ( pqsc->dwStartType != SERVICE_DISABLED )
{
state = installed_state;
}
}
LocalFree(pqsc);
}
if ( state == installed_state )
{
// See if rxapi is already running as a service.
if ( serviceIsRunning(hService) )
{
state = running_state;
}
}
CloseServiceHandle(hService);
}
CloseServiceHandle(hSCM);
}
return state;
}
/**
* Start rxapi as a Windows Service, if possible. This function determines if
* rxapi is installed as a Service and if it is already running as a service.
*
* If it is installled as a service, but not running, an attempt is made to
* start it as a Service.
*
* @return True if now running as a Windows Service, otherwis false.
*/
bool startAsWindowsService(void)
{
bool started;
DWORD errRC;
int iRet;
ServiceStateType state = getServiceState();
if ( state == running_state )
{
return true;
}
if ( state == installed_state )
{
// When the service is started successfully here, we do not return until
// the service has been stopped.
started = startTheService();
if ( ! started )
{
// The service did not start, get the error code.
errRC = GetLastError();
if ( errRC == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT )
{
// This specific error happens when rxapi is not running and is
// started from the command line or by CreateProcess(). Service
// processes can not run when started as console programs.
// (Really we should educate the user not to do this.) We use
// NET START RXAPI, which will invoke the service controller to
// start rxapi correctly. When we return from system(), rxapi
// will be running as a service in another process, so it is
// important to exit this process.
iRet = system("NET start rxapi");
// If the return is not 0, rxapi was not started as a service.
return iRet == 0;
}
else
{
// The service could not be started for some un-anticipated
// reason. Return false so that rxapi will continue by running
// as a standard process.
return false;
}
}
// Do not continue by running rxapi as a standard process.
return true;
}
// Either rxapi is not installed as a Service, or the Service has been set
// to disabled. Continue by running rxapi as a standard process.
return false;
}
/**
* We have command line args, process them. Most likely the args are to install
* or uninstall rxapi as a service.
*
* @param cmdLine The command line, must not be null.
*/
void processCmdLine(const char *cmdLine)
{
char msg[256];
bool verbose = true;
size_t len = strlen(cmdLine);
if ( cmdLine[0] != '/' || len < 2 )
{
showMessage(SYNTAX_HELP, MB_ICONERROR);
return;
}
if ( len >= 5 )
{
char opt = cmdLine[4];
if ( opt == 's' || opt == 'S' || opt == 'q' || opt == 'Q' )
{
verbose = false;
}
}
bool isInstalled = (getServiceState() != uninstalled_state);
switch ( cmdLine[1] )
{
case 'v' :
case 'V' :
sprintf(msg ,"%s Version %d.%d.%d\n\nThe service is %s installed", SERVICENAME,
ORX_VER, ORX_REL, ORX_MOD, isInstalled ? "currently" : "not");
showMessage(msg, MB_ICONINFORMATION);
break;
case 'i' :
case 'I' :
if ( isInstalled )
{
if ( verbose )
{
sprintf(msg, "%s is already installed as a service.", SERVICENAME);
showMessage(msg, MB_ICONWARNING);
}
}
else
{
if ( Install() )
{
if ( verbose )
{
sprintf(msg, "The %s service was installed\n", SERVICENAME);
showMessage(msg, MB_ICONINFORMATION);
}
}
else
{
if ( verbose )
{
sprintf(msg, "The %s service failed to install.\n"
"Error %d\n", SERVICENAME, GetLastError());
showMessage(msg, MB_ICONERROR);
}
}
}
break;
case 'u' :
case 'U' :
if ( ! isInstalled )
{
if ( verbose )
{
sprintf(msg, "%s is not installed as a service\n", SERVICENAME);
showMessage(msg, MB_ICONWARNING);
}
}
else
{
if ( Uninstall() )
{
if ( verbose )
{
sprintf(msg, "%s was uninstalled as a service.\n\n"
"(Open Object REXX is not uninstalled.)", SERVICENAME);
showMessage(msg, MB_ICONINFORMATION);
}
}
else
{
if ( verbose )
{
sprintf(msg, "The %s service could not be uninstalled.\n"
"Error %d\n", SERVICENAME, GetLastError());
showMessage(msg, MB_ICONERROR);
}
}
}
break;
default :
showMessage(SYNTAX_HELP, MB_ICONERROR);
break;
}
return;
}
/**
* The main entry point for rxapi.exe.
*
* When rxapi is installed as a service, the invoker might be the service
* control manager, or the interpreter could be starting rxapi as a service
* because rxapi was not running.
*
* When rxapi is not installed as a service, then the invoker is most likely the
* interpreter starting up rxapi. Although, the user could also be invoking
* rxapi from the command line.
*
* The third possibility is that rxapi is being invoked from the command line
* with arguments to either install, uninstall, or query rxapi as a service.
*
*
* @param hInstance
* @param hPrevInstance
* @param lpCmdLine The only arg we are interested in, the command line
* arguments.
* @param nCmdShow
*
* @return 0
*/
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
if ( isAtLeastVersion(Windows_NT) )
{
// If there are args, we always process them and exit.
if ( strlen(lpCmdLine) != 0 )
{
processCmdLine(lpCmdLine);
exit(0);
}
// If rxapi is already running as a service then startAsWindowsService()
// will return immediately and we will exit. Otherwise, the function
// will attempt to strart rxapi as a service. If successful, we do not
// return from startAsWindowService() until the service is stopped.
if ( startAsWindowsService() )
{
// rxapi was already running as a service, or rxapi was started and
// ran as a service, and is now ended / stopped.
exit(0);
}
}
// For some reason we are not running as an installed service, (either not
// installed as service, the user does not have the authority to start a
// stopped service, or some other reason.) In this case, run rxapi as a
// normal process.
Run(false);
return 0;
}