-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathKLib.Windows.pas
2354 lines (2017 loc) · 66.6 KB
/
KLib.Windows.pas
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
{
KLib Version = 3.0
The Clear BSD License
Copyright (c) 2020 by Karol De Nery Ortiz LLave. All rights reserved.
zitrokarol@gmail.com
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the disclaimer
below) 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 the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
THIS LICENSE. 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 HOLDER 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.
}
unit KLib.Windows;
interface
uses
KLib.Types, Klib.Constants,
Winapi.Windows, Winapi.ShellApi, Winapi.AccCtrl, Winapi.ACLAPI,
System.Classes;
procedure downloadFile(info: TDownloadInfo; forceOverwrite: boolean);
function getFirstPortAvaliable(defaultPort: integer; host: string = LOCALHOST_IP_ADDRESS): integer;
function checkIfPortIsAvaliable(port: Word; host: string = LOCALHOST_IP_ADDRESS): boolean;
function checkIfAddressIsLocalhost(address: string): boolean;
function getIPFromHostName(hostName: string): string; //if hostname is alredy an ip address, returns hostname
function getIP: string;
function checkIfRunUnderWine: boolean;
function checkIfWindowsArchitectureIsX64: boolean;
type
TWindowsArchitecture = (WindowsX86, WindowsX64);
function getWindowsArchitecture: TWindowsArchitecture;
function checkIfUserIsAdmin: boolean;
type
TShowWindowType = (
_SW_HIDE = Winapi.Windows.SW_HIDE,
_SW_SHOWNORMAL = Winapi.Windows.SW_SHOWNORMAL,
_SW_NORMAL = Winapi.Windows.SW_NORMAL,
_SW_SHOWMINIMIZED = Winapi.Windows.SW_SHOWMINIMIZED,
_SW_SHOWMAXIMIZED = Winapi.Windows.SW_SHOWMAXIMIZED,
_SW_MAXIMIZE = Winapi.Windows.SW_MAXIMIZE,
_SW_SHOWNOACTIVATE = Winapi.Windows.SW_SHOWNOACTIVATE,
_SW_SHOW = Winapi.Windows.SW_SHOW,
_SW_MINIMIZE = Winapi.Windows.SW_MINIMIZE,
_SW_SHOWMINNOACTIVE = Winapi.Windows.SW_SHOWMINNOACTIVE,
_SW_SHOWNA = Winapi.Windows.SW_SHOWNA,
_SW_RESTORE = Winapi.Windows.SW_RESTORE,
_SW_SHOWDEFAULT = Winapi.Windows.SW_SHOWDEFAULT,
_SW_FORCEMINIMIZE = Winapi.Windows.SW_FORCEMINIMIZE,
_SW_MAX = Winapi.Windows.SW_MAX
);
procedure openWebPageWithDefaultBrowser(url: string);
procedure openFileWithWord(fileName: string);
function getWordExeFileName: string;
function executeExeAsAdmin(fileName: string; params: string = ''; exceptionIfFunctionFails: boolean = true): integer;
function executeExe(fileName: string; params: string = ''; exceptionIfFunctionFails: boolean = true): integer;
function executeAndWaitExe(fileName: string; params: string = ''; exceptionIfReturnCodeIsNot0: boolean = false): LongInt;
function shellExecuteOpen(fileName: string; params: string = ''; directory: string = ''; showWindowType: TShowWindowType = TShowWindowType._SW_NORMAL;
exceptionIfFunctionFails: boolean = false): integer;
function shellExecuteExeAsAdmin(fileName: string; params: string = ''; showWindowType: TShowWindowType = TShowWindowType._SW_HIDE;
exceptionIfFunctionFails: boolean = false): integer;
function shellExecuteExe(fileName: string; params: string = ''; showWindowType: TShowWindowType = TShowWindowType._SW_HIDE;
exceptionIfFunctionFails: boolean = false; operation: string = 'open'): integer;
function myShellExecute(handle: integer; operation: string; fileName: string; params: string;
directory: string; showWindowType: TShowWindowType; exceptionIfFunctionFails: boolean = false): integer;
function shellExecuteExCMDAndWait(params: string; runAsAdmin: boolean = false;
showWindowType: TShowWindowType = TShowWindowType._SW_HIDE; exceptionIfReturnCodeIsNot0: boolean = false): LongInt;
function shellExecuteExAndWait(fileName: string; params: string = ''; runAsAdmin: boolean = false;
showWindowType: TShowWindowType = TShowWindowType._SW_HIDE; exceptionIfReturnCodeIsNot0: boolean = false): LongInt;
function netShare(targetDir: string; netName: string = ''; netPassw: string = '';
grantAllPermissionToEveryoneGroup: boolean = false): string;
procedure addTCP_IN_FirewallException(ruleName: string; port: Word; description: string = ''; grouping: string = '';
executable: string = '');
procedure deleteFirewallException(ruleName: string);
//#####################################################################################
type
TExplicitAccess = EXPLICIT_ACCESS_A;
procedure grantAllPermissionsNetToTheObjectForTheEveryoneGroup(myObject: string);
procedure grantAllPermissionsNetToTheObjectForTheUsersGroup(myObject: string);
procedure grantAllPermissionNetToTheObject(windowsGroupOrUser: string; myObject: string);
//--------------------------------------------------------------------------------------
procedure grantAllPermissionsToTheObjectForTheEveryoneGroup(myObject: string);
procedure grantAllPermissionsToTheObjectForTheUsersGroup(myObject: string);
procedure grantAllPermissionsToTheObject(windowsGroupOrUser: string; myObject: string);
//--------------------------------------------------------------------------------------
procedure grantAllPermissionsToTheObjectForTheEveryoneGroup2(myObject: string);
procedure grantAllPermissionsToTheObjectForTheUsersGroup2(myObject: string);
procedure grantAllPermissionsToTheObject2(windowsGroupOrUser: string; myObject: string);
//#################################################################################
function checkIfWindowsGroupOrUserExists(windowsGroupOrUser: string): boolean;
procedure createDesktopLink(fileName: string; nameDesktopLink: string; description: string);
function getDesktopDirPath: string;
procedure copyDirIntoTargetDir(sourceDir: string; targetDir: string; forceOverwrite: boolean = NOT_FORCE_OVERWRITE);
procedure copyDir(sourceDir: string; destinationDir: string; silent: boolean = FORCE_SILENT);
procedure createHideDir(dirName: string; forceDelete: boolean = FORCE_DELETE);
procedure deleteDirectoryIfExists(dirName: string; silent: boolean = FORCE_SILENT);
procedure moveFileIntoTargetDir(sourceFileName: string; targetDir: string);
procedure myMoveFile(sourceFileName: string; targetFileName: string);
procedure renameDir(oldDir: string; newDir: string; silent: boolean = FORCE_SILENT);
procedure appendToFileInNewLine(filename: string; text: string; forceCreationFile: boolean = NOT_FORCE); overload;
procedure appendToFile(filename: string; text: string; forceCreationFile: boolean = NOT_FORCE;
forceAppendInNewLine: boolean = NOT_FORCE); overload;
function checkIfIsWindowsSubDir(subDir: string; mainDir: string): boolean;
function getParentDir(source: string): string;
function getValidFullPathInWindowsStyle(path: string): string;
function getPathInWindowsStyle(path: string): string;
function getStringWithEnvVariablesReaded(source: string): string;
//-----------------------------------------------------------------
//TODO REFACTOR
function setProcessWindowToForeground(processName: string): boolean;
function getPIDOfCurrentUserByProcessName(nameProcess: string): DWORD;
function getWindowsUsername: string;
function checkUserOfProcess(userName: String; PID: DWORD): boolean;
function getPIDCredentials(PID: DWORD): TPIDCredentials;
function getPIDByProcessName(nameProcess: string): DWORD;
function getMainWindowHandleByPID(PID: DWORD): DWORD;
//------------------------------------------------------------------
procedure closeApplication(handle: THandle);
function sendMemoryStreamUsing_WM_COPYDATA(handle: THandle; data: TMemoryStream): integer;
function sendStringUsing_WM_COPYDATA(handle: THandle; data: string; msgIdentifier: integer = 0): integer;
procedure mySetForegroundWindow(handle: THandle);
function checkIfWindowExists(className: string = 'TMyForm'; captionForm: string = 'Caption of MyForm'): boolean;
function myFindWindow(className: string = 'TMyForm'; captionForm: string = 'Caption of MyForm'): THandle;
procedure writeIn_HKEY_LOCAL_MACHINE(key: string; name: string; value: Variant; forceCreationKey: boolean = NOT_FORCE);
function readStringFrom_HKEY_LOCAL_MACHINE(key: string; name: string = ''): string;
function checkIfExistsKeyIn_HKEY_LOCAL_MACHINE(key: string): boolean;
procedure deleteKeyInHKEY_LOCAL_MACHINE(key: string);
procedure waitForMultiple(processHandle: THandle; timeout: DWORD = INFINITE; modalMode: boolean = MODAL_MODE);
procedure waitFor(processHandle: THandle; timeout: DWORD = INFINITE; modalMode: boolean = MODAL_MODE);
procedure raiseLastSysErrorMessage;
function getLastSysErrorMessage: string;
function getLocaleDecimalSeparator: char;
procedure terminateCurrentProcess(exitCode: Cardinal = 0; isRaiseExceptionEnabled: boolean = RAISE_EXCEPTION);
procedure myTerminateProcess(processHandle: THandle; exitCode: Cardinal = 0; isRaiseExceptionEnabled: boolean = RAISE_EXCEPTION);
//###########-----NOT WORK ON WINDOWS XP, WINDOWS SERVER 2003, AND EARLIER VERSIONS OF THE WINDOWS OPERATING SYSTEM------------############
function checkIfCurrentProcessIsAServiceProcess: boolean;
function checkIfIsAServiceProcess(processHandle: THandle): boolean;
//###########-----
procedure myAttachConsole(attachToParentIfExists: boolean = true);
function getWMIAsString(wmiClass: string; wmiProperty: string; filter: string = EMPTY_STRING;
wmiHost: string = '.'; root: string = 'root\CIMV2'): string;
function GetWMIstring(wmiHost, root, wmiClass, wmiProperty: string): string;
//################################################################################
function getCurrentPidAsString: string;
function getCurrentPid: integer;
function GetCurrentProcessId: DWORD;
//################################################################################
function getCombinedPathWithCurrentDir(pathToCombine: string): string;
function DirExe: string;
function getDirExe: string;
function exeFileName: string;
function getExeFileName: string;
function getValueOfParameter(parameterNames: TArrayOfStrings): string; overload; //get first param value finded
function getValueOfParameter(parameterNames: TArrayOfStrings; valuesExcluded: TArrayOfStrings): string; overload; //get first param value finded
function getValueOfParameter(parameterName: string): string; overload;
function getValueOfParameter(parameterName: string; valuesExcluded: TArrayOfStrings): string; overload;
function checkIfParameterExists(parameterNames: TArrayOfStrings): boolean; overload;
function checkIfParameterExists(parameterName: string): boolean; overload;
function myParamCount: integer;
function myParamStr(index: integer): string;
function getShellParamsAsString: string;
function getShellParams: TArrayOfStrings;
//################################################################################
function getFileCreationDateTime(fileName: string): TDateTime;
function getFileModifiedDateTime(fileName: string): TDateTime;
function getFileAccessedDateTime(fileName: string): TDateTime;
function getFileTzSpecificLocalTime(fileName: string; fileSystemTimeType: TFileSystemTimeType): TSystemTime;
function getFileSystemTime(fileName: string; fileSystemTimeType: TFileSystemTimeType): TSystemTime;
//################################################################################
//KEPT THE SIGNATURES, NOT RENAME!!!
function IsUserAnAdmin: boolean; external shell32;
function fixedGetNamedSecurityInfo(pObjectName: LPWSTR; ObjectType: SE_OBJECT_TYPE;
SecurityInfo: SECURITY_INFORMATION; ppsidOwner, ppsidGroup: PPSID; ppDacl, ppSacl: PPACL;
var ppSecurityDescriptor: PSECURITY_DESCRIPTOR): DWORD; stdcall;
external 'ADVAPI32.DLL' name 'GetNamedSecurityInfoW';
function GetConsoleWindow: HWnd; stdcall;
external 'kernel32.dll' name 'GetConsoleWindow';
function AttachConsole(ProcessId: DWORD): BOOL; stdcall;
external 'kernel32.dll' name 'AttachConsole';
var
shellParams: TArrayOfStrings;
implementation
uses
KLib.Utils, KLib.Validate, KLib.MyStringList,
Vcl.Forms,
Winapi.TLHelp32, Winapi.ActiveX, Winapi.Shlobj, Winapi.Winsock, Winapi.UrlMon, Winapi.Messages,
System.SysUtils, System.Win.ComObj, System.Win.Registry, System.Variants, System.StrUtils,
IdTCPClient;
procedure downloadFile(info: TDownloadInfo; forceOverwrite: boolean);
const
ERR_MSG = 'Error downloading file.';
var
_downloadSuccess: boolean;
_links: TStringList;
i: integer;
begin
if forceOverwrite then
begin
deleteFileIfExists(info.fileName);
end;
_downloadSuccess := false;
i := 0;
_links := TStringList.Create;
_links.Add(info.link);
_links.AddStrings(info.alternative_links);
try
while (not _downloadSuccess) and (i < _links.Count) do
begin
_downloadSuccess := URLDownloadToFile(nil, pChar(_links[i]), pchar(info.fileName), 0, nil) = S_OK;
Inc(i);
end;
finally
FreeAndNil(_links);
end;
if not _downloadSuccess then
begin
raise Exception.Create(ERR_MSG);
end;
if info.MD5 <> '' then
begin
validateMD5File(info.fileName, info.MD5, ERR_MSG);
end;
end;
function getFirstPortAvaliable(defaultPort: integer; host: string = LOCALHOST_IP_ADDRESS): integer;
var
port: integer;
begin
port := defaultPort;
while not checkIfPortIsAvaliable(port, host) do
begin
inc(port);
end;
Result := port;
end;
function checkIfPortIsAvaliable(port: Word; host: string = LOCALHOST_IP_ADDRESS): boolean;
var
isPortAvaliable: boolean;
_IdTCPClient: TIdTCPClient;
begin
isPortAvaliable := True;
try
_IdTCPClient := TIdTCPClient.Create(nil);
try
_IdTCPClient.Host := host;
_IdTCPClient.Port := port;
_IdTCPClient.Connect;
isPortAvaliable := False;
finally
_IdTCPClient.Free;
end;
except
//Ignore exceptions
end;
Result := isPortAvaliable;
end;
function checkIfAddressIsLocalhost(address: string): boolean;
var
addressIsLocalhost: boolean;
_address: string;
_localhostIP_address: string;
begin
addressIsLocalhost := true;
_address := getIPFromHostName(address);
if _address <> LOCALHOST_IP_ADDRESS then
begin
_localhostIP_address := getIP;
if _address <> _localhostIP_address then
begin
addressIsLocalhost := false;
end;
end;
Result := addressIsLocalhost;
end;
function getIPFromHostName(hostName: string): string;
const
ERR_WINSOCK_MSG = 'Winsock initialization error.';
ERR_NO_IP_FOUND_WITH_HOSTBAME_MSG = 'No IP found with hostname: ';
var
ip: string;
_varTWSAData: TWSAData;
_varPHostEnt: PHostEnt;
_varTInAddr: TInAddr;
begin
if WSAStartup($101, _varTWSAData) <> 0 then
begin
raise Exception.Create(ERR_WINSOCK_MSG);
end
else
begin
try
_varPHostEnt := gethostbyname(PAnsiChar(AnsiString(hostName)));
_varTInAddr := PInAddr(_varPHostEnt^.h_Addr_List^)^;
ip := String(inet_ntoa(_varTInAddr));
except
on E: Exception do
begin
WSACleanup;
raise Exception.Create(ERR_NO_IP_FOUND_WITH_HOSTBAME_MSG + hostName);
end;
end;
end;
WSACleanup;
Result := ip;
end;
function getIP: string;
type
pu_long = ^u_long;
const
ERR_MSG = 'Winsock initialization error.';
var
ip: string;
_varTWSAData: TWSAData;
_varPHostEnt: PHostEnt;
_varTInAddr: TInAddr;
_namebuf: Array [0 .. 255] of ansichar;
begin
if WSAStartup($101, _varTWSAData) <> 0 then
begin
raise Exception.Create(ERR_MSG);
end
else
begin
getHostName(_nameBuf, sizeOf(_nameBuf));
_varPHostEnt := gethostbyname(_nameBuf);
_varTInAddr.S_addr := u_long(pu_long(_varPHostEnt^.h_addr_list^)^);
ip := string(inet_ntoa(_varTInAddr));
end;
WSACleanup;
Result := ip;
end;
function checkIfRunUnderWine: boolean;
const
KEY_WINE = 'Software\Wine';
begin
Result := checkIfExistsKeyIn_HKEY_LOCAL_MACHINE(KEY_WINE);
end;
function checkIfWindowsArchitectureIsX64: boolean;
var
_windowsArchitecture: TWindowsArchitecture;
begin
_windowsArchitecture := getWindowsArchitecture;
Result := _windowsArchitecture = TWindowsArchitecture.WindowsX64;
end;
function getWindowsArchitecture: TWindowsArchitecture;
const
ERR_MSG_PLATFORM = 'The OS. is not Windows.';
ERR_MSG_ARCHITECTURE = 'Unknown OS architecture.';
var
windowsArchitecture: TWindowsArchitecture;
begin
if TOSVersion.Platform <> pfWindows then
begin
raise Exception.Create(ERR_MSG_PLATFORM);
end;
case TOSVersion.Architecture of
arIntelX86:
windowsArchitecture := TWindowsArchitecture.WindowsX86;
arIntelX64:
windowsArchitecture := TWindowsArchitecture.WindowsX64;
else
begin
raise Exception.Create(ERR_MSG_ARCHITECTURE);
end;
end;
Result := windowsArchitecture;
end;
function checkIfUserIsAdmin: boolean;
begin
Result := IsUserAnAdmin;
end;
procedure openWebPageWithDefaultBrowser(url: string);
begin
shellExecuteOpen(url);
end;
procedure openFileWithWord(fileName: string);
var
winwordFileName: string;
begin
winwordFileName := getWordExeFileName();
shellExecuteOpen(winwordFileName, getDoubleQuotedString(fileName));
end;
function getWordExeFileName: string;
const
REG_KEY = '\Software\Microsoft\Windows\CurrentVersion\App Paths\Winword.exe';
begin
Result := readStringFrom_HKEY_LOCAL_MACHINE(REG_KEY);
end;
function executeExeAsAdmin(fileName: string; params: string = ''; exceptionIfFunctionFails: boolean = true): integer;
var
returnCode: integer;
begin
returnCode := shellExecuteExeAsAdmin(fileName, params, TShowWindowType._SW_HIDE, exceptionIfFunctionFails);
Result := returnCode;
end;
function executeExe(fileName: string; params: string = ''; exceptionIfFunctionFails: boolean = true): integer;
var
returnCode: integer;
begin
returnCode := shellExecuteExe(fileName, params, TShowWindowType._SW_HIDE, exceptionIfFunctionFails);
Result := returnCode;
end;
function executeAndWaitExe(fileName: string; params: string = ''; exceptionIfReturnCodeIsNot0: boolean = false): LongInt;
var
returnCode: Longint;
_commad: String;
_startupInfo: TStartupInfo;
_processInfo: TProcessInformation;
begin
returnCode := -1;
_commad := getDoubleQuotedString(fileName) + ' ' + trim(params);
FillChar(_startupInfo, sizeOf(_startupInfo), 0);
with _startupInfo do
begin
cb := SizeOf(TStartupInfo);
wShowWindow := Winapi.Windows.SW_HIDE;
end;
if not CreateProcess(nil, pchar(_commad), nil, nil, false,
// CREATE_NO_WINDOW,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, //TODO check if is ok
nil, nil, _startupInfo, _processInfo) then
begin
raiseLastSysErrorMessage;
end;
//TODO CHECK
waitForMultiple(_processInfo.hProcess);
// waitFor(_processInfo.hProcess);
if not GetExitCodeProcess(_processInfo.hProcess, dword(returnCode)) then //assign return code
begin
raiseLastSysErrorMessage;
end;
CloseHandle(_processInfo.hProcess);
CloseHandle(_processInfo.hThread);
if (exceptionIfReturnCodeIsNot0) and (returnCode <> 0) then
begin
raise Exception.Create(fileName + ' exit code: ' + IntToStr(returnCode));
end;
Result := returnCode;
end;
function shellExecuteOpen(fileName: string; params: string = ''; directory: string = ''; showWindowType: TShowWindowType = TShowWindowType._SW_NORMAL;
exceptionIfFunctionFails: boolean = false): integer;
var
returnCode: integer;
begin
returnCode := myShellExecute(0, 'open', fileName, params, directory, showWindowType, exceptionIfFunctionFails);
Result := returnCode;
end;
function shellExecuteExeAsAdmin(fileName: string; params: string = ''; showWindowType: TShowWindowType = TShowWindowType._SW_HIDE;
exceptionIfFunctionFails: boolean = false): integer;
var
returnCode: integer;
begin
returnCode := shellExecuteExe(fileName, params, showWindowType, exceptionIfFunctionFails, 'runas');
Result := returnCode;
end;
function shellExecuteExe(fileName: string; params: string = ''; showWindowType: TShowWindowType = TShowWindowType._SW_HIDE;
exceptionIfFunctionFails: boolean = false; operation: string = 'open'): integer;
var
returnCode: integer;
_directory: string;
begin
_directory := ExtractFileDir(fileName);
returnCode := myShellExecute(0, operation, getDoubleQuotedString(fileName), params, _directory, showWindowType, exceptionIfFunctionFails);
Result := returnCode;
end;
function myShellExecute(handle: integer; operation: string; fileName: string; params: string;
directory: string; showWindowType: TShowWindowType; exceptionIfFunctionFails: boolean = false): integer;
var
returnCode: integer;
errMsg: string;
begin
returnCode := shellExecute(handle, pchar(operation), pchar(fileName), PCHAR(trim(params)),
pchar(directory), integer(showWindowType));
if exceptionIfFunctionFails then
begin
case returnCode of
0:
errMsg := 'The operating system is out of memory or resources.';
2:
errMsg := 'The specified file was not found';
3:
errMsg := 'The specified path was not found.';
5:
errMsg := 'Windows 95 only: The operating system denied access to the specified file';
8:
errMsg := 'Windows 95 only: There was not enough memory to complete the operation.';
10:
errMsg := 'Wrong Windows version';
11:
errMsg := 'The .EXE file is invalid (non-Win32 .EXE or error in .EXE image)';
12:
errMsg := 'Application was designed for a different operating system';
13:
errMsg := 'Application was designed for MS-DOS 4.0';
15:
errMsg := 'Attempt to load a real-mode program';
16:
errMsg := 'Attempt to load a second instance of an application with non-readonly data segments.';
19:
errMsg := 'Attempt to load a compressed application file.';
20:
errMsg := 'Dynamic-link library (DLL) file failure.';
26:
errMsg := 'A sharing violation occurred.';
27:
errMsg := 'The filename association is incomplete or invalid.';
28:
errMsg := 'The DDE transaction could not be completed because the request timed out.';
29:
errMsg := 'The DDE transaction failed.';
30:
errMsg := 'The DDE transaction could not be completed because other DDE transactions were being processed.';
31:
errMsg := 'There is no application associated with the given extension.';
32:
errMsg := 'Windows 95 only: The specified dynamic-link library was not found.';
else
errMsg := '';
end;
if errMsg <> '' then
begin
raise Exception.Create(errMsg);
end;
end;
Result := returnCode;
end;
function shellExecuteExCMDAndWait(params: string; runAsAdmin: boolean = false;
showWindowType: TShowWindowType = TShowWindowType._SW_HIDE; exceptionIfReturnCodeIsNot0: boolean = false): LongInt;
begin
Result := shellExecuteExAndWait(CMD_EXE_NAME, params, runAsAdmin, showWindowType, exceptionIfReturnCodeIsNot0);
end;
function shellExecuteExAndWait(fileName: string; params: string = ''; runAsAdmin: boolean = false;
showWindowType: TShowWindowType = TShowWindowType._SW_HIDE; exceptionIfReturnCodeIsNot0: boolean = false): LongInt;
var
returnCode: Longint;
_shellExecuteInfo: TShellExecuteInfo;
begin
returnCode := -1;
FillChar(_shellExecuteInfo, SizeOf(_shellExecuteInfo), 0);
with _shellExecuteInfo do
begin
cbSize := SizeOf(_shellExecuteInfo);
fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
Wnd := GetActiveWindow();
if (runAsAdmin) then
begin
_shellExecuteInfo.lpVerb := 'runas';
end
else
begin
_shellExecuteInfo.lpVerb := '';
end;
_shellExecuteInfo.lpParameters := PChar(trim(params));
lpFile := PChar(FileName);
nShow := integer(showWindowType);
end;
if not ShellExecuteEx(@_shellExecuteInfo) then
begin
raiseLastSysErrorMessage;
end;
//TODO CHECK
waitForMultiple(_shellExecuteInfo.hProcess);
// waitFor(_shellExecuteInfo.hProcess);
if not GetExitCodeProcess(_shellExecuteInfo.hProcess, dword(returnCode)) then //assign return code
begin
raiseLastSysErrorMessage;
end;
CloseHandle(_shellExecuteInfo.hProcess);
if (exceptionIfReturnCodeIsNot0) and (returnCode <> 0) then
begin
raise Exception.Create(fileName + ' exit code: ' + IntToStr(returnCode));
end;
Result := returnCode;
end;
type
//----------------------------------
SHARE_INFO_2 = record
shi2_netname: pWideChar;
shi2_type: DWORD;
shi2_remark: pWideChar;
shi2_permissions: DWORD;
shi2_max_uses: DWORD;
shi2_current_uses: DWORD;
shi2_path: pWideChar;
shi2_passwd: pWideChar;
end;
PSHARE_INFO_2 = ^SHARE_INFO_2;
function netShareAdd(servername: PWideChar; level: DWORD; buf: Pointer; parm_err: LPDWORD): DWORD; stdcall;
external 'NetAPI32.dll' name 'NetShareAdd';
function netShare(targetDir: string; netName: string = ''; netPassw: string = '';
grantAllPermissionToEveryoneGroup: boolean = false): string;
const
NERR_SUCCESS = 0;
STYPE_DISKTREE = 0;
STYPE_PRINTQ = 1;
STYPE_DEVICE = 2;
STYPE_IPC = 3;
ACCESS_READ = $01;
ACCESS_WRITE = $02;
ACCESS_CREATE = $04;
ACCESS_EXEC = $08;
ACCESS_DELETE = $10;
ACCESS_ATRIB = $20;
ACCESS_PERM = $40;
ACCESS_ALL = ACCESS_READ or ACCESS_WRITE or ACCESS_CREATE or ACCESS_EXEC or ACCESS_DELETE or ACCESS_ATRIB or ACCESS_PERM;
ERR_MSG = 'Unable to share folder :';
var
pathSharedDir: string;
_targetDir: string;
_AShareInfo: PSHARE_INFO_2;
_parmError: DWORD;
_shareExistsAlready: boolean;
_errMsg: string;
begin
_shareExistsAlready := false;
_targetDir := getValidFullPathInWindowsStyle(targetDir);
_AShareInfo := New(PSHARE_INFO_2);
try
with _AShareInfo^ do
begin
if (netName = '') then
begin
shi2_netname := PWideChar(extractfilename(_targetDir));
end
else
begin
shi2_netname := PWideChar(netName);
end;
shi2_type := STYPE_DISKTREE;
shi2_remark := nil;
shi2_permissions := ACCESS_ALL;
shi2_max_uses := DWORD(-1); // Maximum allowed
shi2_current_uses := 0;
shi2_path := PWideChar(_targetDir);
if (netPassw = '') then
begin
shi2_passwd := nil;
end
else
begin
shi2_passwd := PWideChar(netPassw);
end;
end;
if (netShareAdd(nil, 2, PBYTE(_AShareInfo), @_parmError) <> NERR_SUCCESS) then
begin
_shareExistsAlready := true;
end;
if not checkIfDirExists(pathSharedDir) then
begin
_errMsg := ERR_MSG + getDoubleQuotedString(_targetDir);
raise Exception.Create(_errMsg);
end;
pathSharedDir := '\\' + GetEnvironmentVariable('COMPUTERNAME') + '\' + _AShareInfo.shi2_netname;
if not(_shareExistsAlready) and (grantAllPermissionToEveryoneGroup) then
begin
grantAllPermissionsNetToTheObjectForTheEveryoneGroup(pathSharedDir);
end;
finally
FreeMem(_AShareInfo, SizeOf(PSHARE_INFO_2));
end;
Result := pathSharedDir;
end;
procedure addTCP_IN_FirewallException(ruleName: string; port: Word; description: string = ''; grouping: string = '';
executable: String = '');
const
NET_FW_PROFILE2_DOMAIN = 1;
NET_FW_PROFILE2_PRIVATE = 2;
NET_FW_PROFILE2_PUBLIC = 4;
PROFILES = NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC OR NET_FW_PROFILE2_DOMAIN;
NET_FW_IP_PROTOCOL_TCP = 6;
NET_FW_ACTION_ALLOW = 1;
NET_FW_RULE_DIR_IN = 1;
NET_FW_RULE_DIR_OUT = 2;
var
FwPolicy2: OleVariant;
rules: OleVariant;
newFWRule: OleVariant;
begin
CoInitialize(nil);
newFWRule := CreateOleObject('HNetCfg.FWRule');
newFWRule.Name := ruleName;
if (description <> '') then
begin
newFWRule.Description := description;
end
else
begin
newFWRule.Description := ruleName;
end;
if (executable <> '') then
begin
newFWRule.Applicationname := executable;
end;
newFWRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
newFWRule.LocalPorts := port;
newFWRule.Direction := NET_FW_RULE_DIR_IN;
newFWRule.Enabled := TRUE;
if (grouping <> '') then
begin
newFWRule.Grouping := grouping;
end;
newFWRule.Profiles := PROFILES;
newFWRule.Action := NET_FW_ACTION_ALLOW;
FwPolicy2 := CreateOleObject('HNetCfg.FwPolicy2');
rules := FwPolicy2.Rules;
rules.Add(newFWRule);
CoUninitialize;
end;
procedure deleteFirewallException(ruleName: string);
var
FwPolicy2: OleVariant;
rules: OleVariant;
begin
CoInitialize(nil);
FwPolicy2 := CreateOleObject('HNetCfg.FwPolicy2');
rules := FwPolicy2.Rules;
rules.Remove(ruleName);
CoUninitialize;
end;
procedure grantAllPermissionsNetToTheObjectForTheEveryoneGroup(myObject: string);
begin
grantAllPermissionNetToTheObject(EVERYONE_GROUP, myObject);
end;
procedure grantAllPermissionsNetToTheObjectForTheUsersGroup(myObject: string);
begin
grantAllPermissionNetToTheObject(USERS_GROUP, myObject);
end;
procedure grantAllPermissionNetToTheObject(windowsGroupOrUser: string; myObject: string);
var
NewDacl, OldDacl: PACl;
SD: PSECURITY_DESCRIPTOR;
EA: TExplicitAccess;
begin
validateThatWindowsGroupOrUserExists(windowsGroupOrUser);
fixedGetNamedSecurityInfo(PChar(myObject), SE_LMSHARE, DACL_SECURITY_INFORMATION, nil, nil, @OldDacl, nil, SD);
BuildExplicitAccessWithName(@EA, PChar(windowsGroupOrUser), GENERIC_ALL, GRANT_ACCESS, SUB_CONTAINERS_AND_OBJECTS_INHERIT);
SetEntriesInAcl(1, @EA, OldDacl, NewDacl);
SetNamedSecurityInfo(PChar(myObject), SE_LMSHARE, DACL_SECURITY_INFORMATION, nil, nil, NewDacl, nil);
end;
procedure grantAllPermissionsToTheObjectForTheEveryoneGroup(myObject: string);
begin
grantAllPermissionsToTheObject(EVERYONE_GROUP, myObject);
end;
procedure grantAllPermissionsToTheObjectForTheUsersGroup(myObject: string);
begin
grantAllPermissionsToTheObject(USERS_GROUP, myObject);
end;
procedure grantAllPermissionsToTheObject(windowsGroupOrUser: string; myObject: string);
var
newDACL: PACl;
oldDACL: PACl;
securityDescriptor: PSECURITY_DESCRIPTOR;
explicitAccess: TExplicitAccess;
begin
validateThatWindowsGroupOrUserExists(windowsGroupOrUser);
fixedGetNamedSecurityInfo(PChar(myObject), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nil, nil, @oldDACL,
nil, securityDescriptor);
BuildExplicitAccessWithName(@explicitAccess, PChar(windowsGroupOrUser), GENERIC_ALL, GRANT_ACCESS,
SUB_CONTAINERS_AND_OBJECTS_INHERIT);
SetEntriesInAcl(1, @explicitAccess, oldDACL, newDACL);
SetNamedSecurityInfo(PChar(myObject), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nil, nil, newDACL, nil);
end;
procedure grantAllPermissionsToTheObjectForTheEveryoneGroup2(myObject: string);
begin
grantAllPermissionsToTheObject2(EVERYONE_GROUP, myObject);
end;
procedure grantAllPermissionsToTheObjectForTheUsersGroup2(myObject: string);
begin
grantAllPermissionsToTheObject2(USERS_GROUP, myObject);
end;
procedure grantAllPermissionsToTheObject2(windowsGroupOrUser: string; myObject: string);
begin
validateThatWindowsGroupOrUserExists(windowsGroupOrUser);
shellExecuteExeAsAdmin('icacls', getDoubleQuotedString(myObject) + ' /grant ' + getDoubleQuotedString(windowsGroupOrUser) + ':(OI)(CI)F /T');
end;
function checkIfWindowsGroupOrUserExists(windowsGroupOrUser: string): boolean;
var
windowsGroupOrUserExists: boolean;
_newDACL: PACl;
_explicitAccess: TExplicitAccess;
begin
BuildExplicitAccessWithName(@_explicitAccess, PChar(windowsGroupOrUser), GENERIC_ALL, GRANT_ACCESS,
SUB_CONTAINERS_AND_OBJECTS_INHERIT);
SetEntriesInAcl(1, @_explicitAccess, nil, _newDACL);
windowsGroupOrUserExists := Assigned(_newDACL);
Result := windowsGroupOrUserExists;
end;
procedure createDesktopLink(fileName: string; nameDesktopLink: string; description: string);
const
ERR_MSG = 'Error creating desktop icon.';
var
iobject: iunknown;
islink: ishelllink;
ipfile: ipersistfile;
pidl: pitemidlist;
infolder: array [0 .. MAX_PATH] of char;
targetName: string;
linkname: string;
_desktopDirPath: string;
begin
targetname := getValidFullPathInWindowsStyle(fileName);
IObject := CreateComObject(CLSID_ShellLink);
ISLink := IObject as IShellLink;
IPFile := IObject as IPersistFile;
with ISLink do
begin
SetDescription(PChar(description));
SetPath(PChar(targetName));
SetWorkingDirectory(PChar(ExtractFilePath(targetName)));
end;
SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, PIDL);
SHGetPathFromIDList(PIDL, InFolder);
_desktopDirPath := getDesktopDirPath;
LinkName := IncludeTrailingPathDelimiter(_desktopDirPath);
LinkName := LinkName + nameDesktopLink + '.lnk';
if not IPFile.Save(PWideChar(LinkName), False) = S_OK then
begin
raise Exception.Create(ERR_MSG);
end;
end;
function getDesktopDirPath: string;
var
desktopDirPath: string;
_PIDList: PItemIDList;
_Buffer: array [0 .. MAX_PATH - 1] of Char;
begin
desktopDirPath := '';
SHGetSpecialFolderLocation(0, CSIDL_DESKTOP, _PIDList);
if Assigned(_PIDList) then
begin
if SHGetPathFromIDList(_PIDList, _Buffer) then
begin
desktopDirPath := _Buffer;
end;
end;
Result := desktopDirPath;
end;
procedure copyDirIntoTargetDir(sourceDir: string; targetDir: string; forceOverwrite: boolean = NOT_FORCE_OVERWRITE);
var
_parentDirTargetDir: string;
_sourceDirName: string;
_tempTargetDir: string;
begin
if forceOverwrite then