Dynamic password in Inno Setup - inno-setup

I need that my program be protected with a dynamic password that includes the current date.
I need just the month or the day or the hour or the minute.
I tried this code to include the day into the password:
[Setup]
Password=Password!{code:DateTime|0}
[Code]
function DateTime (Param: string): string;
begin
Result := GetDateTimeString('dd', #0, #0);
end;
But it's not working.
Regards.

The Password directive cannot contain any constants, let alone scripted constants.
So your script makes the password be literally Password!{code:DateTime|0}.
Instead, use CheckPassword event function:
[Code]
function CheckPassword(Password: String): Boolean;
begin
Result := (Password = ('Password!' + GetDateTimeString('dd', #0, #0)));
end;
Though safer than comparing against a literal string (which can be seen in .exe binary) is comparing a checksum.
See How to do a dynamic password in Inno Setup?

Related

Array variables and dynamic access in [Code] section

My installer has Components which come associated with downloadable files. These things are changing from build to build, so I'm using #insert to create the [Components] section as well as the appropriate entries in the [Files] section.
Some of these components rely on common downloadable files.
To now include the correct urls in the downloads page, I'm currently defining array variables that are named like the component and have as values the names of the required downloadable files, for example:
#dim myfeature[2] {"01aed27862e2087bd117e9b677a8685aebb0be09744723b4a948ba78d6011bac", "677756ac5969f814fd01ae677dbb832ab2e642513fea44ea0a529430d5ec1fdc"}
In the code for the download page I'm checking which components where selected via WizardSelectedComponents() and after converting the string to an array of strings, I'm trying to get to the previously defined variable and that is where I'm failing:
function GetDownloads(): Array of String;
var
Downloads: Array of String;
SelectedComponents: String;
SelectedArray: Array of String;
begin
SelectedComponents := WizardSelectedComponents(False);
// a custom procedure to parse the comma seperated string
SelectedArray := ParseArray(SelectedComponents, SelectedArray);
// trying to get to the constant array now this works:
MsgBox(ExpandConstant('{#myfeature[0]}'), mbInformation, MB_OK);
// same but trying to use the selected component value returns this as a literal
// '+SelectedArray[0]+' instead the expanded value
MsgBox(ExpandConstant('{#' + SelectedArray[0] + '[0]}'), mbInformation, MB_OK);
end;
So I understand something is up with the # mark but I could not find a way to solve this properly.
Thank you!
Markus
ExpandConstant expands Inno Setup "constants", not preprocessor values. See also Evaluate preprocessor macro on run time in Inno Setup Pascal Script.
You cannot access elements of a preprocessor compile-time array using run-time indexes.
If you know C/C++, it's like if you were trying to do:
#define VALUE1 123
#define VALUE2 456
int index = 1;
int value = VALUE ## index
I'm not really sure I completely understand what are you doing. But it seems that you need to create an array on compile time from various sources and use it on runtime.
There are several approaches that can be used for that. But you definitely need runtime array initialized on run time. But the code that initializes it can be generated on compile time.
An example of the approach follows (and some links to other approaches are at the end).
At the beginning of your script, define these support functions:
[Code]
var
FeatureDownloads: TStrings;
function AddFeature(
Feature: Integer; CommaSeparatedListOfDownloads: string): Boolean;
begin
if not Assigned(FeatureDownloads) then
begin
FeatureDownloads := TStringList.Create();
end;
while FeatureDownloads.Count <= Feature do
FeatureDownloads.Add('');
if FeatureDownloads[Feature] <> '' then
RaiseException('Downloads for feature already defined');
FeatureDownloads[Feature] := CommaSeparatedListOfDownloads;
Result := True;
end;
#define AddFeature(Feature, CommaSeparatedListOfDownloads) \
"<event('InitializeSetup')>" + NewLine + \
"function InitializeSetupFeature" + Str(Feature) + "(): Boolean;" + NewLine + \
"begin" + NewLine + \
" Result := AddFeature(" + Str(Feature) + ", '" + CommaSeparatedListOfDownloads + "');" + NewLine + \
"end;"
In your components include files, do:
#emit AddFeature(2, "01aed27862e2087bd117e9b677a8685aebb0be09744723b4a948ba78d6011bac,677756ac5969f814fd01ae677dbb832ab2e642513fea44ea0a529430d5ec1fdc")
If you add:
#expr SaveToFile(AddBackslash(SourcePath) + "Preprocessed.iss")
to the end of your main script, you will see in the Preprocessed.iss generated by the preprocessor/compiler that the #emit directive expands to:
<event('InitializeSetup')>
function InitializeSetupFeature2(): Boolean;
begin
Result := AddFeature(2, '01aed27862e2087bd117e9b677a8685aebb0be09744723b4a948ba78d6011bac,677756ac5969f814fd01ae677dbb832ab2e642513fea44ea0a529430d5ec1fdc');
end;
Now you have FeatureDownloads Pascal Script runtime variable that you can access using FeatureDownloads[SelectedArray[0]] to get comma-separated string, which you can parse to the individual downloads.
This can be optimimized/improved a lot, but I do not know/understand the extent of your task. But I believe that once you grasp the concept (it might be difficult at the beginning), you will be able to do it yourself.
Another similar questions:
Evaluate a collection of data from preprocessor on run time in Inno Setup Pascal Script (simple example that be easier to grasp initially)
Scripting capabilities in the Registry section (slightly different approach from times event attributes were not available yet – and that's YOUR question)

Skip files during installation depending on text file command line argument

My scenario is currently that I'd like the possibility for users to skip installation of certain files that a user might have specified via a command line argument at install time.
The idea would be for the user to specify a text file and ideally during installation, the installer would check if the file currently being copied is listed in the supplied text file and decide depending on that.
My [Files] section atm is referencing full directories: would the best approach be to list all files individually and make use of the Check parameter or is there a different approach available? There seems to be no event function that would lend itself for this task.
Thanks
Markus
No need to list all files individually. The Check function is called for each file individually, even when the Source is a wildcard.
Use the CurrentFilename function to tell what file is being processed at the moment.
Note that the Check function is called multiple times for each file.
[Files]
Source: "C:\path\*.*"; DestDir: "{app}"; Check: AllowFile
[Code]
var
Whitelist: TStringList;
function AllowFile: boolean;
var
FileName: string;
begin
FileName := ExtractFileName(ExpandConstant(CurrentFileName));
Result := (Whitelist = nil) or (Whitelist.IndexOf(Uppercase(FileName)) >= 0);
if Result then
Log(Format('Allowing "%s"', [FileName]))
else
Log(Format('Skipping "%s"', [FileName]));
end;
function InitializeSetup(): Boolean;
var
WhitelistFile: string;
Lines: TArrayOfString;
I: Integer;
begin
WhitelistFile := ExpandConstant('{param:Whitelist}');
if WhitelistFile = '' then
begin
Log('No whitelist specified, allowing all files');
end
else
begin
Whitelist := TStringList.Create;
Whitelist.Sorted := True;
LoadStringsFromFile(WhitelistFile, Lines);
for I := 0 to GetArrayLength(Lines) - 1 do
Whitelist.Add(Uppercase(Lines[I]));
Log(Format('Loaded %d entries to whitelist from "%s"', [
Whitelist.Count, WhitelistFile]));
end;
Result := True;
end;

Disallow empty and spaces-only input on Inno Setup custom page

Is there a way to disallow user input if it contains spaces only?
I already tried this solution:
Inno Setup - Create User Input Query Page with input length and format limit and use the input
But, I don't want that solution because it disable -space- completely.
E.g. if input in text field is "my name" it will return error because -space- is not allowed.
Use the same code as in:
Inno Setup - Create User Input Query Page with input length and format limit and use the input
Just use this implementation of ValidateInput:
function ValidateInput(Sender: TWizardPage): Boolean;
begin
Result := True;
if Trim(Page.Values[0]) = '' then
begin
MsgBox('Input cannot be empty.', mbError, MB_OK);
Result := False;
end;
end;
The Trim function is the key.

How to save a string to a .txt file in Delphi?

I need to make a program that generates a password that is saved in a text file format in a specific destination I set and the user needs to open the .txt to get the password to 'unlock' another program.
I have already got the code to generate the password in the string sPass and now I need to use the SaveToFile function to save it into the text file I created called Password.txt but I cannot find the general form to use the SaveTo File Function in Delphi and I do not know where to put the sPass and Password.txt in the function.
It should be something like : SaveToFile(...) but I do not know how to save sPass in Password.txt
Edit :
Just one more question, how do you delete what is previously stored in Password.txt before you add the string to it so that Password.txt is blank before the string is added ? Thanks
The Modern Modern way is to use TFile.WriteAllText in IOUtils (Delphi 2010 and up)
procedure WriteAllText(const Path: string; const Contents: string);
overload; static;
Creates a new file, writes the specified string to the file, and then
closes the file. If the target file already exists, it is overwritten.
The modern way is to create a stringlist and save that to file.
procedure MakeAStringlistAndSaveThat;
var
MyText: TStringlist;
begin
MyText:= TStringlist.create;
try
MyText.Add('line 1');
MyText.Add('line 2');
MyText.SaveToFile('c:\folder\filename.txt');
finally
MyText.Free
end; {try}
end;
Note that Delphi already has a related class that does everything you want: TInifile.
It stores values and keys in a key = 'value' format.
passwordlist:= TInifile.Create;
try
passwordlist.LoadFromFile('c:\folder\passwords.txt');
//Add or replace a password for `user1`
passwordlist.WriteString('sectionname','user1','topsecretpassword');
passwordlist.SaveToFile('c:\folder\passwords.txt');
finally
passwordlist.Free;
end; {try}
Warning
Note that saving unecrypted passwords in a textfile is a security-leak. It's better to hash your passwords using a hashfunction, see: Password encryption in Delphi
For tips on how to save passwords in a secure way.
You can use the TFileStream class to save a string to a file:
uses
Classes;
procedure StrToFile(const FileName, SourceString : string);
var
Stream : TFileStream;
begin
Stream:= TFileStream.Create(FileName, fmCreate);
try
Stream.WriteBuffer(Pointer(SourceString)^, Length(SourceString));
finally
Stream.Free;
end;
end;
and to read
function FileToStr(const FileName : string):string;
var
Stream : TFileStream;
begin
Stream:= TFileStream.Create(FileName, fmOpenRead);
try
SetLength(Result, Stream.Size);
Stream.Position:=0;
Stream.ReadBuffer(Pointer(Result)^, Stream.Size);
finally
Stream.Free;
end;
end;
Fastest and simplest way, no need to declare any variables:
with TStringList.Create do
try
Add(SomeString);
SaveToFile('c:\1.txt');
finally
Free;
end;

How to change defaultdirname parameter just before Install in Inno Setup?

I want to change defaultdirname parameter in ssInstall part. How can I do that? Is there a function for setting [Setup] parameters.
The following global objects are available :
MainForm of type TMainForm, WizardForm of type TWizardForm and UninstallProgressForm of type TUninstallProgressForm and one special constant: crHand of type TControl.Cursor.
If you want to set the default directory in the wizard, just access to it's componants like you would in normal delphi code.
For example, set the directory to a custom value:
WizardForm.DirEdit.Text := 'c:\test';
to read that value you can use the WizardDirValue function.
I say 'just access'... but it took me an hour to figure out ;)
There seems to be no way to change a script constant via scripting.
I think your best bet is to modify the target directory for each entry in the [Files] section, e.g.
[Files]
Source: "MYPROG.EXE"; DestDir: "{code:NewTargetDir}"
and derive your new installation directory like this:
[Code]
function NewTargetDir(Param: String): String;
begin
Result := ExpandConstant('{app}') + '\MySubDir';
end;
Since the NewTargetDir function will be called just before the file is actually copied, this should work.
However, I think you should reconsider your approach. First asking the user to specify a directory to installinto, and then actually installing into a different directory, which seems to be your intent, is the wrong way, IMO. Do you really have a compelling reason to install into another directory than the one specified by the user? Besides, the result of my example code could just as well be achieved by specifying
[Files]
Source: "MYPROG.EXE"; DestDir: "{app}\MySubDir"
without any scripting needed. When in doubt, go for the simpler solution.
I have a similar situation, where the setup app is receiving the install path from the command line.
I'm using the solution proposed by Jonx:
WizardForm.DirEdit.Text := 'c:\test';
Example:
function CompareParameter(param, expected: String): Boolean;
begin
Result := False;
if Length(param) >= Length(expected) then
begin
if CompareText(Copy(param, 1, Length(expected)), expected) = 0 then
begin
Result := True;
end;
end;
end;
function GetParameter(expectedParam: String): String;
var
i : LongInt;
begin
Result := '';
for i := 0 to ParamCount() do
begin
if CompareParameter(ParamStr(i), '/' + expectedParam + '=') then
begin
Result := Copy(ParamStr(i), Length(expectedParam) + 3, Length(ParamStr(i)));
break;
end;
end;
end;
procedure InitializeWizard();
var
newInstallFolder: String;
begin
newInstallFolder := GetParameter('INSTALL_FOLDER');
if Length(newInstallFolder) > 2 then
begin
if Copy(newInstallFolder, 1, 1) = '"' then
newInstallFolder := Copy(newInstallFolder, 2, Length(newInstallFolder) - 2)
if Length(newInstallFolder) > 1 then
WizardForm.DirEdit.Text := newInstallFolder;
end;
end;
The setup app is being started from another setup, in silent mode. It worked OK for me.

Resources