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 
23 
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <process.h>
28 
29 #if defined _MSC_VER
30 #pragma warning(push, 1)
31 #endif
32 #include <windows.h>
33 #if defined _MSC_VER
34 #pragma warning(pop)
35 #endif
36 
37 #include "cppuhelper/findsofficepath.h"
38 #include "sal/types.h"
39 
40 #define MY_LENGTH(s) (sizeof (s) / sizeof *(s) - 1)
41 
42 char const* getPath();
43 char* createCommandLine( char* lpCmdLine );
44 FILE* getErrorFile( int create );
45 void writeError( const char* errstr );
46 void closeErrorFile();
47 
48 /*
49  * The main function implements a loader for applications which use UNO.
50  *
51  * <p>This code runs on the Windows platform only.</p>
52  *
53  * <p>The main function detects a UNO installation on the system and adds the
54  * program directory of the UNO installation to the PATH environment variable.
55  * After that, the application process is loaded and started, whereby the
56  * new process inherits the environment of the calling process, including
57  * the modified PATH environment variable. The application's executable name
58  * must be the same as the name of this executable, prefixed by '_'.</p>
59  *
60  * <p>A UNO installation can be specified by the user by setting the UNO_PATH
61  * environment variable to the program directory of the UNO installation.
62  * If no installation is specified by the user, the default installation on
63  * the system will be taken. The default installation is read from the
64  * default value of the key "Software\OpenOffice.org\UNO\InstallPath" from the
65  * root key HKEY_CURRENT_USER in the Windows Registry. If this key is missing,
66  * the key is read from the root key HKEY_LOCAL_MACHINE.</p>
67  */
68 int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
69                     LPSTR lpCmdLine, int nCmdShow )
70 {
71     const char* ENVVARNAME = "PATH";
72     const char* PATHSEPARATOR = ";";
73 
74     char const* path = NULL;
75     char path2[MAX_PATH];
76     char* value = NULL;
77     char* envstr = NULL;
78     char* cmdline = NULL;
79     int size;
80     STARTUPINFO startup_info;
81     PROCESS_INFORMATION process_info;
82     BOOL bCreate;
83 
84     (void) hInstance; /* unused */
85     (void) hPrevInstance; /* unused */
86     (void) nCmdShow; /* unused */
87 
88     /* get the path of the UNO installation */
89     path = getPath();
90 
91     if ( path != NULL )
92     {
93         wchar_t cmd[
94             MY_LENGTH(L"\"") + MAX_PATH +
95             MY_LENGTH(L"\\unoinfo.exe\" c++")];
96             /* hopefully does not overflow */
97         int pathsize;
98         SECURITY_ATTRIBUTES sec;
99         HANDLE temp;
100         HANDLE stdoutRead;
101         HANDLE stdoutWrite;
102         STARTUPINFOW startinfo;
103         PROCESS_INFORMATION procinfo;
104         int ret;
105         cmd[0] = L'"';
106         pathsize = MultiByteToWideChar(CP_ACP, 0, path, -1, cmd + 1, MAX_PATH);
107         if (pathsize == 0) {
108             writeError("Error: MultiByteToWideChar failed!\n");
109             closeErrorFile();
110             return 1;
111         }
112         if (wcschr(cmd + 1, L'"') != NULL) {
113             writeError("Error: bad characters in UNO installation path!\n");
114             closeErrorFile();
115             return 1;
116         }
117         wcscpy(
118             cmd + pathsize,
119             (L"\\unoinfo.exe\" c++" +
120              (pathsize == 1 || cmd[pathsize - 1] != L'\\' ? 0 : 1)));
121         sec.nLength = sizeof (SECURITY_ATTRIBUTES);
122         sec.lpSecurityDescriptor = NULL;
123         sec.bInheritHandle = TRUE;
124         if (CreatePipe(&temp, &stdoutWrite, &sec, 0) == 0 ||
125             DuplicateHandle(
126                 GetCurrentProcess(), temp, GetCurrentProcess(), &stdoutRead, 0,
127                 FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == 0)
128         {
129             writeError("Error: CreatePipe/DuplicateHandle failed!\n");
130             closeErrorFile();
131             return 1;
132         }
133         memset(&startinfo, 0, sizeof (STARTUPINFOW));
134         startinfo.cb = sizeof (STARTUPINFOW);
135         startinfo.lpDesktop = L"";
136         startinfo.dwFlags = STARTF_USESTDHANDLES;
137         startinfo.hStdOutput = stdoutWrite;
138         ret = CreateProcessW(
139             NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &startinfo, &procinfo);
140         if (ret != 0) {
141             char * buf = NULL;
142             size_t n = 1000;
143             size_t k = 0;
144             DWORD exitcode;
145             int path2size;
146             CloseHandle(stdoutWrite);
147             CloseHandle(procinfo.hThread);
148             for (;;) {
149                 DWORD m;
150                 buf = realloc(buf, n);
151                 if (buf == NULL) {
152                     writeError(
153                         "Error: out of memory reading unoinfo output!\n");
154                     closeErrorFile();
155                     return 1;
156                 }
157                 if (!ReadFile(stdoutRead, buf + k, n - k, &m, NULL))
158                 {
159                     DWORD err = GetLastError();
160                     if (err == ERROR_HANDLE_EOF || err == ERROR_BROKEN_PIPE) {
161                         break;
162                     }
163                     writeError("Error: cannot read unoinfo output!\n");
164                     closeErrorFile();
165                     return 1;
166                 }
167                 if (m == 0) {
168                     break;
169                 }
170                 k += m;
171                 if (k >= n) {
172                     if (n >= SAL_MAX_SIZE / 2) {
173                         writeError(
174                             "Error: out of memory reading unoinfo output!\n");
175                         closeErrorFile();
176                         return 1;
177                     }
178                     n *= 2;
179                 }
180             }
181             if ((k & 1) == 1) {
182                 writeError("Error: bad unoinfo output!\n");
183                 closeErrorFile();
184                 return 1;
185             }
186             CloseHandle(stdoutRead);
187             if (!GetExitCodeProcess(procinfo.hProcess, &exitcode) ||
188                 exitcode != 0)
189             {
190                 writeError("Error: executing unoinfo failed!\n");
191                 closeErrorFile();
192                 return 1;
193             }
194             if (k == 0) {
195                 path2size = 0;
196             } else {
197                 path2size = WideCharToMultiByte(
198                     CP_ACP, 0, (wchar_t *) buf, k / 2, path2, MAX_PATH - 1,
199                     NULL, NULL);
200                 if (path2size == 0) {
201                     writeError("Error: converting unoinfo output failed!\n");
202                     closeErrorFile();
203                     return 1;
204                 }
205             }
206             path2[path2size] = '\0';
207             path = path2;
208         } else {
209             if (GetLastError() != ERROR_FILE_NOT_FOUND) {
210                 writeError("Error: calling unoinfo failed!\n");
211                 closeErrorFile();
212                 return 1;
213             }
214             CloseHandle(stdoutRead);
215             CloseHandle(stdoutWrite);
216         }
217 
218         /* get the value of the PATH environment variable */
219         value = getenv( ENVVARNAME );
220 
221         /*
222          * add the UNO installation path to the PATH environment variable;
223          * note that this only affects the environment variable of the current
224          * process, the command processor's environment is not changed
225          */
226         size = strlen( ENVVARNAME ) + strlen( "=" ) + strlen( path ) + 1;
227 		if ( value != NULL )
228             size += strlen( PATHSEPARATOR ) + strlen( value );
229 		envstr = (char*) malloc( size );
230         strcpy( envstr, ENVVARNAME );
231         strcat( envstr, "=" );
232         strcat( envstr, path );
233 		if ( value != NULL )
234 		{
235             strcat( envstr, PATHSEPARATOR );
236             strcat( envstr, value );
237 		}
238         _putenv( envstr );
239         free( envstr );
240     }
241     else
242     {
243         writeError( "Warning: no UNO installation found!\n" );
244     }
245 
246     /* create the command line for the application process */
247     cmdline = createCommandLine( lpCmdLine );
248     if ( cmdline == NULL )
249     {
250         writeError( "Error: cannot create command line!\n" );
251         closeErrorFile();
252         return 1;
253     }
254 
255     /* create the application process */
256 	memset( &startup_info, 0, sizeof( STARTUPINFO ) );
257 	startup_info.cb = sizeof( STARTUPINFO );
258     bCreate = CreateProcess( NULL, cmdline, NULL,  NULL, FALSE, 0, NULL, NULL,
259                              &startup_info, &process_info );
260     free( cmdline );
261     if ( !bCreate )
262     {
263         writeError( "Error: cannot create process!\n" );
264         closeErrorFile();
265         return 1;
266     }
267 
268     /* close the error file */
269     closeErrorFile();
270 
271     return 0;
272 }
273 
274 /*
275  * Gets the path of a UNO installation.
276  *
277  * @return the installation path or NULL, if no installation was specified or
278  *         found, or if an error occured
279  */
280 char const* getPath()
281 {
282     char const* path = cppuhelper_detail_findSofficePath();
283 
284     if ( path == NULL )
285         writeError( "Warning: getting path from Windows Registry failed!\n" );
286 
287     return path;
288 }
289 
290 /*
291  * Creates the command line for the application process including the absolute
292  * path of the executable.
293  *
294  * <p>The application's executable file name is the name of this executable
295  * prefixed by '_'.</p>
296  *
297  * @param appendix specifies the command line for the application excluding
298  *                 the executable name
299  *
300  * @return the command line for the application process or NULL, if an error
301  *         occured
302  */
303 char* createCommandLine( char* appendix )
304 {
305     const char* CMDPREFIX = "_";
306     const char* DQUOTE = "\"";
307     const char* SPACE = " ";
308 
309     char* cmdline = NULL;
310 
311     char cmdname[ _MAX_PATH ];
312     char drive[ _MAX_DRIVE ];
313     char dir[ _MAX_PATH ];
314     char base[ _MAX_FNAME ];
315     char newbase[ _MAX_FNAME ];
316     char ext[ _MAX_EXT ];
317 
318     /* get the absolute path of the executable file */
319     if ( GetModuleFileName( NULL, cmdname, sizeof( cmdname ) ) )
320     {
321         /* prefix the executable file name by '_' */
322         _splitpath( cmdname, drive, dir, base, ext );
323         strcpy( newbase, CMDPREFIX );
324         strcat( newbase, base );
325         _makepath( cmdname, drive, dir, newbase, ext );
326 
327         /* create the command line */
328         cmdline = (char*) malloc( strlen( DQUOTE ) + strlen( cmdname ) +
329             strlen ( DQUOTE ) + strlen( SPACE ) + strlen( appendix ) + 1 );
330         strcpy( cmdline, DQUOTE );
331         strcat( cmdline, cmdname );
332         strcat( cmdline, DQUOTE );
333         strcat( cmdline, SPACE );
334         strcat( cmdline, appendix );
335     }
336 
337     return cmdline;
338 }
339 
340 /*
341  * Gets the pointer to the error file.
342  *
343  * <p>The error file will only be created, if create != 0.</p>
344  *
345  * <p>The error file has the name <executable file name>-error.log and is
346  * created in the same directory as the executable file. If this fails,
347  * the error file is created in the directory designated for temporary files.
348  * </p>
349 
350  * @param create specifies, if the error file should be created (create != 0)
351  *
352  * @return the pointer to the open error file or NULL, if no error file is
353  *         open or can be created
354  */
355 FILE* getErrorFile( int create )
356 {
357     const char* MODE = "w";
358     const char* BASEPOSTFIX = "-error";
359     const char* EXTENSION = ".log";
360 
361     static FILE* ferr = NULL;
362 
363     char fname[ _MAX_PATH ];
364     char drive[ _MAX_DRIVE ];
365     char dir[ _MAX_PATH ];
366     char base[ _MAX_FNAME ];
367     char newbase[ _MAX_FNAME ];
368     char ext[ _MAX_EXT ];
369 
370     if ( ferr == NULL && create )
371     {
372         /* get the absolute path of the executable file */
373         if ( GetModuleFileName( NULL, fname, sizeof( fname ) ) )
374         {
375             /* create error file in the directory of the executable file */
376             _splitpath( fname, drive, dir, base, ext );
377             strcpy( newbase, base );
378             strcat( newbase, BASEPOSTFIX );
379             _makepath( fname, drive, dir, newbase, EXTENSION );
380             ferr = fopen( fname, MODE );
381 
382             if ( ferr == NULL )
383             {
384                 /* create error file in the temp directory */
385                 GetTempPath( sizeof( fname ), fname );
386                 strcat( fname, newbase );
387                 strcat( fname, EXTENSION );
388                 ferr = fopen( fname, MODE );
389             }
390         }
391     }
392 
393     return ferr;
394 }
395 
396 /*
397  * Writes an error message to the error file.
398  *
399  * @param errstr specifies the error message
400  */
401 void writeError( const char* errstr )
402 {
403     FILE* ferr = getErrorFile( 1 );
404     if ( ferr != NULL )
405     {
406         fprintf( ferr, errstr );
407         fflush( ferr );
408     }
409 }
410 
411 /*
412  * Closes the error file.
413  */
414 void closeErrorFile()
415 {
416     FILE* ferr = getErrorFile( 0 );
417     if ( ferr != NULL )
418         fclose( ferr );
419 }
420