mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

jvergara
26.38.2007 ea36bf18fa9fa03d0c925a1e16c2b5fbedb0da99
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
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License").  You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at
* trunk/opends/resource/legal-notices/OpenDS.LICENSE
* or https://OpenDS.dev.java.net/OpenDS.LICENSE.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at
* trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
* add the following below this CDDL HEADER, with the fields enclosed
* by brackets "[]" replaced with your own identifying * information:
*      Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
*
*      Portions Copyright 2007 Sun Microsystems, Inc.
*/
 
#include "service.h"
 
int _serviceCurStatus;
SERVICE_STATUS_HANDLE *_serviceStatusHandle;
HANDLE _terminationEvent = NULL;
char *_instanceDir = NULL;
HANDLE _eventLog = NULL;
BOOL DEBUG = FALSE;
 
 
// ----------------------------------------------------
// Register a service handler to the service control dispatcher.
// A service handler will manage the control function such as:
// stop, pause, continue, shutdown, interrogate. The control functions
// are sent by the service control dispatcher upon user request
// (ie. NET STOP)
//
// serviceName     the internal name of the service (unique in the system)
// serviceHandler  the handler of the service
// serviceStatusHandle  the service status handle returned by the SCM
// The functions returns SERVICE_RETURN_OK if we could start the service
// and SERVICE_RETURN_ERROR otherwise.
// ----------------------------------------------------
 
ServiceReturnCode registerServiceHandler (
char*                   serviceName,
LPHANDLER_FUNCTION      serviceHandler,
SERVICE_STATUS_HANDLE*  serviceStatusHandle
)
{
  ServiceReturnCode returnValue;
 
  // register the service to the service control dispatcher (SCM)
  *serviceStatusHandle = RegisterServiceCtrlHandler (
  serviceName, (LPHANDLER_FUNCTION) serviceHandler
  );
  if (serviceStatusHandle == NULL)
  {
    returnValue = SERVICE_RETURN_ERROR;
  }
  else
  {
    returnValue = SERVICE_RETURN_OK;
  }
  return returnValue;
}  // registerServiceHandler
 
// ---------------------------------------------------
// Debug utility.  If the _eventLog is not NULL and the DEBUG variable is
// TRUE send the message to the event log.
// If the _eventLog is NULL and the DEBUG variable is TRUE send the message
// to the standard output.
// ---------------------------------------------------
void debug(char* msg)
{
  if (DEBUG == TRUE)
  {
    if (_eventLog != NULL)
    {
      const char* args[1];
      args[0] = msg;
 
      // report the event
      ReportEvent(
      _eventLog,          // event log handle
      EVENTLOG_INFORMATION_TYPE,  // info, warning, error
      WIN_FACILITY_NAME_OPENDS,   // unique category for OPENDS
      WIN_EVENT_ID_DEBUG,
      NULL,           // no user security identifier
      1,              // number of  args
      0,              // raw data size
      (const char**)args,     // args
      NULL            // no war data
      );
    }
    else
    {
      fprintf(stdout, "%s\n", msg);
    }
  }
}
 
// ---------------------------------------------------
// Reports a log event of a given type, id and arguments
// serviceBinPath the binary associated with the service.
// The function returns TRUE if the event could be logged and FALSE otherwise.
// ---------------------------------------------------
BOOL reportLogEvent(WORD eventType, DWORD eventId, WORD argCount,
const char** args)
{
  BOOL reportOk;
 
  if (argCount > 0)
  {
    // report the event
    reportOk = ReportEvent(
    _eventLog,              // event log handle
    eventType,              // info, warning, error
    WIN_FACILITY_NAME_OPENDS,     // unique category for OPENDS
    eventId,
    NULL,               // no user security identifier
    argCount,             // number of args
    0,                  // raw data size
    args,               // args
    NULL                // no raw data
    );
  }
  else
  {
    // report the event
    reportOk = ReportEvent(
    _eventLog,              // event log handle
    eventType,              // info, warning, error
    WIN_FACILITY_NAME_OPENDS,     // unique category for OPENDS
    eventId,
    NULL,               // no user security identifier
    argCount,             // number of args
    0,                  // raw data size
    NULL,               // args
    NULL                // no raw data
    );
  }
 
 
  return reportOk;
}
 
// ---------------------------------------------------------------
// Get a handle to the Service Control Manager (SCM).
// accessRights  the desired access rights; generic access are:
//  - GENERIC_READ     use to get the list of services
//  - GENERIC_WRITE    use to create & remove a service
//  - GENERIC_EXECUTE
//  - GENERIC_ALL
// scm  the handler to the SCM
// The function returns SERVICE_RETURN_OK if we could get the SCM
// and SERVICE_RETURN_ERROR otherwise.
// ---------------------------------------------------------------
 
ServiceReturnCode openScm(DWORD accessRights, SC_HANDLE *scm)
{
  ServiceReturnCode returnValue;
 
  // open Service Control Manager
  *scm = (SC_HANDLE)OpenSCManager (
  NULL,           // local machine
  NULL,           // ServicesActive database
  accessRights    // desired rights
  );
  if (scm == NULL)
  {
    debug("scm is NULL.");
    returnValue = SERVICE_RETURN_ERROR;
  }
  else
  {
    returnValue = SERVICE_RETURN_OK;
  }
  return returnValue;
} // openScm
 
