-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainFormUnit.pas
More file actions
5811 lines (4568 loc) · 194 KB
/
MainFormUnit.pas
File metadata and controls
5811 lines (4568 loc) · 194 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
unit MainFormUnit;
{
Update Fixer version 1.3
By Jouni Flemming (Great Software Company)
Copyright 2023-2025 Jouni Flemming
Official website: https://winupdatefixer.com/
Source code license: GNU General Public License v3
https://www.gnu.org/licenses/gpl-3.0.en.html
Official Github: https://github.com/jv16x/UpdateFixer/
You can contact me: jouni@winupdatefixer.com or jouni.flemming@macecraft.com
If you do, please include “Update Fixer” in the subject line.
Disclaimer:
This source code is provided “as is” without any guarantees of any kind
with the exception that we guarantee the Update Fixer application does not
include any malware or other such hidden malicious functionality.
This project uses MadExcept exception handler by http://madshi.net/
Simply remove the MadExcept references if you wish to compile without it.
This project also uses a few custom UI components, namely:
PTZPanel, PTZStdCtrls, PTZSymbolButton, PTZWinControlButton, ColorPanel,
GUIPanel, GUIPanelHVList, PTZGlyphButton, PTZProgressBar.
You can remove these and replace the controls with standard VCL controls if you wish.
The program has two main steps in its operation
1) In the Analysis step - implemented mostly via the Analyze_xxx functions -
we attempt to detect common problems in the system that can cause Windows Update to fail.
One such common problem is that the System Services relating to Windows Update are disabled.
2) In the processing step - implemented mostly via the Process_xxx functions -
we process, i.e. fix the found issues.
Notice that the process step only does changes as authorized by the user by selecting
from the UI which fixing operations should be performed.
It is possible that the user does not select all the found issues to be fixed,
or that the user chooses to fix all the issues, even in those that were not actually detected.
In such case, user input is interpreted to mean to change the settings of the specific item to its defaults.
The fixing process uses three techniques: in-exe commands, mainly Windows API calls,
running of batch files and running of PowerShell files.
Doing this in these three ways was noted in testing to be the most robust way of performing the fixes.
In other words, in some testing systems, simply attempting to do a fix by executing Windows API
calls within the exe file alone did not work, but attempting to do the same fix by using a
batch file or a PowerShell script file did, or vice versa.
A more elegant way of performing all the fixes would naturally to implement everything without
the need to use any batch or PowerShell script files, but I didn't have the time to do so.
My main goal was to make this work (i.e. be able to fix Windows Update even when the official
Windows Update Troubleshooter couldn't), not to make it work and work in the most elegant way possible
Anyone reviewing this code is free to let me know of fixes and improvements how all this
can be done without the use of Batch/PowerShell script files.
** Change Log **
Changes since version 1.2
1) Improved the user interface
2) Minor source code updates
3) Official exe build now comes with an updated code signing certificate
Changes since version 1.1
1) The app window can now be resized in its results show view.
2) Improved the Debug_GenerateDebugLog directive support and debug log content.
3) Split Process_Init_Pas() into two functions and fixed many bugs there.
4) Removed Debug_ExceptionMessages directive. Debug_GenerateDebugLog is better anyway.
5) Removed DEBUG_WRITE_LOG, because Debug_GenerateDebugLog is better anyway.
Changes since version 1.0
1) Removed the use of encrypted strings in order to improve code readability. They were used to
prevent VirusTotal false positives. I'm going to ass-u-me that since the program is now open source,
it will no longer be flagged with such false positive detections.
2) Replaced all of the hard-coded 'c:\windows\' references with %WINDIR%. While this makes very little difference
for any actual use case, it's still a better way to do it.
3) Other minor code cleanup and maintenance, and added some more comments to document the code.
}
interface
// If enabled, generates a debug log to user's Windows Desktop
{.$DEFINE Debug_GenerateDebugLog}
// If enabled, displays some markers in the UI to show the exact progress of code execution
{.$DEFINE Debug_ShowProgress}
// If Enabled, displays the UI using vivid colors, to see where each UI element exactly is
{.$DEFINE Debug_Colors}
// If Enabled, saves all non-translated UI strings to C:\temp\_t_UpdateFixer.txt
{.$DEFINE Debug_BuildMissingTranslationFile}
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Registry, IniFiles,
Generics.Collections,
ShellAPI,
PTZStdCtrls, GUIPanelHVList, PTZPanel,
PTZGlyphButton, PTZProgressBar,
PTZWinControlButton, ColorPanel,
GUIPanel, Vcl.Imaging.pngimage,
Vcl.Themes, Math,
System.NetEncoding,
System.Character,
AclAPI,
AccCtrl,
StrUtils,
System.IOUtils, TLHelp32,
Win64bitDetector,
System.Win.TaskbarCore, System.Win.Taskbar,
FastStringCaseUtils, InternetUtils,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.AppEvnts,
Vcl.Imaging.GIFImg, Vcl.Menus;
const
APP_VERSION = '1.3';
DEBUG_STORE_BAT = 0; // If 1, saves all the generated script files to user's desktop.
DEBUG_PIRATED = 0; // If 1, the pirated Windows detection will always detect OS as pirated in order to test how the UI looks like
DEBUG_NO_ISSUES = 0; // If 1, the analysis shall not find any problems in order to test how the UI looks like
DEBUG_SOME_ISSUES = 0; // If 1, the analysis shall always find some problems in order to test how the UI looks like
DEBUG_NO_BATCH = 0; // If 1, the fixing shall not use any batch files
DEBUG_SHOW_WINVER = 0; // If 1, the UI will display contents of FWinVer (version of Windows)
Win10DeliveryDirs : Array[0 .. 7] of String =
('%WINDIR%\Temp\',
'%WINDIR%\CbsTemp\',
'%WINDIR%\SoftwareDistribution\',
'%WINDIR%\Logs\',
'%WINDIR%\Logs\WindowsUpdate\',
'%WINDIR%\System32\CatRoot2\',
'%ALLUSERSPROFILE%\Application Data\Microsoft\Network\', // <x> => FAllUserProfile, no trail!
'%ALLUSERSPROFILE%\Microsoft\Network\Downloader\'
);
ServiceNamesArr : Array[0 .. 5] of String =
('WuauServ',
'BITS',
'CryptSvc',
'MsiServer',
'DcomLaunch',
'TrustedInstaller');
ServiceDescsArr : Array[0 .. 5] of String =
('Windows Update',
'Background Intelligent Transfer Service',
'Cryptographic Services',
'Windows Installer',
'Windows Modules Installer',
'Update Orchestrator Service');
ServiceKeySubDirs : Array[0 .. 2] of String =
('Parameters', 'Security', 'TriggerInfo');
// amPortable = A standalone installation without jv16 PowerTools
// amPT = app is run from within jv16 PowerTools
Type TAppMode = (amPortable, amPT);
type
TMainForm = class(TForm)
tmrShow: TTimer;
pnlWaiting: TPanel;
ProgressBar: TPTZProgressBar;
lblDebug: TLabel;
imgSpinner_DM_128: TImage;
imgSpinner_NM_128: TImage;
lblWorking: TLabel;
vlistAnalyze: TGUIPanelVList;
btnAnalyze: TPTZGlyphButton;
lblAnalyze: TLabel;
vlistFix: TGUIPanelVList;
pnlSpaceTop: TPanel;
btnFix: TPTZGlyphButton;
lblFixInfo: TLabel;
pnlSpaceBtm: TPanel;
lblBackup: TLabel;
vlistRecommended: TGUIPanelVList;
lblCaptRecommended: TLabel;
vlistOptional: TGUIPanelVList;
lblCaptOptional: TLabel;
pnlSpaceSubTop1: TPanel;
pnlSpaceSubTop2: TPanel;
pnlWindows: TPanel;
imgConfused: TImage;
lblWindows: TLabel;
lblCaptMain: TLabel;
pnlSpaceTopMain: TPanel;
vlistHolder: TGUIPanelVList;
lblTempFiles: TLabel;
lblDeliveryFiles: TLabel;
lblBlockers: TLabel;
lblRegistry: TLabel;
lblService1: TLabel;
chkTempFiles: TPTZCheckBox;
chkDeliverFiles: TPTZCheckBox;
chkBlockers: TPTZCheckBox;
chkRegistry: TPTZCheckBox;
chkService1: TPTZCheckBox;
lblHostsFile: TLabel;
chkHostsFile: TPTZCheckBox;
pnlSpaceTmp: TPanel;
pnlSpaceDelivery: TPanel;
pnlSpaceHosts: TPanel;
pnlSpaceRegistry: TPanel;
pnlSpaceService1: TPanel;
pnlSpaceBlock: TPanel;
pnlNothing: TPanel;
imgNothing: TImage;
lblNothingToFix: TLabel;
PopupMenu_Rec: TPopupMenu;
chkService2: TPTZCheckBox;
lblService2: TLabel;
pnlSpaceService2: TPanel;
PopupMenu_Opt: TPopupMenu;
pnlSpaceService3: TPanel;
lblService3: TLabel;
chkService3: TPTZCheckBox;
chkService4: TPTZCheckBox;
pnlSpaceService4: TPanel;
lblService4: TLabel;
chkService5: TPTZCheckBox;
pnlSpaceService5: TPanel;
lblService5: TLabel;
chkService0: TPTZCheckBox;
pnlSpaceService0: TPanel;
lblService0: TLabel;
SelectAll1: TMenuItem;
SelectNone1: TMenuItem;
SelectAll2: TMenuItem;
SelectNone2: TMenuItem;
tmrUpdateUiSelections: TTimer;
tmrUpdateUI: TTimer;
vlistRecommendedSub: TGUIPanelVList;
vlistOptionalSub: TGUIPanelVList;
pnlMainParent: TPanel;
lblFooter: TLabel;
lblFooter2: TLabel;
pnlWindowTitle: TColorPanel;
imgLogoSmall: TImage;
lblHeader: TLabel;
hlistWinControls: TGUIPanelHList;
btnWinClose: TPTZWinControlButton;
ScrollBox: TScrollBox;
vlistDone: TGUIPanelVList;
btnClose: TPTZGlyphButton;
pnlSpaceDone: TPanel;
btnReboot: TPTZGlyphButton;
pnlThanks: TPanel;
imgDone: TImage;
lblThanks: TLabel;
lblDone: TLabel;
lblDone2: TLabel;
procedure btnWinCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tmrShowTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure pnlWindowTitleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgLogoSmallClick(Sender: TObject);
procedure lblFooterClick(Sender: TObject);
procedure lblFooterMouseEnter(Sender: TObject);
procedure lblFooterMouseLeave(Sender: TObject);
procedure btnFixClick(Sender: TObject);
procedure lblFooter2MouseEnter(Sender: TObject);
procedure lblFooter2MouseLeave(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnRebootClick(Sender: TObject);
procedure lblTempFilesClick(Sender: TObject);
procedure lblDeliveryFilesClick(Sender: TObject);
procedure lblRegistryClick(Sender: TObject);
procedure lblService1Click(Sender: TObject);
procedure lblBlockersClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnAnalyzeClick(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure lblHostsFileClick(Sender: TObject);
procedure lblService2Click(Sender: TObject);
procedure lblService3Click(Sender: TObject);
procedure lblService4Click(Sender: TObject);
procedure lblService5Click(Sender: TObject);
procedure lblService0Click(Sender: TObject);
procedure SelectAll1Click(Sender: TObject);
procedure PopupMenu_RecPopup(Sender: TObject);
procedure chkTempFilesKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure chkTempFilesMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure tmrUpdateUiSelectionsTimer(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure tmrUpdateUITimer(Sender: TObject);
private
FAppDir : String; // The dir of the app - With a trailing slash
FPTAppDir : String; // The dir of detected jv16 PowerTools installation (if any) - With a trailing slash
FDebugDir : String; // With a trailing slash
FTempDir : String; // With a trailing slash
FDesktopDir : String; // With a trailing slash
FAppMode : TAppMode; // Current app mode: Portable or within jv16 PowerTools
FWinVer : String; // Version of Windows, e.g. 'Windows 10'
FUI_DarkMode : Boolean; // UI in Dark Mode or not
FUI_AutoPos : Boolean; // Whether app window should be automatically centered
FUI_AllowResizing : Boolean; // Whether app window can be resized, i.e. only in the analysis results view
FUI_MIN_HEIGHT : Integer;
FUI_MIN_WIDTH : Integer;
FUI_MAX_WIDTH : Integer;
FUI_MAX_HEIGHT : Integer;
FUI_BORDER_WIDTH : Integer;
FLastTmrShowRun : UInt64;
FLastTmrStarted : UInt64;
FUISelUpdLock : Boolean;
FUIGenUpdLock : Boolean;
FCheckboxes : TList<TPTZCheckBox>;
FServiceCheckboxes : TList<TPTZCheckBox>;
FServiceLabels : TList<TLabel>;
FServicePanels : TList<TPanel>;
FAllOptionControls : TList<TControl>;
FTransStringsCache : TDictionary<String,String>;
FTransHashesCache : TDictionary<String,String>;
FEnvVars : TDictionary<String,String>;
FExistsCache : TDictionary<String, Boolean>;
FTaskbarHelper : TWinTaskbar;
FBatFile : TStringList;
FBlockerRemoval : TStringList;
FRegIniFilename : String;
{$IFDEF Debug_GenerateDebugLog}
FDebugLog : TStringList;
FDebugLogFile : String;
FErrors : Integer; // Number of critical errors detected
{$ENDIF}
FDeliveryDirsOK : Boolean;
FFreeSpaceOK : Boolean;
FHostsFileOK : Boolean;
FPiratedWindows : Boolean;
FServiceOKArr : Array[0 .. 5] of Boolean;
FRegistryOK : Boolean;
FBlockersFound : Boolean;
FWinGenCheckResultFile : String;
FPriviledgeSet : Boolean;
FUI_WindowSizeSet : Boolean;
procedure Init_AppDirs();
procedure Init_AppMode();
procedure Init_LoadColorScheme();
procedure Init_LoadColorScheme_SetActiveStyle();
procedure Init_LoadColorScheme_Apply();
Function Init_Read_PT_DarkMode_Setting() : Integer;
procedure Init_CheckBoxes();
procedure Init_ServiceLists();
Procedure OpenUrl(const URL : String);
{$IFDEF Debug_GenerateDebugLog}
Procedure DebugLog(const Str : String);
{$ENDIF}
Procedure SetLabelHeight(const Lbl : TLabel; const ExtraMargin : Integer = 0);
Procedure UI_UpdateDynamicContent();
Procedure UI_SetWindowSize();
Procedure UI_UpdateSelectionCounts();
Procedure UI_UpdateSelectionCounts_DO();
Procedure UI_Setup_TabOrder();
Procedure UI_IncProgress(const AllDone : Boolean = False);
Procedure UI_Sleep(const SleepyTimeMSEC : Integer);
function CreateMutexDo(MutexName : string; ReleaseMutexAfter : Boolean) : Boolean;
Function UI_AnyServiceCheckboxChecked() : Boolean;
Function UI_AnyCheckboxChecked() : Boolean;
Function DirectoryExists_Cached(Const InputStr : String; const DualModeCheck : Boolean = True) : Boolean;
Function FileExists_Cached(Const InputStr : String; const DualModeCheck : Boolean = True) : Boolean;
procedure Init_Translation();
procedure Init_Translation_LoadSection(const DataList : TStringList; const SectionName : String);
Function GetStringHash(const Str : String) : String;
Function _t(Const Str : String; Const StrID : String; Const InsertDataArr : Array of String) : String; Overload;
Function _t(const Str : String; const StrID : String; const InsertData : String = '') : String; Overload;
Procedure RunBatchFileAndWait(Const FileName: string);
function RunBatchFileAndWait_GetCount() : Integer;
function RunPSFileAndWait_GetCount() : Integer;
Procedure RunPSFileAndWait(Const FileName: string);
Function ExpandEnvVariable(const EnvVar : String) : String;
Function ExpandPath(const Path : String) : String;
Function MyExitWindows(const RebootParam: Longword): Boolean;
Function HasAttrib(const Filename : String; Attr : Integer) : Boolean;
Function GetTempDir() : String;
Function GetCurrentUserDir() : String;
Function GetDesktopDir() : String;
function SetPrivilege(privilegeName: String; enable: boolean): boolean;
Function GetDriveFreeSpaceGB() : Integer;
Function ShellExecuteDo(Const FileName: string; Const Params: string = ''): Boolean;
Function GetAllUserDirs() : TStringList;
// Used for bsNone form resizing via user input:
procedure WM_NCHitTestHandler(var Msg: TWMNCHitTest); message WM_NCHitTest;
public
Function IsByDefaultReadOnlyServKey(const ServName : String) : Boolean;
Function Analyze_System_Service_CanRead(const ServName : String) : Boolean;
Function Analyze_System_Service_CanWrite(const ServName : String) : Boolean;
Function Analyze_System_Service_IsOK(const ServName : String) : Boolean;
Procedure Analyze_System_Services();
Procedure Analyze_System_Registry();
Procedure Analyze_System_Blockers();
Procedure Analyze_DeliveryDirs();
Procedure Analyze_HostsFile();
Procedure Analyze_WinVer();
Function Analyze_CanWrite() : Boolean;
Procedure Analyze_Start_Cmd();
Function Analyze_GenuineWindows_CheckFile(const Filename : String) : Boolean;
Procedure Analyze_GenuineWindows();
Function GetFileSize(const Filename : String) : Int64; // in bytes
Procedure Process_Init();
Procedure Process_Init_Bat();
Procedure Process_Init_PS();
Procedure Process_Init_Pas();
Function Process_Init_Pas_DO(const ServName : String) : Integer;
Procedure Process_Finalize();
Procedure Process_Finalize_PS();
Procedure Process_Registry();
Procedure Process_Services();
Procedure Process_Delivery_Files();
Procedure Process_HostsFile();
Procedure Process_Temporary_Files();
end;
var
MainForm: TMainForm;
// The UI colors are defined as global variables instead of consts,
// because these colors are changed depending whether we are using
// Dark Mode or Light Mode UI
Color_NavBack : TColor;
Color_MainBack : TColor;
Color_MainFont : TColor;
Color_LinkActive : TColor = 13601024; // Light blue color when mouse is over the link text
UI_WIN_BAR_COLOR : TColor = 2760472; // RGB(24,31,42);
UI_WIN_BORDER_COLOR : TColor = 2302239; // RGB(31,33,35);
Color_Btn_WhiteBack : TColor = 14803425; // RGB(225,225,225);
Color_Btn_BorderColor : TColor = 12829635; // RGB(195,195,195);
Color_Btn_ClickColor : TColor = 16119285; // RGB(245,245,245);
Color_Btn_FocusColor : TColor = 15461355; // RGB(235,235,235);
Color_Btn_FocusBorderColor : TColor = 16752680; // RGB(40,160,255);
Function RawReadFile_UTF8(const Filename : String; MaxLen : Integer = -1) : String;
Function UpOneDir(const Dir : String) : String;
Function FastPosExB(const SubStr, Str : String) : Boolean;
Function Murmur2Hash(const AString: String): LongWord;
Function EnsureTrail(const Path : String) : String;
Function ExtractTopDir(Dir : String) : String;
Function Capitalize(const Str : String) : String;
implementation
{$R *.dfm}
procedure TMainForm.WM_NCHitTestHandler(var Msg: TWMNCHitTest);
var
deltaRect : TRect;
bResize : Boolean;
begin
inherited;
if FUI_AllowResizing = False then EXIT;
if Msg.Result = htClient then Msg.Result := htCaption;
with Msg, deltaRect do
begin
Left := XPos - BoundsRect.Left;
Right := BoundsRect.Right - XPos;
Top := YPos - BoundsRect.Top;
Bottom := BoundsRect.Bottom - YPos;
bResize := False;
if (Top <= FUI_BORDER_WIDTH) and (Left <= FUI_BORDER_WIDTH) then
begin
Result := HTTOPLEFT;
bResize := True;
end
else if (Top < FUI_BORDER_WIDTH) and (Right < FUI_BORDER_WIDTH) then
begin
Result := HTTOPRIGHT;
bResize := True;
end
else if (Bottom <= FUI_BORDER_WIDTH) and (Left <= FUI_BORDER_WIDTH) then
begin
Result := HTBOTTOMLEFT;
bResize := True;
end
else if (Bottom <= FUI_BORDER_WIDTH) and (Right <= FUI_BORDER_WIDTH) then
begin
Result := HTBOTTOMRIGHT;
bResize := True;
end
else if (Top <= FUI_BORDER_WIDTH) then
begin
Result := HTTOP;
bResize := True;
end
else if (Left <= FUI_BORDER_WIDTH) then
begin
Result := HTLEFT;
bResize := True;
end
else if (Bottom <= FUI_BORDER_WIDTH) then
begin
Result := HTBOTTOM;
bResize := True;
end
else if (Right <= FUI_BORDER_WIDTH) then
begin
Result := HTRIGHT;
bResize := True;
end;
if bResize then
begin
FUI_AutoPos := False;
tmrUpdateUI.Enabled := True;
end;
end;
end;
Function Capitalize(const Str : String) : String;
begin
Result := Str;
If Result <> '' then
begin
Result := FastLowerCase(Result);
Result[1] := GLOB_CharUpCaseTable[Result[1]];
end;
end;
// ExtractTopDir('c:\foobar\foo\') = > 'foo'
// ExtractTopDir('c:\foobar\foo\\') = > 'foo'
// ExtractTopDir('c:\foobar\foo\foo.exe') => 'foo.exe'
// ExtractTopDir('foobar') => 'foobar'
Function ExtractTopDir(Dir : String) : String;
Var
x : Integer;
idx : Integer;
len : Integer;
begin
Result := '';
// Remove trailing whitespace and slash(es):
while True do
begin
len := Length(Dir);
if len < 1 then Exit;
// detect trailing whitespace and slash (92):
x := ord(Dir[len]);
if (x <= 32) or (x = 92) then
begin
if len < 2 then Exit;
Dir := Copy(Dir, 1, len-1);
End else break;
end;
idx := LastDelimiter('\', Dir);
if idx > 0 then Result := Copy(Dir, idx+1, len) else Result := Dir;
// Remove possibly prefixing whitespace and slash (92):
while True do
begin
if Result = '' then Break;
x := ord(Result[1]);
if (x <= 32) or (x = 92) then
begin
Result := Copy(Result, 2, len);
End else break;
end;
End;
Function EnsureTrail(const Path : String) : String;
begin
Result := Trim(Path);
if (Result <> '') and
(Result[Length(Result)] <> '\') then Result := Result + '\';
end;
Function FastPosExB(const SubStr, Str : String) : Boolean;
Var
SubStrLC : String;
StrLC : String;
begin
StrLC := FastLowerCase(Str);
SubStrLC := FastLowerCase(SubStr);
Result := Pos(SubStrLC, StrLC) > 0;
end;
// UpOneDir('c:\foobar\foo\') = > 'c:\foobar\'
// UpOneDir('c:\foobar\foo\\') = > 'c:\foobar\'
// UpOneDir('c:\foobar\foo\foo.exe') => 'c:\foobar\'
// UpOneDir('foobar') => ''
// UpOneDir('\\share\foo\fii\') = > '\\share\foobar\'
Function UpOneDir(const Dir : String) : String;
Var
idx : Integer;
bool : Boolean;
begin
Result := '';
idx := Length(Dir) - 1;
bool := False;
while idx > 1 do
begin
if Dir[idx] = '\' then
begin
if Bool then
begin
Result := Trim(Copy(Dir, 1, idx));
Exit;
end;
end else if Dir[idx].IsWhiteSpace = False then bool := True;
Dec(idx);
end;
End;
Function RawReadFile_UTF8(const Filename : String; MaxLen : Integer = -1) : String;
Var
TmpList : TStringList;
Fail : Boolean;
begin
TmpList := TStringList.Create;
Fail := False;
Try
TmpList.LoadFromFile(Filename, TEncoding.UTF8);
Except
Fail := True;
End;
if Fail then
begin
Try
TmpList.LoadFromFile(Filename);
Fail := False;
Except
Fail := True;
End;
end;
if Fail then Result := '' else Result := TmpList.Text;
TmpList.Free;
if MaxLen > 0 then Result := Copy(Result, 1, MaxLen);
end;
Function TMainForm.Analyze_CanWrite() : Boolean;
Var
Dir : String;
Filename : String;
List : TStringList;
TmpStr : String;
begin
Result := False;
Try
Dir := GetTempDir();
Filename := Dir + 'UpdateFixer_can_delete_write_test_' + IntToStr(GetTickCount) + '.tmp';
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_CanWrite: ' + FileName); {$ENDIF}
List := TStringList.Create;
List.Add('Foobar');
List.SaveToFile(Filename, TEncoding.UTF8);
List.Free;
TmpStr := Trim(RawReadFile_UTF8(Filename));
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_CanWrite File Content: ' + TmpStr); {$ENDIF}
If TmpStr = 'Foobar' then
begin
Result := True;
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_CanWrite: OK'); {$ENDIF}
end;
DeleteFile(Filename);
if FileExists_Cached(Filename) then
begin
Result := False;
{$IFDEF Debug_GenerateDebugLog} DebugLog('Error: Analyze_CanWrite File Delete Failed?'); {$ENDIF}
end;
Except
Exit;
End;
end;
Procedure TMainForm.Analyze_Start_Cmd();
Const
Cmd = 'cscript /Nologo "%WINDIR%\System32\slmgr.vbs" /dli';
begin
if DEBUG_NO_BATCH = 1 then EXIT;
FWinGenCheckResultFile := GetTempDir() + 'update_fixer_can_be_deleted_' + IntToStr(GetTickCount) +'.tmp';
ShellExecuteDo('cmd.exe', '/C ' + ExpandPath(Cmd) + ' > "' + FWinGenCheckResultFile + '"');
end;
Function TMainForm.ShellExecuteDo(Const FileName: string; Const Params: string = ''): Boolean;
var
exInfo: TShellExecuteInfo;
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('ShellExecuteDo: ' + FileName + ' | ' + Params); {$ENDIF}
Result := False;
FillChar(exInfo, SizeOf(exInfo), 0);
with exInfo do
begin
cbSize := SizeOf(exInfo);
fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
Wnd := GetActiveWindow();
exInfo.lpVerb := 'open';
exInfo.lpParameters := PChar(Params);
lpFile := PChar(FileName);
nShow := SW_HIDE;
end;
if ShellExecuteEx(@exInfo) then Result := true;
Application.ProcessMessages;
Sleep(200);
end;
// Result : True => All is now done
Function TMainForm.Analyze_GenuineWindows_CheckFile(const Filename : String) : Boolean;
Var
FileData : String;
begin
Result := False;
if FileExists_Cached(Filename) = False then
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows_CheckFile File does not exist: ' + ExtractFilename(Filename)); {$ENDIF}
EXIT;
End;
FileData := RawReadFile_UTF8(Filename);
if Length(FileData) < 5 then
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows_CheckFile: (nodata)'); {$ENDIF}
EXIT;
end;
if FastPosExB('license', FileData) then Result := True;
if FastPosExB('non-genuine', FileData) or
FastPosExB('(null)', FileData) or
FastPosExB('slui.exe', FileData) then FPiratedWindows := True;
{$IFDEF Debug_GenerateDebugLog}
DebugLog('Analyze_GenuineWindows_CheckFile: ' + FileData);
{$ENDIF}
end;
Function TMainForm.GetFileSize(const Filename : String) : Int64;
var
Sr : TSearchRec;
begin
Result := -1;
Try
Try
Sr.FindData.nFileSizeHigh := 0;
Sr.FindData.nFileSizeLow := 0;
FindFirst(Filename, faAnyFile, Sr);
Result := Int64(Sr.FindData.nFileSizeHigh) shl Int64(32) +
Int64(Sr.FindData.nFileSizeLow);
{$IFDEF Debug_GenerateDebugLog} DebugLog('GetFileSize ' + ExtractFilename(Filename) + ' [32b]: ' + IntToStr(Result)); {$ENDIF}
Finally
if Result < 0 then Result := 0;
FindClose(sr);
End;
if (Result < 1) and
(Is64bitWindows()) and
(Assigned(GLOBAL_Wow64RevertWow64FsRedirection)) and
(Assigned(GLOBAL_Wow64DisableWow64FsRedirection)) then
begin
GLOBAL_Wow64DisableWow64FsRedirection(GLOBAL_Wow64FsEnableRedirection);
Try
Sr.FindData.nFileSizeHigh := 0;
Sr.FindData.nFileSizeLow := 0;
FindFirst(Filename, faAnyFile, Sr);
Result := Int64(Sr.FindData.nFileSizeHigh) shl Int64(32) +
Int64(Sr.FindData.nFileSizeLow);
{$IFDEF Debug_GenerateDebugLog} DebugLog('GetFileSize ' + ExtractFilename(Filename) + ' [64b]: ' + IntToStr(Result)); {$ENDIF}
Finally
if Result < 0 then Result := 0;
FindClose(sr);
GLOBAL_Wow64RevertWow64FsRedirection(GLOBAL_Wow64FsEnableRedirection);
End;
End;
Except
{$IFDEF Debug_GenerateDebugLog} DebugLog('Error: GetFileSize ' + ExtractFilename(Filename) + ' FAIL'); {$ENDIF}
Exit(-1);
End;
End;
Procedure TMainForm.Analyze_GenuineWindows();
Var
i : Integer;
x : Integer;
Filename : String;
TmpFile : String;
Row : String;
ScriptData : TStringList;
begin
// Method 1: check whether Windows activation related files are missing or null
Filename := ExpandPath('%WINDIR%\System32\slmgr.vbs');
GetFileSize(Filename);
If (FileExists_Cached(Filename) = False) or
(GetFileSize(Filename) < 1000*50) then
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows Exit-1'); {$ENDIF}
FPiratedWindows := True;
EXIT;
end;
Filename := ExpandPath('%WINDIR%\System32\slui.exe');
GetFileSize(Filename);
If (FileExists_Cached(Filename) = False) or
(GetFileSize(Filename) < 1000*100) then
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows Exit-2'); {$ENDIF}
FPiratedWindows := True;
EXIT;
end;
// Method 1:
If FileExists_Cached(FWinGenCheckResultFile) then
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows Primary Check Start'); {$ENDIF}
If Analyze_GenuineWindows_CheckFile(FWinGenCheckResultFile) then EXIT;
end else
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows Primary Check SKIPPED'); {$ENDIF}
end;
// Method 2 - should only happen in non English Windows:
// c:\windows\system32\slmgr.vbs /DLI result is LOCALIZED,
// Hence, we need to do this very hacky solution of creating a copy of slmgr.vbs,
// editing that copy not to translate (localize) its output and run that instead
// of running the original vbs file.
// Todo: To detect whether user is using a genuine Windows with a more elegant way
Filename := ExpandPath('%WINDIR%\System32\slmgr.vbs');
ScriptData := TStringList.Create;
ScriptData.text := RawReadFile_UTF8(Filename);
if ScriptData.Count < 1000 then
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows Exit-3'); {$ENDIF}
ScriptData.Free;
FPiratedWindows := True;
EXIT;
end;
i := 0;
While i <= ScriptData.Count-5 do
begin
Inc(i);
Row := ScriptData[i];
if FastPosExB('function GetResource(name)', Row) or
FastPosExB('sub GetResource(name)', Row) then
begin
Inc(i);
ScriptData[i] := ' GetResource = Eval(name)';
for x := i+1 to ScriptData.Count-1 do
begin
if FastPosExB('End Function', ScriptData[x]) then Break;
if FastPosExB('End Sub', ScriptData[x]) then Break;
ScriptData[x] := '';
end;
end;
end;
Filename := GetTempDir() + 'se_can_delete_qq_' + IntToStr(GetTickCount64()) + '.vbs';
TmpFile := GetTempDir() + 'se_can_delete_qq_' + IntToStr(GetTickCount64()) + '.tmp';
Try
ScriptData.SaveToFile(Filename, TEncoding.ANSI); // Important: VBS scripts don't like no UTF8 encoding!
except
{$IFDEF Debug_GenerateDebugLog} on E : Exception do DebugLog('Error: Analyze_GenuineWindows Save Exception: ' + E.Message); {$ENDIF}
end;
ScriptData.Free;
If FileExists_Cached(Filename) = False then
begin
{$IFDEF Debug_GenerateDebugLog} DebugLog('Analyze_GenuineWindows Exit-4'); {$ENDIF}
FPiratedWindows := True; // yeah, we gonna assume pirated Windows in this case, too
EXIT;
End;
x := RunBatchFileAndWait_GetCount();
ShellExecuteDo('cmd.exe', '/C cscript /Nologo "' + Filename + '" /DLI > "' + TmpFile + '"');