-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtiscommonwin.inc
More file actions
1504 lines (1364 loc) · 42.6 KB
/
tiscommonwin.inc
File metadata and controls
1504 lines (1364 loc) · 42.6 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
{ -----------------------------------------------------------------------
# This file is part of WAPT
# Copyright (C) 2013 Tranquil IT Systems http://www.tranquil.it
# WAPT aims to help Windows systems administrators to deploy
# setup and update applications on users PC.
#
# Part of this file is based on JEDI JCL library
#
# WAPT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WAPT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WAPT. If not, see <http://www.gnu.org/licenses/>.
#
# -----------------------------------------------------------------------
}
function IsAdminLoggedOn: Boolean;
{ Returns True if the logged-on user is a member of the Administrators local
group. Always returns True on Windows 9x/Me. }
const
DOMAIN_ALIAS_RID_ADMINS = $00000220;
begin
Result := UserInGroup(DOMAIN_ALIAS_RID_ADMINS);
end;
function UserInGroupWindows(Group :DWORD) : Boolean;
var
pIdentifierAuthority :TSidIdentifierAuthority;
apSid : PSID;
IsMember : BOOL;
begin
pIdentifierAuthority := SECURITY_NT_AUTHORITY;
Result := AllocateAndInitializeSid(@pIdentifierAuthority,2, SECURITY_BUILTIN_DOMAIN_RID, Group, 0, 0, 0, 0, 0, 0, apSid);
try
if Result then
if not CheckTokenMembership(0, apSid, IsMember) then //passing 0 means which the function will be use the token of the calling thread.
Result:= False
else
Result:=IsMember;
finally
FreeSid(apSid);
end;
end;
function UserInGroup(Group: DWORD): Boolean;
begin
Result := UserInGroupWindows(group);
end;
type
WinIsWow64 = function( Handle: THandle; var Iret: BOOL ): BOOL; stdcall;
//from http://stackoverflow.com/questions/1436185/how-can-i-tell-if-im-running-on-x64
function IsWin64: Boolean;
var
HandleTo64BitsProcess: WinIsWow64;
Iret : BOOL;
begin
Result := False;
HandleTo64BitsProcess := WinIsWow64(pointer( GetProcAddress(GetModuleHandle('kernel32.dll'), 'IsWow64Process')));
if Assigned(HandleTo64BitsProcess) then
begin
if not HandleTo64BitsProcess(GetCurrentProcess, Iret) then
Raise Exception.Create('Invalid handle');
Result := Iret;
end;
end;
function GetAccountSid(const Server, User: WideString; var Sid: PSID): DWORD;
var
dwDomainSize, dwSidSize: DWord;
R : LongBool;
wDomain : WideString;
Use : DWord;
begin
Result := 0;
SetLastError(0);
dwSidSize := 0;
dwDomainSize := 0;
R := LookupAccountNameW(PWideChar(Server), PWideChar(User), nil, dwSidSize,
nil, dwDomainSize, Use);
if (not R) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
SetLength(wDomain, dwDomainSize);
Sid := GetMemory(dwSidSize);
R := LookupAccountNameW(PWideChar(Server), PWideChar(User), Sid,
dwSidSize, PWideChar(wDomain), dwDomainSize, Use);
if not R then
begin
FreeMemory(Sid);
Sid := nil;
end;
end
else
Result := GetLastError;
end;
function GetAccountSidString(const Server, User: WideString):String;
var
ASID:PSid;
begin
ASID:=Nil;
try
if GetAccountSid(Server,User,ASID)=0 then
Result := SIDToStringSID(ASID)
else
Result := '';
finally
if ASID<>Nil then
Freememory(ASID);
end;
end;
(*
* Procedure : StrSIDToName
* Author : MPu
*)
function StrSIDToName(const StrSID: AnsiString; var Name: Ansistring; var SIDType: DWORD): Boolean;
var
SID : PSID;
Buffer : PAnsiChar;
NameLen, TempLen : Cardinal;
err : Boolean;
begin
SID := nil;
err := ConvertStringSIDToSID(PChar(StrSID), SID);
if err then
begin
NameLen := 0;
TempLen := 0;
LookupAccountSidA(nil, SID, nil, NameLen, nil, TempLen, SIDType);
GetMem(Buffer, NameLen);
try
err := LookupAccountSidA(nil, SID, Buffer, NameLen, nil, TempLen, SIDType);
if err then
SetString(Name, Buffer, Namelen);
finally
FreeMem(Buffer);
end;
end;
if Assigned(SID) then
LocalFree(Cardinal(SID));
result := err;
end;
function SIDToStringSID(const aSID:PSID): String;
var
Buffer : PAnsiChar;
err : Boolean;
begin
err := ConvertSidToStringSid(aSID,Buffer);
if err then
begin
Result := String(Buffer);
if Assigned(Buffer) then
LocalFree(HLocal(Buffer));
end
else
Result :='';
end;
(*
* Procedure : AddToGroup
* Author : MPu
* Adds a domain account to a local group
*)
function AddToGroup(const member, Group: WideString): NET_API_STATUS;
var
memberInfo : LOCALGROUP_MEMBERS_INFO_3;
NetError : DWORD;
begin
NetError := 0;
if (member <> '') and (Group <> '') then
begin
memberInfo.lgrmi3_domainandname:=PWideChar(member);
NetError := NetLocalGroupAddMembers(Nil, PWideChar(Group), 3, @memberInfo, 1);
if NetError = 1378 then //Le nom de compte spécifié est déjà membre du groupe"
NetError := 0;
end;
result := NetError;
end;
(*
* Procedure : UserModalsGet
* Author : MPu
* Password stuff
*)
function UserModalsGet(const Server: String): USER_MODALS_INFO_0;
var
UserModalsInfo : PUSER_MODALS_INFO_0;
dwRet : DWORD;
begin
FillZero(Result,SizeOf(Result));
UserModalsInfo := nil;
dwRet := NetUserModalsGet(nil, 0, Pointer(UserModalsInfo));
if ((dwRet = NERR_Success) and Assigned(UserModalsInfo)) then
begin
result.usrmod0_min_passwd_len := UserModalsInfo^.usrmod0_min_passwd_len;
result.usrmod0_max_passwd_age := UserModalsInfo^.usrmod0_max_passwd_age;
result.usrmod0_min_passwd_age := UserModalsInfo^.usrmod0_min_passwd_age;
result.usrmod0_force_logoff := UserModalsInfo^.usrmod0_force_logoff;
result.usrmod0_password_hist_len := UserModalsInfo^.usrmod0_password_hist_len;
NetApiBufferFree(UserModalsInfo);
end;
end;
function DomainGet: String;
var
UserModalsInfo : PUSER_MODALS_INFO_2;
dwRet : DWORD;
begin
result := '';
UserModalsInfo := nil;
dwRet := NetUserModalsGet(nil, 2, Pointer(UserModalsInfo));
if ((dwRet = NERR_Success) and Assigned(UserModalsInfo)) then
begin
Result := UserModalsInfo^.usrmod2_domain_name;
//result.usrmod2_domain_id := UserModalsInfo^.usrmod2_domain_id;
NetApiBufferFree(UserModalsInfo);
end;
end;
function DomainSID: String;
var
UserModalsInfo : PUSER_MODALS_INFO_2;
dwRet : DWORD;
begin
Result := '';
UserModalsInfo := nil;
dwRet := NetUserModalsGet(nil, 2, Pointer(UserModalsInfo));
if ((dwRet = NERR_Success) and Assigned(UserModalsInfo)) then
begin
Result := SIDToStringSID(UserModalsInfo^.usrmod2_domain_id);
//result.usrmod2_domain_id := UserModalsInfo^.usrmod2_domain_id;
NetApiBufferFree(UserModalsInfo);
end;
end;
function GetJoinInformation:String;
var
name: LPWSTR;
status: NETSETUP_JOIN_STATUS;
begin
Result := '';
Name := Nil;
if NetGetJoinInformation(Nil,name,@status)=NERR_Success then
begin
if status=NetSetupDomainName then
Result := name;
NetApiBufferFree(name);
end;
end;
function EnablePrivilege(const Privilege: string; fEnable: Boolean; out PreviousState: Boolean): DWORD;
var
Token : THandle;
NewState : TTokenPrivileges;
Luid : _LUID;
PrevState : TTokenPrivileges;
Return : DWORD;
begin
PreviousState := True;
if (GetVersion() > $80000000) then
// Win9x
Result := ERROR_SUCCESS
else
begin
// WinNT
if not OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, Token) then
Result := GetLastError()
else
try
if not LookupPrivilegeValue(nil, PChar(Privilege), Luid) then
Result := GetLastError()
else
begin
NewState.PrivilegeCount := 1;
NewState.Privileges[0].Luid := Luid;
if fEnable then
NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
else
NewState.Privileges[0].Attributes := 0;
if not AdjustTokenPrivileges(Token, False, @NewState,
SizeOf(TTokenPrivileges), @PrevState, @Return) then
Result := GetLastError()
else
begin
Result := ERROR_SUCCESS;
PreviousState :=
(PrevState.Privileges[0].Attributes and SE_PRIVILEGE_ENABLED <> 0);
end;
end;
finally
CloseHandle(Token);
end;
end;
end;
function GetAdminSid: PSID;
// Author : Nico Bendlin
const
// bekannte SIDs ... (WinNT.h)
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
// bekannte RIDs ... (WinNT.h)
SECURITY_BUILTIN_DOMAIN_RID: DWORD = $00000020;
DOMAIN_ALIAS_RID_ADMINS: DWORD = $00000220;
begin
Result := nil;
AllocateAndInitializeSid(@SECURITY_NT_AUTHORITY, 2,
SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, Result);
end;
function IsAdmin: LongBool;
// Author : Nico Bendlin
var
TokenHandle : THandle;
ReturnLength : DWORD;
TokenInformation : PTokenGroups;
AdminSid : PSID;
Loop : Integer;
begin
Result := False;
TokenHandle := 0;
if OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, TokenHandle) then
try
ReturnLength := 0;
GetTokenInformation(TokenHandle, TokenGroups, nil, 0, ReturnLength);
TokenInformation := GetMemory(ReturnLength);
if Assigned(TokenInformation) then
try
if GetTokenInformation(TokenHandle, TokenGroups, TokenInformation,
ReturnLength, ReturnLength) then
begin
AdminSid := GetAdminSid;
for Loop := 0 to TokenInformation^.GroupCount - 1 do
begin
if EqualSid(TokenInformation^.Groups[Loop].Sid, AdminSid) then
begin
Result := True;
Break;
end;
end;
FreeSid(AdminSid);
end;
finally
FreeMemory(TokenInformation);
end;
finally
CloseHandle(TokenHandle);
end;
end;
procedure AddToUserPath(APath:String);
var
SystemPath : String;
begin
with TRegistry.Create do
try
//RootKey:=HKEY_LOCAL_MACHINE;
OpenKey('Environment',False);
SystemPath:=ReadString('PATH');
if pos(LowerCase(APath),LowerCase(SystemPath))=0 then
begin
if RightStr(SystemPath,1)<>';' then SystemPath:=SystemPath+';';
SystemPath:=SystemPath+APath;
if RightStr(SystemPath,1)<>';' then SystemPath:=SystemPath+';';
WriteString('PATH',SystemPath);
end;
finally
Free;
end;
end;
procedure UpdateApplication(fromURL:String;SetupExename,SetupParams,ExeName,RestartParam:String);
var
bat: TextFile;
tempdir,tempfn,updateBatch,zipfn,version : String;
files:TStringList;
UnZipper: TZipRead;
i,hinstance:integer;
begin
Files := TStringList.Create;
try
Logger('Updating application...');
tempdir := GetUniqueTempdir('tis');
if ExeName='' then
ExeName :=ExtractFileName(ParamStr(0));
tempfn := AppendPathDelim(tempdir)+SetupExename;
mkdir(tempdir);
Logger('Getting new file from: '+fromURL+' into '+tempfn);
try
if wget(fromURL,tempfn,Nil,Nil,{enableProxy=}True, {forceReload=}False , {UserAgent=}'') then
begin
version := GetApplicationVersion(tempfn);
if version='' then
raise Exception.create('no version information in downloaded file.');
Logger(' got '+SetupExename+' version: '+version);
Files.Add(SetupExename);
end
else
Raise Exception.CreateFmt('Unable to download %s',[fromURL]);
except
//trying to get a zip file instead (exe files blocked by proxy ...)
zipfn:= AppendPathDelim(tempdir)+ChangeFileExt(SetupExename,'.zip');
if wget(ChangeFileExt(fromURL,ansistring('.zip')),zipfn,Nil,Nil,True) then
begin
Logger(' unzipping file '+zipfn);
UnZipper := TZipRead.Create(zipfn);
try
UnZipper.UnZipAll(tempdir);
for i := 0 to Length(UnZipper.Entry) -1 do
if not UnZipper.Entry[i].dir^.IsDosFolder then
Files.Add(StringReplace(UnZipper.Entry[i].zipName ,'/','\',[rfReplaceAll]));
finally
UnZipper.Free;
end;
version := GetApplicationVersion(tempfn);
if version='' then
raise Exception.create('no version information in downloaded exe file.');
Logger(' got '+SetupExename+' version: '+version);
end
else
Raise Exception.CreateFmt('Unable to download %s',[fromURL]);
end;
if FileExistsUtf8(tempfn) and (FileSizeUtf8(tempfn)>0) then
begin
// small batch to replace current running application
updatebatch := AppendPathDelim(tempdir) + 'update.bat';
AssignFile(bat,updateBatch);
Rewrite(bat);
try
Logger(' Creating update batch file '+updateBatch);
// wait for program to terminate..
Writeln(bat,'timeout /T 2');
Writeln(bat,'taskkill /im '+Exename+' /f');
Writeln(bat,'"'+IncludeTrailingPathDelimiter(tempdir)+SetupExename+'" '+SetupParams);
Writeln(bat,'cd ..');
if RestartParam<>'' then
Writeln(bat,'start "" "'+ParamStr(0)+'" '+restartparam);
Writeln(bat,'rmdir /s /q "'+tempdir+'"');
finally
CloseFile(bat)
end;
Logger(' Launching update batch file '+updateBatch);
hinstance := ShellExecute(
0,
PAnsiChar('open'),
PAnsiChar( SysUtils.GetEnvironmentVariable(AnsiString('ComSpec'))),
PAnsiChar(AnsiString('/C '+ updatebatch)),
PAnsiChar(TempDir),
SW_HIDE);
if hinstance<=32 then
begin
writeln('Error launching update batch file :'+IntToStr(hinstance));
ExitProcess(1);
end
else
ExitProcess(0)
end;
finally
Files.Free;
end;
end;
function GetSpecialFolderLocation(csidl: Integer; ForceFolder: Boolean = False ): String;
Var
APath : Array[0..MAX_PATH] of WideChar;
WS: UnicodeString;
Len: SizeInt;
hr: HRESULT;
begin
Result := '';
If (@SHGetFolderPathW <> Nil) then
begin
FillChar(APath{%H-}, SizeOf(APath), #0);
hr := SHGetFolderPathW(0,csidl or CSIDL_FLAG_CREATE,0,0, @APATH[0]);
if hr = S_OK then
begin
Len := StrLenW(APath);
SetLength(WS, Len);
System.Move(APath[0], WS[1], Len * SizeOf(WideChar));
Result := AppendPathDelim(Utf8Decode(APath));
end;
end;
end;
function GetSendToFolder: String;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create;
Registry.RootKey := HKEY_CURRENT_USER;
if Registry.OpenKeyReadOnly( strnShellFolders ) then
Result := AppendPathDelim(Registry.ReadString( 'SendTo' ))
else
Result := '';
Registry.Free;
end;
function GetUserNameExW(NameFormat: DWORD; lpNameBuffer: LPWSTR; var nSize: DWORD): Boolean; stdcall; external
'secur32.dll' Name 'GetUserNameExW';
function GetCurrentUserName(fFormat: TUsernameFormat): Ansistring;
const
cnMaxUserNameLen = 254;
var
sUserName : WideString;
dwUserNameLen : DWord;
begin
dwUserNameLen := cnMaxUserNameLen-1;
SetLength( sUserName, cnMaxUserNameLen );
GetUserNameExW(ord(fFormat),
PWideChar( sUserName ),
dwUserNameLen );
SetLength( sUserName, dwUserNameLen );
Result := Utf8Encode(sUserName);
end;
function GetPersonalFolder:String;
begin
result := GetSpecialFolderLocation(CSIDL_PERSONAL)
end;
function GetLocalAppdataFolder:String;
begin
result := GetSpecialFolderLocation(CSIDL_LOCAL_APPDATA);
end;
function GetAppdataFolder:String;
begin
result := GetSpecialFolderLocation(CSIDL_APPDATA);
end;
function GetAppUserFolder(AApplicationName: String): String;
begin
if AApplicationName='' then
AApplicationName := ApplicationName;
Result := IncludeTrailingPathDelimiter(GetSpecialFolderLocation(CSIDL_APPDATA)) + AApplicationName;
end;
function GetStartMenuFolder: String;
begin
result := GetSpecialFolderLocation(CSIDL_STARTMENU);
end;
function GetCommonStartMenuFolder: String;
begin
result := GetSpecialFolderLocation(CSIDL_COMMON_STARTMENU);
end;
function GetStartupFolder: String;
begin
result := GetSpecialFolderLocation(CSIDL_STARTUP);
end;
function GetCommonStartupFolder: String;
begin
result := GetSpecialFolderLocation(CSIDL_COMMON_STARTUP);
end;
function GetSystemFolder: String;
begin
Result := GetSpecialFolderLocation(CSIDL_SYSTEM);
end;
function GetWindowsFolder: String;
begin
Result := GetEnvironmentVariableUTF8('WINDIR');
end;
function GetCurrentUser: String;
var
charBuffer: array[0..128] of WideChar;
intgBufferSize: DWORD;
begin
intgBufferSize := 128;
if GetUserNameW( charBuffer, intgBufferSize ) then
begin
Result := StrPas( charBuffer );
end
else
begin
Result := '';
end;
end;
// to store use specific settings for this application
function AppUserIniPath(AApplicationName: String): String;
var
dir : String;
begin
if AApplicationName='' then
AApplicationName := ApplicationName;
dir := IncludeTrailingPathDelimiter(GetAppdataFolder)+AApplicationName;
if not DirectoryExistsUTF8(dir) then
MkDir(dir);
Result:=IncludeTrailingPathDelimiter(dir)+AApplicationName+'.ini';
end;
function GetOSVersionInfo: TOSVersionInfoEx;
begin
FillChar(Result, SizeOf(TOSVersionInfoEx), 0);
Result.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
if not GetVersionEx(POSVersionInfo(@Result)) then
Result.dwOSVersionInfoSize := 0;
end;
function IsWinXP:Boolean;
var
Info : TOSVersionInfoEx;
begin
Result := False;
info := GetOSVersionInfo;
if info.dwOSVersionInfoSize>0 then
result := (Info.dwPlatformId = VER_PLATFORM_WIN32_NT) and
(Info.dwMajorVersion = 5) and (Info.dwMinorVersion = 1)
end;
type
PFixedFileInfo = ^TFixedFileInfo;
TFixedFileInfo = record
dwSignature : DWORD;
dwStrucVersion : DWORD;
wFileVersionMS : WORD; // Minor Version
wFileVersionLS : WORD; // Major Version
wProductVersionMS : WORD; // Build Number
wProductVersionLS : WORD; // Release Version
dwFileFlagsMask : DWORD;
dwFileFlags : DWORD;
dwFileOS : DWORD;
dwFileType : DWORD;
dwFileSubtype : DWORD;
dwFileDateMS : DWORD;
dwFileDateLS : DWORD;
end; // TFixedFileInfo
function GetApplicationVersion(FileName: String): String;
var
dwHandle, dwVersionSize : DWORD;
strSubBlock : String;
pTemp : Pointer;
pData : Pointer;
begin
Result:='';
if Filename='' then
FileName:=ParamStr(0);
strSubBlock := '\';
// get version information values
dwVersionSize := GetFileVersionInfoSizeW( PWideChar( UTF8Decode(FileName) ), // pointer to filename string
dwHandle ); // pointer to variable to receive zero
// if GetFileVersionInfoSize is successful
if dwVersionSize <> 0 then
begin
GetMem( pTemp, dwVersionSize );
try
if GetFileVersionInfo( PAnsiChar( FileName ), // pointer to filename string
dwHandle, // ignored
dwVersionSize, // size of buffer
pTemp ) then // pointer to buffer to receive file-version info.
if VerQueryValue( pTemp, // pBlock - address of buffer for version resource
PAnsiChar( strSubBlock ), // lpSubBlock - address of value to retrieve
pData, // lplpBuffer - address of buffer for version pointer
dwVersionSize ) then // puLen - address of version-value length buffer
with PFixedFileInfo( pData )^ do
Result:=IntToSTr(wFileVersionLS)+'.'+IntToSTr(wFileVersionMS)+
'.'+IntToStr(wProductVersionLS)+'.'+IntToStr(wProductVersionMS);
finally
FreeMem( pTemp );
end; // try
end; // if dwVersionSize
end;
function ProcessExists(ExeFileName: string): boolean;
{description checks if the process is running. Adapted for freepascal from:
URL: http://www.swissdelphicenter.ch/torry/showcode.php?id=2554}
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
CurrentPId:LongWord;
begin
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
Result := False;
CurrentPId:=longWord(GetCurrentProcessId);
while integer(ContinueLoop) <> 0 do
begin
if (FProcessEntry32.th32ProcessID <> CurrentPId) and ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeFileName))) then
begin
Result := True;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
function KillTask(ExeFileName: string): integer;
const
PROCESS_TERMINATE=$0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot
(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle,
FProcessEntry32);
while integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile))
= UpperCase(ExeFileName)) or
(UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeFileName))) then
Result := Integer(TerminateProcess(OpenProcess(
PROCESS_TERMINATE, BOOL(0),
FProcessEntry32.th32ProcessID), 0));
ContinueLoop := Process32Next(FSnapshotHandle,
FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
//From Pascal SCADA / sockets_w32_w64 (C) Fabio Luis Girardi
function WaitForConnection(FListenerSocket:TSocket; timeout:LongInt):Boolean;
var
readsel,wrsel:TFDSet;
mode:u_long;
tv : TTimeVal;
p:ptimeval;
begin
if timeout=-1 then
p:=nil
else begin
tv.tv_Sec:=Timeout div 1000;
tv.tv_Usec:=(Timeout mod 1000)*1000;
p:=@tv;
end;
FD_ZERO(readsel);
FD_SET(FListenerSocket, readsel);
FD_ZERO(wrsel);
FD_SET(FListenerSocket, wrsel);
// XXX should probably be "FListenerSocket + 1" (ie. max_fd + 1)
mode := select(FListenerSocket, @readsel, @wrsel, nil, p);
if (mode <= 0) then begin
Result := false;
end else
if (mode > 0) then begin
Result := true;
end;
end;
function GetIPFromHostWindows(const HostName: String): String;
type
TaPInAddr = array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
i: Integer;
GInitData: TWSAData;
begin
WSAStartup($101, GInitData);
Result := '';
phe := gethostbyname(PAnsiChar(HostName));
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
i := 0;
while pPtr^[i] <> nil do
begin
Result := inet_ntoa(pptr^[i]^);
Inc(i);
end;
WSACleanup;
end;
function GetIPFromHost(const Hostname: String): String;
begin
Result := GetIPFromHostWindows(Hostname);
end;
// From JCL library
function GetServiceStatusByName(const AServer,AServiceName:ansistring):TServiceState;
var
ServiceHandle,
SCMHandle: DWORD;
SCMAccess,Access:DWORD;
ServiceStatus: TServiceStatus;
begin
Result:=ssUnknown;
SCMAccess := SC_MANAGER_CONNECT or SC_MANAGER_ENUMERATE_SERVICE or SC_MANAGER_QUERY_LOCK_STATUS;
Access:=SERVICE_INTERROGATE or GENERIC_READ;
SCMHandle:= OpenSCManager(PAnsiChar(AServer), Nil, SCMAccess);
if SCMHandle <> 0 then
try
ServiceHandle:=OpenService(SCMHandle,PAnsiChar(AServiceName),Access);
if ServiceHandle <> 0 then
try
ResetMemory(ServiceStatus, SizeOf(ServiceStatus));
if QueryServiceStatus(ServiceHandle,ServiceStatus) then
Result:=TServiceState(ServiceStatus.dwCurrentState);
finally
CloseServiceHandle(ServiceHandle);
end;
finally
CloseServiceHandle(SCMHandle);
end;
end;
function StartServiceByName(const AServer,AServiceName: AnsiString):Boolean;
var
ServiceHandle,
SCMHandle: DWORD;
p: PAnsiChar;
ts:TDateTime;
SS:SERVICE_STATUS;
begin
p:=nil;
Result:=False;
SCMHandle := OpenSCManager(PAnsiChar(AServer), nil, SC_MANAGER_ALL_ACCESS);
if SCMHandle <> 0 then
try
ServiceHandle := OpenService(SCMHandle,PAnsiChar(AServiceName),SERVICE_ALL_ACCESS);
if ServiceHandle <> 0 then
try
StartService(ServiceHandle,0,p);
ts := Now;
repeat
ResetMemory(SS, SizeOf(SS));
QueryServiceStatus(ServiceHandle,SS);
until (SS.dwCurrentState = SERVICE_RUNNING) or ((Now-ts)> 5/24/3600);
Result := SS.dwCurrentState = SERVICE_RUNNING;
finally
CloseServiceHandle(ServiceHandle);
end;
finally
CloseServiceHandle(SCMHandle);
end;
end;
function StopServiceByName(const AServer, AServiceName: AnsiString):Boolean;
var
ServiceHandle,
SCMHandle: DWORD;
SS: SERVICE_STATUS;
ts:TDateTime;
begin
Result := False;
SCMHandle := OpenSCManager(PAnsiChar(AServer), nil, SC_MANAGER_ALL_ACCESS);
if SCMHandle <> 0 then
try
ServiceHandle := OpenService(SCMHandle, PAnsiChar(AServiceName), SERVICE_ALL_ACCESS);
if ServiceHandle <> 0 then
begin
ResetMemory(SS, SizeOf(SS));
Result := ControlService(ServiceHandle, SERVICE_CONTROL_STOP, SS);
if Result then
begin
ts := Now;
repeat
ResetMemory(SS, SizeOf(SS));
QueryServiceStatus(ServiceHandle,SS);
until (SS.dwCurrentState = SERVICE_STOPPED) or ((Now-ts)> 5/24/3600);
Result := SS.dwCurrentState = SERVICE_STOPPED;
end;
end;
CloseServiceHandle(ServiceHandle);
finally
CloseServiceHandle(SCMHandle);
end;
end;
function GetServiceStartType(const AServer, AServiceName: AnsiString; out StartType: TServiceStartType): Boolean;
var
ServiceHandle,
SCMHandle, ServiceConfigSize: DWORD;
PServiceConfig: LPQUERY_SERVICE_CONFIG;
begin
Result := False;
SCMHandle := OpenSCManager(PAnsiChar(AServer), nil, SC_MANAGER_ALL_ACCESS);
if SCMHandle <> 0 then
try
ServiceHandle := OpenService(SCMHandle, PAnsiChar(AServiceName), STANDARD_RIGHTS_REQUIRED or SERVICE_QUERY_CONFIG or SERVICE_QUERY_STATUS);
if ServiceHandle <> 0 then
try
ServiceConfigSize := 0;
QueryServiceConfig(ServiceHandle,Nil,0, ServiceConfigSize);
PServiceConfig := GetMem(ServiceConfigSize);
try
if QueryServiceConfig(ServiceHandle,PServiceConfig, ServiceConfigSize, ServiceConfigSize) then
begin
Result := True;
StartType := TServiceStartType(PServiceConfig^.dwStartType);
end
else
Result := False;
finally
FreeMem(PServiceConfig);
end;
finally
CloseServiceHandle(ServiceHandle);
end
else
Result := False;
finally
CloseServiceHandle(SCMHandle);
end;
end;
function SetServiceStartType(const AServer, AServiceName: AnsiString; const StartType: TServiceStartType ):Boolean;
var
ServiceHandle,
SCMHandle: DWORD;
begin
Result := False;
SCMHandle := OpenSCManager(PAnsiChar(AServer), nil, SC_MANAGER_ALL_ACCESS);
if SCMHandle <> 0 then
try
ServiceHandle := OpenService(SCMHandle, PAnsiChar(AServiceName), SERVICE_ALL_ACCESS);
if ServiceHandle <> 0 then
Result := ChangeServiceConfigA(ServiceHandle,SERVICE_NO_CHANGE,ord(StartType),SERVICE_NO_CHANGE,Nil,Nil,Nil,Nil,Nil,Nil,Nil)
else
Result := False;
CloseServiceHandle(ServiceHandle);
finally
CloseServiceHandle(SCMHandle);
end;
end;
function GetGroups(srvName, usrName: WideString):TStringArray;
var
dwEntriesRead, dwEntriesTotal: DWORD;
grpi0: Pointer;
pInfo: PGroupInfo0;
nErr: Integer;
begin
SetLength(Result,0);
nErr := NetUserGetGroups(PWideChar(srvName), PWideChar(usrName), 0, grpi0,MAX_PREFERRED_LENGTH, @dwEntriesRead, @dwEntriesTotal);
if nErr = NERR_SUCCESS then
begin
pInfo := grpi0;
while dwEntriesRead > 0 do
begin
SetLength(result,length(result)+1);