// ---------------------------------------------------
// Creates the registry key to send events based on the name of the service.
// serviceName the serviceName.
// serviceBinPath the binary associated with the service.
// The function returns TRUE if the key could be registered (or was already
// registered) and FALSE otherwise.
// ---------------------------------------------------
BOOLEAN createRegistryKey(char* serviceName)
{
  // true if the server is already registered
  BOOL alreadyRegistered = FALSE;
 
  // false as soon as an error occurs
  BOOL success = TRUE;
 
  // handle to the created/opened key
  HKEY hkey = NULL;
 
  // Create the event source subkey (or open it if it already exists)
  char subkey [MAX_REGISTRY_KEY];
 
  long result;
 
  DWORD nbCategories = 1;
 
  // get the full path to the current executable file: is safe to do it
  // here because we already required it to figure out to get the service
  // name based on the command to run associated with it.
  char execName [MAX_PATH];
  GetModuleFileName (
  NULL,
  execName,
  MAX_PATH
  );
 
  // Check whether the Registry Key is already created,
  // If so don't create a new one.
  sprintf (subkey, EVENT_LOG_KEY, serviceName);
  result = RegOpenKeyEx(
  HKEY_LOCAL_MACHINE,
  subkey,
  0,
  KEY_QUERY_VALUE,      // to query the values of a registry key.
  &hkey           // OUT
  );
  if (result == ERROR_SUCCESS)
  {
    alreadyRegistered = TRUE;
    success = FALSE;
  }
 
  if (success)
  {
    DWORD disposition;
    result = RegCreateKeyEx(
    HKEY_LOCAL_MACHINE,         //
    subkey,                     //
    0,                          // reserved
    NULL,                       // key object class
    REG_OPTION_NON_VOLATILE,    // option
    KEY_WRITE,                  // desired access
    NULL,                       // hkey cannot be inherited
    &hkey,                      // OUT
    &disposition                // OUT new key / existing key
    );
    if (result != ERROR_SUCCESS)
    {
      debug("RegCreateKeyEx failed.");
      success = FALSE;
    }
  }
 
  if (success)
  {
    result = RegSetValueEx(
    hkey,                           // subkey handle
    "EventMessageFile",             // value name
    0,                              // must be zero
    REG_EXPAND_SZ,          // value type
    (LPBYTE)execName,       // pointer to value data
    (DWORD) (lstrlen(execName) + 1)
    * sizeof(TCHAR)         // length of value data
    );
    if (result != ERROR_SUCCESS)
    {
      success = FALSE;
    }
  }
 
  // Set the supported event types
  if (success)
  {
    DWORD supportedTypes =
    EVENTLOG_SUCCESS
    | EVENTLOG_ERROR_TYPE
    | EVENTLOG_WARNING_TYPE
    | EVENTLOG_INFORMATION_TYPE;
 
    result = RegSetValueEx(
    hkey,                          // subkey handle
    "TypesSupported",              // value name
    0,                             // must be zero
    REG_DWORD,                     // value type
    (LPBYTE) &supportedTypes,      // pointer to value data
    sizeof(DWORD)                  // length of value data
    );
    if (result != ERROR_SUCCESS)
    {
      success = FALSE;
    }
  }
 
  // Set the category message file
  if (success)
  {
    result = RegSetValueEx(
    hkey,                           // subkey handle
    "CategoryMessageFile",          // value name
    0,                              // must be zero
    REG_EXPAND_SZ,                  // value type
    (LPBYTE)execName,       // pointer to value data
    (DWORD) (lstrlen(execName) + 1)
    *sizeof(TCHAR)          // length of value data
    );
    if (result != ERROR_SUCCESS)
    {
      success = FALSE;
    }
  }
 
  // Set the number of categories: 1 (OPENDS)
  if (success)
  {
    long result = RegSetValueEx(
    hkey,                    // subkey handle
    "CategoryCount",         // value name
    0,                       // must be zero
    REG_DWORD,               // value type
    (LPBYTE) &nbCategories,  // pointer to value data
    sizeof(DWORD)            // length of value data
    );
    if (result != ERROR_SUCCESS)
    {
      success = FALSE;
    }
  }
 
  // close the key before leaving
  if (hkey != NULL)
  {
    RegCloseKey (hkey);
  }
 
  if (alreadyRegistered || success)
  {
    return TRUE;
  }
  else
  {
    debug("Could not create a registry key.");
    return FALSE;
  }
}  // createRegistryKey
 
 
// ---------------------------------------------------
// Removes the registry key to send events based on the name of the service.
// serviceName the serviceName.
// The function returns TRUE if the key could be unregistered (or it was not
// registered) and FALSE otherwise.
// ---------------------------------------------------
BOOLEAN removeRegistryKey(char* serviceName)
{
  BOOL returnValue;
 
  // Create the event source subkey (or open it if it already exists)
  char subkey [MAX_REGISTRY_KEY];
 
  long result;
 
  HKEY hkey = NULL;
 
  // Check whether the Registry Key is already created,
  // If so don't create a new one.
  sprintf (subkey, EVENT_LOG_KEY, serviceName);
  result = RegOpenKeyEx(
  HKEY_LOCAL_MACHINE,
  subkey,
  0,
  KEY_QUERY_VALUE,      // to query the values of a registry key.
  &hkey           // OUT
  );
  if (result != ERROR_SUCCESS)
  {
    // Assume that the registry key does not exist.
    returnValue = TRUE;
  }
  else
  {
    result = RegDeleteKey (HKEY_LOCAL_MACHINE, subkey);
    if (result == ERROR_SUCCESS)
    {
      returnValue = TRUE;
    }
  }
 
  return returnValue;
}  // removeRegistryKey
 
// ---------------------------------------------------
// Register the source of event and returns the handle
// for the event log.
// serviceName the serviceName.
// ---------------------------------------------------
HANDLE registerEventLog(char *serviceName)
{
  HANDLE eventLog = NULL;
 
  // subkey under Eventlog registry key
  char subkey [MAX_SERVICE_NAME];
  sprintf (subkey, serviceName);
 
  eventLog = RegisterEventSource(
  NULL,      // local host
  subkey     // subkey under Eventlog registry key
  );
 
  return eventLog;
 
}  // registerEventLog
 
// ---------------------------------------------------
// Deregister the source of event.
// ---------------------------------------------------
void deregisterEventLog()
{
  if (_eventLog != NULL)
  {
    DeregisterEventSource(_eventLog);
  }
}
 
// ----------------------------------------------------
// Check if the server is running or not.
// The functions returns SERVICE_RETURN_OK if we could determine if
// the server is running or not and false otherwise.
// ----------------------------------------------------
ServiceReturnCode isServerRunning(BOOL *running)
{
  ServiceReturnCode returnValue;
  char* relativePath = "\\locks\\server.lock";
  char lockFile[MAX_PATH];
  if (strlen(relativePath)+strlen(_instanceDir)+1 < MAX_PATH)
  {
    int fd;
 
    sprintf(lockFile, "%s%s", _instanceDir, relativePath);
 
    fd = _open(lockFile, _O_RDWR);
 
    if (fd != -1)
    {
      returnValue = SERVICE_RETURN_OK;
      // Test if there is a lock
      /* Lock some bytes and read them. Then unlock. */
      if(_locking(fd, LK_NBLCK, 1) != -1)
      {
        *running = FALSE;
      }
      else
      {
        if (errno == EACCES)
        {
          *running = TRUE;
        }
        else
        {
          *running = FALSE;
          returnValue = SERVICE_RETURN_ERROR;
          debug("Unexpected error locking");
        }
      }
      _close(fd);
    }
    else
    {
      *running = FALSE;
      returnValue = SERVICE_RETURN_ERROR;
    }
  }
  else
  {
    *running = FALSE;
    returnValue = SERVICE_RETURN_ERROR;
  }
  return returnValue;
}  // isServerRunning
 
// ----------------------------------------------------
// Start the application using start-ds.bat
// The functions returns SERVICE_RETURN_OK if we could start the server
// and SERVICE_RETURN_ERROR otherwise.
// ----------------------------------------------------
ServiceReturnCode doStartApplication()
{
  ServiceReturnCode returnValue;
  // init out params
  char* relativePath = "\\bat\\start-ds.bat";
  char command[COMMAND_SIZE];
  if (strlen(relativePath)+strlen(_instanceDir)+1 < COMMAND_SIZE)
  {
    sprintf(command, "\"%s%s\" --windowsNetStart", _instanceDir, relativePath);
 
    // launch the command
    if (spawn(command, FALSE) != 0)
    {
      // Try to see if server is really running
      int nTries = 10;
      BOOL running = FALSE;
      // Wait to be able to launch the java process in order it to free the lock
      // on the file.
      Sleep(3000);
      while ((nTries > 0) && !running)
      {
        if (isServerRunning(&running) != SERVICE_RETURN_OK)
        {
          break;
        }
        if (!running)
        {
          Sleep(2000);
        }
      }
      if (running)
      {
        returnValue = SERVICE_RETURN_OK;
      }
      else
      {
        returnValue = SERVICE_RETURN_ERROR;
      }
    }
    else
    {
      returnValue = SERVICE_RETURN_ERROR;
    }
  }
  else
  {
    returnValue = SERVICE_RETURN_ERROR;
  }
  return returnValue;
}  // doStartApplication
 
