xref: /trunk/main/desktop/win32/source/setup/setup.cpp (revision c34c9f813125780dafc52d725b4057487d838338)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 // MARKER(update_precomp.py): autogen include statement, do not remove
23 #include "precompiled_desktop.hxx"
24 
25 #define  UNICODE    1
26 #define _UNICODE    1
27 
28 #define WIN // scope W32 API
29 
30 #if defined _MSC_VER
31 #pragma warning(push, 1)
32 #endif
33 #include <windows.h>
34 #if defined _MSC_VER
35 #pragma warning(pop)
36 #endif
37 #include <tchar.h>
38 #include <assert.h>
39 #include <shlwapi.h>
40 #include <new>
41 #include <time.h>
42 #include <mbctype.h>
43 #include <locale.h>
44 #include <Msiquery.h>
45 #include <MsiDefs.h>
46 #include "strsafe.h"
47 
48 #include "setup.hxx"
49 #include "aoo_msi.hxx"
50 
51 #include "resource.h"
52 
53 //--------------------------------------------------------------------------
54 
55 #define MAX_STR_LENGTH     32000
56 #define MAX_TEXT_LENGTH     1024
57 #define MAX_LANGUAGE_LEN      80
58 #define MAX_STR_CAPTION      256
59 #define VERSION_SIZE          80
60 #define SECTION_SETUP       TEXT( "Setup" )
61 #define SECTION_LANGUAGE    TEXT( "Languages" )
62 #define PRODUCT_NAME_VAR    TEXT( "%PRODUCTNAME" )
63 #define PRODUCT_VERSION     TEXT( "ProductVersion" )
64 #define ERROR_SHOW_USAGE      -2
65 #define ERROR_SETUP_TO_OLD    -3
66 #define ERROR_SETUP_NOT_FOUND -4
67 #define ERROR_OS_TO_OLD       -5
68 #define ERROR_RUNTIME_FAILED  -6
69 
70 // Lowest Windows this office can run on: Windows 7 SP1 (6.1 SP1), matching the
71 // WINVER/_WIN32_WINNT 0x0601 the office is compiled for and the MSI launch
72 // condition.  The bundled VC v14 redistributable must still install there --
73 // current releases do not; see external/vcredist/README.
74 #define REQUIRED_WINDOWS_MAJOR  6
75 #define REQUIRED_WINDOWS_MINOR  1
76 #define REQUIRED_WINDOWS_SP     1
77 
78 #define PARAM_SETUP_USED    TEXT( " SETUP_USED=1 " )
79 #define PARAM_PACKAGE       TEXT( "/I " )
80 #define PARAM_MINOR_UPGRADE TEXT( "/FVOMUS " )
81 #define PARAM_ADMIN         TEXT( "/A " )
82 #define PARAM_TRANSFORM     TEXT( " TRANSFORMS=" )
83 #define PARAM_REBOOT        TEXT( " REBOOT=Force" )
84 #define PARAM_PATCH         TEXT( " /update " )
85 #define PARAM_REG_ALL_MSO_TYPES TEXT( "REGISTER_ALL_MSO_TYPES=1 " )
86 #define PARAM_REG_NO_MSO_TYPES  TEXT( "REGISTER_NO_MSO_TYPES=1 " )
87 // The VC v14 redistributable is a Burn bundle, not the old MSI-style installer the
88 // VC++ 2008 package was.  It does not understand /Q; its silent switches are these.
89 // /norestart matters -- without it the bundle may reboot the machine mid-install.
90 #define PARAM_SILENTINSTALL     TEXT( " /install /quiet /norestart" )
91 
92 // Burn exit codes that mean "the runtime is now present".  1638 is
93 // ERROR_PRODUCT_VERSION: a NEWER runtime is already installed, which is success for
94 // our purposes -- it is also the common case on any developer machine.
95 #define RUNTIME_INSTALL_OK          0L
96 #define RUNTIME_INSTALL_NEWER       1638L
97 #define RUNTIME_INSTALL_REBOOT_REQ  3010L
98 
99 #define PARAM_RUNNING           TEXT( "ignore_running" )
100 #define CMDLN_REG_ALL_MSO_TYPES TEXT( "msoreg=1" )
101 #define CMDLN_REG_NO_MSO_TYPES  TEXT( "msoreg=0" )
102 
103 #define ADVAPI32_DLL        TEXT( "advapi32.dll" )
104 #define PROFILE_NAME        TEXT( "setup.ini" )
105 
106 #define RUNTIME_X64_NAME    TEXT( "redist\\vcredist_x64.exe" )
107 #define RUNTIME_X86_NAME    TEXT( "redist\\vcredist_x86.exe" )
108 
109 // There is deliberately no ProductCode here any more.  The old code gated on
110 // MsiQueryProductState() against a hardcoded VC++ 2008 GUID, which cannot work for the
111 // v14 runtime: Microsoft reissues that redistributable with a NEW ProductCode on every
112 // servicing revision, so an exact-GUID test misreports every machine that has anything
113 // other than the one pinned build.  We test for the runtime functionally instead --
114 // see RuntimeAlreadyPresent().
115 
116 #define ADVAPI32API_CheckTokenMembership "CheckTokenMembership"
117 
118 typedef BOOL (WINAPI* PFnCheckTokenMembership)(HANDLE TokenHandle, PSID SidToCheck, PBOOL IsMember);
119 
120 #ifdef DEBUG
OutputDebugStringFormat(LPCTSTR pFormat,...)121 inline void OutputDebugStringFormat( LPCTSTR pFormat, ... )
122 {
123     TCHAR    buffer[1024];
124     va_list  args;
125 
126     va_start( args, pFormat );
127     StringCchVPrintf( buffer, sizeof(buffer), pFormat, args );
128     OutputDebugString( buffer );
129 }
130 #else
OutputDebugStringFormat(LPCTSTR,...)131 static inline void OutputDebugStringFormat( LPCTSTR, ... )
132 {
133 }
134 #endif
135 
136 //--------------------------------------------------------------------------
137 
138 const TCHAR sMsiExe[]        = TEXT( "\\msiexec.exe" );
139 const TCHAR sDelayReboot[]   = TEXT( " /c:\"msiinst /delayreboot\"" );
140 const TCHAR sMsiQuiet[]      = TEXT( " /q" );
141 const TCHAR sMemMapName[]    = TEXT( "Global\\MsiErrorObject" );
142 
143 //--------------------------------------------------------------------------
SetupApp()144 SetupApp::SetupApp()
145 {
146     m_uiRet         = ERROR_SUCCESS;
147 
148     // Get OS version
149     OSVERSIONINFO sInfoOS;
150 
151     ZeroMemory( &sInfoOS, sizeof(OSVERSIONINFO) );
152     sInfoOS.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
153 
154     GetVersionEx( &sInfoOS );
155 
156     m_nOSVersion    = sInfoOS.dwMajorVersion;
157     m_nMinorVersion = sInfoOS.dwMinorVersion;
158     m_bIsWin9x      = ( VER_PLATFORM_WIN32_NT != sInfoOS.dwPlatformId );
159     m_bNeedReboot   = false;
160     m_bAdministrative = false;
161 
162     m_hInst     = NULL;
163     m_hMapFile  = NULL;
164     m_pAppTitle = NULL;
165     m_pCmdLine  = NULL;
166 
167     m_pDatabase = NULL;
168     m_pReqVersion   = NULL;
169     m_pProductName  = NULL;
170     m_pAdvertise    = NULL;
171     m_pTmpName      = NULL;
172     m_pLogFile      = NULL;
173     m_pModuleFile   = NULL;
174     m_pPatchFiles   = NULL;
175     m_pMSIErrorCode = NULL;
176     m_pUpgradeKey   = NULL;
177     m_pProductVersion = NULL;
178 
179     m_pErrorText    = new TCHAR[ MAX_TEXT_LENGTH ];
180     m_pErrorText[0] = '\0';
181 
182     m_nLanguageID     = 0;
183     m_nLanguageCount  = 0;
184     m_ppLanguageList  = NULL;
185 
186     m_bQuiet          = false;
187     m_bRegNoMsoTypes  = false;
188     m_bRegAllMsoTypes = false;
189     m_bIsMinorUpgrade = false;
190     m_bSupportsPatch  = false;
191 
192     m_bIgnoreAlreadyRunning = false;
193 }
194 
195 //--------------------------------------------------------------------------
~SetupApp()196 SetupApp::~SetupApp()
197 {
198     if ( m_ppLanguageList )
199     {
200         for ( int i = 0; i < m_nLanguageCount; i++ )
201             if ( m_ppLanguageList[i] )
202                 delete m_ppLanguageList[ i ];
203         delete [] m_ppLanguageList;
204     }
205 
206     time_t aTime;
207     time( &aTime );
208     tm *pTime = localtime( &aTime );   // Convert time to struct tm form
209 
210     Log( TEXT( "End: %s\n\r\n\r\n" ), _tasctime( pTime ) );
211 
212     if ( m_pLogFile ) fclose( m_pLogFile );
213 
214     if ( m_pTmpName )
215     {
216         _tremove( m_pTmpName );
217         free( m_pTmpName );
218     }
219 
220     if ( m_pMSIErrorCode ) UnmapViewOfFile( m_pMSIErrorCode );
221     if ( m_hMapFile ) CloseHandle( m_hMapFile );
222 
223     if ( m_pAppTitle ) delete [] m_pAppTitle;
224     if ( m_pDatabase ) delete [] m_pDatabase;
225     if ( m_pReqVersion ) delete [] m_pReqVersion;
226     if ( m_pProductName ) delete [] m_pProductName;
227     if ( m_pAdvertise )   delete [] m_pAdvertise;
228     if ( m_pLogFile )     delete [] m_pLogFile;
229     if ( m_pErrorText )   delete [] m_pErrorText;
230     if ( m_pModuleFile )  delete [] m_pModuleFile;
231     if ( m_pPatchFiles )  delete [] m_pPatchFiles;
232     if ( m_pUpgradeKey )  delete [] m_pUpgradeKey;
233     if ( m_pProductVersion ) delete [] m_pProductVersion;
234 }
235 
236 //--------------------------------------------------------------------------
Initialize(HINSTANCE hInst)237 boolean SetupApp::Initialize( HINSTANCE hInst )
238 {
239     m_pCmdLine  = WIN::GetCommandLine();
240     m_hInst     = hInst;
241 
242     // Load our AppTitle (caption)
243     m_pAppTitle     = new TCHAR[ MAX_STR_CAPTION ];
244     m_pAppTitle[0]  = '\0';
245     WIN::LoadString( hInst, IDS_APP_TITLE, m_pAppTitle, MAX_STR_CAPTION );
246 
247     // Obtain path we are running from
248     m_pModuleFile       = new TCHAR[ MAX_PATH ];
249     m_pModuleFile[ 0 ]  = '\0';
250 
251     if ( 0 == WIN::GetModuleFileName( hInst, m_pModuleFile, MAX_PATH ) )
252     {
253         SetError( WIN::GetLastError() );
254         return false;
255     }
256 
257     if ( ! GetCmdLineParameters( &m_pCmdLine ) )
258         return false;
259 
260     m_hMapFile = CreateFileMapping(
261                  INVALID_HANDLE_VALUE,      // use paging file
262                  NULL,                      // default security
263                  PAGE_READWRITE,            // read/write access
264                  0,                         // max. object size
265                  sizeof( int ),             // buffer size
266                  sMemMapName );
267     if ( m_hMapFile )
268     {
269         m_pMSIErrorCode = (int*) MapViewOfFile( m_hMapFile,  // handle to map object
270                         FILE_MAP_ALL_ACCESS,   // read/write permission
271                         0,
272                         0,
273                         sizeof( int ) );
274         if ( m_pMSIErrorCode )
275             *m_pMSIErrorCode = 0;
276         else
277             OutputDebugStringFormat( TEXT("Could not map view of file (%d).\n"), GetLastError() );
278     }
279     else
280         OutputDebugStringFormat( TEXT("Could not create file mapping object (%d).\n"), GetLastError() );
281 
282     Log( TEXT("Starting: %s\r\n"), m_pModuleFile );
283     Log( TEXT(" CommandLine=<%s>\r\n"), m_pCmdLine );
284 
285     if ( m_bQuiet )
286         Log( TEXT(" Using quiet install mode\r\n") );
287 
288     time_t aTime;
289     time( &aTime );
290     tm* pTime = localtime( &aTime );
291     Log( TEXT(" Begin: %s\n"), _tasctime( pTime ) );
292 
293     return true;
294 }
295 
296 //--------------------------------------------------------------------------
GetProfileSection(LPCTSTR pFileName,LPCTSTR pSection,DWORD & rSize,LPTSTR * pRetBuf)297 boolean SetupApp::GetProfileSection( LPCTSTR pFileName, LPCTSTR pSection,
298                                       DWORD& rSize, LPTSTR *pRetBuf )
299 {
300     if ( !rSize || !*pRetBuf )
301     {
302         rSize = 512;
303         *pRetBuf = new TCHAR[ rSize ];
304     }
305 
306     DWORD nRet = GetPrivateProfileSection( pSection, *pRetBuf, rSize, pFileName );
307 
308     if ( nRet && ( nRet + 2 > rSize ) ) // buffer was too small, retry with bigger one
309     {
310         if ( nRet < 32767 - 2 )
311         {
312             delete [] (*pRetBuf);
313             rSize = nRet + 2;
314             *pRetBuf = new TCHAR[ rSize ];
315 
316             nRet = GetPrivateProfileSection( pSection, *pRetBuf, rSize, pFileName );
317         }
318     }
319 
320     if ( !nRet )
321     {
322         SetError( WIN::GetLastError() );
323 
324         TCHAR sBuf[80];
325         StringCchPrintf( sBuf, 80, TEXT("ERROR: GetPrivateProfileSection(): GetLastError returned %u\r\n"), GetError() );
326         Log( sBuf );
327         return false;
328     }
329     else if ( nRet + 2 > rSize )
330     {
331         SetError( ERROR_OUTOFMEMORY );
332         Log( TEXT( "ERROR: GetPrivateProfileSection() out of memory\r\n" ) );
333         return false;
334     }
335 
336     Log( TEXT( " GetProfileSection read %s\r\n" ), pSection );
337 
338     return true;
339 }
340 
341 //--------------------------------------------------------------------------
ReadProfile()342 boolean SetupApp::ReadProfile()
343 {
344     boolean bRet = false;
345     TCHAR *sProfilePath = 0;
346 
347     if ( GetPathToFile( PROFILE_NAME, &sProfilePath ) )
348     {
349         DWORD nSize = 0;
350         LPTSTR pRetBuf = NULL;
351 
352         Log( TEXT( " Open ini file: <%s>\r\n" ), sProfilePath );
353 
354         bRet = GetProfileSection( sProfilePath, SECTION_SETUP, nSize, &pRetBuf );
355 
356         if ( !bRet )
357         {
358             LPTSTR pTmpFile = CopyIniFile( sProfilePath );
359             delete [] sProfilePath;
360             sProfilePath = pTmpFile;
361 
362             if ( sProfilePath )
363             {
364                 SetError( ERROR_SUCCESS );
365 
366                 Log( TEXT( " Could not open inifile, copied ini file to: <%s>\r\n" ), sProfilePath );
367                 bRet = GetProfileSection( sProfilePath, SECTION_SETUP, nSize, &pRetBuf );
368             }
369         }
370 
371         if ( bRet )
372         {
373             LPTSTR pCurLine = pRetBuf;
374             while ( *pCurLine )
375             {
376                 LPTSTR pName = 0;
377                 LPTSTR pValue = 0;
378 
379                 pCurLine += GetNameValue( pCurLine, &pName, &pValue );
380 
381                 if ( lstrcmpi( TEXT( "database" ), pName ) == 0 )
382                 {
383                     m_pDatabase = pValue;
384                     Log( TEXT( "    Database = %s\r\n" ), pValue );
385                 }
386                 else if ( lstrcmpi( TEXT( "msiversion" ), pName ) == 0 )
387                 {
388                     m_pReqVersion = pValue;
389                     Log( TEXT( "    msiversion = %s\r\n" ), pValue );
390                 }
391                 else if ( lstrcmpi( TEXT( "productname" ), pName ) == 0 )
392                 {
393                     m_pProductName = pValue;
394                     Log( TEXT( "    productname = %s\r\n" ), pValue );
395                     m_pAppTitle = SetProdToAppTitle( m_pProductName );
396                 }
397                 else if ( lstrcmpi( TEXT( "upgradekey" ), pName ) == 0 )
398                 {
399                     m_pUpgradeKey = pValue;
400                     Log( TEXT( "    upgradekey = %s\r\n" ), pValue );
401                 }
402                 else if ( lstrcmpi( TEXT( "productversion" ), pName ) == 0 )
403                 {
404                     m_pProductVersion = pValue;
405                     Log( TEXT( "    productversion = %s\r\n" ), pValue );
406                 }
407                 else if ( lstrcmpi( TEXT( "productcode" ), pName ) == 0 )
408                 {
409                     delete [] pValue;
410                 }
411                 else
412                 {
413                     Log( TEXT( "Warning: unknown entry in profile <%s>\r\n" ), pName );
414                     delete [] pValue;
415                 }
416             }
417         }
418 
419         if ( bRet && ( !m_pDatabase || !m_pReqVersion || !m_pProductName ) )
420         {
421             Log( TEXT( "ERROR: incomplete 'Setup' section in profile\r\n" ) );
422             SetError( ERROR_INVALID_DATA );
423             bRet = false;
424         }
425 
426         if ( bRet )
427             bRet = GetProfileSection( sProfilePath, SECTION_LANGUAGE, nSize, &pRetBuf );
428 
429         if ( bRet )
430         {
431             LPTSTR pName = 0;
432             LPTSTR pValue = 0;
433             LPTSTR pCurLine = pRetBuf;
434             LPTSTR pLastChar;
435             int  nNext = 0;
436 
437             // first line in this section should be the language count
438             nNext = GetNameValue( pCurLine, &pName, &pValue );
439             if ( lstrcmpi( TEXT( "count" ), pName ) == 0 )
440             {
441                 Log( TEXT( "    Languages = %s\r\n" ), pValue );
442                 m_nLanguageCount = _tcstol( pValue, &pLastChar, 10 );
443                 pCurLine += nNext;
444                 delete [] pValue;
445             }
446 
447             m_ppLanguageList = new LanguageData*[ m_nLanguageCount ];
448 
449             for ( int i=0; i < m_nLanguageCount; i++ )
450             {
451                 if ( !*pCurLine )
452                 {
453                     m_nLanguageCount = i;
454                     break;
455                 }
456 
457                 pCurLine += GetNameValue( pCurLine, &pName, &pValue );
458                 m_ppLanguageList[ i ] = new LanguageData( pValue );
459                 Log( TEXT( "    Language = %s\r\n" ), pValue );
460 
461                 if ( m_ppLanguageList[ i ]->m_pTransform )
462                     Log( TEXT( "      Transform = %s\r\n" ), m_ppLanguageList[ i ]->m_pTransform );
463 
464                 delete [] pValue;
465             }
466         }
467 
468         if ( pRetBuf )
469             delete [] pRetBuf;
470     }
471 
472     if ( sProfilePath && ! m_pTmpName )
473         delete [] sProfilePath;
474 
475     return bRet;
476 }
477 
478 //--------------------------------------------------------------------------
AddFileToPatchList(TCHAR * pPath,TCHAR * pFile)479 void SetupApp::AddFileToPatchList( TCHAR* pPath, TCHAR* pFile )
480 {
481     if ( m_pPatchFiles == NULL )
482     {
483         m_pPatchFiles = new TCHAR[ MAX_STR_LENGTH ];
484         StringCchCopy( m_pPatchFiles, MAX_STR_LENGTH, TEXT("\"") );
485     }
486     else
487         StringCchCat( m_pPatchFiles, MAX_STR_LENGTH, TEXT(";") );
488 
489     StringCchCat( m_pPatchFiles, MAX_STR_LENGTH, pPath );
490     StringCchCat( m_pPatchFiles, MAX_STR_LENGTH, pFile );
491 }
492 
493 //--------------------------------------------------------------------------
GetPatches()494 boolean SetupApp::GetPatches()
495 {
496     boolean bRet = true;
497 
498     int nPatternLen = lstrlen( m_pModuleFile ) + 7; // 1 for null terminator, 1 for back slash, 5 for extensions
499     TCHAR* pPattern = new TCHAR[ nPatternLen ];
500     TCHAR* pBaseDir = new TCHAR[ nPatternLen ];
501 
502     // find 'setup.exe' in the path so we can remove it
503     TCHAR *pFilePart = 0;
504     if ( 0 == GetFullPathName( m_pModuleFile, nPatternLen, pPattern, &pFilePart ) )
505     {
506         SetError( WIN::GetLastError() );
507         bRet = false;
508     }
509     else
510     {
511         if ( pFilePart )
512             *pFilePart = '\0';
513         StringCchCopy( pBaseDir, nPatternLen, pPattern );
514         StringCchCat( pPattern, nPatternLen, TEXT("*.msp") );
515 
516         WIN32_FIND_DATA aFindFileData;
517 
518         HANDLE hFindPatches = FindFirstFile( pPattern, &aFindFileData );
519 
520         if ( hFindPatches != INVALID_HANDLE_VALUE )
521         {
522             if ( ! IsPatchInstalled( pBaseDir, aFindFileData.cFileName ) )
523                 AddFileToPatchList( pBaseDir, aFindFileData.cFileName );
524 
525             while ( FindNextFile( hFindPatches, &aFindFileData ) )
526             {
527                 if ( ! IsPatchInstalled( pBaseDir, aFindFileData.cFileName ) )
528                     AddFileToPatchList( pBaseDir, aFindFileData.cFileName );
529             }
530 
531             if ( m_pPatchFiles != NULL )
532                 StringCchCat( m_pPatchFiles, MAX_STR_LENGTH, TEXT("\"") );
533 
534             FindClose( hFindPatches );
535         }
536     }
537 
538     delete [] pPattern;
539     delete [] pBaseDir;
540 
541     return bRet;
542 }
543 
544 //--------------------------------------------------------------------------
GetPathToFile(TCHAR * pFileName,TCHAR ** pPath)545 boolean SetupApp::GetPathToFile( TCHAR* pFileName, TCHAR** pPath )
546 {
547     // generate the path to the file = szModuleFile + FileName
548     // note: FileName is a relative path
549 
550     boolean bRet = true;
551 
552     int nTempPath = lstrlen( m_pModuleFile ) + lstrlen( pFileName ) + 2; // 1 for null terminator, 1 for back slash
553     TCHAR* pTempPath = new TCHAR[ nTempPath ];
554 
555     // find 'setup.exe' in the path so we can remove it
556     TCHAR *pFilePart = 0;
557     if ( 0 == GetFullPathName( m_pModuleFile, nTempPath, pTempPath, &pFilePart ) )
558     {
559         SetError( WIN::GetLastError() );
560         bRet = false;
561     }
562     else
563     {
564         if ( pFilePart )
565             *pFilePart = '\0';
566 
567         StringCchCat( pTempPath, nTempPath, pFileName );
568 
569         int nPath = 2 * nTempPath;
570         *pPath = new TCHAR[ nPath ];
571 
572         // normalize the path
573         int nReturn = GetFullPathName( pTempPath, nPath, *pPath, &pFilePart );
574 
575         if ( nReturn > nPath )
576         {
577             // try again, with larger buffer
578             delete [] (*pPath);
579             nPath = nReturn;
580             *pPath = new TCHAR[ nPath ];
581 
582             nReturn = GetFullPathName( pTempPath, nPath, *pPath, &pFilePart );
583         }
584 
585         if ( 0 == nReturn )
586         {
587             // error -- invalid path
588             SetError( WIN::GetLastError() );
589             bRet = false;
590         }
591     }
592 
593     if ( bRet ) // check for the file's existence
594     {
595         DWORD dwFileAttrib = GetFileAttributes( *pPath );
596 
597         if (0xFFFFFFFF == dwFileAttrib)
598         {
599             StringCchCopy( m_pErrorText, MAX_TEXT_LENGTH, pFileName );
600             SetError( ERROR_FILE_NOT_FOUND );
601             bRet = false;
602         }
603     }
604 
605     delete [] pTempPath;
606     return bRet;
607 }
608 
609 //--------------------------------------------------------------------------
GetNameValue(TCHAR * pLine,TCHAR ** pName,TCHAR ** pValue)610 int SetupApp::GetNameValue( TCHAR* pLine, TCHAR** pName, TCHAR** pValue )
611 {
612     int nRet = lstrlen( pLine ) + 1;
613     *pValue = 0;
614 
615     if ( nRet == 1 )
616         return nRet;
617 
618     LPTSTR pChar = pLine;
619     LPTSTR pLast = NULL;
620 
621     // Skip leading spaces.
622     while (' ' == *pChar || '\t' == *pChar)
623         pChar = CharNext( pChar );
624 
625     *pName = pChar;
626 
627     // look for the end of the name
628     while( *pChar && (' ' != *pChar) &&
629            ( '\t' != *pChar ) && ( '=' != *pChar ) )
630         pChar = CharNext( pChar );
631 
632     if ( ! *pChar )
633         return nRet;
634 
635     pLast = pChar;
636     pChar = CharNext( pChar );
637     *pLast = '\0';
638 
639     // look for the start of the value
640     while( ( ' ' == *pChar ) || ( '\t' == *pChar ) ||
641            ( '=' == *pChar ) )
642         pChar = CharNext( pChar );
643 
644     int nValueLen = lstrlen( pChar ) + 1;
645     *pValue = new TCHAR[ nValueLen ];
646 
647     if ( *pValue )
648         StringCchCopy( *pValue, nValueLen, pChar );
649 
650     return nRet;
651 }
652 
653 //--------------------------------------------------------------------------
ChooseLanguage(long & rLanguage)654 boolean SetupApp::ChooseLanguage( long& rLanguage )
655 {
656     rLanguage = 0;
657 
658     if ( m_bQuiet )
659         return true;
660 
661     // When there are none or only one language, there is nothing
662     // to do here
663     if ( m_nLanguageCount > 1 )
664     {
665         TCHAR *sString = new TCHAR[ MAX_LANGUAGE_LEN ];
666 
667         LANGID nUserDefLang = GetUserDefaultLangID();
668         LANGID nSysDefLang = GetSystemDefaultLangID();
669 
670         int nUserPrimary = PRIMARYLANGID( nUserDefLang );
671         int nSysPrimary = PRIMARYLANGID( nSysDefLang );
672 
673         long nUserIndex = -1;
674         long nUserPrimIndex = -1;
675         long nSystemIndex = -1;
676         long nSystemPrimIndex = -1;
677         long nParamIndex = -1;
678 
679         for ( long i=0; i<GetLanguageCount(); i++ )
680         {
681             long nLanguage = GetLanguageID( i );
682             int nPrimary = PRIMARYLANGID( nLanguage );
683             GetLanguageName( nLanguage, sString );
684             Log( TEXT( "    Info: found Language: %s\r\n" ), sString );
685 
686             if ( nLanguage == nUserDefLang )
687                 nUserIndex = i;
688             if ( nPrimary == nUserPrimary )
689                 nUserPrimIndex = i;
690             if ( nLanguage == nSysDefLang )
691                 nSystemIndex = i;
692             if ( nPrimary == nSysPrimary )
693                 nSystemPrimIndex = i;
694             if ( m_nLanguageID && ( nLanguage == m_nLanguageID ) )
695                 nParamIndex = i;
696         }
697 
698         if ( m_nLanguageID && ( nParamIndex == -1 ) )
699         {
700             Log( TEXT( "Warning: Language chosen with parameter -lang not found.\r\n" ) );
701         }
702 
703         if ( nParamIndex != -1 )
704         {
705             Log( TEXT( "Info: Found language chosen with parameter -lang.\r\n" ) );
706             rLanguage = GetLanguageID( nParamIndex );
707         }
708         else if ( nUserIndex != -1 )
709         {
710             Log( TEXT( "Info: Found user default language.\r\n" ) );
711             rLanguage = GetLanguageID( nUserIndex );
712         }
713         else if ( nUserPrimIndex != -1 )
714         {
715             Log( TEXT( "Info: Found user default primary language.\r\n" ) );
716             rLanguage = GetLanguageID( nUserPrimIndex );
717         }
718         else if ( nSystemIndex != -1 )
719         {
720             Log( TEXT( "Info: Found system default language.\r\n" ) );
721             rLanguage = GetLanguageID( nSystemIndex );
722         }
723         else if ( nSystemPrimIndex != -1 )
724         {
725             Log( TEXT( "Info: Found system default primary language.\r\n" ) );
726             rLanguage = GetLanguageID( nSystemPrimIndex );
727         }
728         else
729         {
730             Log( TEXT( "Info: Use default language from ini file.\r\n" ) );
731             rLanguage = GetLanguageID( 0 );
732         }
733         delete [] sString;
734     }
735 
736     return true;
737 }
738 
739 
740 //--------------------------------------------------------------------------
GetPathToMSI()741 LPCTSTR SetupApp::GetPathToMSI()
742 {
743     LPTSTR  sMsiPath = NULL;
744     HKEY    hInstKey = NULL;
745     TCHAR  *sMsiFolder = getInstallerLocation();
746     DWORD   nMsiFolderSize = MAX_PATH + 1;
747 
748     if ( sMsiFolder[0] == '\0' ) // use the default location
749     {
750         Log( TEXT( "  Could not find path to msiexec.exe in registry" ) );
751 
752         DWORD nRet = WIN::GetSystemDirectory( sMsiFolder, nMsiFolderSize );
753         if ( nRet > nMsiFolderSize )
754         {
755             delete [] sMsiFolder;
756             sMsiFolder = new TCHAR[ nRet ];
757             nMsiFolderSize = nRet;
758 
759             nRet = WIN::GetSystemDirectory( sMsiFolder, nMsiFolderSize );
760         }
761         if ( 0 == nRet )
762         {
763             sMsiFolder[0] = '\0';
764             SetError( WIN::GetLastError() );
765         }
766         nMsiFolderSize = nRet;
767     }
768 
769     if ( sMsiFolder[0] != '\0' )
770     {
771         int nLength = lstrlen( sMsiExe ) + lstrlen( sMsiFolder ) + 1;
772         sMsiPath = new TCHAR[ nLength ];
773 
774         if ( FAILED( StringCchCopy( sMsiPath, nLength, sMsiFolder ) ) ||
775              FAILED( StringCchCat( sMsiPath, nLength, sMsiExe ) ) )
776         {
777             delete [] sMsiPath;
778             sMsiPath = NULL;
779         }
780     }
781 
782     if ( ! sMsiPath )
783         Log( TEXT( "ERROR: Can't build path to msiexec.exe!" ) );
784 
785     return sMsiPath;
786 }
787 
788 //--------------------------------------------------------------------------
LaunchInstaller(LPCTSTR pParam)789 boolean SetupApp::LaunchInstaller( LPCTSTR pParam )
790 {
791     LPCTSTR sMsiPath = GetPathToMSI();
792 
793     if ( !sMsiPath )
794     {
795         Log( TEXT( "ERROR: msiexec not found!" ) );
796         SetError( ERROR_FILE_NOT_FOUND );
797         return false;
798     }
799 
800     STARTUPINFO         aSUI;
801     PROCESS_INFORMATION aPI;
802 
803     Log( TEXT( " Will install using <%s>\r\n" ), sMsiPath );
804     Log( TEXT( "   Parameters are: %s\r\n" ), pParam );
805 
806     OutputDebugStringFormat( TEXT( " Will install using <%s>\r\n" ), sMsiPath );
807     OutputDebugStringFormat( TEXT( "   Parameters are: %s\r\n" ), pParam );
808 
809     ZeroMemory( (void*)&aPI, sizeof( PROCESS_INFORMATION ) );
810     ZeroMemory( (void*)&aSUI, sizeof( STARTUPINFO ) );
811 
812     aSUI.cb          = sizeof(STARTUPINFO);
813     aSUI.dwFlags     = STARTF_USESHOWWINDOW;
814     aSUI.wShowWindow = SW_SHOW;
815 
816     DWORD nCmdLineLength = lstrlen( sMsiPath ) + lstrlen( pParam ) + 2;
817     TCHAR *sCmdLine = new TCHAR[ nCmdLineLength ];
818 
819     if ( FAILED( StringCchCopy( sCmdLine, nCmdLineLength, sMsiPath ) ) ||
820          FAILED( StringCchCat(  sCmdLine, nCmdLineLength, TEXT( " " ) ) ) ||
821          FAILED( StringCchCat(  sCmdLine, nCmdLineLength, pParam ) ) )
822     {
823         delete [] sCmdLine;
824         SetError( ERROR_INSTALL_FAILURE );
825         return false;
826     }
827 
828     if ( !WIN::CreateProcess( NULL, sCmdLine, NULL, NULL, FALSE,
829                               CREATE_DEFAULT_ERROR_MODE, NULL, NULL,
830                               &aSUI, &aPI ) )
831     {
832         Log( TEXT( "ERROR: Could not create process %s.\r\n" ), sCmdLine );
833         SetError( WIN::GetLastError() );
834         delete [] sCmdLine;
835         return false;
836     }
837 
838     DWORD nResult = WaitForProcess( aPI.hProcess );
839     bool bRet = true;
840 
841     if( ERROR_SUCCESS != nResult )
842     {
843         Log( TEXT( "ERROR: While waiting for %s.\r\n" ), sCmdLine );
844         SetError( nResult );
845         bRet = false;
846     }
847     else
848     {
849         GetExitCodeProcess( aPI.hProcess, &nResult );
850         SetError( nResult );
851 
852         if ( nResult != ERROR_SUCCESS )
853         {
854             TCHAR sBuf[80];
855             StringCchPrintf( sBuf, 80, TEXT("Warning: msiexec returned %u.\r\n"), nResult );
856             Log( sBuf );
857         }
858         else
859             Log( TEXT( " Installation completed successfully.\r\n" ) );
860     }
861 
862     CloseHandle( aPI.hProcess );
863 
864     delete [] sCmdLine;
865 
866     return bRet;
867 }
868 
869 //--------------------------------------------------------------------------
Install(long nLanguage)870 boolean SetupApp::Install( long nLanguage )
871 {
872     LPTSTR pTransform = NULL;
873 
874     if ( nLanguage ) // look for transformation
875     {
876         for ( int i = 0; i < m_nLanguageCount; i++ )
877         {
878             if ( m_ppLanguageList[i]->m_nLanguageID == nLanguage )
879             {
880                 if ( m_ppLanguageList[i]->m_pTransform )
881                 {
882                     if ( !GetPathToFile( m_ppLanguageList[i]->m_pTransform,
883                                         &pTransform ) )
884                     {
885                         Log( TEXT( "ERROR: Could not find transform <%s\r\n" ), m_ppLanguageList[i]->m_pTransform );
886                         return false;
887                     }
888                 }
889                 break;
890             }
891         }
892     }
893 
894     TCHAR *pDataBasePath = NULL;
895 
896     if ( ! GetPathToFile( m_pDatabase, &pDataBasePath ) )
897     {
898         Log( TEXT( "ERROR: Could not find database <%s\r\n" ), m_pDatabase );
899         SetError( ERROR_INSTALL_SOURCE_ABSENT );
900         return false;
901     }
902 
903     // we will always use the parameter setup used
904     int nParLen = lstrlen( PARAM_SETUP_USED );
905 
906     if ( m_bRegNoMsoTypes )
907         nParLen += lstrlen( PARAM_REG_NO_MSO_TYPES );
908     else if ( m_bRegAllMsoTypes )
909         nParLen += lstrlen( PARAM_REG_ALL_MSO_TYPES );
910 
911     if ( m_pAdvertise )
912         nParLen += lstrlen( m_pAdvertise ) + 1;     // one for the space
913     else if ( m_bIsMinorUpgrade )
914         nParLen += lstrlen( PARAM_MINOR_UPGRADE );
915     else
916         nParLen += lstrlen( PARAM_PACKAGE );
917 
918     nParLen += lstrlen( pDataBasePath ) + 3;        // two quotes, one null
919 
920     if ( NeedReboot() )
921         nParLen += lstrlen( PARAM_REBOOT );
922 
923     if ( m_pPatchFiles )
924     {
925         nParLen += lstrlen( PARAM_PATCH );
926         nParLen += lstrlen( m_pPatchFiles );
927     }
928 
929     if ( pTransform )
930     {
931         nParLen += lstrlen( PARAM_TRANSFORM );
932         nParLen += lstrlen( pTransform ) + 2;       // two quotes
933     }
934 
935     if ( m_pCmdLine )
936         nParLen += lstrlen( m_pCmdLine ) + 1;       // one for the space;
937 
938     TCHAR *pParams = new TCHAR[ nParLen ];
939 
940     StringCchCopy( pParams, nParLen, PARAM_SETUP_USED );
941 
942     if ( m_bRegNoMsoTypes )
943         StringCchCat( pParams, nParLen, PARAM_REG_NO_MSO_TYPES );
944     else if ( m_bRegAllMsoTypes )
945         StringCchCat( pParams, nParLen, PARAM_REG_ALL_MSO_TYPES );
946 
947     if ( m_pAdvertise )
948         StringCchCat( pParams, nParLen, m_pAdvertise );
949     else if ( IsAdminInstall() )
950         StringCchCat( pParams, nParLen, PARAM_ADMIN );
951     else if ( m_bIsMinorUpgrade )
952         StringCchCat( pParams, nParLen, PARAM_MINOR_UPGRADE );
953     else
954         StringCchCat( pParams, nParLen, PARAM_PACKAGE );
955 
956     StringCchCat( pParams, nParLen, TEXT( "\"" ) );
957     StringCchCat( pParams, nParLen, pDataBasePath );
958     StringCchCat( pParams, nParLen, TEXT( "\"" ) );
959 
960     if ( NeedReboot() )
961         StringCchCat( pParams, nParLen, PARAM_REBOOT );
962 
963     if ( m_pPatchFiles )
964     {
965         StringCchCat( pParams, nParLen, PARAM_PATCH );
966         StringCchCat( pParams, nParLen, m_pPatchFiles );
967     }
968 
969     if ( pTransform )
970     {
971         StringCchCat( pParams, nParLen, PARAM_TRANSFORM );
972         StringCchCat( pParams, nParLen, TEXT( "\"" ) );
973         StringCchCat( pParams, nParLen, pTransform );
974         StringCchCat( pParams, nParLen, TEXT( "\"" ) );
975     }
976 
977     if ( m_pCmdLine )
978     {
979         StringCchCat( pParams, nParLen, TEXT( " " ) );
980         StringCchCat( pParams, nParLen, m_pCmdLine );
981     }
982 
983     return LaunchInstaller( pParams );
984 }
985 
986 //--------------------------------------------------------------------------
GetError() const987 UINT SetupApp::GetError() const
988 {
989     UINT nErr = 0;
990 
991     if ( m_pMSIErrorCode )
992         nErr = (UINT) *m_pMSIErrorCode;
993 
994     if ( nErr == 0 )
995         nErr = m_uiRet;
996 
997     if ( nErr != 0 )
998         OutputDebugStringFormat( TEXT("Setup will return error (%d).\n"), nErr );
999     return nErr;
1000 }
1001 
1002 //--------------------------------------------------------------------------
DisplayError(UINT nErr) const1003 void SetupApp::DisplayError( UINT nErr ) const
1004 {
1005     TCHAR sError[ MAX_TEXT_LENGTH ] = {0};
1006     TCHAR sTmp[ MAX_TEXT_LENGTH ] = {0};
1007 
1008     UINT  nMsgType = MB_OK | MB_ICONERROR;
1009 
1010     switch ( nErr )
1011     {
1012         case ERROR_SUCCESS:     break;  // 0
1013 
1014         case ERROR_FILE_NOT_FOUND:  // 2
1015                                 WIN::LoadString( m_hInst, IDS_FILE_NOT_FOUND, sTmp, MAX_TEXT_LENGTH );
1016                                 StringCchPrintf( sError, MAX_TEXT_LENGTH, sTmp, m_pErrorText );
1017                                 break;
1018         case ERROR_INVALID_DATA:    // 13
1019                                 WIN::LoadString( m_hInst, IDS_INVALID_PROFILE, sError, MAX_TEXT_LENGTH );
1020                                 break;
1021         case ERROR_OUTOFMEMORY: WIN::LoadString( m_hInst, IDS_OUTOFMEM, sError, MAX_TEXT_LENGTH );
1022                                 break;
1023         case ERROR_INSTALL_USEREXIT:
1024                                 WIN::LoadString( m_hInst, IDS_USER_CANCELED, sError, MAX_TEXT_LENGTH );
1025                                 break;
1026         case ERROR_INSTALL_ALREADY_RUNNING: // 1618
1027                                 WIN::LoadString( m_hInst, IDS_ALREADY_RUNNING, sError, MAX_TEXT_LENGTH );
1028                                 break;
1029         case ERROR_INSTALL_SOURCE_ABSENT:
1030                                 WIN::LoadString( m_hInst, IDS_NOMSI, sError, MAX_TEXT_LENGTH );
1031                                 break;
1032         case ERROR_DS_INSUFF_ACCESS_RIGHTS: // 8344
1033                                 WIN::LoadString( m_hInst, IDS_REQUIRES_ADMIN_PRIV, sError, MAX_TEXT_LENGTH );
1034                                 break;
1035         case E_ABORT:           WIN::LoadString( m_hInst, IDS_UNKNOWN_ERROR, sError, MAX_TEXT_LENGTH );
1036                                 break;
1037         case ERROR_INVALID_PARAMETER:   // 87
1038                                 WIN::LoadString( m_hInst, IDS_INVALID_PARAM, sTmp, MAX_TEXT_LENGTH );
1039                                 StringCchPrintf( sError, MAX_TEXT_LENGTH, sTmp, m_pErrorText );
1040                                 break;
1041 
1042         case ERROR_SETUP_TO_OLD:    // - 3
1043                                 WIN::LoadString( m_hInst, IDS_SETUP_TO_OLD, sTmp, MAX_TEXT_LENGTH );
1044                                 StringCchPrintf( sError, MAX_TEXT_LENGTH, sTmp, m_pReqVersion, m_pErrorText );
1045                                 break;
1046         case ERROR_SETUP_NOT_FOUND: // - 4
1047                                 WIN::LoadString( m_hInst, IDS_SETUP_NOT_FOUND, sTmp, MAX_TEXT_LENGTH );
1048                                 StringCchPrintf( sError, MAX_TEXT_LENGTH, sTmp, m_pReqVersion );
1049                                 break;
1050         case ERROR_SHOW_USAGE:      // - 2
1051                                 nMsgType = MB_OK | MB_ICONINFORMATION;
1052                                 WIN::LoadString( m_hInst, IDS_USAGE, sError, MAX_TEXT_LENGTH );
1053                                 break;
1054         case ERROR_OS_TO_OLD:       // - 5
1055                                 WIN::LoadString( m_hInst, IDS_OS_TO_OLD, sError, MAX_TEXT_LENGTH );
1056                                 break;
1057         case ERROR_RUNTIME_FAILED:  // - 6
1058                                 WIN::LoadString( m_hInst, IDS_RUNTIME_FAILED, sError, MAX_TEXT_LENGTH );
1059                                 break;
1060 
1061         default:                WIN::LoadString( m_hInst, IDS_UNKNOWN_ERROR, sError, MAX_TEXT_LENGTH );
1062                                 break;
1063     }
1064 
1065     if ( sError[0] )
1066     {
1067         if ( !m_bQuiet )
1068         {
1069             ConvertNewline( sError );
1070             WIN::MessageBox( NULL, sError, m_pAppTitle, nMsgType );
1071         }
1072 
1073         Log( TEXT( "ERROR: %s\r\n" ), sError );
1074     }
1075 }
1076 
1077 //--------------------------------------------------------------------------
GetLanguageID(long nIndex) const1078 long SetupApp::GetLanguageID( long nIndex ) const
1079 {
1080     if ( nIndex >=0 && nIndex < m_nLanguageCount )
1081         return m_ppLanguageList[ nIndex ]->m_nLanguageID;
1082     else
1083         return 0;
1084 }
1085 
1086 //--------------------------------------------------------------------------
GetLanguageName(long nLanguage,LPTSTR sName) const1087 void SetupApp::GetLanguageName( long nLanguage, LPTSTR sName ) const
1088 {
1089     switch ( nLanguage )
1090     {
1091         case 1028: WIN::LoadString( m_hInst, IDS_LANGUAGE_ZH_TW, sName, MAX_LANGUAGE_LEN ); break;
1092         case 1029: WIN::LoadString( m_hInst, IDS_LANGUAGE_CS,    sName, MAX_LANGUAGE_LEN ); break;
1093         case 1030: WIN::LoadString( m_hInst, IDS_LANGUAGE_DA,    sName, MAX_LANGUAGE_LEN ); break;
1094         case 1031: WIN::LoadString( m_hInst, IDS_LANGUAGE_DE_DE, sName, MAX_LANGUAGE_LEN ); break;
1095         case 1032: WIN::LoadString( m_hInst, IDS_LANGUAGE_EL,    sName, MAX_LANGUAGE_LEN ); break;
1096         case 1033: WIN::LoadString( m_hInst, IDS_LANGUAGE_EN_US, sName, MAX_LANGUAGE_LEN ); break;
1097         case 1034: WIN::LoadString( m_hInst, IDS_LANGUAGE_ES,    sName, MAX_LANGUAGE_LEN ); break;
1098         case 1035: WIN::LoadString( m_hInst, IDS_LANGUAGE_FI,    sName, MAX_LANGUAGE_LEN ); break;
1099         case 1036: WIN::LoadString( m_hInst, IDS_LANGUAGE_FR_FR, sName, MAX_LANGUAGE_LEN ); break;
1100         case 1037: WIN::LoadString( m_hInst, IDS_LANGUAGE_HE,    sName, MAX_LANGUAGE_LEN ); break;
1101         case 1038: WIN::LoadString( m_hInst, IDS_LANGUAGE_HU,    sName, MAX_LANGUAGE_LEN ); break;
1102         case 1040: WIN::LoadString( m_hInst, IDS_LANGUAGE_IT_IT, sName, MAX_LANGUAGE_LEN ); break;
1103         case 1041: WIN::LoadString( m_hInst, IDS_LANGUAGE_JA,    sName, MAX_LANGUAGE_LEN ); break;
1104         case 1042: WIN::LoadString( m_hInst, IDS_LANGUAGE_KO,    sName, MAX_LANGUAGE_LEN ); break;
1105         case 1043: WIN::LoadString( m_hInst, IDS_LANGUAGE_NL_NL, sName, MAX_LANGUAGE_LEN ); break;
1106         case 1044: WIN::LoadString( m_hInst, IDS_LANGUAGE_NO_NO, sName, MAX_LANGUAGE_LEN ); break;
1107         case 1045: WIN::LoadString( m_hInst, IDS_LANGUAGE_PL,    sName, MAX_LANGUAGE_LEN ); break;
1108         case 1046: WIN::LoadString( m_hInst, IDS_LANGUAGE_PT_BR, sName, MAX_LANGUAGE_LEN ); break;
1109         case 1049: WIN::LoadString( m_hInst, IDS_LANGUAGE_RU,    sName, MAX_LANGUAGE_LEN ); break;
1110         case 1051: WIN::LoadString( m_hInst, IDS_LANGUAGE_SK,    sName, MAX_LANGUAGE_LEN ); break;
1111         case 1053: WIN::LoadString( m_hInst, IDS_LANGUAGE_SV_SE, sName, MAX_LANGUAGE_LEN ); break;
1112         case 1054: WIN::LoadString( m_hInst, IDS_LANGUAGE_TH,    sName, MAX_LANGUAGE_LEN ); break;
1113         case 1055: WIN::LoadString( m_hInst, IDS_LANGUAGE_TR,    sName, MAX_LANGUAGE_LEN ); break;
1114         case 1061: WIN::LoadString( m_hInst, IDS_LANGUAGE_ET,    sName, MAX_LANGUAGE_LEN ); break;
1115         case 2052: WIN::LoadString( m_hInst, IDS_LANGUAGE_ZH_CN, sName, MAX_LANGUAGE_LEN ); break;
1116         case 2070: WIN::LoadString( m_hInst, IDS_LANGUAGE_PT_PT, sName, MAX_LANGUAGE_LEN ); break;
1117 
1118         default:
1119             {
1120                 TCHAR sTmp[ MAX_LANGUAGE_LEN ] = {0};
1121 
1122                 WIN::LoadString( m_hInst, IDS_UNKNOWN_LANG, sTmp, MAX_LANGUAGE_LEN );
1123                 StringCchPrintf( sName, MAX_LANGUAGE_LEN, sTmp, nLanguage );
1124             }
1125     }
1126 }
1127 
1128 //--------------------------------------------------------------------------
CheckVersion()1129 boolean SetupApp::CheckVersion()
1130 {
1131     boolean bRet = false;
1132 
1133     Log( TEXT( " Looking for installed MSI with version >= %s\r\n" ), m_pReqVersion );
1134 
1135     DLLVERSIONINFO aInfo;
1136 
1137     aInfo.cbSize = sizeof( DLLVERSIONINFO );
1138     if ( NOERROR == aoo_MsiDllGetVersion( &aInfo ) )
1139     {
1140     TCHAR pMsiVersion[ VERSION_SIZE ];
1141     StringCchPrintf( pMsiVersion, VERSION_SIZE, TEXT("%d.%d.%4d"),
1142              aInfo.dwMajorVersion,
1143              aInfo.dwMinorVersion,
1144              aInfo.dwBuildNumber );
1145     if ( _tcsncmp( pMsiVersion, m_pReqVersion, _tcslen( pMsiVersion ) ) < 0 )
1146         {
1147         StringCchCopy( m_pErrorText, MAX_TEXT_LENGTH, pMsiVersion );
1148         SetError( (UINT) ERROR_SETUP_TO_OLD );
1149         Log( TEXT( "Warning: Old MSI version found <%s>, update needed!\r\n" ), pMsiVersion );
1150     }
1151     else
1152     {
1153         Log( TEXT( " Found MSI version <%s>, no update needed\r\n" ), pMsiVersion );
1154         bRet = true;
1155     }
1156     if ( aInfo.dwMajorVersion >= 3 )
1157         m_bSupportsPatch = true;
1158     else
1159         Log( TEXT("Warning: Patching not supported! MSI-Version <%s>\r\n"), pMsiVersion );
1160     }
1161 
1162     return bRet;
1163 }
1164 
1165 //--------------------------------------------------------------------------
CheckForUpgrade()1166 boolean SetupApp::CheckForUpgrade()
1167 {
1168     // When we have patch files we will never try an Minor upgrade
1169     if ( m_pPatchFiles ) return true;
1170 
1171     if ( !m_pUpgradeKey || ( _tcslen( m_pUpgradeKey ) == 0 ) )
1172     {
1173         Log( TEXT( "    No Upgrade Key Found -> continue with standard installation!\r\n" ) );
1174         return true;
1175     }
1176 
1177     HKEY hInstKey = NULL;
1178 
1179     if ( ERROR_SUCCESS == RegOpenKeyEx( HKEY_LOCAL_MACHINE, m_pUpgradeKey, 0, KEY_READ, &hInstKey ) )
1180     {
1181         Log( TEXT( " Found Upgrade Key in Registry (HKLM) -> will try minor upgrade!\r\n" ) );
1182         m_bIsMinorUpgrade = true;
1183     }
1184     else if ( ERROR_SUCCESS == RegOpenKeyEx( HKEY_CURRENT_USER, m_pUpgradeKey, 0, KEY_READ, &hInstKey ) )
1185     {
1186         Log( TEXT( " Found Upgrade Key in Registry (HKCU) -> will try minor upgrade!\r\n" ) );
1187         m_bIsMinorUpgrade = true;
1188     }
1189     else
1190     {
1191         Log( TEXT( " Didn't Find Upgrade Key in Registry -> continue with standard installation!\r\n" ) );
1192         return true;
1193     }
1194 
1195     if ( m_pProductVersion && ( _tcslen( m_pProductVersion ) > 0 ) )
1196     {
1197         TCHAR *sProductVersion = new TCHAR[ MAX_PATH + 1 ];
1198         DWORD  nSize = MAX_PATH + 1;
1199 
1200         sProductVersion[0] = '\0';
1201 
1202         // get product version
1203         if ( ERROR_SUCCESS == RegQueryValueEx( hInstKey, PRODUCT_VERSION, NULL, NULL, (LPBYTE)sProductVersion, &nSize ) )
1204         {
1205             if ( lstrcmpi( sProductVersion, m_pProductVersion ) == 0 )
1206             {
1207                 Log( TEXT( " Same Product Version already installed, no minor upgrade!\r\n" ) );
1208                 m_bIsMinorUpgrade = false;
1209             }
1210         }
1211 
1212         delete [] sProductVersion;
1213     }
1214 
1215     return true;
1216 }
1217 
1218 //--------------------------------------------------------------------------
IsTerminalServerInstalled() const1219 boolean SetupApp::IsTerminalServerInstalled() const
1220 {
1221     boolean bIsTerminalServer = false;
1222 
1223     const TCHAR sSearchStr[]   = TEXT("Terminal Server");
1224     const TCHAR sKey[]         = TEXT("System\\CurrentControlSet\\Control\\ProductOptions");
1225     const TCHAR sValue[]       = TEXT("ProductSuite");
1226 
1227     DWORD dwSize = 0;
1228     HKEY  hKey = 0;
1229     DWORD dwType = 0;
1230 
1231     if ( ERROR_SUCCESS == RegOpenKeyEx( HKEY_LOCAL_MACHINE, sKey, 0, KEY_READ, &hKey ) &&
1232          ERROR_SUCCESS == RegQueryValueEx( hKey, sValue, NULL, &dwType, NULL, &dwSize ) &&
1233          dwSize > 0 &&
1234          REG_MULTI_SZ == dwType )
1235     {
1236         TCHAR* sSuiteList = new TCHAR[ (dwSize*sizeof(byte)/sizeof(TCHAR)) + 1 ];
1237 
1238         ZeroMemory(sSuiteList, dwSize);
1239 
1240         if ( ERROR_SUCCESS == RegQueryValueEx( hKey, sValue, NULL, &dwType, (LPBYTE)sSuiteList, &dwSize) )
1241         {
1242             DWORD nMulti = 0;
1243             DWORD nSrch  = lstrlen( sSearchStr );
1244             const TCHAR *sSubString = sSuiteList;
1245 
1246             while (*sSubString)
1247             {
1248                 nMulti = lstrlen( sSubString );
1249                 if ( nMulti == nSrch && 0 == lstrcmp( sSearchStr, sSubString ) )
1250                 {
1251                     bIsTerminalServer = true;
1252                     break;
1253                 }
1254 
1255                 sSubString += (nMulti + 1);
1256             }
1257         }
1258         delete [] sSuiteList;
1259     }
1260 
1261     if ( hKey )
1262         RegCloseKey( hKey );
1263 
1264     return bIsTerminalServer;
1265 }
1266 
1267 //--------------------------------------------------------------------------
AlreadyRunning() const1268 boolean SetupApp::AlreadyRunning() const
1269 {
1270     if ( m_bIgnoreAlreadyRunning )
1271     {
1272         Log( TEXT("Ignoring already running MSI instance!\r\n") );
1273         return false;
1274     }
1275 
1276     const TCHAR *sMutexName    = NULL;
1277     const TCHAR sGUniqueName[] = TEXT( "Global\\_MSISETUP_{EA8130C1-8D3D-4338-9309-1A52D530D846}" );
1278     const TCHAR sUniqueName[]  = TEXT( "_MSISETUP_{EA8130C1-8D3D-4338-9309-1A52D530D846}" );
1279 
1280     if ( IsWin9x() )
1281         sMutexName = sUniqueName;
1282     else if ( ( GetOSVersion() < 5 ) && ! IsTerminalServerInstalled() )
1283         sMutexName = sUniqueName;
1284     else
1285         sMutexName = sGUniqueName;
1286 
1287     HANDLE hMutex = 0;
1288 
1289     hMutex = WIN::CreateMutex( NULL, FALSE, sMutexName );
1290 
1291     if ( !hMutex || ERROR_ALREADY_EXISTS == WIN::GetLastError() )
1292     {
1293         if ( !hMutex )
1294             Log( TEXT( "ERROR: AlreadyRunning() could not create mutex!\r\n" ) );
1295         else
1296             Log( TEXT( "ERROR: There's already a setup running!\r\n" ) );
1297 
1298         return true;
1299     }
1300     Log( TEXT( " No running Setup found\r\n" ) );
1301 
1302     return false;
1303 }
1304 
1305 //--------------------------------------------------------------------------
WaitForProcess(HANDLE hHandle)1306 DWORD SetupApp::WaitForProcess( HANDLE hHandle )
1307 {
1308     DWORD nResult = NOERROR;
1309     boolean bLoop = true;
1310 
1311     MSG aMsg;
1312     ZeroMemory( (void*) &aMsg, sizeof(MSG) );
1313 
1314     while ( bLoop )
1315     {
1316         switch ( WIN::MsgWaitForMultipleObjects( 1, &hHandle, false,
1317                                                  INFINITE, QS_ALLINPUT ) )
1318         {
1319             case WAIT_OBJECT_0: bLoop = false;
1320                 break;
1321 
1322             case (WAIT_OBJECT_0 + 1):
1323             {
1324                 if ( WIN::PeekMessage( &aMsg, NULL, NULL, NULL, PM_REMOVE ) )
1325                 {
1326                     WIN::TranslateMessage( &aMsg );
1327                     WIN::DispatchMessage( &aMsg );
1328                 }
1329                 break;
1330             }
1331 
1332             default:
1333             {
1334                 nResult = WIN::GetLastError();
1335                 bLoop = false;
1336             }
1337         }
1338     }
1339 
1340     return nResult;
1341 }
1342 
1343 //--------------------------------------------------------------------------
Log(LPCTSTR pMessage,LPCTSTR pText) const1344 void SetupApp::Log( LPCTSTR pMessage, LPCTSTR pText ) const
1345 {
1346     if ( m_pLogFile )
1347     {
1348         static boolean bInit = false;
1349 
1350         if ( !bInit )
1351         {
1352             bInit = true;
1353             if ( ! IsWin9x() )
1354                 _ftprintf( m_pLogFile, TEXT("%c"), 0xfeff );
1355 
1356             _tsetlocale( LC_ALL, TEXT("") );
1357             _ftprintf( m_pLogFile, TEXT("\nCodepage=%s\nMultiByte Codepage=[%d]\n"),
1358                                    _tsetlocale( LC_ALL, NULL ), _getmbcp() );
1359         }
1360         if ( pText )
1361         {
1362             _ftprintf( m_pLogFile, pMessage, pText );
1363             OutputDebugStringFormat( pMessage, pText );
1364         }
1365         else
1366         {
1367             _ftprintf( m_pLogFile, pMessage );
1368             OutputDebugStringFormat( pMessage );
1369         }
1370 
1371         fflush( m_pLogFile );
1372     }
1373 }
1374 
1375 //--------------------------------------------------------------------------
GetNextArgument(LPCTSTR pStr,LPTSTR * pArg,LPTSTR * pNext,boolean bStripQuotes)1376 DWORD SetupApp::GetNextArgument( LPCTSTR pStr, LPTSTR *pArg, LPTSTR *pNext,
1377                                   boolean bStripQuotes )
1378 {
1379     boolean bInQuotes = false;
1380     boolean bFoundArgEnd = false;
1381     LPCTSTR pChar = pStr;
1382     LPCTSTR pFirst = NULL;
1383 
1384     if ( NULL == pChar )
1385         return ERROR_NO_MORE_ITEMS;
1386 
1387     while ( ' ' == (*pChar) || '\t' == (*pChar) )
1388         pChar = CharNext( pChar );
1389 
1390     if ( '\0' == (*pChar) )
1391         return ERROR_NO_MORE_ITEMS;
1392 
1393     int nCount = 1;
1394     pFirst = pChar;
1395 
1396     while ( ! bFoundArgEnd )
1397     {
1398         if ( '\0' == (*pChar) )
1399             bFoundArgEnd = true;
1400         else if ( !bInQuotes && ' ' == (*pChar) )
1401             bFoundArgEnd = true;
1402         else if ( !bInQuotes && '\t' == (*pChar) )
1403             bFoundArgEnd = true;
1404         else
1405         {
1406             if ( '\"' == (*pChar) )
1407             {
1408                 bInQuotes = !bInQuotes;
1409                 if ( bStripQuotes )
1410                 {
1411                     if ( pChar == pFirst )
1412                         pFirst = CharNext( pFirst );
1413                     nCount -= 1;
1414                 }
1415             }
1416 
1417             pChar = CharNext( pChar );
1418             nCount += 1;
1419         }
1420     }
1421 
1422     if ( pArg )
1423     {
1424         *pArg = new TCHAR[ nCount ];
1425         StringCchCopyN ( *pArg, nCount, pFirst, nCount-1 );
1426     }
1427 
1428     if ( pNext )
1429         *pNext = CharNext( pChar );
1430 
1431     return ERROR_SUCCESS;
1432 }
1433 
1434 //--------------------------------------------------------------------------
GetCmdLineParameters(LPTSTR * pCmdLine)1435 boolean SetupApp::GetCmdLineParameters( LPTSTR *pCmdLine )
1436 {
1437     int    nRet   = ERROR_SUCCESS;
1438     LPTSTR pStart = NULL;
1439     LPTSTR pNext  = NULL;
1440 
1441     if ( GetNextArgument( *pCmdLine, NULL, &pNext ) != ERROR_SUCCESS )
1442     {
1443         SetError( ERROR_NO_MORE_ITEMS );
1444         return false;
1445     }
1446 
1447     int    nSize = lstrlen( *pCmdLine ) + 2;
1448     TCHAR *pNewCmdLine = new TCHAR[ nSize ];
1449     pNewCmdLine[0] = '\0';
1450 
1451     while ( GetNextArgument( pNext, &pStart, &pNext ) == ERROR_SUCCESS )
1452     {
1453         boolean bDeleteStart = true;
1454 
1455         if ( (*pStart) == '/' || (*pStart) == '-' )
1456         {
1457             LPTSTR pSub = CharNext( pStart );
1458             if ( (*pSub) == 'l' || (*pSub) == 'L' )
1459             {
1460                 pSub = CharNext( pSub );
1461                 if ( (*pSub) == 'a' || (*pSub) == 'A' )
1462                 {   // --- handle the lang parameter ---
1463                     LPTSTR pLanguage = NULL;
1464                     LPTSTR pLastChar;
1465                     if ( GetNextArgument( pNext, &pLanguage, &pNext, true ) != ERROR_SUCCESS )
1466                     {
1467                         StringCchCopy( m_pErrorText, MAX_TEXT_LENGTH, pStart );
1468                         nRet = ERROR_INVALID_PARAMETER;
1469                         break;
1470                     }
1471 
1472                     m_nLanguageID = _tcstol( pLanguage, &pLastChar, 10 );
1473                     delete [] pLanguage;
1474                 }
1475                 else
1476                 {   // --- handle the l(og) parameter ---
1477                     boolean bAppend = false;
1478                     LPTSTR  pFileName = NULL;
1479 
1480                     while ( *pSub )
1481                     {
1482                         if ( *pSub == '+' )
1483                         {
1484                             bAppend = true;
1485                             break;
1486                         }
1487                         pSub = CharNext( pSub );
1488                     }
1489 
1490                     if ( GetNextArgument( pNext, &pFileName, &pNext, true ) != ERROR_SUCCESS )
1491                     {
1492                         StringCchCopy( m_pErrorText, MAX_TEXT_LENGTH, pStart );
1493                         nRet = ERROR_INVALID_PARAMETER;
1494                         break;
1495                     }
1496 
1497                     if ( FAILED( StringCchCat( pNewCmdLine, nSize, pStart ) ) )
1498                     {
1499                         nRet = ERROR_OUTOFMEMORY;
1500                         break;
1501                     }
1502                     // we need to append a '+' otherwise msiexec would overwrite our log file
1503                     if ( !bAppend && FAILED( StringCchCat( pNewCmdLine, nSize, TEXT( "+" ) ) ) )
1504                     {
1505                         nRet = ERROR_OUTOFMEMORY;
1506                         break;
1507                     }
1508                     if ( FAILED( StringCchCat( pNewCmdLine, nSize, TEXT( " \"" ) ) ) ||
1509                         FAILED( StringCchCat( pNewCmdLine, nSize, pFileName ) ) ||
1510                         FAILED( StringCchCat( pNewCmdLine, nSize, TEXT( "\" " ) ) ) )
1511                     {
1512                         nRet = ERROR_OUTOFMEMORY;
1513                         break;
1514                     }
1515 
1516                     if ( bAppend )
1517                         m_pLogFile = _tfopen( pFileName, TEXT( "ab" ) );
1518                     else
1519                         m_pLogFile = _tfopen( pFileName, TEXT( "wb" ) );
1520 
1521                     delete [] pFileName;
1522                 }
1523             }
1524             else if ( (*pSub) == 'q' || (*pSub) == 'Q' )
1525             {   // --- Handle quiet file parameter ---
1526                 pSub = CharNext( pSub );
1527                 if ( ! (*pSub) || (*pSub) == 'n' || (*pSub) == 'N' )
1528                     m_bQuiet = true;
1529 
1530                 if ( FAILED( StringCchCat( pNewCmdLine, nSize, pStart ) ) ||
1531                      FAILED( StringCchCat( pNewCmdLine, nSize, TEXT( " " ) ) ) )
1532                 {
1533                     nRet = ERROR_OUTOFMEMORY;
1534                     break;
1535                 }
1536             }
1537             else if ( _tcsnicmp( pSub, PARAM_RUNNING, _tcslen( PARAM_RUNNING ) ) == 0 )
1538             {
1539                 m_bIgnoreAlreadyRunning = true;
1540             }
1541             else if ( _tcsnicmp( pSub, CMDLN_REG_ALL_MSO_TYPES, _tcslen( CMDLN_REG_ALL_MSO_TYPES ) ) == 0 )
1542             {
1543                 m_bRegAllMsoTypes = true;
1544             }
1545             else if ( _tcsnicmp( pSub, CMDLN_REG_NO_MSO_TYPES, _tcslen( CMDLN_REG_NO_MSO_TYPES ) ) == 0 )
1546             {
1547                 m_bRegNoMsoTypes = true;
1548             }
1549             else if ( (*pSub) == 'i' || (*pSub) == 'I' || (*pSub) == 'f' || (*pSub) == 'F' ||
1550                       (*pSub) == 'p' || (*pSub) == 'P' || (*pSub) == 'x' || (*pSub) == 'X' ||
1551                       (*pSub) == 'y' || (*pSub) == 'Y' || (*pSub) == 'z' || (*pSub) == 'Z' )
1552             {
1553                 StringCchCopy( m_pErrorText, MAX_TEXT_LENGTH, pStart );
1554                 nRet = ERROR_INVALID_PARAMETER;
1555                 break;
1556             }
1557             else if ( (*pSub) == 'a' || (*pSub) == 'A' )
1558             {   // --- Handle Administrative Installation ---
1559                 SetAdminInstall( true );
1560             }
1561             else if ( (*pSub) == 'j' || (*pSub) == 'J' )
1562             {   // --- Handle Administrative Installation ---
1563                 m_pAdvertise = pStart;
1564                 m_bQuiet     = true;
1565                 bDeleteStart = false;
1566             }
1567             else if ( (*pSub) == '?' || (*pSub) == 'h' || (*pSub) == 'H' )
1568             {   // --- Handle Show Usage ---
1569                 nRet = ERROR_SHOW_USAGE;
1570                 break;
1571             }
1572             else
1573             {
1574                 if ( FAILED( StringCchCat( pNewCmdLine, nSize, pStart ) ) ||
1575                      FAILED( StringCchCat( pNewCmdLine, nSize, TEXT( " " ) ) ) )
1576                 {
1577                     nRet = ERROR_OUTOFMEMORY;
1578                     break;
1579                 }
1580             }
1581         }
1582         else
1583         {
1584             if ( FAILED( StringCchCat( pNewCmdLine, nSize, pStart ) ) ||
1585                  FAILED( StringCchCat( pNewCmdLine, nSize, TEXT( " " ) ) ) )
1586             {
1587                 nRet = ERROR_OUTOFMEMORY;
1588                 break;
1589             }
1590         }
1591 
1592         if ( bDeleteStart ) delete [] pStart;
1593         pStart = NULL;
1594     }
1595 
1596     if ( pStart ) delete [] pStart;
1597 
1598     *pCmdLine = pNewCmdLine;
1599 
1600     if ( nRet != ERROR_SUCCESS )
1601     {
1602         SetError( nRet );
1603         return false;
1604     }
1605     else
1606         return true;
1607 }
1608 
1609 //--------------------------------------------------------------------------
IsAdmin()1610 boolean SetupApp::IsAdmin()
1611 {
1612     if ( IsWin9x() )
1613         return true;
1614 
1615     PSID aPsidAdmin;
1616     SID_IDENTIFIER_AUTHORITY aAuthority = SECURITY_NT_AUTHORITY;
1617 
1618     if ( !AllocateAndInitializeSid( &aAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
1619                                     DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
1620                                     &aPsidAdmin ) )
1621         return false;
1622 
1623     BOOL bIsAdmin = FALSE;
1624 
1625     if ( GetOSVersion() >= 5 )
1626     {
1627         HMODULE hAdvapi32 = LoadLibrary( ADVAPI32_DLL );
1628 
1629         if ( !hAdvapi32 )
1630             bIsAdmin = FALSE;
1631         else
1632         {
1633             PFnCheckTokenMembership pfnCheckTokenMembership = (PFnCheckTokenMembership) GetProcAddress( hAdvapi32, ADVAPI32API_CheckTokenMembership);
1634             if ( !pfnCheckTokenMembership || !pfnCheckTokenMembership( NULL, aPsidAdmin, &bIsAdmin ) )
1635                 bIsAdmin = FALSE;
1636         }
1637         FreeLibrary( hAdvapi32 );
1638     }
1639     else
1640     {
1641         // NT4, check groups of user
1642         HANDLE hAccessToken = 0;
1643         UCHAR *szInfoBuffer = new UCHAR[ 1024 ]; // may need to resize if TokenInfo too big
1644         DWORD dwInfoBufferSize = 1024;
1645         DWORD dwRetInfoBufferSize = 0;
1646         UINT i=0;
1647 
1648         if ( WIN::OpenProcessToken( WIN::GetCurrentProcess(), TOKEN_READ, &hAccessToken ) )
1649         {
1650             bool bSuccess = false;
1651             bSuccess = WIN::GetTokenInformation( hAccessToken, TokenGroups,
1652                                                  szInfoBuffer, dwInfoBufferSize,
1653                                                  &dwRetInfoBufferSize ) == TRUE;
1654 
1655             if( dwRetInfoBufferSize > dwInfoBufferSize )
1656             {
1657                 delete [] szInfoBuffer;
1658                 szInfoBuffer = new UCHAR[ dwRetInfoBufferSize ];
1659                 dwInfoBufferSize = dwRetInfoBufferSize;
1660                 bSuccess = WIN::GetTokenInformation( hAccessToken, TokenGroups,
1661                                                      szInfoBuffer, dwInfoBufferSize,
1662                                                      &dwRetInfoBufferSize ) == TRUE;
1663             }
1664 
1665             WIN::CloseHandle( hAccessToken );
1666 
1667             if ( bSuccess )
1668             {
1669                 PTOKEN_GROUPS pGroups = (PTOKEN_GROUPS)(UCHAR*) szInfoBuffer;
1670                 for( i=0; i<pGroups->GroupCount; i++ )
1671                 {
1672                     if( WIN::EqualSid( aPsidAdmin, pGroups->Groups[i].Sid ) )
1673                     {
1674                         bIsAdmin = TRUE;
1675                         break;
1676                     }
1677                 }
1678             }
1679 
1680             delete [] szInfoBuffer;
1681         }
1682     }
1683 
1684     WIN::FreeSid( aPsidAdmin );
1685 
1686     return bIsAdmin ? true : false;
1687 }
1688 
1689 //--------------------------------------------------------------------------
CopyIniFile(LPCTSTR pIniFile)1690 LPTSTR SetupApp::CopyIniFile( LPCTSTR pIniFile )
1691 {
1692     m_pTmpName = _ttempnam( TEXT( "C:\\" ), TEXT( "Setup" ) );
1693 
1694     if ( !m_pTmpName )
1695     {
1696         Log( TEXT( "ERROR: Could not create temp file\n" ) );
1697         return NULL;
1698     }
1699 
1700     FILE *pOut  = _tfopen( m_pTmpName, TEXT( "wb" ) );
1701     FILE *pIn   = _tfopen( pIniFile, TEXT( "rb" ) );
1702 
1703     if ( pOut && pIn )
1704     {
1705         size_t  nRead, nWritten;
1706         BYTE    pBuf[1024];
1707 
1708         nRead = fread( pBuf, sizeof( BYTE ), 1024, pIn );
1709         while ( nRead && !ferror( pIn ) )
1710         {
1711             nWritten = fwrite( pBuf, sizeof( BYTE ), nRead, pOut );
1712             if ( nWritten != nRead )
1713             {
1714                 Log( TEXT( "ERROR: Could not write all bytes to temp file\n" ) );
1715                 break;
1716             }
1717             nRead = fread( pBuf, sizeof( BYTE ), 1024, pIn );
1718         }
1719     }
1720 
1721     if ( pOut ) fclose( pOut );
1722     if ( pIn ) fclose( pIn );
1723 
1724     return m_pTmpName;
1725 }
1726 
1727 //--------------------------------------------------------------------------
ConvertNewline(LPTSTR pText) const1728 void SetupApp::ConvertNewline( LPTSTR pText ) const
1729 {
1730     int i=0;
1731 
1732     while ( pText[i] != 0 )
1733     {
1734         if ( ( pText[i] == '\\' ) && ( pText[i+1] == 'n' ) )
1735         {
1736             pText[i] = 0x0d;
1737             pText[i+1] = 0x0a;
1738             i+=2;
1739         }
1740         else
1741             i+=1;
1742     }
1743 }
1744 
1745 //--------------------------------------------------------------------------
SetProdToAppTitle(LPCTSTR pProdName)1746 LPTSTR SetupApp::SetProdToAppTitle( LPCTSTR pProdName )
1747 {
1748     if ( !pProdName ) return m_pAppTitle;
1749 
1750     LPTSTR pAppProdTitle = new TCHAR[ MAX_STR_CAPTION ];
1751            pAppProdTitle[0] = '\0';
1752 
1753     WIN::LoadString( m_hInst, IDS_APP_PROD_TITLE, pAppProdTitle, MAX_STR_CAPTION );
1754 
1755     int nAppLen = lstrlen( pAppProdTitle );
1756     int nProdLen = lstrlen( pProdName );
1757 
1758     if ( ( nAppLen == 0 ) || ( nProdLen == 0 ) )
1759     {
1760         delete [] pAppProdTitle;
1761         return m_pAppTitle;
1762     }
1763 
1764     int nLen = nAppLen + nProdLen + 3;
1765 
1766     if ( nLen > STRSAFE_MAX_CCH ) return m_pAppTitle;
1767 
1768     LPTSTR pIndex = _tcsstr( pAppProdTitle, PRODUCT_NAME_VAR );
1769 
1770     if ( pIndex )
1771     {
1772         int nOffset = pIndex - pAppProdTitle;
1773         int nVarLen = lstrlen( PRODUCT_NAME_VAR );
1774 
1775         LPTSTR pNewTitle = new TCHAR[ nLen ];
1776         pNewTitle[0] = '\0';
1777 
1778         if ( nOffset > 0 )
1779         {
1780             StringCchCopyN( pNewTitle, nLen, pAppProdTitle, nOffset );
1781         }
1782 
1783         StringCchCat( pNewTitle, nLen, pProdName );
1784 
1785         if ( nOffset + nVarLen < nAppLen )
1786         {
1787             StringCchCat( pNewTitle, nLen, pIndex + nVarLen );
1788         }
1789 
1790         delete [] m_pAppTitle;
1791         m_pAppTitle = pNewTitle;
1792     }
1793 
1794     delete [] pAppProdTitle;
1795 
1796     return m_pAppTitle;
1797 }
1798 
1799 
1800 //--------------------------------------------------------------------------
IsPatchInstalled(TCHAR * pBaseDir,TCHAR * pFileName)1801 boolean SetupApp::IsPatchInstalled( TCHAR* pBaseDir, TCHAR* pFileName )
1802 {
1803     if ( !m_bSupportsPatch )
1804         return false;
1805 
1806     PMSIHANDLE hSummaryInfo;
1807     int nLen = lstrlen( pBaseDir ) + lstrlen( pFileName ) + 1;
1808     TCHAR *szDatabasePath = new TCHAR [ nLen ];
1809     TCHAR sBuf[80];
1810 
1811     StringCchCopy( szDatabasePath, nLen, pBaseDir );
1812     StringCchCat( szDatabasePath, nLen, pFileName );
1813 
1814     UINT nRet = aoo_MsiGetSummaryInformation( NULL, szDatabasePath, 0, &hSummaryInfo );
1815 
1816     if ( nRet != ERROR_SUCCESS )
1817     {
1818         StringCchPrintf( sBuf, 80, TEXT("ERROR: IsPatchInstalled: MsiGetSummaryInformation returned %u.\r\n"), nRet );
1819         Log( sBuf );
1820         return false;
1821     }
1822 
1823     UINT    uiDataType;
1824     LPTSTR  szPatchID = new TCHAR[ 64 ];
1825     DWORD   cchValueBuf = 64;
1826     nRet = aoo_MsiSummaryInfoGetProperty( hSummaryInfo, PID_REVNUMBER, &uiDataType, NULL, NULL, szPatchID, &cchValueBuf );
1827 
1828     if ( nRet != ERROR_SUCCESS )
1829     {
1830         StringCchPrintf( sBuf, 80, TEXT("ERROR: IsPatchInstalled: MsiSummaryInfoGetProperty returned %u.\r\n"), nRet );
1831         Log( sBuf );
1832         return false;
1833     }
1834 
1835     nRet = aoo_MsiGetPatchInfo( szPatchID, INSTALLPROPERTY_LOCALPACKAGE, NULL, NULL );
1836 
1837     StringCchPrintf( sBuf, 80, TEXT("  GetPatchInfo for (%s) returned (%u)\r\n"), szPatchID, nRet );
1838     Log( sBuf );
1839 
1840     delete []szPatchID;
1841 
1842     if ( nRet == ERROR_BAD_CONFIGURATION )
1843         return false;
1844     else if ( nRet == ERROR_INVALID_PARAMETER )
1845         return false;
1846     else if ( nRet == ERROR_MORE_DATA )
1847         return true;
1848     else if ( nRet == ERROR_SUCCESS )
1849         return true;
1850     else if ( nRet == ERROR_UNKNOWN_PRODUCT )
1851         return false;
1852     else if ( nRet == ERROR_UNKNOWN_PROPERTY )
1853         return false;
1854     else return false;
1855 }
1856 
1857 //--------------------------------------------------------------------------
1858 // The real Windows version, not the shimmed one.
1859 //
1860 // GetVersionEx() and the Windows Installer VersionNT / WindowsBuild properties all
1861 // report Windows 8.1 (6.3 / 9600) on Windows 10 and 11 unless the caller carries a
1862 // supportedOS manifest entry.  Measured on Windows 11 build 26200, msiexec reports
1863 // VersionNT=603 and WindowsBuild=9600 -- which is why this check cannot be expressed
1864 // as an MSI LaunchCondition, and lives here instead.
1865 //
1866 // RtlGetVersion is not subject to that shim.
GetRealWindowsVersion(OSVERSIONINFOEXW * pInfo)1867 static bool GetRealWindowsVersion( OSVERSIONINFOEXW *pInfo )
1868 {
1869     typedef LONG ( WINAPI *pfnRtlGetVersion_t )( OSVERSIONINFOEXW * );
1870 
1871     HMODULE hNtdll = ::GetModuleHandle( TEXT( "ntdll.dll" ) );
1872     if ( hNtdll == NULL )
1873         return false;
1874 
1875     pfnRtlGetVersion_t pRtlGetVersion =
1876         (pfnRtlGetVersion_t)::GetProcAddress( hNtdll, "RtlGetVersion" );
1877     if ( pRtlGetVersion == NULL )
1878         return false;
1879 
1880     ZeroMemory( pInfo, sizeof( *pInfo ) );
1881     pInfo->dwOSVersionInfoSize = sizeof( *pInfo );
1882 
1883     return pRtlGetVersion( pInfo ) == 0;
1884 }
1885 
1886 //--------------------------------------------------------------------------
CheckOSVersion()1887 boolean SetupApp::CheckOSVersion()
1888 {
1889     OSVERSIONINFOEXW aInfo;
1890 
1891     if ( !GetRealWindowsVersion( &aInfo ) )
1892     {
1893         // Could not determine the version.  Let the install proceed rather than
1894         // refuse on a machine we simply failed to identify -- if the OS really is too
1895         // old the runtime install will fail next, and say so.
1896         Log( TEXT( "Warning: could not determine the Windows version.\r\n" ) );
1897         return true;
1898     }
1899 
1900     TCHAR sBuf[ 128 ];
1901 
1902     StringCchPrintf( sBuf, 128, TEXT( " Windows version %u.%u build %u, service pack %u\r\n" ),
1903                      aInfo.dwMajorVersion, aInfo.dwMinorVersion, aInfo.dwBuildNumber,
1904                      (DWORD)aInfo.wServicePackMajor );
1905     Log( sBuf );
1906 
1907     const DWORD nHave = ( aInfo.dwMajorVersion << 16 ) | ( aInfo.dwMinorVersion << 8 )
1908                         | aInfo.wServicePackMajor;
1909     const DWORD nNeed = ( REQUIRED_WINDOWS_MAJOR << 16 ) | ( REQUIRED_WINDOWS_MINOR << 8 )
1910                         | REQUIRED_WINDOWS_SP;
1911 
1912     if ( nHave < nNeed )
1913     {
1914         StringCchPrintf( sBuf, 128,
1915                          TEXT( "ERROR: Windows %u.%u SP%u is older than the required Windows %u.%u SP%u.\r\n" ),
1916                          aInfo.dwMajorVersion, aInfo.dwMinorVersion,
1917                          (DWORD)aInfo.wServicePackMajor,
1918                          (DWORD)REQUIRED_WINDOWS_MAJOR, (DWORD)REQUIRED_WINDOWS_MINOR,
1919                          (DWORD)REQUIRED_WINDOWS_SP );
1920         Log( sBuf );
1921         SetError( ERROR_OS_TO_OLD );
1922         return false;
1923     }
1924 
1925     return true;
1926 }
1927 
1928 //--------------------------------------------------------------------------
1929 // Is the VC v14 runtime already usable in THIS process?
1930 //
1931 // Deliberately functional rather than a registry or ProductCode lookup: it needs no
1932 // GUID that goes stale with every servicing update, no registry view juggling, and it
1933 // tests the thing that actually matters -- whether our DLLs will be able to bind.
1934 //
1935 // LOAD_LIBRARY_SEARCH_SYSTEM32 so we probe the machine-wide runtime and cannot be
1936 // fooled by a stray copy sitting next to setup.exe.
1937 //
1938 // This can only answer for setup.exe's own bitness -- a 64 bit process cannot load a
1939 // 32 bit DLL and vice versa.  That is fine: the caller only uses it to skip the
1940 // matching redistributable.  For the other architecture we just run the bundle, which
1941 // is idempotent and returns 1638 quickly when a newer runtime is already there.
RuntimeAlreadyPresent()1942 static bool RuntimeAlreadyPresent()
1943 {
1944     const TCHAR *pModules[] = {
1945         TEXT( "vcruntime140.dll" ),
1946         TEXT( "msvcp140.dll" ),
1947 #if defined( _WIN64 )
1948         // x64 only -- the separate EH runtime introduced with VS2017.
1949         TEXT( "vcruntime140_1.dll" ),
1950 #endif
1951     };
1952 
1953     for ( size_t i = 0; i < sizeof( pModules ) / sizeof( pModules[0] ); ++i )
1954     {
1955         HMODULE hMod = ::LoadLibraryEx( pModules[i], NULL,
1956                                         LOAD_LIBRARY_SEARCH_SYSTEM32 );
1957         if ( hMod == NULL )
1958             return false;
1959         ::FreeLibrary( hMod );
1960     }
1961 
1962     return true;
1963 }
1964 
1965 //--------------------------------------------------------------------------
InstallRuntimes(TCHAR * sRuntimePath,bool bMatchesOwnArchitecture)1966 boolean SetupApp::InstallRuntimes( TCHAR *sRuntimePath, bool bMatchesOwnArchitecture )
1967 {
1968     if ( bMatchesOwnArchitecture && RuntimeAlreadyPresent() )
1969     {
1970         Log( TEXT( " Runtime already present, skipping <%s>\r\n" ), sRuntimePath );
1971         return true;
1972     }
1973 
1974     Log( TEXT( " Will install runtime <%s>\r\n" ), sRuntimePath );
1975     OutputDebugStringFormat( TEXT( " Will install runtime <%s>\r\n" ), sRuntimePath );
1976 
1977     STARTUPINFO         aSUI;
1978     PROCESS_INFORMATION aPI;
1979 
1980     ZeroMemory( (void*)&aPI, sizeof( PROCESS_INFORMATION ) );
1981     ZeroMemory( (void*)&aSUI, sizeof( STARTUPINFO ) );
1982 
1983     aSUI.cb          = sizeof(STARTUPINFO);
1984     aSUI.dwFlags     = STARTF_USESHOWWINDOW;
1985     aSUI.wShowWindow = SW_SHOW;
1986 
1987     DWORD nCmdLineLength = lstrlen( sRuntimePath ) + lstrlen( PARAM_SILENTINSTALL ) + 2;
1988     TCHAR *sCmdLine = new TCHAR[ nCmdLineLength ];
1989 
1990     if ( FAILED( StringCchCopy( sCmdLine, nCmdLineLength, sRuntimePath ) ) ||
1991          FAILED( StringCchCat(  sCmdLine, nCmdLineLength, PARAM_SILENTINSTALL ) ) )
1992     {
1993         delete [] sCmdLine;
1994         SetError( ERROR_INSTALL_FAILURE );
1995         return false;
1996     }
1997 
1998     if ( !WIN::CreateProcess( NULL, sCmdLine, NULL, NULL, FALSE,
1999                               CREATE_DEFAULT_ERROR_MODE, NULL, NULL,
2000                               &aSUI, &aPI ) )
2001     {
2002         Log( TEXT( "ERROR: Could not create process %s.\r\n" ), sCmdLine );
2003         SetError( WIN::GetLastError() );
2004         delete [] sCmdLine;
2005         return false;
2006     }
2007 
2008     DWORD nResult = WaitForProcess( aPI.hProcess );
2009     bool bRet = true;
2010 
2011     if( ERROR_SUCCESS != nResult )
2012     {
2013         Log( TEXT( "ERROR: While waiting for %s.\r\n" ), sCmdLine );
2014         SetError( nResult );
2015         bRet = false;
2016     }
2017     else
2018     {
2019         GetExitCodeProcess( aPI.hProcess, &nResult );
2020 
2021         // Burn reports more than one flavour of success.  Treating anything non-zero as
2022         // a failure would flag every machine that already carries a newer runtime.
2023         if ( nResult == RUNTIME_INSTALL_OK )
2024         {
2025             Log( TEXT( " Installation of runtime completed successfully.\r\n" ) );
2026         }
2027         else if ( nResult == RUNTIME_INSTALL_NEWER )
2028         {
2029             Log( TEXT( " A newer runtime is already installed, nothing to do.\r\n" ) );
2030         }
2031         else if ( nResult == RUNTIME_INSTALL_REBOOT_REQ )
2032         {
2033             Log( TEXT( " Installation of runtime completed, a reboot is required.\r\n" ) );
2034         }
2035         else
2036         {
2037             TCHAR sBuf[80];
2038             StringCchPrintf( sBuf, 80,
2039                              TEXT("ERROR: install runtime returned %u.\r\n"), nResult );
2040             Log( sBuf );
2041             SetError( nResult );
2042             bRet = false;
2043         }
2044     }
2045 
2046     CloseHandle( aPI.hProcess );
2047 
2048     delete [] sCmdLine;
2049 
2050     return bRet;
2051 }
2052 
2053 //--------------------------------------------------------------------------
InstallRuntimes()2054 boolean SetupApp::InstallRuntimes()
2055 {
2056     TCHAR *sRuntimePath = 0;
2057     SYSTEM_INFO siSysInfo;
2058 
2059     HMODULE hKernel32 = ::LoadLibrary(_T("Kernel32.dll"));
2060     if ( hKernel32 != NULL )
2061     {
2062         typedef void (CALLBACK* pfnGetNativeSystemInfo_t)(LPSYSTEM_INFO);
2063         pfnGetNativeSystemInfo_t pfnGetNativeSystemInfo;
2064         pfnGetNativeSystemInfo = (pfnGetNativeSystemInfo_t)::GetProcAddress(hKernel32, "GetNativeSystemInfo");
2065         if ( pfnGetNativeSystemInfo != NULL )
2066         {
2067             pfnGetNativeSystemInfo(&siSysInfo);
2068         }
2069         else
2070         {
2071             // GetNativeSystemInfo does not exist. Maybe the code is running under Windows 2000.
2072             // Use GetSystemInfo instead.
2073             GetSystemInfo(&siSysInfo);
2074         }
2075         FreeLibrary(hKernel32);
2076     }
2077     else
2078     {
2079         // Failed to check Kernel32.dll. There may be something wrong.
2080         // Use GetSystemInfo instead anyway.
2081         GetSystemInfo(&siSysInfo);
2082     }
2083 
2084     OutputDebugStringFormat( TEXT( "found architecture<%d>\r\n" ), siSysInfo.wProcessorArchitecture );
2085 
2086     bool bOk = true;
2087 
2088 #if defined( _WIN64 )
2089 
2090     // A 64 bit office ships no 32 bit binaries at all, so it needs only the x64
2091     // runtime.  (The 32 bit office is the other way round: it cross-builds 64 bit
2092     // shell extensions, which is why the branch below installs both.)
2093     (void)siSysInfo;
2094 
2095     if ( GetPathToFile( RUNTIME_X64_NAME, &sRuntimePath ) )
2096         bOk = InstallRuntimes( sRuntimePath, true ) ? true : false;
2097     else
2098     {
2099         Log( TEXT( "ERROR: no installer for x64 runtime libraries found!\r\n" ) );
2100         bOk = false;
2101     }
2102 
2103     if ( sRuntimePath )
2104         delete [] sRuntimePath;
2105 
2106 #else
2107 
2108     // 32 bit office.  On 64 bit Windows it additionally needs the x64 runtime, because
2109     // its shell extensions (shlxthdl_x64, ooofilt_x64, propertyhdl_x64, so_activex_x64)
2110     // are 64 bit and get loaded by 64 bit Explorer and friends.
2111     if ( siSysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 )
2112     {
2113         if ( GetPathToFile( RUNTIME_X64_NAME, &sRuntimePath ) )
2114         {
2115             if ( !InstallRuntimes( sRuntimePath, false ) )  // cannot probe x64 from a 32 bit process
2116                 bOk = false;
2117         }
2118         else
2119         {
2120             Log( TEXT( "ERROR: no installer for x64 runtime libraries found!\r\n" ) );
2121             bOk = false;
2122         }
2123 
2124         if ( sRuntimePath )
2125         {
2126             delete [] sRuntimePath;
2127             sRuntimePath = 0;
2128         }
2129     }
2130 
2131     if ( GetPathToFile( RUNTIME_X86_NAME, &sRuntimePath ) )
2132     {
2133         if ( !InstallRuntimes( sRuntimePath, true ) )
2134             bOk = false;
2135     }
2136     else
2137     {
2138         Log( TEXT( "ERROR: no installer for x86 runtime libraries found!\r\n" ) );
2139         bOk = false;
2140     }
2141 
2142     if ( sRuntimePath )
2143         delete [] sRuntimePath;
2144 
2145 #endif
2146 
2147     // A failed runtime install used to be swallowed here -- the per-runtime result was
2148     // discarded and this returned true regardless.  The office then installed and could
2149     // not start, with nothing to point at.  Fail loudly instead.
2150     if ( !bOk )
2151     {
2152         Log( TEXT( "ERROR: the Visual C++ runtime could not be installed.\r\n" ) );
2153         SetError( ERROR_RUNTIME_FAILED );
2154         return false;
2155     }
2156 
2157     return true;
2158 }
2159 
2160 //--------------------------------------------------------------------------
2161 //--------------------------------------------------------------------------
LanguageData(LPTSTR pData)2162 LanguageData::LanguageData( LPTSTR pData )
2163 {
2164     m_nLanguageID = 0;
2165     m_pTransform = NULL;
2166 
2167     LPTSTR pLastChar;
2168 
2169     m_nLanguageID = _tcstol( pData, &pLastChar, 10 );
2170 
2171     if ( *pLastChar == ',' )
2172     {
2173         pLastChar += 1;
2174         int nLen = lstrlen( pLastChar ) + 1;
2175         m_pTransform = new TCHAR [ nLen ];
2176         StringCchCopy( m_pTransform, nLen, pLastChar );
2177     }
2178 }
2179 
2180 //--------------------------------------------------------------------------
~LanguageData()2181 LanguageData::~LanguageData()
2182 {
2183     if ( m_pTransform ) delete [] m_pTransform;
2184 }
2185 
2186 //--------------------------------------------------------------------------
2187