[r9364]: ooDialog / trunk / ooDialog / oodWinMain.cpp  Maximize  Restore  History

Download this file

2202 lines (1865 with data), 67.9 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
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
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
/*----------------------------------------------------------------------------*/
/* */
/* Copyright (c) 2013-2013 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.oorexx.org/license.html */
/* */
/* 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. */
/* */
/*----------------------------------------------------------------------------*/
/**
* oodMain.cpp
*
* ooDialog.exe, a stand alone interface to run ooDialog programs. This is
* essentially rexxhide, with some ooDialog specific modifications.
*
* At this time there is no ooDialog specific code that would prevent
* ooDialog.exe from running any ooRexx program with no console.
*/
#include <windows.h>
#include <commctrl.h>
#include <oorexxapi.h>
#include <stdio.h>
#include <shlwapi.h>
#include <shlobj.h>
#include "oodShared.hpp"
#include "oodExecutable.hpp"
inline CSTRING level2text(uint32_t level)
{
switch ( level )
{
case SECURITY_MANDATORY_UNTRUSTED_RID: return "Untrusted";
case SECURITY_MANDATORY_LOW_RID: return "Low";
case SECURITY_MANDATORY_MEDIUM_RID: return "Medium";
case SECURITY_MANDATORY_HIGH_RID: return "High";
case SECURITY_MANDATORY_SYSTEM_RID: return "System";
default: return "Unknown";
}
}
inline bool requiresElevation(pConfigureArguments pca)
{
if ( pca->isVistaOrLater && ! pca->isRunAsAdmin )
{
return true;
}
return false;
}
static void setDlgIcon(HWND hDlg, HINSTANCE hInstance)
{
HANDLE hIcon = LoadImage(hInstance, MAKEINTRESOURCE(IDI_APP_ICON), IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
if( hIcon )
{
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
}
}
/**
* Formats an error message for a system error and shows it in a message box
*
* @param function Name of system function that failed
* @param title Caption for message box
* @param dw System error code
*/
static void reportError(HWND hwnd, CSTRING function, CSTRING title, HRESULT dw)
{
char msgBuf[HUGE_BUF_SIZE];
void *formatMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&formatMsgBuf, 0, NULL);
_snprintf(msgBuf, HUGE_BUF_SIZE, "Error executing Windows API:\n\nFunction:\t\t%s\nError Code:\t%d\n\n%s",
function, dw, formatMsgBuf);
MessageBox(hwnd, (LPCTSTR)msgBuf, title, MB_ICONERROR);
LocalFree(formatMsgBuf);
}
/**
* Formats an error message for a system error, plus some follow up text, and
* shows it in a message box
*
* @param function Name of system function that failed
* @param title Caption for message box
* @param dw System error code
*/
static void reportErrorPlus(HWND hwnd, CSTRING function, CSTRING title, CSTRING extraMsg, HRESULT dw)
{
char msgBuf[HUGE_BUF_SIZE];
void *formatMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&formatMsgBuf, 0, NULL);
_snprintf(msgBuf, HUGE_BUF_SIZE, "Error executing Windows API:\n\nFunction:\t\t%s\n"
"Error Code:\t%d\n\n%s\n\n%s",
function, dw, formatMsgBuf, extraMsg);
MessageBox(hwnd, (LPCTSTR)msgBuf, title, MB_ICONERROR);
LocalFree(formatMsgBuf);
}
/**
* Formats an error message using static memory and shows it in a message box.
*
* This is primarily for use in memory allocation errors. The idea is to avoid
* allocating memory to display an out of memory message. If we failed to
* allocate memory, I doubt this will work anyway.
*
* @param fmtStr
* @param title
* @param dw
*/
static void reportError(HWND hwnd, CSTRING fmtStr, CSTRING title, CSTRING function, uint32_t rc)
{
char msgBuf[HUGE_BUF_SIZE];
_snprintf(msgBuf, HUGE_BUF_SIZE, fmtStr, function, rc);
MessageBox(hwnd, (LPCTSTR)msgBuf, title, MB_ICONERROR);
}
/**
*
*
*
* @return uint32_t
*
* @notes This function must be run on Vista or later, or it fails. We assume
* the caller has already checked the OS.
*/
uint32_t getProcessIntegrityLevel(HWND hwnd, uint32_t *rc)
{
PTOKEN_MANDATORY_LABEL pTokenIL = NULL;
uint32_t integrityLevel = 0;
uint32_t error = ERROR_SUCCESS;
HANDLE hToken = NULL;
uint32_t tokenSize = 0;
// Open the primary access token of the process with TOKEN_QUERY.
if ( ! OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken) )
{
error = GetLastError();
reportError(hwnd, "OpenProcessToken", "Windows Operating System Error", error);
goto done_out;
}
// Query the size of the token integrity level so we can allocate a buffer
// for it.
if ( ! GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, (DWORD *)&tokenSize) )
{
if ( GetLastError() != ERROR_INSUFFICIENT_BUFFER )
{
error = GetLastError();
reportError(hwnd, "GetTokenInformation", "Windows Operating System Error", error);
goto done_out;
}
}
// Now we allocate a buffer for the integrity level information.
pTokenIL = (TOKEN_MANDATORY_LABEL *)LocalAlloc(LPTR, tokenSize);
if (pTokenIL == NULL)
{
error = GetLastError();
reportError(hwnd, "LocalAlloc", "Windows Operating System Error", error);
goto done_out;
}
// Retrieve token integrity level information.
if ( ! GetTokenInformation(hToken, TokenIntegrityLevel, pTokenIL, tokenSize, (DWORD *)&tokenSize))
{
error = GetLastError();
reportError(hwnd, "GetTokenInformation", "Windows Operating System Error", error);
goto done_out;
}
// Integrity Level SIDs are in the form of S-1-16-0xXXXX. (e.g.
// S-1-16-0x1000 stands for low integrity level SID). There is one and
// only one subauthority.
integrityLevel = *GetSidSubAuthority(pTokenIL->Label.Sid, 0);
done_out:
if ( hToken )
{
CloseHandle(hToken);
}
if ( pTokenIL)
{
LocalFree(pTokenIL);
}
*rc = error;
return integrityLevel;
}
/**
*
*
*
* @param hwnd
* @param isVistaOrLater
* @param rc
*
* @return bool
*/
bool isUserInAdminGroup(HWND hwnd, bool isVistaOrLater, uint32_t *rc)
{
HANDLE hTokenToCheck = NULL;
HANDLE hToken = NULL;
bool inGroup = false;
uint32_t error = ERROR_SUCCESS;
DWORD cbSize = 0;
// Open the primary access token of the process for query and duplicate.
if ( ! OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &hToken) )
{
error = GetLastError();
reportError(hwnd, "OpenProcessToken", "Windows Operating System Error", error);
goto done_out;
}
if ( isVistaOrLater )
{
// Running Windows Vista or later. Determine token type: limited,
// elevated, or default.
TOKEN_ELEVATION_TYPE elevType;
if ( ! GetTokenInformation(hToken, TokenElevationType, &elevType, sizeof(elevType), &cbSize) )
{
error = GetLastError();
reportError(hwnd, "GetTokenInformation", "Windows Operating System Error", error);
goto done_out;
}
// If limited, get the linked elevated token for further check.
if ( TokenElevationTypeLimited == elevType )
{
if ( ! GetTokenInformation(hToken, TokenLinkedToken, &hTokenToCheck, sizeof(hTokenToCheck), &cbSize) )
{
error = GetLastError();
reportError(hwnd, "GetTokenInformation", "Windows Operating System Error", error);
goto done_out;
}
}
}
// CheckTokenMembership requires an impersonation token. If we just got a
// linked token, it already is an impersonation token. If we did not get
// a linked token, duplicate the original into an impersonation token for
// CheckTokenMembership.
if ( ! hTokenToCheck )
{
if ( ! DuplicateToken(hToken, SecurityIdentification, &hTokenToCheck) )
{
error = GetLastError();
reportError(hwnd, "DuplicateToken", "Windows Operating System Error", error);
goto done_out;
}
}
// Create the SID corresponding to the Administrators group.
BYTE adminSID[SECURITY_MAX_SID_SIZE];
cbSize = sizeof(adminSID);
if ( ! CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, &adminSID, &cbSize) )
{
error = GetLastError();
reportError(hwnd, "CreateWellKnownSid", "Windows Operating System Error", error);
goto done_out;
}
// Check if the token to be checked contains admin SID.
// http://msdn.microsoft.com/en-us/library/aa379596(VS.85).aspx:
// To determine whether a SID is enabled in a token, that is, whether it
// has the SE_GROUP_ENABLED attribute, call CheckTokenMembership.
BOOL inAdminGroup;
if ( ! CheckTokenMembership(hTokenToCheck, &adminSID, &inAdminGroup) )
{
error = GetLastError();
reportError(hwnd, "CheckTokenMembership", "Windows Operating System Error", error);
goto done_out;
}
inGroup = inAdminGroup ? true : false;
done_out:
if ( hToken )
{
CloseHandle(hToken);
}
if ( hTokenToCheck )
{
CloseHandle(hTokenToCheck);
}
*rc = error;
return inGroup;
}
/**
*
*
*
* @return bool
*
* @notes This function must be run on Vista or later, or it fails. We assume
* the caller has already checked the OS.
*/
bool isProcessElevated(HWND hwnd, uint32_t *rc)
{
uint32_t error = ERROR_SUCCESS;
HANDLE hToken = NULL;
bool elevated = false;
// Open the primary access token of the process with TOKEN_QUERY.
if ( ! OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
error = GetLastError();
reportError(hwnd, "OpenProcessToken", "Windows Operating System Error", error);
goto done_out;
}
// Retrieve token elevation information.
TOKEN_ELEVATION elevation;
uint32_t size;
if ( ! GetTokenInformation(hToken, TokenElevation, &elevation, sizeof(elevation), (DWORD *)&size) )
{
error = GetLastError();
reportError(hwnd, "GetTokenInformation", "Windows Operating System Error", error);
goto done_out;
}
elevated = elevation.TokenIsElevated ? true : false;
done_out:
if ( hToken )
{
CloseHandle(hToken);
}
*rc = error;
return elevated;
}
/**
*
*
* @param hwnd
* @param isVistaOrLater
* @param rc
*
* @return bool
*/
bool runningAsAdmin(HWND hwnd, uint32_t *rc)
{
PSID adminGroup = NULL;
bool result = false;
uint32_t error = ERROR_SUCCESS;
// get SID of the admin group.
SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY;
if ( ! AllocateAndInitializeSid(&authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, &adminGroup) )
{
error = GetLastError();
reportError(hwnd, "AllocateAndInitializeSid", "Windows Operating System Error", error);
goto done_out;
}
// Determine whether the SID of administrators group is enabled in
// the primary access token of the process.
BOOL isAdmin;
if ( ! CheckTokenMembership(NULL, adminGroup, &isAdmin) )
{
error = GetLastError();
reportError(hwnd, "CheckTokenMembership", "Windows Operating System Error", error);
goto done_out;
}
done_out:
if ( adminGroup )
{
FreeSid(adminGroup);
}
*rc = error;
return isAdmin ? true : false;
}
uint32_t determineStatus(HWND hDlg, pConfigureArguments pca)
{
OSVERSIONINFO osver = { sizeof(osver) };
uint32_t rc = ERROR_SUCCESS;
pca->requiresElevation = true;
if ( ! GetVersionEx(&osver) )
{
rc = GetLastError();
reportError(hDlg, "GetVersionEx", "Windows Operating System Error", rc);
goto done_out;
}
if (osver.dwMajorVersion >= 6)
{
pca->isVistaOrLater = true;
}
pca->isInAdminGroup = isUserInAdminGroup(hDlg, pca->isVistaOrLater, &rc);
if ( rc != ERROR_SUCCESS )
{
goto done_out;
}
pca->isRunAsAdmin = runningAsAdmin(hDlg, &rc);
if ( rc != ERROR_SUCCESS )
{
goto done_out;
}
if ( pca->isVistaOrLater )
{
pca->isElevated = isProcessElevated(hDlg, &rc);
if ( rc != ERROR_SUCCESS )
{
goto done_out;
}
pca->integrityLevel = getProcessIntegrityLevel(hDlg, &rc);
}
pca->requiresElevation = requiresElevation(pca);
done_out:
return rc;
}
INT_PTR CALLBACK WinMainDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static HFONT font = NULL;
if ( uMsg == WM_INITDIALOG )
{
pProgramArguments pa = (pProgramArguments)lParam;
setDlgIcon(hDlg, pa->hInstance);
// Initialize the edit control that displays the long text.
HWND hEdit = GetDlgItem(hDlg, IDC_EDIT);
int height = -MulDiv(10, GetDeviceCaps(GetDC(hDlg), LOGPIXELSY), 72);
font = CreateFont(height, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_TT_ONLY_PRECIS,
CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, FF_MODERN, "Courier New");
SendMessage(hEdit, WM_SETFONT, (WPARAM)font, TRUE);
SendMessage(hEdit, WM_SETTEXT, 0, (LPARAM)pa->mainMsg);
// Initialize the short banner text and the dialog title.
char tmp[MEDIUM_BUF_SIZE];
HWND hMsg = GetDlgItem(hDlg, IDC_ST_SHORT_MSG);
switch ( pa->dlgType )
{
case conditionDisplay :
SetWindowText(hDlg, "ooDialog Execute Program: Condition Raised");
_snprintf(tmp, MEDIUM_BUF_SIZE, "A Condition was raised while executing:\n\t%s", pa->oodProgram);
break;
case versionDisplay :
SetWindowText(hDlg, "ooDialog Execute Program: Version Information");
_snprintf(tmp, MEDIUM_BUF_SIZE, "ooDialog version %u.%u.%u.%u", OOD_VER, OOD_REL, OOD_MOD, OOD_BLD);
break;
case syntaxDisplay :
SetWindowText(hDlg, "ooDialog Execute Program: Syntax Information");
_snprintf(tmp, MEDIUM_BUF_SIZE, "ooDialog version %u.%u.%u.%u", OOD_VER, OOD_REL, OOD_MOD, OOD_BLD);
break;
default :
SetWindowText(hDlg, "ooDialog Execute Program: Internal Error");
_snprintf(tmp, MEDIUM_BUF_SIZE, "An unexpected internal error has happend:\n");
break;
}
SendMessage(hMsg, WM_SETTEXT, 0, (LPARAM)tmp);
// Set the proper icon image.
LPCTSTR imageName = IDI_INFORMATION;
if ( pa->dlgType == conditionDisplay )
{
imageName = IDI_ERROR;
}
HANDLE hNewIcon = LoadImage(NULL, imageName, IMAGE_ICON, 0, 0, LR_SHARED | LR_DEFAULTSIZE);
HWND hSt = GetDlgItem(hDlg, IDC_ST_DISPLAY_ICON);
SendMessage(hSt, STM_SETICON, (WPARAM)hNewIcon, 0);
if ( pa->allowServices )
{
ShowWindow(GetDlgItem(hDlg, IDC_GB_SERVICES), SW_SHOWNA);
ShowWindow(GetDlgItem(hDlg, IDC_CK_FILEASSOC), SW_SHOWNA);
}
setWindowPtr(hDlg, GWLP_USERDATA, (LONG_PTR)pa);
return TRUE;
}
switch ( uMsg )
{
case WM_COMMAND:
switch ( LOWORD(wParam) )
{
case IDC_CK_FILEASSOC :
{
if ( HIWORD(wParam) == BN_CLICKED )
{
if ( IsDlgButtonChecked(hDlg, IDC_CK_FILEASSOC) == BST_CHECKED )
{
SetDlgItemText(hDlg, IDOK, "Continue");
}
else
{
SetDlgItemText(hDlg, IDOK, "Close");
}
}
}
break;
case IDOK:
{
if ( IsDlgButtonChecked(hDlg, IDC_CK_FILEASSOC) == BST_CHECKED )
{
pProgramArguments pa = (pProgramArguments)getWindowPtr(hDlg, GWLP_USERDATA);
pa->doConfigure = true;
}
EndDialog(hDlg, wParam);
if ( font )
{
DeleteObject(font);
}
}
return TRUE;
case IDCANCEL:
{
EndDialog(hDlg, wParam);
if ( font )
{
DeleteObject(font);
}
}
return TRUE;
}
default:
break;
}
return FALSE;
}
/**
* Given an extension information record for the specified ext, determines where
* (in which locations) the extension is associated with the specified progID,
* and or if it is associated with a different progID.
*
* Essentially this fills out the fields of the record for an extension that
* show where, or if, that extension is registered to a file type.
*
* @param keyName The extension, .ood, for example
* @param rec An allocated extension information record
* @param progID The progID we are interested in. Actually this should always
* be OODIALOG_PROGID_VERSIONED, but for testing and flexibility
* we use an input argument.
*
*/
void qualifyExtensionInfo(char *extKeyName, pExtensionInfo rec, char *progID)
{
char value[MAX_HKEY_VALUE] = {'\0'};
uint32_t maxValue = MAX_HKEY_VALUE;
HKEY hKey, hSubkey;
// See if extKeyName is a subkey for current user
if( RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Classes", 0, KEY_READ, &hKey) == ERROR_SUCCESS )
{
if ( RegOpenKeyEx(hKey, extKeyName, 0, KEY_QUERY_VALUE, &hSubkey) == ERROR_SUCCESS )
{
if ( RegQueryValueEx(hSubkey, "", NULL, NULL, (LPBYTE)value, (LPDWORD)&maxValue) == ERROR_SUCCESS )
{
if ( StrCmpI(value, progID) == 0 )
{
rec->curUser = true;
}
else
{
rec->curUserOther = true;
}
}
RegCloseKey(hSubkey);
}
RegCloseKey(hKey);
}
// See if extKeyName is a subkey for local machine classes
if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Classes", 0, KEY_READ, &hKey) == ERROR_SUCCESS )
{
if ( RegOpenKeyEx(hKey, extKeyName, 0, KEY_QUERY_VALUE, &hSubkey) == ERROR_SUCCESS )
{
value[0] = '\0';
maxValue = MAX_HKEY_VALUE;
if ( RegQueryValueEx(hSubkey, "", NULL, NULL, (LPBYTE)value, (LPDWORD)&maxValue) == ERROR_SUCCESS )
{
if ( StrCmpI(value, progID) == 0 )
{
rec->allUsers = true;
}
else
{
rec->allUsersOther = true;
}
}
RegCloseKey(hSubkey);
}
RegCloseKey(hKey);
}
char *prefix = "- - ";
if ( rec->allUsers )
{
if ( rec->curUser )
{
prefix = "* * ";
}
else if ( rec->curUserOther )
{
prefix = "* + ";
}
else
{
prefix = "* - ";
}
}
else if ( rec->curUser )
{
if ( rec->allUsersOther )
{
prefix = "+ * ";
}
else
{
prefix = "- * ";
}
}
else
{
// Not associated with our program ID, but may be in use by others.
if ( rec->allUsersOther )
{
if ( rec->curUserOther )
{
prefix = "+ + ";
}
else
{
prefix = "+ - ";
}
}
else if ( rec->curUser )
{
prefix = "- + ";
}
}
_snprintf(rec->displayName, MAX_EXT_DISPLAY, "%s%s", prefix, extKeyName);
}
/**
* Gets the extension information records for all extensions mapped to the
* specified progID currently in the registry.
*
* @param progID The progID we are looking for IN
* @param count The count of records found OUT
*
* @return An allocated array of extension records.
*
* @note The caller is responsible for freeing the array.
*/
pExtensionInfo getExtensionRecords(HWND hDlg, char *progID, size_t *count)
{
uint32_t cSubKeys = 0;
HKEY hKCR = HKEY_CLASSES_ROOT;
// We only need the number of subkeys.
uint32_t retCode = RegQueryInfoKey(HKEY_CLASSES_ROOT, NULL, NULL, NULL, (LPDWORD)&cSubKeys,
NULL, NULL, NULL, NULL, NULL, NULL, NULL);
uint32_t maxName; // Size of name buffer
char keyName[MAX_HKEY_NAME]; // Buffer for subkey name
uint32_t maxValue = MAX_HKEY_VALUE; // Size of value buffer
char value[MAX_HKEY_VALUE]; // Buffer for default value for subkey
// Enumerate the subkeys, and see if the prog ID matches our ooDialog prog
// ID. We go through the loop twice, once to count the number of matches so
// we can allocate the array of extension records. Then a second time to
// actually fill in the records.
pExtensionInfo recs = NULL;
size_t matches = 0;
for ( uint32_t i = 0; i < cSubKeys; i++ )
{
maxName = MAX_HKEY_NAME;
retCode = RegEnumKeyEx(hKCR, i, keyName, (LPDWORD)&maxName, NULL, NULL, NULL, NULL);
if (retCode == ERROR_SUCCESS)
{
if ( *keyName == '.' )
{
HKEY hExtKey;
retCode = RegOpenKeyEx(hKCR, keyName, 0, KEY_QUERY_VALUE, &hExtKey);
if ( retCode == ERROR_SUCCESS )
{
maxValue = MAX_HKEY_VALUE;
value[0] = '\0';
retCode = RegQueryValueEx(hExtKey, "", NULL, NULL, (LPBYTE)value, (LPDWORD)&maxValue);
if ( retCode == ERROR_SUCCESS )
{
if ( StrCmpI(value, progID) == 0 )
{
matches++;
}
}
RegCloseKey(hExtKey);
}
}
}
}
if ( matches == 0 )
{
goto done_out;
}
recs = (pExtensionInfo)LocalAlloc(LPTR, matches * sizeof(extensionInfo));
if ( recs == NULL )
{
reportError(hDlg, OUT_OF_MEMORY_FMT_STR, "Windows Operating System Error", "LocalAlloc", GetLastError());
goto done_out;
}
size_t processed = 0;
for ( uint32_t i = 0; i < cSubKeys; i++ )
{
maxName = MAX_HKEY_NAME;
retCode = RegEnumKeyEx(hKCR, i, keyName, (LPDWORD)&maxName, NULL, NULL, NULL, NULL);
if (retCode == ERROR_SUCCESS)
{
if ( *keyName == '.' )
{
HKEY hExtKey;
retCode = RegOpenKeyEx(hKCR, keyName, 0, KEY_QUERY_VALUE, &hExtKey);
if ( retCode == ERROR_SUCCESS )
{
maxValue = MAX_HKEY_VALUE;
value[0] = '\0';
retCode = RegQueryValueEx(hExtKey, "", NULL, NULL, (LPBYTE)value, (LPDWORD)&maxValue);
if ( retCode == ERROR_SUCCESS )
{
if ( StrCmpI(value, progID) == 0 )
{
pExtensionInfo current = &recs[processed++];
current->exists = true;
strcpy(current->extension, keyName);
qualifyExtensionInfo(keyName, current, progID);
printf("%s -> %s\n", keyName, value);
}
}
RegCloseKey(hExtKey);
}
}
}
}
done_out:
*count = matches;
return recs;
}
void checkRegistration(pAssocArguments paa)
{
char value[MAX_HKEY_VALUE] = {'\0'};
uint32_t maxValue = MAX_HKEY_VALUE;
HKEY hKey, hSubkey;
paa->ftypeIsRegistered = false;
paa->registeredAllUsers = false;
paa->registeredCurUsers = false;
// See if our progID is a subkey of classes root
if( RegOpenKeyEx(HKEY_CLASSES_ROOT, paa->progID, 0, KEY_QUERY_VALUE , &hKey) == ERROR_SUCCESS )
{
paa->ftypeIsRegistered = true;
char buf[MEDIUM_BUF_SIZE];
_snprintf(buf, MEDIUM_BUF_SIZE, "SOFTWARE\\Classes\\%s", paa->progID);
// See if progID is a subkey for local machine
if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, buf, 0, KEY_QUERY_VALUE, &hSubkey) == ERROR_SUCCESS )
{
paa->registeredAllUsers = true;
RegCloseKey(hSubkey);
}
// See if progID is a subkey for current user
if( RegOpenKeyEx(HKEY_CURRENT_USER, buf, 0, KEY_QUERY_VALUE, &hSubkey) == ERROR_SUCCESS )
{
paa->registeredCurUsers = true;
RegCloseKey(hSubkey);
}
RegCloseKey(hKey);
}
}
void maybeEmptyLB(HWND hLB)
{
LRESULT count = SendMessage(hLB, LB_GETCOUNT, NULL, NULL);
if ( count > 0 )
{
for (LRESULT i = 0; i > count; i++ )
{
pExtensionInfo info = (pExtensionInfo)SendMessage(hLB, LB_GETITEMDATA, i, 0);
safeLocalFree(info);
}
SendMessage(hLB, LB_RESETCONTENT, 0, 0);
}
}
/**
* Adds the suggested file extensions to the list box. The first time through,
* the list box will be empty. But, we may do this several times if the user
* adds and / or removes the registration for the file type.
*
* If there are any items in the list box, we need to not only remove them, but
* to also free the extension memory.
*
* @param hDlg
* @param paa
*
* @return bool
*/
bool addSuggestedExt(HWND hDlg, pAssocArguments paa)
{
HWND hLB = paa->lbSuggested;
maybeEmptyLB(hLB);
for ( size_t i = 0; i < OOD_SUGGESTED_EXT_COUNT; i++ )
{
pExtensionInfo info = (pExtensionInfo)LocalAlloc(LPTR, sizeof(extensionInfo));
if ( info == NULL )
{
reportError(hDlg, OUT_OF_MEMORY_FMT_STR, "Windows Operating System Error", "LocalAlloc", GetLastError());
return false;
}
strcpy(info->extension, oodSuggestedExts[i]);
info->suggested = true;
qualifyExtensionInfo(oodSuggestedExts[i], info, paa->progID);
LRESULT index = SendMessage(hLB, LB_ADDSTRING, i, (LPARAM)info->displayName);
SendMessage(hLB, LB_SETITEMDATA, index, (LPARAM)info);
}
return true;
}
void addCurrentExt(HWND hDlg, pAssocArguments paa)
{
size_t count = 0;
HWND hLB = paa->lbCurrent;
maybeEmptyLB(hLB);
pExtensionInfo recs = getExtensionRecords(hDlg, paa->progID, &count);
for ( size_t i = 0; i < count; i++ )
{
pExtensionInfo current = &recs[i];
LRESULT index = SendMessage(hLB, LB_ADDSTRING, i, (LPARAM)current->displayName);
SendMessage(hLB, LB_SETITEMDATA, index, (LPARAM)current);
}
}
void testRegistry()
{
HKEY envKey;
char msg[MEDIUM_BUF_SIZE];
char buf[MEDIUM_BUF_SIZE];
char *key = "Console\\Left";
HKEY hKey;
uint32_t rc = RegOpenKeyEx(HKEY_CURRENT_USER, key, 0, STANDARD_RIGHTS_READ | KEY_QUERY_VALUE, &hKey);
if ( rc == ERROR_SUCCESS )
{
uint32_t type;
uint32_t count = MEDIUM_BUF_SIZE;
rc = RegQueryValueEx(hKey, "FaceName", NULL, (LPDWORD)&type, (LPBYTE)buf, (LPDWORD)&count);
if ( rc == ERROR_SUCCESS )
{
_snprintf(msg, MEDIUM_BUF_SIZE, "Queried key=%s for FaceName value=%s, type=0x%x count=%d\n", key, buf, type, count);
internalInfoMsgBox(msg, "ooDialog");
}
else
{
_snprintf(msg, MEDIUM_BUF_SIZE, "RegQueryValueEx() for default rc=%d\n", rc);
internalInfoMsgBox(msg, "ooDialog");
}
RegCloseKey(hKey);
}
else
{
_snprintf(msg, MEDIUM_BUF_SIZE, "RegOpenKeyEx() for %s failed rc=%d\n", key, rc);
internalInfoMsgBox(msg, "ooDialog");
}
rc = RegOpenKeyEx(HKEY_CURRENT_USER, "Environment", 0, STANDARD_RIGHTS_READ | KEY_QUERY_VALUE, &envKey);
if ( rc == ERROR_SUCCESS )
{
uint32_t type;
uint32_t count = MEDIUM_BUF_SIZE;
rc = RegQueryValueEx(envKey, "PATHEXT", NULL, (LPDWORD)&type, (LPBYTE)buf, (LPDWORD)&count);
if ( rc == ERROR_SUCCESS )
{
_snprintf(msg, MEDIUM_BUF_SIZE, "PATHEXT=%s, type=0x%x count=%d\n", buf, type, count);
internalInfoMsgBox(msg, "ooDialog");
}
else
{
_snprintf(msg, MEDIUM_BUF_SIZE, "RegQueryValueEx() failed rc=%d\n", rc);
internalInfoMsgBox(msg, "ooDialog");
}
RegCloseKey(envKey);
}
else
{
_snprintf(msg, MEDIUM_BUF_SIZE, "RegOpenKeyEx() failed rc=%d\n", rc);
internalInfoMsgBox(msg, "ooDialog");
}
}
void setAssocControls(HWND hDlg, pAssocArguments paa, bool flag)
{
BOOL enable = flag ? TRUE : FALSE;
EnableWindow(paa->lbCurrent, enable);
EnableWindow(paa->lbSuggested, enable);
EnableWindow(paa->lbPathExt, enable);
EnableWindow(GetDlgItem(hDlg, IDC_EDIT_EXTENSION), enable);
EnableWindow(GetDlgItem(hDlg, IDC_PB_ADD_EXTENSION), enable);
EnableWindow(GetDlgItem(hDlg, IDC_PB_ADD_CURRENT), enable);
EnableWindow(GetDlgItem(hDlg, IDC_PB_REMOVE_CURRENT), enable);
EnableWindow(GetDlgItem(hDlg, IDC_PB_ADD_PATHEXT), enable);
EnableWindow(GetDlgItem(hDlg, IDC_PB_REMOVE_PATHEXT), enable);
}
/**
* Sets the state of the dialog controls.
*
* @param hDlg
* @param paa
*
* @note This is a little complex. At this time I think the Register push
* button should always be enabled.
*/
void setRegisterdState(HWND hDlg, pAssocArguments paa)
{
// The static text for these controls can vary during the life-time of the
// dialog:
SetDlgItemText(hDlg, IDC_ST_REGISTERED, paa->ftypeIsRegistered ? "True" : "False");
SetDlgItemText(hDlg, IDC_ST_REGALL, paa->registeredAllUsers ? "Yes" : "No");
SetDlgItemText(hDlg, IDC_ST_REGCURRENT, paa->registeredCurUsers ? "Yes" : "No");
if ( ! paa->ftypeIsRegistered )
{
if ( paa->allUsers )
{
SetWindowText(paa->pbRegister, "Register ooDialog File Type For All Users");
}
else
{
SetWindowText(paa->pbRegister, "Register ooDialog File Type For the Current User");
}
setAssocControls(hDlg, paa, false);
addSuggestedExt(hDlg, paa);
addCurrentExt(hDlg, paa);
return;
}
// Our progID is registered for either all users or current user. Maybe
// both, but not necessarily both. How we set the state is dependent on the
// scope and if progID is registered for that scope.
if ( paa->registeredAllUsers && paa->registeredCurUsers )
{
if ( paa->allUsers )
{
SetWindowText(paa->pbRegister, "Un-register ooDialog File Type For All Users");
}
else
{
SetWindowText(paa->pbRegister, "Un-register ooDialog File Type For the Current User");
}
}
else if ( paa->registeredAllUsers )
{
if ( paa->allUsers )
{
SetWindowText(paa->pbRegister, "Un-register ooDialog File Type For All Users");
}
else
{
SetWindowText(paa->pbRegister, "Register ooDialog File Type For the Current User");
}
}
else
{
if ( paa->allUsers )
{
SetWindowText(paa->pbRegister, "Register ooDialog File Type For All Users");
}
else
{
SetWindowText(paa->pbRegister, "Un-register ooDialog File Type For the Current User");
}
}
setAssocControls(hDlg, paa, true);
addSuggestedExt(hDlg, paa);
addCurrentExt(hDlg, paa);
}
HFONT fontCreate(int32_t fontSize)
{
int width = 0; // average character width
int escapement = 0; // angle of escapement
int orientation = 0; // base-line orientation angle
int weight = FW_NORMAL; // font weight
BOOL italic = FALSE; // italic attribute option
BOOL underline = FALSE; // underline attribute option
BOOL strikeOut = FALSE; // strikeout attribute option
uint32_t charSet = DEFAULT_CHARSET; // character set identifier
uint32_t outputPrecision = OUT_TT_PRECIS; // output precision
uint32_t clipPrecision = CLIP_DEFAULT_PRECIS; // clipping precision
uint32_t quality = DEFAULT_QUALITY; // output quality
uint32_t pitchAndFamily = FF_DONTCARE; // pitch and family
HDC hdc = CreateDC("DISPLAY", NULL, NULL, NULL);
int height = -MulDiv(fontSize, GetDeviceCaps(hdc, LOGPIXELSY), 72);
DeleteDC(hdc);
HFONT f = CreateFont(height, width, escapement, orientation, weight, italic, underline, strikeOut,
charSet, outputPrecision, clipPrecision, quality, pitchAndFamily, "Courier New");
return f;
}
void setStaticText(HWND hDlg, pAssocArguments paa)
{
SetDlgItemText(hDlg, IDC_GB_ASSOCIATE, paa->allUsers ?
"Associating File Extensions with ooDialog.exe File Type for All Users" :
"Associating File Extensions with ooDialog.exe File Type for the Current User");
SetDlgItemText(hDlg, IDC_ST_FTYPE, paa->progID);
SetDlgItemText(hDlg, IDC_ST_SCOPE, paa->allUsers ? "All Users" : "CurrentUser");
SetDlgItemText(hDlg, IDC_ST_RUNAS, paa->isRunAsAdmin ? "True" : "False");
SetDlgItemText(hDlg, IDC_ST_ELEVATED, paa->isElevated ? "True" : "False");
}
void setUp(HWND hDlg, pAssocArguments paa)
{
setWindowPtr(hDlg, GWLP_USERDATA, (LONG_PTR)paa);
paa->lbSuggested = GetDlgItem(hDlg, IDC_LB_SUGGESTED);
paa->lbCurrent = GetDlgItem(hDlg, IDC_LB_CURRENT);
paa->lbPathExt = GetDlgItem(hDlg, IDC_LB_PATHEXT);
paa->pbRegister = GetDlgItem(hDlg, IDC_PB_REGISTER);
HFONT font = fontCreate(8);
SendMessage(paa->lbSuggested, WM_SETFONT, (WPARAM)font, FALSE);
SendMessage(paa->lbCurrent, WM_SETFONT, (WPARAM)font, FALSE);
SendMessage(paa->lbPathExt, WM_SETFONT, (WPARAM)font, FALSE);
setDlgIcon(hDlg, paa->hInstance);
setStaticText(hDlg, paa);
setRegisterdState(hDlg, paa);
}
/**
* Creates, or opens, a subkey and, optionally, writes its Default string value.
*
* @param openedKey An already open registry key
* @param subkey A subkey of 'openedKey to create or open
* @param defValue The value for the Default entry for subkey. If this is
* null, then writing a value for Default is just skipped.
*
* @param hDlg The window handle of the dialog, for error displary
* @param user A string for the error dispaly that specifies if we are
* writing the subkey in current user or all users (local
* machine.)
*
* @return The opened subkey on success, otherwise NULL.
*/
HKEY writeRegSubkeyValue(HKEY openedKey, char *subkey, char *defValue, HWND hDlg, char *user)
{
uint32_t disp;
uint32_t rc;
char extraMsg[SMALL_BUF_SIZE];
HKEY hKey = NULL;
rc = RegCreateKeyEx(openedKey, subkey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | DELETE, NULL, &hKey, (LPDWORD)&disp);
if ( rc != ERROR_SUCCESS )
{
_snprintf(extraMsg, SMALL_BUF_SIZE, "Failed to create or open the %s registry key for %s", subkey, user);
reportErrorPlus(hDlg, "RegCreateKeyEx", "Windows Registry Error", extraMsg, rc);
return NULL;
}
// Set the default value, if requested ...
if ( defValue != NULL )
{
size_t len = strlen(defValue) + 1;
rc = RegSetValueEx(hKey, "", 0, REG_SZ, (LPBYTE)defValue, (uint32_t)len);
if ( rc != ERROR_SUCCESS )
{
_snprintf(extraMsg, SMALL_BUF_SIZE,
"Failed to set the default value (%s) for the %s registry key for %s",
defValue, subkey, user);
reportErrorPlus(hDlg, "RegSetValueEx", "Windows Registry Error", extraMsg, rc);
RegCloseKey(hKey);
hKey = NULL;
}
}
return hKey;
}
/**
* Writes a named string value for an opened registry key.
*
* @param openedKey An already open registry key
* @param valueName The name of the value to be written
* @param value The value to be written
* @param hDlg The window handle of the dialog, for error displary
* @param user A string for the error dispaly that specifies if we are
* writing the subkey in current user or all users (local
* machine.)
*
* @return True on success, false on error.
*/
bool writeRegKeyValue(HKEY openedKey, char *valueName, char *value, HWND hDlg, char *user)
{
uint32_t rc;
size_t len = strlen(value) + 1;
rc = RegSetValueEx(openedKey, valueName, 0, REG_SZ, (LPBYTE)value, (uint32_t)len);
if ( rc != ERROR_SUCCESS )
{
char extraMsg[SMALL_BUF_SIZE];
_snprintf(extraMsg, SMALL_BUF_SIZE,
"Failed to set the %s value (%s) for %s",
valueName, value, user);
reportErrorPlus(hDlg, "RegSetValueEx", "Windows Registry Error", extraMsg, rc);
return false;
}
return true;
}
bool removeRegProgID(HWND hDlg, pAssocArguments paa)
{
internalInfoMsgBox("removeProgID() not implemented", "ooDialog");
return false;
}
bool writeRegProgID(HWND hDlg, pAssocArguments paa)
{
HKEY hPreDefKey = HKEY_CURRENT_USER;
char *user = "the current user.";
if ( paa->allUsers )
{
hPreDefKey = HKEY_LOCAL_MACHINE;
user = "all users";
}
HKEY hProgIdKey = NULL;
HKEY hKey = NULL;
char valueBuf[MEDIUM_BUF_SIZE];
// Do the ooRexx.ooDialog.1 subkey of software\classees
_snprintf(valueBuf, MEDIUM_BUF_SIZE, "SOFTWARE\\Classes\\%s", paa->progID);
hProgIdKey = writeRegSubkeyValue(hPreDefKey, valueBuf, OODIALOG_FRIENDLY_NAME, hDlg, user);
if ( hProgIdKey == NULL )
{
goto done_out;
}
// Do the DefaultIcon subkey of ooRexx.ooDialog.1
_snprintf(valueBuf, MEDIUM_BUF_SIZE, "%s,-%d", paa->exeName, IDI_APP_BLUE_BEAKER_ICON);
hKey = writeRegSubkeyValue(hProgIdKey, "DefaultIcon", valueBuf, hDlg, user);
if ( hKey == NULL )
{
goto done_out;
}
RegCloseKey(hKey);
// Do the CurVer subkey of ooRexx.ooDilaog.1
hKey = writeRegSubkeyValue(hProgIdKey, "CurVer", paa->progID, hDlg, user);
if ( hKey == NULL )
{
goto done_out;
}
RegCloseKey(hKey);
// Do the FiendlyTypeName value of ooRexx.ooDialog.1
_snprintf(valueBuf, MEDIUM_BUF_SIZE, "@%s,-%d", paa->exeName, IDS_FRIENDLY_NAME);
if ( ! writeRegKeyValue(hProgIdKey, "FriendlyTypeName", valueBuf, hDlg, user) )
{
goto done_out;
}
// Do the InfoTip value of ooRexx.ooDailog.1
_snprintf(valueBuf, MEDIUM_BUF_SIZE, "@%s,-%d", paa->exeName, IDS_INFOTIP);
if ( ! writeRegKeyValue(hProgIdKey, "InfoTip", valueBuf, hDlg, user) )
{
goto done_out;
}
// Do the shell subkey of ooRexx.ooDiallog.1 and its subkeys.
// This will create the shell\open sub subky and set its default to Run
hKey = writeRegSubkeyValue(hProgIdKey, "shell\\open", "Run", hDlg, user);
if ( hKey == NULL )
{
goto done_out;
}
RegCloseKey(hKey);
// Now create the shell\open\command sub sub subkey
_snprintf(valueBuf, MEDIUM_BUF_SIZE, "\"%s\" \"%%1\" %%*", paa->exeName);
hKey = writeRegSubkeyValue(hProgIdKey, "shell\\open\\command", valueBuf, hDlg, user);
if ( hKey == NULL )
{
goto done_out;
}
RegCloseKey(hKey);
// Write the default value for shell\open. This won't created the subkey,
// it was just created, it will just open it.
/* TODO add code to set an editor. (shell\edit) */
/* TODO add code to use rexxc ? (shell\compile) */
// Do the shellex\DropHandler subkey of ooRexx.ooDialog.1
hKey = writeRegSubkeyValue(hProgIdKey, "ShellEx\\DropHandler", OODIALOG_DROP_HANDLER, hDlg, user);
if ( hKey == NULL )
{
goto done_out;
}
RegCloseKey(hKey);
RegCloseKey(hProgIdKey);
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
return true;
done_out:
if ( hProgIdKey != NULL )
{
RegCloseKey(hProgIdKey);
// We delete the key because it was not completely written.
_snprintf(valueBuf, MEDIUM_BUF_SIZE, "SOFTWARE\\Classes\\%s", paa->progID);
uint32_t rc = SHDeleteKey(hPreDefKey, valueBuf);
if ( rc != ERROR_SUCCESS )
{
char extraMsg[SMALL_BUF_SIZE];
_snprintf(extraMsg, SMALL_BUF_SIZE, "Failed to delete the %s key for %s", valueBuf, user);
reportErrorPlus(hDlg, "RegSetValueEx", "Windows Registry Error", extraMsg, rc);
}
}
return false;
}
/**
* Handles a click on the Register / Un-register push button
*
* @param hDlg
*
* @return INT_PTR
*/
INT_PTR pbRegister(HWND hDlg)
{
pAssocArguments paa = (pAssocArguments)getWindowPtr(hDlg, GWLP_USERDATA);
if ( paa->allUsers )
{
if ( paa->registeredAllUsers )
{
removeRegProgID(hDlg, paa);
}
else
{
if ( writeRegProgID(hDlg, paa) )
{
paa->ftypeIsRegistered = true;
if ( paa->allUsers )
{
paa->registeredAllUsers = true;
}
else
{
paa->registeredCurUsers = true;
}
setRegisterdState(hDlg, paa);
}
else
{
// Failed to create the progID entry, disable this push button so
// the user can't try this again.
EnableWindow(paa->pbRegister, FALSE);
}
}
}
else
{
if ( paa->registeredCurUsers )
{
removeRegProgID(hDlg, paa);
}
else
{
if ( writeRegProgID(hDlg, paa) )
{
paa->ftypeIsRegistered = true;
if ( paa->allUsers )
{
paa->registeredAllUsers = true;
}
else
{
paa->registeredCurUsers = true;
}
setRegisterdState(hDlg, paa);
}
else
{
// Failed to create the progID entry, disable this push button
// so the user can't try this again.
EnableWindow(paa->pbRegister, FALSE);
}
}
}
return TRUE;
}
INT_PTR handleButtonClick(HWND hDlg, WPARAM wParam, LPARAM lParam)
{
switch ( LOWORD(wParam) )
{
case IDOK:
case IDCANCEL:
{
EndDialog(hDlg, wParam);
}
return TRUE;
case IDC_PB_REGISTER :
return pbRegister(hDlg);
break;
case IDC_PB_ADD_EXTENSION :
break;
case IDC_PB_ADD_CURRENT :
break;
case IDC_PB_REMOVE_CURRENT :
break;
case IDC_PB_ADD_PATHEXT :
break;
case IDC_PB_REMOVE_PATHEXT :
break;
default:
break;
}
return FALSE;
}
/**
* HKEY_CURRENT_USER \ Environment
*
* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session
* Manager\Environment
*
* @param hDlg
* @param uMsg
* @param wParam
* @param lParam
*
* @return INT_PTR CALLBACK
*/
INT_PTR CALLBACK FileAssocDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if ( uMsg == WM_INITDIALOG )
{
pAssocArguments paa = (pAssocArguments)lParam;
// Query the registry to see if ooDialog ftype / progID is already
// registered. If so ...
checkRegistration(paa);
//strcpy(paa->progID, "SlickEdit"); // temp for testing
setUp(hDlg, paa);
return TRUE;
}
switch ( uMsg )
{
case WM_COMMAND:
// This is okay because we do not have any menus:
if ( HIWORD(wParam) == BN_CLICKED )
{
return handleButtonClick(hDlg, wParam, lParam);
}
break;
default:
break;
}
return FALSE;
}
INT_PTR CALLBACK ConfigureDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if ( uMsg == WM_INITDIALOG )
{
pConfigureArguments pca = (pConfigureArguments)lParam;
setDlgIcon(hDlg, pca->hInstance);
if ( pca->wasElevated )
{
// We are only restarted as elevated when all users is checked.
CheckDlgButton(hDlg, IDC_RB_ALL, BST_CHECKED);
}
else
{
CheckDlgButton(hDlg, IDC_RB_CURRENT, BST_CHECKED);
}
uint32_t rc = determineStatus(hDlg, pca);
if ( rc != ERROR_SUCCESS )
{
internalErrorMsgBox("Operaring system errors prevent continuing. Going to abort",
"ooDialog Configure Services: Windows Error");
EndDialog(hDlg, wParam);
return FALSE;
}
SetDlgItemText(hDlg, IDC_ST_INADMINGROUP, pca->isInAdminGroup ? "True" : "False");
SetDlgItemText(hDlg, IDC_ST_ISRUNASADMIN, pca->isRunAsAdmin ? "True" : "False");
if ( pca->isVistaOrLater )
{
SetDlgItemText(hDlg, IDC_ST_ISELEVATED, pca->isElevated ? "True" : "False");
SetDlgItemText(hDlg, IDC_ST_IL, level2text(pca->integrityLevel));
}
else
{
SetDlgItemText(hDlg, IDC_ST_ISELEVATED, "N/A");
SetDlgItemText(hDlg, IDC_ST_IL, "N/A");
// If not running as admin on XP, can not select all users.
if ( ! pca->isRunAsAdmin )
{
EnableWindow(GetDlgItem(hDlg, IDC_RB_ALL), FALSE);
}
}
setWindowPtr(hDlg, GWLP_USERDATA, (LONG_PTR)pca);
if ( pca->wasElevated )
{
PostMessage(hDlg, WM_COMMAND, MAKEWPARAM(IDC_PB_CONFIGURE, BN_CLICKED), 0);
}
return TRUE;
}
pConfigureArguments pca = (pConfigureArguments)getWindowPtr(hDlg, GWLP_USERDATA);
switch ( uMsg )
{
case WM_COMMAND:
switch ( LOWORD(wParam) )
{
case IDC_RB_ALL :
{
if ( HIWORD(wParam) == BN_CLICKED && pca->requiresElevation )
{
Button_SetElevationRequiredState(GetDlgItem(hDlg, IDC_PB_CONFIGURE), TRUE);
}
}
break;
case IDC_RB_CURRENT :
{
if ( HIWORD(wParam) == BN_CLICKED && pca->requiresElevation )
{
Button_SetElevationRequiredState(GetDlgItem(hDlg, IDC_PB_CONFIGURE), FALSE);
}
}
break;
case IDC_PB_CONFIGURE :
{
if ( HIWORD(wParam) == BN_CLICKED )
{
uint32_t error;
bool isAllUsers = IsDlgButtonChecked(hDlg, IDC_RB_ALL) ? true : false;
if ( isAllUsers && pca->requiresElevation )
{
char exeName[MAX_PATH];
if ( GetModuleFileName(NULL, exeName, ARRAYSIZE(exeName)) )
{
// Re-execute ourself as Administrator
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.lpVerb = "runas";
sei.lpFile = exeName;
sei.lpParameters = "-confElevatedAllUsers";
sei.hwnd = hDlg;
sei.nShow = SW_NORMAL;
if ( ! ShellExecuteEx(&sei))
{
error = GetLastError();
if ( error == ERROR_CANCELLED )
{
// The user refused the elevation.
// Do nothing ...
}
else
{
reportError(hDlg, "ShellExecuteEx", "Windows Operating System Error", error);
}
}
else
{
// Quit this process.
ShowWindow(hDlg, SW_HIDE);
EndDialog(hDlg, TRUE);
}
}
else
{
error = GetLastError();
reportError(hDlg, "GetModuleFileName", "Windows Operating System Error", error);
}
}
else
{
// Start the file assoc dialog.
assocArguments aa = { 0 };
aa.isRunAsAdmin = pca->isRunAsAdmin;
aa.hInstance = pca->hInstance;
aa.allUsers = isAllUsers;
aa.isElevated = pca->isElevated;
aa.exeName = pca->exeName;
strcpy(aa.progID, OODIALOG_PROGID_VERSIONED);
DialogBoxParam(pca->hInstance, MAKEINTRESOURCE(IDD_FILEASSOC), hDlg, FileAssocDlgProc, (LPARAM)&aa);
}
}
}
break;
case IDOK:
case IDCANCEL:
EndDialog(hDlg, wParam);
return TRUE;
}
break;
default:
break;
}
return FALSE;
}
inline bool haveFlag(CSTRING a)
{
return *a == '-' || *a == '/';
}
static int32_t displayCondition(RexxThreadContext *c, pProgramArguments pa)
{
wholenumber_t code = 0;
char *msg = getStandardConditionMsg(c, &code, NULL);
if ( msg )
{
pa->mainMsg = msg;
pa->dlgType = conditionDisplay;
DialogBoxParam(pa->hInstance, MAKEINTRESOURCE(IDD_OODIALOG_DISPLAY), NULL, WinMainDlgProc, (LPARAM)pa);
LocalFree(msg);
}
return (int32_t)code;
}
static int32_t ooDialogServices(pProgramArguments pa)
{
configureArguments ca = { 0 };
ca.hInstance = pa->hInstance;
ca.exeName = pa->exeName;
DialogBoxParam(pa->hInstance, MAKEINTRESOURCE(IDD_CONFIGURE_SERVICES), NULL, ConfigureDlgProc, (LPARAM)&ca);
return 0;
}
static int32_t displaySyntax(pProgramArguments pa)
{
pa->dlgType = syntaxDisplay;
pa->mainMsg = long_syntax_text;
DialogBoxParam(pa->hInstance, MAKEINTRESOURCE(IDD_OODIALOG_DISPLAY), NULL, WinMainDlgProc, (LPARAM)pa);
if ( pa->doConfigure )
{
ooDialogServices(pa);
}
return 0;
}
static int32_t displayVersion(RexxThreadContext *c, pProgramArguments pa)
{
if ( pa->showShortVersion )
{
char buf[MEDIUM_BUF_SIZE];
_snprintf(buf, MEDIUM_BUF_SIZE, "ooDialog version %u.%u.%u.%u", OOD_VER, OOD_REL, OOD_MOD, OOD_BLD);
internalInfoMsgBox(buf, "ooDialog Execute Program: Version Information");
return 0;
}
char *ver = getCompleteVersion(c);
if ( ver )
{
pa->dlgType = versionDisplay;
pa->mainMsg = ver;
DialogBoxParam(pa->hInstance, MAKEINTRESOURCE(IDD_OODIALOG_DISPLAY), NULL, WinMainDlgProc, (LPARAM)pa);
LocalFree(ver);
}
else
{
internalErrorMsgBox("ooDialog internal error, could not get version string.", "ooDialog Execute Program: Internal Error");
return -1;
}
return 0;
}
/**
* Grabs the fully qualified executable name.
*
* @param exeName
*
* @return bool
*
* @note This function duplicates some code from commandLineToArgv()
*/
static bool saveExecutableName(char *exeName)
{
LPWSTR *szArglist = NULL;
int32_t nArgs = 0;
char buf[512] = {'\0'}; // Possible error message buffer
szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
if ( NULL == szArglist || nArgs < 1 )
{
sprintf(buf, "Operating system parsing of the command line failed.\n\n"
"Last reported error code: %d\n", GetLastError());
internalErrorMsgBox(buf, "ooDialog Execute Program: Windows Error");
return false;
}
char *tmp = unicode2ansi(szArglist[0]);
if ( tmp )
{
// TODO need to check for fully qualified name ...
strcpy(exeName, tmp);
LocalFree(tmp);
}
else
{
sprintf(buf, "Conversion from Unicode to ANSI, or memory\n"
"allocation, failed.");
internalErrorMsgBox(buf, "ooDialog Execute Program: Windows Error");
return false;
}
return true;
}
/**
* Gets the wide character string command line arguments in conventional argv /
* argc format and converst the argument array to an array of ANSI strings.
*
* @param count
*
* @return An array of null-terminated ANSI strings, or null on error.
*
* @note The returned array does not contain the executable name.
*
* If there is no error, it is the responsibility of the caller to free
* both the returned array and the strings in the array.
*
* On error, there is no memory to free. We free the allocated argv and
* any strings it may point to, even though we do not need to free this
* memory. On error, we are going to immediately exit the program and
* the OS will free the memory. We just do it because it looks a little
* cleaner.
*/
static char **commandLineToArgv(int32_t *count, char *exeName)
{
LPWSTR *szArglist = NULL;
char **args = NULL;
int32_t nArgs = 0;
int32_t i;
char buf[512] = {'\0'}; // Possible error message buffer
szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
if ( NULL == szArglist )
{
sprintf(buf, "Operating system parsing of the command line failed.\n\n"
"Last reported error code: %d\n", GetLastError());
internalErrorMsgBox(buf, "ooDialog Execute Program: Windows Error");
goto done_out;
}
// Need to save the fully qualified executable name.
char *tmp = unicode2ansi(szArglist[0]);
if ( tmp )
{
strcpy(exeName, tmp);
LocalFree(tmp);
if ( PathIsRelative(exeName) )
{
PathFindOnPath(exeName, NULL);
}
}
else
{
sprintf(buf, "Conversion from Unicode to ANSI, or memory\n"
"allocation, failed.");
internalErrorMsgBox(buf, "ooDialog Execute Program: Windows Error");
goto done_out;
}
// For the returned argument array, we are going skip the first arg, the
// executable name.
nArgs--;
args = (char **)LocalAlloc(LPTR, nArgs * sizeof(char **));
if ( args == NULL )
{
sprintf(buf, "Conversion from Unicode to ANSI, or memory\n"
"allocation, failed.");
internalErrorMsgBox(buf, "ooDialog Execute Program: Windows Error");
goto done_out;
}
for ( i = 0; i < nArgs; i++)
{
LPWSTR a = szArglist[i + 1];
if ( wcslen(a) == 0 )
{
sprintf(buf, "Argument %d is the empty string (\"\").\n\n"
"This is not allowed.\n", i + 1);
internalErrorMsgBox(buf, "ooDialog Execute Program: User Error");
goto error_out;
}
tmp = unicode2ansi(a);
if ( tmp )
{
args[i] = tmp;
}
else
{
sprintf(buf, "Conversion from Unicode to ANSI, or memory\n"
"allocation, failed.");
internalErrorMsgBox(buf, "ooDialog Execute Program: Windows Error");
goto error_out;
}
}
goto done_out;
error_out:
if ( args != NULL )
{
for ( int32_t j = 0; j < nArgs; j++ )
{
safeLocalFree(args[j]);
}
LocalFree(args);
}
args = NULL;
nArgs = 0;
done_out:
LocalFree(szArglist);
*count = nArgs;
return args;
}
static bool getFlags(RexxThreadContext *c, pProgramArguments pa, char **argv, int32_t argc, int32_t *currentArg)
{
int32_t i = *currentArg;
while ( i < argc && haveFlag(argv[i]) )
{
switch ( argv[i][1] )
{
case '?' :
case 'h' :
pa->showShortHelp = true;
c->ArrayPut(pa->rxOodArgs, c->String(argv[i]), i + 1);
LocalFree(argv[i]);
break;
case 'H' :
pa->showHelp = true;
c->ArrayPut(pa->rxOodArgs, c->String(argv[i]), i + 1);
LocalFree(argv[i]);
break;
case 's' :
pa->doConfigure = true;
c->ArrayPut(pa->rxOodArgs, c->String(argv[i]), i + 1);
LocalFree(argv[i]);
break;
case 'v' :
pa->showShortVersion = true;
c->ArrayPut(pa->rxOodArgs, c->String(argv[i]), i + 1);
LocalFree(argv[i]);
break;
case 'V' :
pa->showVersion = true;
c->ArrayPut(pa->rxOodArgs, c->String(argv[i]), i + 1);
LocalFree(argv[i]);
break;
case '-' :
if ( stricmp(argv[i], "--version") == 0 )
{
pa->showVersion = true;
c->ArrayPut(pa->rxOodArgs, c->String(argv[i]), i + 1);
LocalFree(argv[i]);
}
else if ( stricmp(argv[i], "--help") == 0 )
{
pa->showHelp = true;
c->ArrayPut(pa->rxOodArgs, c->String(argv[i]), i + 1);
LocalFree(argv[i]);
}
break;
default :
{
char msg[256];
sprintf(msg, "Invalid command line argument:\n\n"
" Argument:\t%s\n"
" Position:\t\t%d\n",
argv[i], i + 1);
internalErrorMsgBox(msg, "ooDialog Execute Program: User Error");
LocalFree(argv[i]);
return false;
}
}
i++;
}
*currentArg = i;
return true;
}
static bool parseArgs(RexxThreadContext *c, pProgramArguments pa, char **argv, int32_t argc, LPSTR lpCmdLine)
{
int32_t currentArg = 0;
bool result = false;
pa->rxOodArgs = c->NewArray(argc);
if ( ! getFlags(c, pa, argv, argc, &currentArg) )
{
displaySyntax(pa);
goto done_out;
}
if ( pa->showShortHelp || pa->showShortVersion || pa->showHelp || pa->showVersion || pa->doConfigure )
{
// If any of these are set, we're done;
result = true;
goto done_out;
}
if ( currentArg >= argc )
{
internalErrorMsgBox("The ooDialog program to execute was not specified.", "ooDialog Execute Program: User Error");
displaySyntax(pa);
goto done_out;
}
size_t prgLen = strlen(argv[currentArg]);
pa->oodProgram = (char *)LocalAlloc(LPTR, prgLen + 1);
if ( pa->oodProgram == NULL )
{
internalErrorMsgBox("The Operating System failed to allocate memory.", "ooDialog Execute Program: Windows Error");
LocalFree(argv[currentArg]);
goto done_out;
}
memcpy((void *)pa->oodProgram, argv[currentArg], prgLen);
LocalFree(argv[currentArg++]);
if ( currentArg >= argc )
{
pa->callArg = c->NewArray(0);
result = true;
goto done_out;
}
char *tmp = strstr(lpCmdLine, pa->oodProgram);
tmp += prgLen;
while( isspace(*tmp) )
{
tmp++;
}
pa->callArg = c->ArrayOfOne(c->String(tmp));
pa->rxCArgs = c->NewArray(argc - currentArg);
for ( int32_t j = 1; currentArg < argc; currentArg++, j++ )
{
c->ArrayPut(pa->rxCArgs, c->String(argv[currentArg]), currentArg + 1);
c->ArrayPut(pa->rxOodArgs, c->String(argv[currentArg]), j);
LocalFree(argv[currentArg]);
}
result = true;
done_out:
LocalFree(argv);
return result;
}
/**
* Standard Windows entry point.
*
* @param hInstance
* @param hPrevInstance
* @param lpCmdLine
* @param nCmdShow
*
* @return int
*
* @notes Testing shows that lpCmdLine is never null.
*
* If the first argument is exactly: -confElevatedAllUsers then this a
* special case. We were in the ConfigureDlgProc procedure and the user
* requested to change or set the All Users file associations, on Vista
* or later, and elevation was required. So, we have been restarted
* through ShellExcuteEx().
*
*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
programArguments pa = { 0 };
int32_t rc = 0;
pa.hInstance = hInstance;
if ( strlen(lpCmdLine) == 0 )
{
pa.allowServices = true;
return displaySyntax(&pa);
}
// Get the command line in a C style argument vector form.
int32_t argc;
char **argv = commandLineToArgv(&argc, pa.exeName);
if ( argv == NULL )
{
return -1;
}
if ( strcmp(argv[0], "-confElevatedAllUsers") == 0 )
{
configureArguments ca = { 0 };
ca.hInstance = hInstance;
ca.wasElevated = true;
ca.exeName = pa.exeName;
DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_CONFIGURE_SERVICES), NULL, ConfigureDlgProc, (LPARAM)&ca);
return 0;
}
// Mostly, we will be executing a Rexx program. parseArgs() needs an
// interpreter thread context, so we create the interpreter here. For the
// few times it is not needed, the overhead is negligible.
RexxThreadContext *c;
RexxInstance *interpreter;
if ( ! RexxCreateInterpreter(&interpreter, &c, NULL) )
{
internalErrorMsgBox("The ooRexx interpreter instance could not be created",
"ooDialog Execute Program: ooRexx Error");
return -1;
}
if ( ! parseArgs(c, &pa, argv, argc, lpCmdLine) )
{
rc = -1;
goto done_out;
}
if ( pa.showVersion || pa.showShortVersion )
{
displayVersion(c, &pa);
goto done_out;
}
if ( pa.showHelp || pa.showShortHelp )
{
pa.allowServices = pa.showHelp ? true : false;
displaySyntax(&pa);
goto done_out;
}
if ( pa.doConfigure )
{
ooDialogServices(&pa);
goto done_out;
}
// We put 2 argument arrays into the .local environment
RexxDirectoryObject localEnv = (RexxDirectoryObject)c->GetLocalEnvironment();
c->DirectoryPut(localEnv, pa.rxCArgs, "SYSCARGS");
c->DirectoryPut(localEnv, pa.rxOodArgs, "OODCARGS");
// Have the interpreter run the program:
RexxObjectPtr result = c->CallProgram(pa.oodProgram, pa.callArg);
if ( c->CheckCondition() )
{
rc = displayCondition(c, &pa);
rc = -rc; // Traditionally, the return code is negated on a condition.
}
else
{
if ( result != NULLOBJECT )
{
c->ObjectToInt32(result, &rc);
}
}
done_out:
interpreter->Terminate();
return rc;
}

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

JavaScript is required for this form.





No, thanks