// ----------------------------------------------------
// Start the application using stop-ds.bat
// The functions returns SERVICE_RETURN_OK if we could stop the server
// and SERVICE_RETURN_ERROR otherwise.
// ----------------------------------------------------
ServiceReturnCode doStopApplication()
{
  ServiceReturnCode returnValue;
  // init out params
  char* relativePath = "\\bat\\stop-ds.bat";
  char command[COMMAND_SIZE];
  if (strlen(relativePath)+strlen(_instanceDir)+1 < COMMAND_SIZE)
  {
    sprintf(command, "\"%s%s\" --windowsNetStop", _instanceDir, relativePath);
 
    // launch the command
    if (spawn(command, FALSE) != 0)
    {
      // Try to see if server is really stopped
      int nTries = 10;
      BOOL running = TRUE;
      // Wait to be able to launch the java process in order it to free the lock
      // on the file.
      Sleep(3000);
      while ((nTries > 0) && running)
      {
        if (isServerRunning(&running) != SERVICE_RETURN_OK)
        {
          break;
        }
        if (running)
        {
          Sleep(2000);
        }
      }
      if (!running)
      {
        returnValue = SERVICE_RETURN_OK;
      }
      else
      {
        returnValue = SERVICE_RETURN_ERROR;
      }
    }
    else
    {
      returnValue = SERVICE_RETURN_ERROR;
    }
  }
  else
  {
    returnValue = SERVICE_RETURN_ERROR;
  }
  return returnValue;
}  // doStopApplication
 
// ---------------------------------------------------------------
// Build the path to the binary that contains serviceMain.
// Actually, the binary is the current executable file...
// serviceBinPath  the path to the service binary.
// instanceDir the instanceDirectory.
// The string stored in serviceBinPath looks like
// <SERVER_ROOT>/lib/service.exe start <_instanceDir>
// It is up to the caller of the function to allocate
// at least MAX_PATH bytes in serviceBinPath.
// The function returns SERVICE_RETURN_OK if we could create the binary
// path name and SERVICE_RETURN_ERROR otherwise.
// ---------------------------------------------------------------
 
ServiceReturnCode createServiceBinPath(char* serviceBinPath)
{
  ServiceReturnCode returnValue = SERVICE_RETURN_OK;
 
  // get the full path to the current executable file
  char fileName [MAX_PATH];
  DWORD result = GetModuleFileName (
  NULL,    // get the path to the current executable file
  fileName,
  MAX_PATH
  );
 
  if (result == 0)
  {
    // failed to get the path of the executable file
    returnValue = SERVICE_RETURN_ERROR;
  }
  else
  {
    if (result == MAX_PATH)
    {
      // buffer was too small, executable name is probably not valid
      returnValue = SERVICE_RETURN_ERROR;
    }
    else
    {
      if (strlen(fileName) + strlen(" start ") + strlen(_instanceDir)
        < MAX_PATH)
      {
        sprintf(serviceBinPath, "%s start \"%s\"", fileName,
        _instanceDir);
      }
      else
      {
        // buffer was too small, executable name is probably not valid
        returnValue = SERVICE_RETURN_ERROR;
      }
    }
  }
 
  return returnValue;
} // createServiceBinPath
 
// ----------------------------------------------------
// Returns the service name that maps the command used to start the
// product. All commands are supposed to be unique because they have
// the instance dir as parameter.
//
// The functions returns SERVICE_RETURN_OK if we could create a service name
// and SERVICE_RETURN_ERROR otherwise.
// The serviceName buffer must be allocated OUTSIDE the function and its
// minimum size must be of 256 (the maximum string length of a Service Name).
// ----------------------------------------------------
 
ServiceReturnCode getServiceName(char* cmdToRun, char* serviceName)
{
  // returned status code
  ServiceReturnCode returnValue = SERVICE_RETURN_OK;
 
  // retrieve list of services
  ServiceDescriptor* serviceList = NULL;
  int nbServices = -1;
  returnValue = getServiceList(&serviceList, &nbServices);
 
  // go through the list of services and search for the service name
  // whose display name is [displayName]
  if (returnValue == SERVICE_RETURN_OK)
  {
    int i;
    returnValue = SERVICE_RETURN_ERROR;
    if (nbServices > 0)
    {
      for (i = 0; i<nbServices; i++)
      {
        ServiceDescriptor curService = serviceList[i];
        if (curService.cmdToRun != NULL)
        {
          if (_stricmp(cmdToRun, curService.cmdToRun) == 0)
          {
            if (strlen(curService.serviceName) < MAX_SERVICE_NAME)
            {
              // This function assumes that there are at least
              // MAX_SERVICE_NAME (256) characters reserved in
              // servicename.
              sprintf(serviceName, curService.serviceName);
              returnValue = SERVICE_RETURN_OK;
            }
            break;
          }
        }
      }
      free (serviceList);
    }
  }
  else
  {
    debug("getServiceName: could not get service list.");
  }
  return returnValue;
 
}  // getServiceName
 
// ----------------------------------------------------
// Set the current status for the service.
//
// statusToSet current service status to set
// win32ExitCode determine which exit code to use
// serviceExitCode service code to return in case win32ExitCode says so
// checkPoint incremental value use to report progress during a lenghty
// operation (start, stop...).
// waitHint estimated time required for a pending operation (in ms); if
// the service has not updated the checkpoint or change the state then
// the service controler thinks the service should be stopped!
// serviceStatusHandle  the handle used to set the service status
// The functions returns SERVICE_RETURN_OK if we could start the service
// and SERVICE_RETURN_ERROR otherwise.
// ----------------------------------------------------
 
ServiceReturnCode updateServiceStatus (
DWORD  statusToSet,
DWORD  win32ExitCode,
DWORD  serviceExitCode,
DWORD  checkPoint,
DWORD  waitHint,
SERVICE_STATUS_HANDLE *serviceStatusHandle
)
{
  ServiceReturnCode returnValue;
 
  // elaborate service type:
  // SERVICE_WIN32_OWN_PROCESS means this is not a driver and there is
  // only one service in the process
  DWORD serviceType = SERVICE_WIN32_OWN_PROCESS;
 
  // elaborate the commands supported by the service:
  // - STOP        customer has performed a stop-ds (or NET STOP)
  // - SHUTDOWN    the system is rebooting
  // - INTERROGATE service controler can interogate the service
  // - No need to support PAUSE/CONTINUE
  //
  // Note: INTERROGATE *must* be supported by the service handler
  DWORD controls;
  SERVICE_STATUS serviceStatus;
  BOOL success;
  if (statusToSet == SERVICE_START_PENDING)
  {
    // do not accept any command when the service is starting up...
    controls = SERVICE_ACCEPT_NONE;
  }
  else
  {
    controls =
    SERVICE_ACCEPT_STOP
    | SERVICE_ACCEPT_SHUTDOWN
    | SERVICE_CONTROL_INTERROGATE;
  }
 
  // fill in the status structure
  serviceStatus.dwServiceType              = serviceType;
  serviceStatus.dwCurrentState             = statusToSet;
  serviceStatus.dwControlsAccepted         = controls;
  serviceStatus.dwWin32ExitCode            = win32ExitCode;
  serviceStatus.dwServiceSpecificExitCode  = serviceExitCode;
  serviceStatus.dwCheckPoint               = checkPoint;
  serviceStatus.dwWaitHint                 = waitHint;
 
 
  // set the service status
 
  success = SetServiceStatus(
  *serviceStatusHandle,
  &serviceStatus
  );
 
  if (!success)
  {
    returnValue = SERVICE_RETURN_ERROR;
  }
  else
  {
    returnValue = SERVICE_RETURN_OK;
  }
 
  return returnValue;
}  // updateServiceStatus
 
