Debian Codegraph @

Source/exehead/Main.c

raw
1 /*
2 * main.c: executable header main code
3 *
4 * This file is a part of NSIS.
5 *
6 * Copyright (C) 1999-2026 Nullsoft and Contributors
7 *
8 * Licensed under the zlib/libpng license (the "License");
9 * you may not use this file except in compliance with the License.
10 *
11 * Licence details can be found in the file COPYING.
12 *
13 * This software is provided 'as-is', without any express or implied
14 * warranty.
15 */
16
17 #include "../Platform.h"
18 #include <shlobj.h>
19 #include "resource.h"
20 #include "util.h"
21 #include "fileform.h"
22 #include "state.h"
23 #include "ui.h"
24 #include "lang.h"
25 #include "exec.h"
26 #include "plugin.h"
27
28 #ifndef LOAD_LIBRARY_SEARCH_USER_DIRS
29 #define LOAD_LIBRARY_SEARCH_USER_DIRS 0x00000400
30 #define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
31 #endif
32 #ifndef SHTDN_REASON_FLAG_PLANNED
33 #define SHTDN_REASON_FLAG_PLANNED 0x80000000
34 #endif
35 #ifndef SHTDN_REASON_MAJOR_APPLICATION
36 #define SHTDN_REASON_MAJOR_APPLICATION 0x00040000
37 #endif
38 #ifndef SHTDN_REASON_MINOR_INSTALLATION
39 #define SHTDN_REASON_MINOR_INSTALLATION 0x0002
40 #endif
41 #ifndef SHUTDOWN_RESTART
42 #define SHUTDOWN_RESTART 0x00000004
43 #endif
44 #ifndef SHUTDOWN_FORCE_OTHERS
45 #define SHUTDOWN_FORCE_OTHERS 0x00000001
46 #endif
47 #ifndef SHUTDOWN_GRACE_OVERRIDE
48 #define SHUTDOWN_GRACE_OVERRIDE 0x00000020
49 #endif
50
51 #if defined(_MSC_VER) && _MSC_VER >= 1200
52 EXTERN_C IMAGE_DOS_HEADER __ImageBase;
53 #define HINST_THISCOMPONENT ( (HINSTANCE) &__ImageBase )
54 #define HINST_APPLICATION HINST_THISCOMPONENT
55 #else
56 #define HINST_APPLICATION ( (HINSTANCE) GetModuleHandle(NULL) )
57 #endif
58
59 #if !defined(NSIS_CONFIG_VISIBLE_SUPPORT) && !defined(NSIS_CONFIG_SILENT_SUPPORT)
60 #error One of NSIS_CONFIG_SILENT_SUPPORT or NSIS_CONFIG_VISIBLE_SUPPORT must be defined.
61 #endif
62 #ifdef NSIS_COMPRESS_WHOLE
63 extern HANDLE dbd_hFile;
64 #endif
65
66 TCHAR g_caption[NSIS_MAX_STRLEN*2]; // Why does this have to be NSIS_MAX_STRLEN*2?
67 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
68 HWND g_hwnd;
69 HANDLE g_hInstance;
70 #endif
71 void *g_SHGetFolderPath;
72 DWORD g_WinVer;
73
74 void NSISCALL CleanUp();
75
76 TCHAR *ValidateTempDir()
77 {
78 validate_filename(state_temp_dir);
79 if (!validpathspec(state_temp_dir))
80 return NULL;
81 addtrailingslash(state_temp_dir);
82 CreateNormalDirectory(state_temp_dir);
83 // state_language is used as a temp var here
84 return my_GetTempFileName(state_language, state_temp_dir);
85 }
86
87
88 NSIS_ENTRYPOINT_GUINOCRT
89 EXTERN_C void NSISWinMainNOCRT()
90 {
91 int ret = 0;
92 const TCHAR *m_Err = _LANG_ERRORWRITINGTEMP;
93 int cl_flags = 0;
94
95 TCHAR *realcmds;
96 TCHAR seekchar=_T(' ');
97 TCHAR *cmdline;
98 OSVERSIONINFOEX ovi;
99
100 SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
101
102 // Get the version as reported by Windows
103 if (sizeof(void*) < 8)
104 {
105 *((UINT32*)&ovi.szCSDVersion[0]) = 0; // Zero out SP
106 *((UINT64*)&ovi.wServicePackMajor) = 0; // wServicePackMajor, wSuiteMask and wProductType
107 }
108 ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
109 if (!GetVersionEx((OSVERSIONINFO*) &ovi) && sizeof(void*) < 8)
110 {
111 ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
112 GetVersionEx((OSVERSIONINFO*) &ovi);
113 if (sizeof(TCHAR) == 2 || ovi.dwPlatformId == VER_PLATFORM_WIN32_NT)
114 {
115 ovi.wProductType = 4; // TODO: For < NT4SP6, look it up in the registry. 4 means not W9x and not VER_NT_*
116 ovi.wServicePackMajor = ovi.szCSDVersion[0] == 'S' ? ovi.szCSDVersion[13] - '0' : 0;
117 }
118 }
119 if (sizeof(TCHAR) == 1 && ovi.dwPlatformId < VER_PLATFORM_WIN32_NT)
120 {
121 ovi.wProductType = 0;
122 ovi.wServicePackMajor = ovi.szCSDVersion[1] >= 'A' ? ovi.szCSDVersion[1] - ('A'-1) : 0; // A, B or C
123 }
124 if (sizeof(void*) < 8 && ovi.dwMajorVersion < 10) // Ideally (sizeof(TCHAR) == 1 && ovi.dwMajorVersion < 5) but the compatibility tab emulates this bug
125 {
126 ovi.dwBuildNumber &= 0xffff; // Remove W9x garbage
127 }
128 // Save the packed version information
129 {
130 UINT32 *p = &g_osinfo.WVBuild;
131 p[0] = ovi.dwBuildNumber;
132 p[1] = MAKELONG(MAKEWORD(ovi.wProductType, ovi.wServicePackMajor), MAKEWORD(ovi.dwMinorVersion, ovi.dwMajorVersion));
133 }
134
135 {
136 // bug #1125: Don't load modules from the application nor current directory.
137 // SetDefaultDllDirectories() allows us to restrict implicitly loaded and
138 // dynamically loaded modules to just %windir%\System32 and directories
139 // added with AddDllDirectory(). This prevents DLL search order attacks (CAPEC-471).
140 // CoCreateInstance(CLSID_ShellLink, ...) fails on Vista if SetDefaultDllDirectories is called
141 BOOL avoidwinbug = IsWinVista();
142 if (!avoidwinbug)
143 {
144 FARPROC fp = myGetProcAddress(MGA_SetDefaultDllDirectories);
145 if (fp) ((BOOL(WINAPI*)(DWORD))fp)(LOAD_LIBRARY_SEARCH_SYSTEM32|LOAD_LIBRARY_SEARCH_USER_DIRS);
146 }
147 // SetDefaultDllDirectories might not be available so we try to preload various libraries as
148 // best we can before Windows gets a chance to mess things up by loading from the wrong directory.
149 {
150 static const char preload[] =
151 "UXTHEME\0" // Vista: OleInitialize calls NtUserCreateWindowEx and that pulls in UXTheme.dll
152 "USERENV\0" // Vista: SHGetFileInfo ends up in SHELL32.kfapi::GetUserProfileDir and that pulls in UserEnv.dll
153 "SETUPAPI\0" // XP: SHGetFileInfo ends up in CMountPoint::_InitLocalDriveHelper and that pulls in SetupAPI.dll
154 "APPHELP\0" // Vista: SHGetFileInfo ... SHELL32.SHILAliasTranslate ... SHELL32.ApphelpCheckShellObject
155 "PROPSYS\0" // Vista: SHGetFileInfo ... SHELL32.SHILAliasTranslate ... SHLWAPI.#187 ... SHLWAPI.#505/SHPropertyBag_ReadGUID
156 "DWMAPI\0" // Win7 without KB2533623: UXTheme pulls in DWMAPI.dll
157 "CRYPTBASE\0" // Win7 without KB2533623: OleInitialize ... RPCRT4.UuidCreate ... RPCRT4.GenerateRandomNumber
158 "OLEACC\0" // Vista: SHFileOperation ... SHELL32.CProgressDialogUI::_Setup ... SHELL32.GetRoleTextW
159 "CLBCATQ\0" // XP.SP2&SP3: SHAutoComplete ... OLE32!InitializeCatalogIfNecessary ... OLE32!CComCatalog::TryToLoadCLB
160 "NTMARTA\0" // Win7 without KB2533623 (Bug #1204): SHGetFileInfo ... SetEntriesInAcl ... ADVAPI32!AccProvpLoadMartaFunctions
161 #ifndef NSIS_SUPPORT_GETDLLVERSION
162 "VERSION\0"
163 #endif
164 ;
165 const char *dll;
166 for (dll = preload; dll[0]; dll += lstrlenA(dll) + 1)
167 LoadSystemLibrary(dll);
168 }
169 }
170
171 // Because myGetProcAddress now loads dlls with a full path
172 // under GetSystemDirectory() the previous issues in <= v3.0b2 with
173 // 'SetOutPath' and/or 'File "shfolder.dll"' no longer apply.
174 // All MGA dlls still need to be loaded early here because installers
175 // running under WoW64 might disable WoW64 FS redirection in .onInit and
176 // because GetSystemDirectory() can return the native system32 path we need
177 // the redirection to be turned off so LoadLibrary uses the correct folder.
178 // Note: We also import directly from KERNEL32, ADVAPI32 and SHELL32 so they
179 // are exempt from this requirement and SHELL32 imports from SHLWAPI on
180 // WoW64 systems and it is also on the KnownDLLs list so
181 // SHLWAPI also gets a pass and that just leaves
182 #ifdef NSIS_SUPPORT_GETDLLVERSION
183 myGetProcAddress(MGA_GetFileVersionInfo); // VERSION
184 #endif
185 g_SHGetFolderPath = myGetProcAddress(MGA_SHGetFolderPath); // and SHFOLDER
186
187 #ifndef _WIN64
188 {
189 // KEY_WOW64_xxKEY flags causes registry functions to fail on WinNT4 & Win2000.
190 // We don't filter them out because all registry instructions are supposed to fail when
191 // accessing a unsupported view and RegKey* takes care of that by looking at the WOW64 flag.
192 FARPROC fp = myGetProcAddress(MGA_IsOS);
193 enum { os_wow6432 = 30 };
194 if (fp && ((BOOL(WINAPI*)(UINT))fp)(os_wow6432)) g_osinfo.WVProd |= NSIS_OSINFO_PROD_WOW64FLAG;
195 }
196 #endif
197
198 InitCommonControls();
199
200 #if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
201 {
202 extern HRESULT g_hres;
203 g_hres=OleInitialize(NULL);
204 }
205 #endif
206
207
208 {
209 // workaround for bug #1008632
210 // http://sourceforge.net/tracker/index.php?func=detail&aid=1008632&group_id=22049&atid=373085
211 //
212 // without this, SHGetSpecialFolderLocation doesn't always recognize
213 // some special folders, like the desktop folder for all users, on
214 // Windows 9x. unlike SHGetSpecialFolderPath, which is not available
215 // on all versions of Windows, SHGetSpecialFolderLocation doesn't try
216 // too hard to make sure the caller gets what he asked for. so we give
217 // it a little push in the right direction by doing part of the work
218 // for it.
219 //
220 // part of what SHGetFileInfo does, is to convert a path into an idl.
221 // to do this conversion, it first needs to initialize the list of
222 // special idls, which are exactly the idls we use to get the paths
223 // of special folders (CSIDL_*).
224
225 SHFILEINFO shfi;
226 SHGetFileInfo(_T(""), 0, &shfi, sizeof(SHFILEINFO), 0);
227 }
228
229 mystrcpy(g_caption,_LANG_GENERIC_ERROR);
230
231 mystrcpy(state_command_line, GetCommandLine());
232
233 #ifdef NSIS_CONFIG_VISIBLE_SUPPORT
234 g_hInstance = HINST_APPLICATION;
235 #endif//NSIS_CONFIG_VISIBLE_SUPPORT
236
237 cmdline = state_command_line;
238 if (*cmdline == _T('\"')) seekchar = *cmdline++;
239
240 cmdline=findchar(cmdline, seekchar);
241 cmdline=CharNext(cmdline);
242 realcmds=cmdline;
243
244 while (*cmdline)
245 {
246 // skip over any spaces
247 while (*cmdline == _T(' ')) cmdline++;
248
249 // get char we should look for to get the next parm
250 seekchar = _T(' ');
251 if (cmdline[0] == _T('\"'))
252 {
253 cmdline++;
254 seekchar = _T('\"');
255 }
256
257 // is it a switch?
258 if (cmdline[0] == _T('/'))
259 {
260 cmdline++;
261
262 #define END_OF_ARG(c) (c == _T(' ') || c == _T('\0'))
263
264 #if defined(NSIS_CONFIG_VISIBLE_SUPPORT) && defined(NSIS_CONFIG_SILENT_SUPPORT)
265 if (cmdline[0] == _T('S') && END_OF_ARG(cmdline[1]))
266 g_exec_flags.silent = 1; // bug #1076 - just set the silent flag. the user really wants it silent.
267 // loadHeaders() will not reset this as it uses |= to apply the script flags.
268 // there is also no option to force non-silent like `CRCCheck force`
269 #endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT
270 #ifdef NSIS_CONFIG_CRC_SUPPORT
271 if (CMP4CHAR(cmdline, _T("NCRC")) && END_OF_ARG(cmdline[4]))
272 cl_flags |= FH_FLAGS_NO_CRC;
273 #endif//NSIS_CONFIG_CRC_SUPPORT
274
275 if (CMP4CHAR(cmdline-2, _T(" /D=")))
276 {
277 *(cmdline-2)=_T('\0'); // keep this from being passed to uninstaller if necessary
278 mystrcpy(state_install_directory,cmdline+2);
279 break; // /D= must always be last
280 }
281 }
282
283 // skip over our parm
284 cmdline = findchar(cmdline, seekchar);
285 // skip the quote
286 if (*cmdline == _T('\"'))
287 cmdline++;
288 }
289
290 GetTempPath(NSIS_MAX_STRLEN, state_temp_dir);
291 if (!ValidateTempDir())
292 {
293 GetWindowsDirectory(state_temp_dir, NSIS_MAX_STRLEN - 5); // leave space for \Temp
294 mystrcat(state_temp_dir, _T("\\Temp"));
295 if (!ValidateTempDir())
296 {
297 // Bug #1326:
298 // Don't try the Low IL temp directory if we are elevated.
299 // This prevents the SYSTEM user from using the shared c:\Windows\Temp\Low directory.
300 if (UserIsAdminGrpMember()) goto end;
301
302 // Bug #2909242:
303 // When running at <= Low IL we cannot write to %Temp% but we can try the temp folder used by IE.
304 // There does not seem to be a API to get the low temp dir directly, so we build the path on our own
305
306 GetTempPath(NSIS_MAX_STRLEN - 4, state_temp_dir); // leave space for \Low
307 mystrcat(state_temp_dir, _T("Low"));
308
309 // If we don't call SetEnvironmentVariable
310 // child processes will use %temp% and not %temp%\Low
311 // and some apps probably can't handle a read only %temp%
312 // Do it before ValidateTempDir() because it appends a backslash.
313 // TODO: Should this be moved to ValidateTempDir() so it also updates for %windir%\Temp?
314 SetEnvironmentVariable(_T("TEMP"), state_temp_dir);
315 SetEnvironmentVariable(_T("TMP"), state_temp_dir);
316
317 if (!ValidateTempDir())
318 {
319 goto end;
320 }
321 }
322 }
323 DeleteFile(state_language);
324
325 m_Err = loadHeaders(cl_flags);
326 if (m_Err) goto end;
327
328 #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
329 if (g_is_uninstaller)
330 {
331 TCHAR *p = findchar(state_command_line, 0);
332
333 // state_command_line has state_install_directory right after it in memory, so reading
334 // a bit over state_command_line won't do any harm
335 while (p >= state_command_line && !CMP4CHAR(p, _T(" _?="))) p--;
336
337 m_Err = _LANG_UNINSTINITERROR;
338
339 if (p >= state_command_line)
340 {
341 *p=0; // terminate before "_?="
342 p+=4; // skip over " _?="
343 if (is_valid_instpath(p))
344 {
345 mystrcpy(state_install_directory, p);
346 mystrcpy(state_output_directory, p);
347 m_Err = 0;
348 }
349 else
350 {
351 goto end;
352 }
353 }
354 else
355 {
356 int admin = UserIsAdminGrpMember();
357 WORD tries; // 0xfffe attempts or bust
358 size_t cchtmpslash = mystrlen(state_temp_dir);
359 LPTSTR unexe = g_usrvars[5], unexecmd = g_usrvars[6];
360
361 mystrcpy(g_usrvars[0], realcmds);
362 if (!(*state_install_directory))
363 {
364 mystrcpy(state_install_directory, state_exe_directory);
365 }
366
367 for (tries = 0; ++tries != 0;)
368 {
369 DWORD retry = 0, ec;
370 retry_un_dir:
371 wsprintf(state_temp_dir + cchtmpslash, _T("~nsu%X.tmp"), tries);
372 GetNSISString(unexe, g_header->str_uninstchild); // '$TEMP\Un.exe'
373 if (admin)
374 {
375 ec = CreateRestrictedDirectory(state_temp_dir);
376 }
377 else
378 {
379 ec = CreateNormalDirectory(state_temp_dir);
380 }
381
382 if (ec)
383 {
384 // Delete previous uninstaller (if it is safe to do so) (Bug #1296)
385 if (!(GetFileAttributes(unexe) & FILE_ATTRIBUTE_REPARSE_POINT) && DeleteFile(unexe))
386 {
387 myDelete(state_temp_dir, DEL_DIR);
388 if (!retry++) goto retry_un_dir;
389 }
390 }
391 else
392 {
393 HANDLE hProc;
394 SetCurrentDirectory(state_temp_dir);
395 #ifdef NSIS_SUPPORT_MOVEONREBOOT
396 MoveFileOnReboot(state_temp_dir, NULL);
397 #endif
398 if (CopyFile(state_exe_path, unexe, TRUE))
399 {
400 #ifdef NSIS_SUPPORT_MOVEONREBOOT
401 MoveFileOnReboot(unexe, NULL);
402 #endif
403 GetNSISString(unexecmd, g_header->str_uninstcmd); // '"$TEMP\Un.exe" $0 _?=$INSTDIR\'
404 hProc = myCreateProcess(unexecmd);
405 if (hProc)
406 {
407 CloseHandle(hProc);
408 m_Err = 0; // Success
409 }
410 else if (!retry++ && !file_exists(unexe))
411 {
412 // Another instance deleted us between CopyFile and CreateProcess
413 goto retry_un_dir;
414 }
415 }
416 break; // We called CreateProcess; success or failure, we are done.
417 }
418 }
419 goto end;
420 }
421 }
422 #endif//NSIS_CONFIG_UNINSTALL_SUPPORT
423
424 g_exec_flags.errlvl = -1;
425 ret = ui_doinstall();
426
427 #ifdef NSIS_CONFIG_LOG
428 #if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT)
429 log_write(1);
430 #endif//!NSIS_CONFIG_LOG_ODS && !NSIS_CONFIG_LOG_STDOUT
431 #endif//NSIS_CONFIG_LOG
432 end:
433
434 CleanUp();
435
436 #if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
437 OleUninitialize();
438 #endif
439
440 if (m_Err)
441 {
442 my_MessageBox(m_Err, MB_OK | MB_ICONSTOP | (IDOK << 21));
443 ExitProcess(2);
444 }
445
446 #ifdef NSIS_SUPPORT_REBOOT
447 if (g_exec_flags.reboot_called)
448 {
449 const DWORD reason = SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION;
450 BOOL (WINAPI *IS)(LPTSTR,LPTSTR,DWORD,DWORD,DWORD);
451 HANDLE hToken;
452 TOKEN_PRIVILEGES tkp;
453 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
454 {
455 LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
456 tkp.PrivilegeCount = 1;
457 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
458 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
459 }
460
461 IS=myGetProcAddress(MGA_InitiateShutdown);
462 if ( (IS && !IS(NULL, NULL, 0, SHUTDOWN_RESTART | SHUTDOWN_FORCE_OTHERS | SHUTDOWN_GRACE_OVERRIDE, reason))
463 || (!ExitWindowsEx(EWX_REBOOT, reason))
464 )
465 ExecuteCallbackFunction(CB_ONREBOOTFAILED);
466 }
467 #endif//NSIS_SUPPORT_REBOOT
468
469 if (g_exec_flags.errlvl != -1)
470 ret = g_exec_flags.errlvl;
471
472 ExitProcess(ret);
473 }
474
475 void NSISCALL CleanUp()
476 {
477 if (g_db_hFile != INVALID_HANDLE_VALUE)
478 {
479 CloseHandle(g_db_hFile);
480 g_db_hFile = INVALID_HANDLE_VALUE;
481 }
482 #ifdef NSIS_COMPRESS_WHOLE
483 if (dbd_hFile != INVALID_HANDLE_VALUE)
484 {
485 CloseHandle(dbd_hFile);
486 dbd_hFile = INVALID_HANDLE_VALUE;
487 }
488 #endif
489 #ifdef NSIS_CONFIG_PLUGIN_SUPPORT
490 // Notify plugins that we are about to unload
491 Plugins_UnloadAll();
492
493 // Clean up after plug-ins
494 myDelete(state_plugins_dir, DEL_DIR | DEL_RECURSE | DEL_REBOOT);
495 #endif // NSIS_CONFIG_PLUGIN_SUPPORT
496 #ifdef DEBUG
497 // GlobalFree(g_header); ?
498 #endif
499 }