// ----------------------------------------------------
// This function is the "main" of the service. It has been registered
// to the SCM by the main right after the service has been started through
// NET START command.
//
//  The job of the serviceMain is
//
//  1- to register a handler to manage the commands STOP, PAUSE, CONTINUE,
//     SHUTDOWN and INTERROGATE sent by the SCM
//  2- to start the main application using "start-ds"
//
//  The serviceMain will return only when the service is terminated.
// ----------------------------------------------------
void serviceMain(int argc, char* argv[])
{
  // returned status
  char cmdToRun[MAX_PATH];
  char serviceName[MAX_SERVICE_NAME];
  ServiceReturnCode code;
  // a checkpoint value indicate the progress of an operation
  DWORD checkPoint = CHECKPOINT_FIRST_VALUE;
  SERVICE_STATUS_HANDLE serviceStatusHandle;
 
  code = createServiceBinPath(cmdToRun);
 
  if (code == SERVICE_RETURN_OK)
  {
    code = getServiceName(cmdToRun, serviceName);
  }
 
  if (code == SERVICE_RETURN_OK)
  {
    // first register the service control handler to the SCM
    code = registerServiceHandler(serviceName,
    (LPHANDLER_FUNCTION) serviceHandler,
    &serviceStatusHandle);
    if (code == SERVICE_RETURN_OK)
    {
      _serviceStatusHandle = &serviceStatusHandle;
    }
  }
 
 
  // update the service status to START_PENDING
  if (code == SERVICE_RETURN_OK)
  {
    _serviceCurStatus = SERVICE_START_PENDING;
    code = updateServiceStatus (
    SERVICE_START_PENDING,
    NO_ERROR,
    0,
    checkPoint++,
    TIMEOUT_CREATE_EVENT,
    _serviceStatusHandle);
  }
 
  // create an event to signal the application termination
  if (code == SERVICE_RETURN_OK)
  {
    _terminationEvent = CreateEvent(
    NULL,   // handle is not inherited by the child process
    TRUE,   // event has to be reset manually after a signal
    FALSE,  // initial state is "non signaled"
    NULL    // the event has no name
    );
  }
 
  // update the service status to START_PENDING
  if (code == SERVICE_RETURN_OK)
  {
    _serviceCurStatus = SERVICE_START_PENDING;
    updateServiceStatus (
    _serviceCurStatus,
    NO_ERROR,
    0,
    checkPoint++,
    TIMEOUT_START_SERVICE,
    _serviceStatusHandle
    );
  }
 
  // start the application
  if (code == SERVICE_RETURN_OK)
  {
    WORD argCount = 1;
    const char *argc[] = {_instanceDir};
    code = doStartApplication();
 
    switch (code)
    {
      case SERVICE_RETURN_OK:
      // start is ok
      _serviceCurStatus = SERVICE_RUNNING;
      updateServiceStatus (
      _serviceCurStatus,
      NO_ERROR,
      0,
      CHECKPOINT_NO_ONGOING_OPERATION,
      TIMEOUT_NONE,
      _serviceStatusHandle
      );
      reportLogEvent(
      EVENTLOG_SUCCESS,
      WIN_EVENT_ID_SERVER_STARTED,
      argCount, argc
      );
      break;
 
      default:
      code = SERVICE_RETURN_ERROR;
      _serviceCurStatus = SERVICE_STOPPED;
      updateServiceStatus (
      _serviceCurStatus,
      ERROR_SERVICE_SPECIFIC_ERROR,
      -1,
      CHECKPOINT_NO_ONGOING_OPERATION,
      TIMEOUT_NONE,
      _serviceStatusHandle);
      reportLogEvent(
      EVENTLOG_ERROR_TYPE,
      WIN_EVENT_ID_SERVER_START_FAILED,
      argCount, argc
      );
    }
  }
  else
  {
    updateServiceStatus (
    _serviceCurStatus,
    ERROR_SERVICE_SPECIFIC_ERROR,
    0,
    CHECKPOINT_NO_ONGOING_OPERATION,
    TIMEOUT_NONE,
    _serviceStatusHandle);
  }
 
  // if all is ok wait for the application to die before we leave
  if (code == SERVICE_RETURN_OK)
  {
    WaitForSingleObject (_terminationEvent, INFINITE);
  }
 
  // update the service status to STOPPED if it's not already done
  if ((_serviceCurStatus != SERVICE_STOPPED) &&
    (_serviceStatusHandle != NULL))
  {
    _serviceCurStatus = SERVICE_STOPPED;
    updateServiceStatus (
    _serviceCurStatus,
    NO_ERROR,
    0,
    CHECKPOINT_NO_ONGOING_OPERATION,
    TIMEOUT_NONE,
    _serviceStatusHandle
    );
  }
}  // serviceMain
 
 
// ----------------------------------------------------
// Notify the serviceMain that service is now terminated.
//
// terminationEvent  the event upon which serviceMain is blocked
// ----------------------------------------------------
void doTerminateService(HANDLE terminationEvent)
{
  SetEvent(terminationEvent);
  return;
 
}  // doTerminateService
 
// ----------------------------------------------------
// This function is the handler of the service. It is processing the
// commands send by the SCM. Commands can be: STOP, PAUSE, CONTINUE,
// SHUTDOWN and INTERROGATE.
//  controlCode  the code of the command
// ----------------------------------------------------
 
void serviceHandler(DWORD controlCode)
{
  ServiceReturnCode code;
  DWORD checkpoint;
  BOOL running;
  switch (controlCode)
  {
    case SERVICE_CONTROL_SHUTDOWN:
    // If system is shuting down then stop the service
    // -> no break here
    case SERVICE_CONTROL_STOP:
    {
      // update service status to STOP_PENDING
      debug("Stop called");
      _serviceCurStatus = SERVICE_STOP_PENDING;
      checkpoint = CHECKPOINT_FIRST_VALUE;
      updateServiceStatus (
      _serviceCurStatus,
      NO_ERROR,
      0,
      checkpoint++,
      TIMEOUT_STOP_SERVICE,
      _serviceStatusHandle
      );
 
      // let's try to stop the application whatever may be the status above
      // (best effort mode)
      code = doStopApplication();
      if (code == SERVICE_RETURN_OK)
      {
        WORD argCount = 1;
        const char *argc[] = {_instanceDir};
        _serviceCurStatus = SERVICE_STOPPED;
        updateServiceStatus (
        _serviceCurStatus,
        NO_ERROR,
        0,
        CHECKPOINT_NO_ONGOING_OPERATION,
        TIMEOUT_NONE,
        _serviceStatusHandle
        );
 
        // again, let's ignore the above status and
        // notify serviceMain that service has stopped
        doTerminateService (_terminationEvent);
        reportLogEvent(
        EVENTLOG_SUCCESS,
        WIN_EVENT_ID_SERVER_STOP,
        argCount, argc
        );
      }
      else
      {
        WORD argCount = 1;
        const char *argc[] = {_instanceDir};
        // We could not stop the server
        reportLogEvent(
        EVENTLOG_ERROR_TYPE,
        WIN_EVENT_ID_SERVER_STOP_FAILED,
        argCount, argc
        );
      }
      break;
    }
 
 
    // Request to pause the service
    // ----------------------------
    case SERVICE_CONTROL_PAUSE:
    // not supported
    break;
 
    // Request to resume the service
    // -----------------------------
    case SERVICE_CONTROL_CONTINUE:
    // not supported
    break;
 
    // Interrogate the service status
    // ------------------------------
    case SERVICE_CONTROL_INTERROGATE:
    code = isServerRunning(&running);
    if (code != SERVICE_RETURN_OK)
    {
 
    }
    else if (running)
    {
      _serviceCurStatus = SERVICE_RUNNING;
    }
    else
    {
      _serviceCurStatus = SERVICE_STOPPED;
    }
    updateServiceStatus (
    _serviceCurStatus,
    NO_ERROR,
    0,
    CHECKPOINT_NO_ONGOING_OPERATION,
    TIMEOUT_NONE,
    _serviceStatusHandle
    );
    break;
 
    // Other codes are ignored
    default:
 
    break;
  }
 
}  // serviceHandler
 
// ---------------------------------------------------------------
// Retrieve the binaryPathName from the SCM database for a given service.
//
// scm is the SCM handler (must not be NULL)
// serviceName  the name of the service.
// It is up to the caller of the function to allocate at least MAX_PATH bytes
// in binPathName.
// The function returns SERVICE_RETURN_OK if we could create the binary
// path name and SERVICE_RETURN_ERROR otherwise.
// ---------------------------------------------------------------
 
ServiceReturnCode getBinaryPathName(HANDLE scm, char* serviceName,
char* binPathName)
{
  ServiceReturnCode returnValue;
  // pathtname to return
  char* binPathname = NULL;
 
  // handle to the service
  SC_HANDLE myService = NULL;
 
 
  BOOL  getConfigOk = FALSE;
  DWORD configSize  = 4096;
  LPQUERY_SERVICE_CONFIG serviceConfig =
  (LPQUERY_SERVICE_CONFIG)malloc(configSize);
 
  returnValue = SERVICE_RETURN_ERROR;
 
  // if SCM exists then retrieve the config info of the service
  if (scm != NULL)
  {
    myService = OpenService(
    scm,
    serviceName,
    SERVICE_QUERY_CONFIG
    );
  }
 
  if (myService != NULL)
  {
    while (!getConfigOk)
    {
      DWORD bytesNeeded;
 
      getConfigOk = QueryServiceConfig(
      myService,
      serviceConfig,
      configSize,
      &bytesNeeded
      );
 
      if (!getConfigOk)
      {
        DWORD errCode = GetLastError();
        if (errCode == ERROR_INSUFFICIENT_BUFFER)
        {
          // buffer nor big enough...
          configSize += bytesNeeded;
          serviceConfig =
          (LPQUERY_SERVICE_CONFIG)realloc(serviceConfig, configSize);
          continue;
        }
        else
        {
          break;
        }
      }
      else
      {
        if (strlen(serviceConfig->lpBinaryPathName) < MAX_PATH)
        {
          sprintf(binPathName, serviceConfig->lpBinaryPathName);
          returnValue = SERVICE_RETURN_OK;
        }
      }
    }
  }
 
  // free buffers
  if (serviceConfig != NULL)
  {
    free(serviceConfig);
  }
 
  return returnValue;
} // getBinaryPathName
 
// ---------------------------------------------------------------
// Returns the list of NT services being created on the current host.
// The function allocates the memory for the returned buffer.
// serviceList contains the list of services.
// nbServices the number of services returned in the list.
// The functions returns SERVICE_RETURN_OK if we could create the service
// list and SERVICE_RETURN_ERROR otherwise.
// ---------------------------------------------------------------
 
ServiceReturnCode getServiceList(ServiceDescriptor** serviceList,
int *nbServices)
{
  ServiceReturnCode returnValue;
 
  // open Service Control Manager
  SC_HANDLE scm = NULL;
  // get the list of services being configured in the SCM database
  // 1- first try with a single data structure ENUM_SERVICE_STATUS
  ENUM_SERVICE_STATUS  serviceData;
  ENUM_SERVICE_STATUS* lpServiceData = &serviceData;
  DWORD dataSize = sizeof (serviceData);
  DWORD neededSize;
  DWORD resumeHandle  = 0;
  unsigned long nbSvc = 0;
 
  if (openScm(SC_MANAGER_ENUMERATE_SERVICE, &scm) == SERVICE_RETURN_OK)
  {
    BOOL svcStatusOk = EnumServicesStatus(
    scm,                   // handle to the SCM
    SERVICE_WIN32,         // for OWN_PROCESS | SHARE_PROCESS
    SERVICE_STATE_ALL,     // all services (runing & stopped)
    &serviceData,          // output buffer
    dataSize,              // output buffer size
    &neededSize,           // sized needed to get the entries
    &nbSvc,                // number of services
    &resumeHandle          // next service entry to read
    );
 
    if (! svcStatusOk)
    {
      DWORD lastError = GetLastError();
      if (lastError != ERROR_MORE_DATA)
      {
        char msg[200];
        sprintf(msg, "getServiceList: generic error. Code [%d]",
        lastError);
        // error
        debug(msg);
        returnValue = SERVICE_RETURN_ERROR;
      }
      else
      {
        debug("getServiceList: error More Data.");
        // buffer is not big enough: try again with a proper size
        dataSize += neededSize;
        lpServiceData = (ENUM_SERVICE_STATUS*)calloc(
        dataSize, sizeof(ENUM_SERVICE_STATUS));
 
        svcStatusOk = EnumServicesStatus(
        scm,                   // handle to the SCM
        SERVICE_WIN32,         // for OWN_PROCESS | SHARE_PROCESS
        SERVICE_STATE_ALL,     // all services (running & stopped)
        lpServiceData,         // output buffer
        dataSize,              // output buffer size
        &neededSize,           // sized needed to get the entries
        &nbSvc,                // number of services
        &resumeHandle          // next service entry to read
        );
 
        if (! svcStatusOk)
        {
          DWORD lastError = GetLastError();
          if (lastError != ERROR_MORE_DATA)
          {
            returnValue = SERVICE_RETURN_ERROR;
          }
          else
          {
            // Data buffer is not large enough. This case should
            // never happen as proper buffer size has been
            // provided!...
            debug("getServiceList: buffer error");
            returnValue = SERVICE_RETURN_ERROR;
          }
        }
        else
        {
          returnValue = SERVICE_RETURN_OK;
        }
      }
    }
    else
    {
      returnValue = SERVICE_RETURN_OK;
    }
  }
  else
  {
    returnValue = SERVICE_RETURN_ERROR;
  }
 
  // now elaborate the list of service to return...
  if (returnValue == SERVICE_RETURN_OK)
  {
    int i;
    int aux = (int)nbSvc;
    ServiceDescriptor* l;
 
    ENUM_SERVICE_STATUS* curService = lpServiceData;
 
    *nbServices = aux;
    if (aux > 0)
    {
      char binPath[MAX_PATH];
      l = (ServiceDescriptor*)calloc(sizeof(ServiceDescriptor), aux);
      for (i = 0; i < aux; i++)
      {
        l[i].serviceName = strdup(curService->lpServiceName);
        l[i].displayName = strdup(curService->lpDisplayName);
 
        if (getBinaryPathName(scm, l[i].serviceName, binPath) ==
          SERVICE_RETURN_OK)
        {
          l[i].cmdToRun = strdup(binPath);
        }
        curService++;
      }
      *serviceList = l;
    }
  }
 
  // close the handle to the SCM
  if (scm != NULL)
  {
    CloseServiceHandle (scm);
    // free the result buffer
    if (lpServiceData != NULL)
    {
      free (lpServiceData);
    }
  }
 
  return returnValue;
} // getServiceList
 
// ---------------------------------------------------------------
// Function used to know if a given service name is in use or not.
// Returns SERVICE_IN_USE if the provided service name is in use.
// Returns NOT_SERVICE_IN_USE if the provided service name is not in use.
// Returns SERVICE_RETURN_ERROR if the function could not determine if the
// service name is in use or not.
// ---------------------------------------------------------------
 
ServiceReturnCode serviceNameInUse(char* serviceName)
{
  ServiceReturnCode returnValue;
 
  // retrieve list of services
  ServiceDescriptor* serviceList = NULL;
  ServiceDescriptor curService;
  int nbServices = -1;
  int i;
 
  // go through the list of services and search for the service name
  if (getServiceList(&serviceList, &nbServices) == SERVICE_RETURN_OK)
  {
    returnValue = SERVICE_NOT_IN_USE;
 
    if (nbServices > 0)
    {
      for (i = 0; i < nbServices && (returnValue == SERVICE_NOT_IN_USE);
      i++)
      {
        curService = serviceList[i];
        if (curService.serviceName == NULL)
        {
          debug("The service name is NULL.\n");
        }
        else
        {
          if (strcmp (serviceName, curService.serviceName) == 0)
          {
            // found the service!
            returnValue = SERVICE_IN_USE;
          }
        }
      }
      free(serviceList);
    }
  }
  else
  {
    returnValue = SERVICE_RETURN_ERROR;
  }
  return returnValue;
} // serviceNameInUse
 
// ---------------------------------------------------------------
// Build a service name for OpenDS and make sure
// the service name is unique on the system. To achieve this requirement
// the service name looks like <baseName> for the first OpenDS and
// <baseName>-n if there are more than one.
//
// The functions returns SERVICE_RETURN_OK if we could create a service
// name and SERVICE_RETURN_ERROR otherwise.
// The serviceName buffer must be allocated OUTSIDE the function and its
// minimum size must be of 256 (the maximum string length of a Service Name).
// ---------------------------------------------------------------
 
ServiceReturnCode createServiceName(char* serviceName, char* baseName)
{
  ServiceReturnCode returnValue = SERVICE_RETURN_OK;
  int i = 1;
  BOOL ended = FALSE;
  ServiceReturnCode nameInUseResult;
  while (!ended)
  {
    if (i == 1)
    {
      sprintf(serviceName, baseName);
    }
    else
    {
      sprintf(serviceName, "%s-%d", baseName, i);
    }
 
    nameInUseResult = serviceNameInUse(serviceName);
 
    if (nameInUseResult == SERVICE_IN_USE)
    {
      // this service name is already in use: try another one...
      i++;
    }
    else if (nameInUseResult == SERVICE_NOT_IN_USE)
    {
      // this service name is not used so it's a good candidate
      ended = TRUE;
    }
    else
    {
      // an error occurred checking the service name
      returnValue = SERVICE_RETURN_ERROR;
      ended = TRUE;
    }
  }
 
  return returnValue;
} // createServiceName
 
 
// ---------------------------------------------------------------
// Create a service in the SCM database. Once the service is created,
// we can view it with "service list".
// displayName is the display name of the service
// description is the description of the service
// cmdToRun    is the command to be run by the SCM upon NET START
//
// The function returns SERVICE_RETURN_OK if we could create the service and
// SERVICE_RETURN_ERROR otherwise.
// ---------------------------------------------------------------
 
ServiceReturnCode createServiceInScm(char* displayName, char* description,
char* cmdToRun)
{
  ServiceReturnCode returnValue;
  SC_HANDLE scm       = NULL;
  SC_HANDLE myService = NULL;
 
  // local vars
  // - serviceName is the service name
  char* serviceName = (char*) calloc(1, MAX_SERVICE_NAME);
 
  // elaborate the service name based on the displayName provided
  returnValue = createServiceName(serviceName, displayName);
 
  // create the service
  if (returnValue == SERVICE_RETURN_OK)
  {
    if (openScm(GENERIC_WRITE, &scm) != SERVICE_RETURN_OK)
    {
      returnValue = SERVICE_RETURN_ERROR;
      debug("createServiceInScm: openScm did not work.");
    }
  }
  else
  {
    returnValue = SERVICE_RETURN_ERROR;
    debug("createServiceInScm: createServiceName did not work.");
  }
 
  if (returnValue == SERVICE_RETURN_OK)
  {
    myService = CreateService(
    scm,
    serviceName,                // name of service
    serviceName,                // service name to display
    SERVICE_ALL_ACCESS,         // desired access
    SERVICE_WIN32_OWN_PROCESS,  // service type
    SERVICE_AUTO_START,         // start service during
    // system startup
    SERVICE_ERROR_NORMAL,       // error control type
    cmdToRun,                   // path to service's binary
    NULL,                       // no load ordering group
    NULL,                       // no tag identifier
    NULL,                       // no dependencies
    NULL,                       // LocalSystem account
    NULL                        // no password
    );
  }
 
  if ((returnValue == SERVICE_RETURN_OK) && (myService == NULL))
  {
    DWORD errCode = GetLastError();
    if (errCode == ERROR_DUPLICATE_SERVICE_NAME)
    {
      returnValue = DUPLICATED_SERVICE_NAME;
    }
    else if (errCode == ERROR_SERVICE_EXISTS)
    {
      returnValue = SERVICE_ALREADY_EXISTS;
    }
    else
    {
      returnValue = SERVICE_RETURN_ERROR;
    }
  }
 
  // add description field
  if (returnValue == SERVICE_RETURN_OK)
  {
    BOOL success;
    SERVICE_DESCRIPTION serviceDescription;
    serviceDescription.lpDescription = description;
 
    success = ChangeServiceConfig2(
    myService,
    SERVICE_CONFIG_DESCRIPTION,
    (LPVOID) &serviceDescription
    );
 
    if (!success)
    {
      returnValue = SERVICE_RETURN_ERROR;
    }
  }
 
  // close handles
  if (myService != NULL)
  {
    CloseServiceHandle (myService);
  }
 
  if (scm != NULL)
  {
    CloseServiceHandle (scm);
  }
 
  // free names
  if (serviceName != NULL)
  {
    free (serviceName);
  }
 
  return returnValue;
} // createServiceInScm
 
 
// ---------------------------------------------------------------
// Remove a service with the name serviceName from SCM.
// If the service could be removed returns SERVICE_RETURN_OK.
// If the service cannot be removed because still in use by any process
// then returned status is SERVICE_MARKED_FOR_DELETION.
// If an error occurs returns SERVICE_RETURN_ERROR.
// ---------------------------------------------------------------
ServiceReturnCode removeServiceFromScm(char* serviceName)
{
  // local vars
  ServiceReturnCode returnValue = SERVICE_RETURN_OK;
  SC_HANDLE scm       = NULL;
  SC_HANDLE myService = NULL;
  SERVICE_STATUS serviceStatus;
 
  returnValue = openScm(GENERIC_WRITE, &scm);
 
  // open the service
  if (returnValue == SERVICE_RETURN_OK)
  {
    myService = OpenService(
    scm,
    serviceName,
    SERVICE_ALL_ACCESS | DELETE
    );
    if (myService == NULL)
    {
      returnValue = SERVICE_RETURN_ERROR;
    }
  }
 
  if (returnValue == SERVICE_RETURN_OK)
  {
    BOOL success = QueryServiceStatus(
    myService,
    &serviceStatus
    );
    if (!success)
    {
      returnValue = SERVICE_RETURN_ERROR;
    }
  }
 
  // stop the service if necessary
  if (returnValue == SERVICE_RETURN_OK)
  {
    if (serviceStatus.dwCurrentState != SERVICE_STOPPED)
    {
      BOOL success = ControlService (
      myService,
      SERVICE_CONTROL_STOP,
      &serviceStatus
      );
      if (!success)
      {
        DWORD errCode = GetLastError();
        if (errCode == ERROR_SERVICE_MARKED_FOR_DELETE)
        {
          returnValue = SERVICE_MARKED_FOR_DELETION;
        }
        else
        {
          returnValue = SERVICE_RETURN_ERROR;
        }
      }
      else
      {
        Sleep (500);
      }
    }
  }
 
  // remove the service
  if (returnValue == SERVICE_RETURN_OK)
  {
    BOOL success = DeleteService (myService);
    if (!success)
    {
 
      DWORD errCode = GetLastError();
      if (errCode == ERROR_SERVICE_MARKED_FOR_DELETE)
      {
        returnValue = SERVICE_MARKED_FOR_DELETION;
      }
      else
      {
        returnValue = SERVICE_RETURN_ERROR;
      }
    }
  }
 
  // close handles
  if (myService != NULL)
  {
    CloseServiceHandle (myService);
  }
 
  if (scm != NULL)
  {
    CloseServiceHandle (scm);
  }
 
  return returnValue;
 
}  // removeServiceFromScm
 
 
// ---------------------------------------------------------------
// Function called to create a service for the OpenDS instance
// where this executable is installed.
// The first argument that is passed is the displayName of the service
// and the second the description,
//
// Returns 0 if the service was successfully created.
// Returns 1 if the service already existed for this instance.
// Returns 2 if the service name we created already exists.
// Returns 3 if an error occurred.
// ---------------------------------------------------------------
int createService(char* displayName, char* description)
{
  int returnCode = 0;
  char cmdToRun[MAX_PATH];
  ServiceReturnCode code;
 
  code = createServiceBinPath(cmdToRun);
 
  if (code == SERVICE_RETURN_OK)
  {
    char serviceName[MAX_SERVICE_NAME];
    code = getServiceName(cmdToRun, serviceName);
    if (code == SERVICE_RETURN_OK)
    {
      // There is a valid serviceName for the command to run, so
      // OpenDS is registered as a service.
      code = SERVICE_ALREADY_EXISTS;
      createRegistryKey(serviceName);
      debug("createService: service already exists for this instance.");
    }
    else
    {
      // We could not find a serviceName for the command to run, so
      // try to create the service.
      code = createServiceInScm(displayName, description, cmdToRun);
      if (code == SERVICE_RETURN_OK)
      {
        code = getServiceName(cmdToRun, serviceName);
        if (code == SERVICE_RETURN_OK)
        {
          createRegistryKey(serviceName);
        }
      }
    }
  }
 
  switch (code)
  {
    case SERVICE_RETURN_OK:
    returnCode = 0;
    break;
    case SERVICE_ALREADY_EXISTS:
    returnCode = 1;
    break;
    case DUPLICATED_SERVICE_NAME:
    returnCode = 2;
    break;
    default:
    returnCode = 3;
  }
 
  return returnCode;
} // createService
 
// ---------------------------------------------------------------
// Function called to know if the OpenDS instance where this
// executable is installed is running as a service or not.
// Returns 0 if the instance is running as a service and print the
// serviceName in the standard output.
// Returns 1 if the instance is not running as a service.
// Returns 2 if an error occurred or we cannot determine if Open DS
// is running as a service or not.
// ---------------------------------------------------------------
int serviceState()
{
  int returnCode = 0;
  char cmdToRun[MAX_PATH];
  char serviceName[MAX_SERVICE_NAME];
  ServiceReturnCode code;
 
  code = createServiceBinPath(cmdToRun);
 
  if (code == SERVICE_RETURN_OK)
  {
    code = getServiceName(cmdToRun, serviceName);
    if (code == SERVICE_RETURN_OK)
    {
      // There is a valid serviceName for the command to run, so
      // OpenDS is registered as a service.
      fprintf(stdout, serviceName);
      returnCode = 0;
    }
    else
    {
      returnCode = 1;
    }
  }
  else
  {
    returnCode = 2;
  }
 
  return returnCode;
} // serviceState
 
// ---------------------------------------------------------------
// Function called to remove the service associated with a given
// service name.
// Returns 0 if the service was successfully removed.
// Returns 1 if the service does not exist.
// Returns 2 if the service was marked for deletion but is still in
// use.
// Returns 3 if an error occurred.
// ---------------------------------------------------------------
int removeServiceWithServiceName(char *serviceName)
{
  int returnCode = 0;
  ServiceReturnCode code = serviceNameInUse(serviceName);
  
  if (code != SERVICE_IN_USE)
  {
    returnCode = 1;
  }
  else
  {
    code = removeServiceFromScm(serviceName);
 
    switch (code)
    {
      case SERVICE_RETURN_OK:
      removeRegistryKey(serviceName);
      returnCode = 0;
      break;
      case SERVICE_MARKED_FOR_DELETION:
      removeRegistryKey(serviceName);
      returnCode = 2;
      break;
      default:
      returnCode = 3;
    }
  }
  
  return returnCode;
} // removeServiceWithServiceName
 
// ---------------------------------------------------------------
// Function called to remove the service for the OpenDS instance
// where this executable is installed.
// Returns 0 if the service was successfully removed.
// Returns 1 if the service does not exist.
// Returns 2 if the service was marked for deletion but is still in
// use.
// Returns 3 if an error occurred.
// ---------------------------------------------------------------
int removeService()
{
  int returnCode = 0;
  char cmdToRun[MAX_PATH];
  char serviceName[MAX_SERVICE_NAME];
  ServiceReturnCode code;
 
  code = createServiceBinPath(cmdToRun);
 
  if (code == SERVICE_RETURN_OK)
  {
    code = getServiceName(cmdToRun, serviceName);
    if (code == SERVICE_RETURN_OK)
    {
      returnCode = removeServiceWithServiceName(serviceName);
    }
    else
    {
      returnCode = 1;
    }
  }
  else
  {
    returnCode = 2;
  }
 
  return returnCode;
} // removeService
 
 
 
// ---------------------------------------------------------------
// Function called to start the service where this executable is installed.
// Returns 0 if the service runs.
// Returns 1 if an error occurred.
// ---------------------------------------------------------------
 
int startService()
{
  int returnCode;
  char serviceName[MAX_SERVICE_NAME];
  char cmdToRun[MAX_PATH];
  ServiceReturnCode code;
 
  code = createServiceBinPath(cmdToRun);
 
  if (code == SERVICE_RETURN_OK)
  {
    code = getServiceName(cmdToRun, serviceName);
  }
 
  if (code == SERVICE_RETURN_OK)
  {
    BOOL success;
    SERVICE_TABLE_ENTRY serviceTable[] =
    {
      {serviceName, (LPSERVICE_MAIN_FUNCTION) serviceMain},
      {NULL, NULL}
    };
    _eventLog = registerEventLog(serviceName);
 
    // register the service to the SCM. The function will return once the
    // service is terminated.
    success = StartServiceCtrlDispatcher(serviceTable);
    if (!success)
    {
      WORD argCount = 2;
      DWORD lastError = GetLastError();
      const char *argc[2];
      argc[0] = _instanceDir;
      if (lastError == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
      {
        argc[1] =
        "startService: StartServiceCtrlDispatcher did not work: \
        ERROR_FAILED_SERVICE_CONTROLLER_CONNECT.";
      }
      else if (lastError == ERROR_INVALID_DATA)
      {
        argc[1] =
        "startService: StartServiceCtrlDispatcher did not work: \
        ERROR_INVALID_DATA.";
      }
      else if (lastError == ERROR_SERVICE_ALREADY_RUNNING)
      {
        argc[1] =
        "startService: StartServiceCtrlDispatcher did not work: \
        ERROR_SERVICE_ALREADY_RUNNING.";
      }
      else
      {
        argc[1] =
        "startService: StartServiceCtrlDispatcher did not work.";
      }
      code = SERVICE_RETURN_ERROR;
      reportLogEvent(
      EVENTLOG_ERROR_TYPE,
      WIN_EVENT_ID_SERVER_START_FAILED,
      argCount, argc
      );
    }
    deregisterEventLog();
  }
  else
  {
    debug("startService: Could not get service name.");
  }
 
  if (code == SERVICE_RETURN_OK)
  {
    returnCode = 0;
  }
  else
  {
    returnCode = 1;
  }
  return returnCode;
 
}  // startService
 
 
// ---------------------------------------------------------------
// Function called to know if the --debug option was passed
// when calling this executable or not.  The DEBUG variable is
// updated accordingly.
// ---------------------------------------------------------------
 
void updateDebugFlag(char* argv[], int argc, int startIndex)
{
  int i;
  DEBUG = FALSE;
  for (i=startIndex; (i<argc) && !DEBUG; i++)
  {
    if (strcmp(argv[i], "--debug") == 0)
    {
      DEBUG = TRUE;
    }
  }
}
 
int main(int argc, char* argv[])
{
  char* subcommand;
  int returnCode = 0;
 
  if (argc <= 1)
  {
    fprintf(stderr,
    "Subcommand required: create, state, remove, start or cleanup.\n");
    returnCode = -1;
  }
  else
  {
    subcommand = argv[1];
    if (strcmp(subcommand, "create") == 0)
    {
      if (argc <= 4)
      {
        fprintf(stderr,
    "Subcommand create requires instance dir, service name and description.\n");
        returnCode = -1;
      }
      else
      {
        _instanceDir = strdup(argv[2]);
        updateDebugFlag(argv, argc, 5);
        returnCode = createService(argv[3], argv[4]);
        free(_instanceDir);
      }
    }
    else if (strcmp(subcommand, "state") == 0)
    {
      if (argc <= 2)
      {
        fprintf(stderr,
        "Subcommand state requires instance dir.\n");
        returnCode = -1;
      }
      else
      {
        _instanceDir = strdup(argv[2]);
        updateDebugFlag(argv, argc, 3);
        returnCode = serviceState();
        free(_instanceDir);
      }
    }
    else if (strcmp(subcommand, "remove") == 0)
    {
      if (argc <= 2)
      {
        fprintf(stderr,
        "Subcommand remove requires instance dir.\n");
        returnCode = -1;
      }
      else
      {
        _instanceDir = strdup(argv[2]);
        updateDebugFlag(argv, argc, 3);
        returnCode = removeService();
        free(_instanceDir);
      }
    }
    else if (strcmp(subcommand, "start") == 0)
    {
      if (argc <= 2)
      {
        fprintf(stderr,
        "Subcommand start requires instance dir.\n");
        returnCode = -1;
      }
      else
      {
        _instanceDir = strdup(argv[2]);
        updateDebugFlag(argv, argc, 3);
        returnCode = startService();
        free(_instanceDir);
      }
    }
    else if (strcmp(subcommand, "isrunning") == 0)
    {
      if (argc <= 2)
      {
        fprintf(stderr,
        "Subcommand isrunning requires instance dir.\n");
        returnCode = -1;
      }
      else
      {
        BOOL running;
        ServiceReturnCode code;
        _instanceDir = strdup(argv[2]);
        updateDebugFlag(argv, argc, 3);
        code = isServerRunning(&running);
        if (code == SERVICE_RETURN_OK)
        {
          returnCode = 0;
        }
        else
        {
          returnCode = -1;
        }
        free(_instanceDir);
      }
 
    }
    else if (strcmp(subcommand, "cleanup") == 0)
    {
      if (argc <= 2)
      {
        fprintf(stderr,
        "Subcommand cleanup requires service name.\n");
        returnCode = -1;
      }
      else
      {
        char* serviceName = strdup(argv[2]);
        updateDebugFlag(argv, argc, 3);
        returnCode = removeServiceWithServiceName(serviceName);
        free(serviceName);
      }
    }
 
    else
    {
      fprintf(stderr, "Unknown subcommand: [%s]\n", subcommand);
      returnCode = -1;
    }
  }
 
  return returnCode;
} // main