summaryrefslogtreecommitdiffstats
path: root/desktop/win32/source/loader.cxx
blob: d30f0ef90896c5530ac15de1e08ccd130514c511 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "loader.hxx"
#include <cassert>
#include <systools/win32/uwinapi.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <desktop/exithelper.h>
#include <tools/pathutils.hxx>

#include <fstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>

namespace {

void fail()
{
    LPWSTR buf = nullptr;
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
        GetLastError(), 0, reinterpret_cast< LPWSTR >(&buf), 0, nullptr);
    MessageBoxW(nullptr, buf, nullptr, MB_OK | MB_ICONERROR);
    HeapFree(GetProcessHeap(), 0, buf);
    TerminateProcess(GetCurrentProcess(), 255);
}

LPWSTR* GetCommandArgs(int* pArgc) { return CommandLineToArgvW(GetCommandLineW(), pArgc); }

// tdf#120249: quotes in arguments need to be escaped; backslashes before quotes need doubling. See
// https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-commandlinetoargvw
std::wstring EscapeArg(LPCWSTR sArg)
{
    const size_t nOrigSize = wcslen(sArg);
    LPCWSTR const end = sArg + nOrigSize;
    std::wstring sResult(L"\"");

    LPCWSTR lastPosQuote = sArg;
    LPCWSTR posQuote;
    while ((posQuote = std::find(lastPosQuote, end, L'"')) != end)
    {
        LPCWSTR posBackslash = posQuote;
        while (posBackslash != lastPosQuote && *(posBackslash - 1) == L'\\')
            --posBackslash;

        sResult.append(lastPosQuote, posBackslash);
        sResult.append((posQuote - posBackslash) * 2 + 1, L'\\'); // 2n+1 '\' to escape the '"'
        sResult.append(1, L'"');
        lastPosQuote = posQuote + 1;
    }

    LPCWSTR posTrailingBackslashSeq = end;
    while (posTrailingBackslashSeq != lastPosQuote && *(posTrailingBackslashSeq - 1) == L'\\')
        --posTrailingBackslashSeq;
    sResult.append(lastPosQuote, posTrailingBackslashSeq);
    sResult.append((end - posTrailingBackslashSeq) * 2, L'\\'); // 2n '\' before closing '"'
    sResult.append(1, L'"');

    return sResult;
}

void AddEscapedArg(LPCWSTR sArg, std::vector<std::wstring>& aEscapedArgs,
                   std::size_t& iLengthAccumulator)
{
    std::wstring sEscapedArg = EscapeArg(sArg);
    aEscapedArgs.push_back(sEscapedArg);
    iLengthAccumulator += sEscapedArg.length() + 1; // a space between args
}

bool HasWildCard(LPCWSTR sArg)
{
    while (*sArg != L'\0')
    {
        if (*sArg == L'*' || *sArg == L'?')
            return true;
        sArg++;
    }
    return false;
}

}

namespace desktop_win32 {

void extendLoaderEnvironment(WCHAR * binPath, WCHAR * iniDirectory) {
    if (!GetModuleFileNameW(nullptr, iniDirectory, MAX_PATH)) {
        fail();
    }
    WCHAR * iniDirEnd = tools::filename(iniDirectory);
    WCHAR name[MAX_PATH + MY_LENGTH(L".bin")];
        // hopefully std::size_t is large enough to not overflow
    WCHAR * nameEnd = name;
    for (WCHAR * p = iniDirEnd; *p != L'\0'; ++p) {
        *nameEnd++ = *p;
    }
    if (!(nameEnd - name >= 4 && nameEnd[-4] == L'.' &&
         (((nameEnd[-3] == L'E' || nameEnd[-3] == L'e') &&
           (nameEnd[-2] == L'X' || nameEnd[-2] == L'x') &&
           (nameEnd[-1] == L'E' || nameEnd[-1] == L'e')) ||
          ((nameEnd[-3] == L'C' || nameEnd[-3] == L'c') &&
           (nameEnd[-2] == L'O' || nameEnd[-2] == L'o') &&
           (nameEnd[-1] == L'M' || nameEnd[-1] == L'm')))))
    {
        *nameEnd = L'.';
        nameEnd += 4;
    }
    nameEnd[-3] = 'b';
    nameEnd[-2] = 'i';
    nameEnd[-1] = 'n';
    tools::buildPath(binPath, iniDirectory, iniDirEnd, name, nameEnd - name);
    *iniDirEnd = L'\0';
    std::size_t const maxEnv = 32767;
    WCHAR env[maxEnv];
    DWORD n = GetEnvironmentVariableW(L"PATH", env, maxEnv);
    if ((n >= maxEnv || n == 0) && GetLastError() != ERROR_ENVVAR_NOT_FOUND) {
        fail();
    }
    // must be first in PATH to override other entries
    assert(*(iniDirEnd - 1) == L'\\'); // hence -1 below
    if (wcsncmp(env, iniDirectory, iniDirEnd - iniDirectory - 1) != 0
        || env[iniDirEnd - iniDirectory - 1] != L';')
    {
        WCHAR pad[MAX_PATH + maxEnv];
            // hopefully std::size_t is large enough to not overflow
        WCHAR * p = commandLineAppend(pad, iniDirectory, iniDirEnd - iniDirectory - 1);
        if (n != 0) {
            *p++ = L';';
            for (DWORD i = 0; i <= n; ++i) {
                *p++ = env[i];
            }
        } else {
            *p++ = L'\0';
        }
        if (!SetEnvironmentVariableW(L"PATH", pad)) {
            fail();
        }
    }
}

int officeloader_impl(bool bAllowConsole)
{
    WCHAR szTargetFileName[MAX_PATH] = {};
    WCHAR szIniDirectory[MAX_PATH];
    STARTUPINFOW aStartupInfo;

    desktop_win32::extendLoaderEnvironment(szTargetFileName, szIniDirectory);

    ZeroMemory(&aStartupInfo, sizeof(aStartupInfo));
    aStartupInfo.cb = sizeof(aStartupInfo);

    // Create process with same command line, environment and stdio handles which
    // are directed to the created pipes
    GetStartupInfoW(&aStartupInfo);

    DWORD dwExitCode = DWORD(-1);

    bool fSuccess = false;
    LPWSTR lpCommandLine = nullptr;
    bool bFirst = true;
    WCHAR cwd[MAX_PATH];
    DWORD cwdLen = GetCurrentDirectoryW(MAX_PATH, cwd);
    if (cwdLen >= MAX_PATH)
    {
        cwdLen = 0;
    }
    std::vector<std::wstring> aEscapedArgs;

    // read limit values from bootstrap.ini
    unsigned int nMaxMemoryInMB = 0;
    bool bExcludeChildProcesses = true;

    const WCHAR* szIniFile = L"\\bootstrap.ini";
    const size_t nDirLen = wcslen(szIniDirectory);
    if (wcslen(szIniFile) + nDirLen < MAX_PATH)
    {
        WCHAR szBootstrapIni[MAX_PATH];
        wcscpy(szBootstrapIni, szIniDirectory);
        wcscpy(&szBootstrapIni[nDirLen], szIniFile);

        try
        {
            boost::property_tree::ptree pt;
            std::ifstream aFile(szBootstrapIni);
            boost::property_tree::ini_parser::read_ini(aFile, pt);
            nMaxMemoryInMB = pt.get("Win32.LimitMaximumMemoryInMB", nMaxMemoryInMB);
            bExcludeChildProcesses = pt.get("Win32.ExcludeChildProcessesFromLimit", bExcludeChildProcesses);
        }
        catch (...)
        {
            nMaxMemoryInMB = 0;
        }
    }

    // create a Windows JobObject with a memory limit
    HANDLE hJobObject = nullptr;
    if (nMaxMemoryInMB > 0)
    {
        JOBOBJECT_EXTENDED_LIMIT_INFORMATION aJobLimit;
        aJobLimit.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY;
        if (bExcludeChildProcesses)
            aJobLimit.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
        aJobLimit.JobMemoryLimit = nMaxMemoryInMB * 1024 * 1024;
        hJobObject = CreateJobObjectW(nullptr, nullptr);
        if (hJobObject != nullptr)
            SetInformationJobObject(hJobObject, JobObjectExtendedLimitInformation, &aJobLimit,
                                    sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
    }

    do
    {
        if (bFirst)
        {
            int argc = 0;
            LPWSTR* argv = GetCommandArgs(&argc);
            std::size_t n = 0;
            for (int i = 0; i < argc; ++i)
            {
                // check for wildCards in arguments- windows does not expand automatically
                if (HasWildCard(argv[i]))
                {
                    WIN32_FIND_DATAW aFindData;
                    HANDLE h = FindFirstFileW(argv[i], &aFindData);
                    if (h == INVALID_HANDLE_VALUE)
                    {
                        AddEscapedArg(argv[i], aEscapedArgs, n);
                    }
                    else
                    {
                        const int nPathSize = 32 * 1024;
                        wchar_t drive[nPathSize];
                        wchar_t dir[nPathSize];
                        wchar_t path[nPathSize];
                        _wsplitpath_s(argv[i], drive, nPathSize, dir, nPathSize, nullptr, 0,
                                      nullptr, 0);
                        _wmakepath_s(path, nPathSize, drive, dir, aFindData.cFileName, nullptr);
                        AddEscapedArg(path, aEscapedArgs, n);

                        while (FindNextFileW(h, &aFindData))
                        {
                            _wmakepath_s(path, nPathSize, drive, dir, aFindData.cFileName, nullptr);
                            AddEscapedArg(path, aEscapedArgs, n);
                        }
                        FindClose(h);
                    }
                }
                else
                {
                    AddEscapedArg(argv[i], aEscapedArgs, n);
                }
            }
            LocalFree(argv);
            n += MY_LENGTH(L" \"-env:OOO_CWD=2") + 4 * cwdLen + MY_LENGTH(L"\"") + 1;
            // 4 * cwdLen: each char preceded by backslash, each trailing
            // backslash doubled
            lpCommandLine = new WCHAR[n];
        }
        WCHAR* p = desktop_win32::commandLineAppend(lpCommandLine, aEscapedArgs[0].c_str(),
                                                    aEscapedArgs[0].length());
        for (size_t i = 1; i < aEscapedArgs.size(); ++i)
        {
            const std::wstring& rArg = aEscapedArgs[i];
            if (bFirst || EXITHELPER_NORMAL_RESTART == dwExitCode
                || wcsncmp(rArg.c_str(), MY_STRING(L"\"-env:")) == 0)
            {
                p = desktop_win32::commandLineAppend(p, MY_STRING(L" "));
                p = desktop_win32::commandLineAppend(p, rArg.c_str(), rArg.length());
            }
        }

        p = desktop_win32::commandLineAppend(p, MY_STRING(L" \"-env:OOO_CWD="));
        if (cwdLen == 0)
        {
            p = desktop_win32::commandLineAppend(p, MY_STRING(L"0"));
        }
        else
        {
            p = desktop_win32::commandLineAppend(p, MY_STRING(L"2"));
            p = desktop_win32::commandLineAppendEncoded(p, cwd);
        }
        desktop_win32::commandLineAppend(p, MY_STRING(L"\""));
        bFirst = false;

        WCHAR szParentProcessId[64]; // This is more than large enough for a 128 bit decimal value
        bool bHeadlessMode(false);

        {
            // Check command line arguments for "--headless" parameter. We only
            // set the environment variable "ATTACHED_PARENT_PROCESSID" for the headless
            // mode as self-destruction of the soffice.bin process can lead to
            // certain side-effects (log-off can result in data-loss, ".lock" is not deleted.
            // See 138244 for more information.
            int argc2;
            LPWSTR* argv2 = GetCommandArgs(&argc2);

            if (argc2 > 1)
            {
                int n;

                for (n = 1; n < argc2; n++)
                {
                    if (0 == wcsnicmp(argv2[n], L"-headless", 9)
                        || 0 == wcsnicmp(argv2[n], L"--headless", 10))
                    {
                        bHeadlessMode = true;
                    }
                }
            }

            LocalFree(argv2);
        }

        if (_ltow(static_cast<long>(GetCurrentProcessId()), szParentProcessId, 10) && bHeadlessMode)
            SetEnvironmentVariableW(L"ATTACHED_PARENT_PROCESSID", szParentProcessId);

        PROCESS_INFORMATION aProcessInfo;

        fSuccess = CreateProcessW(szTargetFileName, lpCommandLine, nullptr, nullptr, TRUE,
                                  bAllowConsole ? 0 : DETACHED_PROCESS, nullptr, szIniDirectory,
                                  &aStartupInfo, &aProcessInfo);

        if (fSuccess)
        {
            DWORD dwWaitResult;

            if (hJobObject)
                AssignProcessToJobObject(hJobObject, aProcessInfo.hProcess);

            do
            {
                // On Windows XP it seems as the desktop calls WaitForInputIdle after "OpenWith" so
                // we have to do so as if we were processing any messages

                dwWaitResult = MsgWaitForMultipleObjects(1, &aProcessInfo.hProcess, FALSE, INFINITE,
                                                         QS_ALLEVENTS);

                if (WAIT_OBJECT_0 + 1 == dwWaitResult)
                {
                    MSG msg;

                    PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE);
                }
            } while (WAIT_OBJECT_0 + 1 == dwWaitResult);

            dwExitCode = 0;
            GetExitCodeProcess(aProcessInfo.hProcess, &dwExitCode);

            CloseHandle(aProcessInfo.hProcess);
            CloseHandle(aProcessInfo.hThread);
        }
    } while (fSuccess
             && (EXITHELPER_CRASH_WITH_RESTART == dwExitCode
                 || EXITHELPER_NORMAL_RESTART == dwExitCode));

    if (hJobObject)
        CloseHandle(hJobObject);

    delete[] lpCommandLine;

    return fSuccess ? dwExitCode : -1;
}

int unopkgloader_impl(bool bAllowConsole)
{
    WCHAR        szTargetFileName[MAX_PATH];
    WCHAR        szIniDirectory[MAX_PATH];
    desktop_win32::extendLoaderEnvironment(szTargetFileName, szIniDirectory);

    STARTUPINFOW aStartupInfo{};
    aStartupInfo.cb = sizeof(aStartupInfo);
    GetStartupInfoW(&aStartupInfo);

    DWORD   dwExitCode = DWORD(-1);

    size_t iniDirLen = wcslen(szIniDirectory);
    WCHAR cwd[MAX_PATH];
    DWORD cwdLen = GetCurrentDirectoryW(MAX_PATH, cwd);
    if (cwdLen >= MAX_PATH) {
        cwdLen = 0;
    }
    WCHAR redirect[MAX_PATH];
    DWORD dummy;
    bool hasRedirect =
        tools::buildPath(
            redirect, szIniDirectory, szIniDirectory + iniDirLen,
            MY_STRING(L"redirect.ini")) != nullptr &&
            (GetBinaryTypeW(redirect, &dummy) || // cheaper check for file existence?
                GetLastError() != ERROR_FILE_NOT_FOUND);
    LPWSTR cl1 = GetCommandLineW();
    WCHAR* cl2 = new WCHAR[
        wcslen(cl1) +
            (hasRedirect
                ? (MY_LENGTH(L" \"-env:INIFILENAME=vnd.sun.star.pathname:") +
                    iniDirLen + MY_LENGTH(L"redirect.ini\""))
                : 0) +
            MY_LENGTH(L" \"-env:OOO_CWD=2") + 4 * cwdLen + MY_LENGTH(L"\"") + 1];
    // 4 * cwdLen: each char preceded by backslash, each trailing backslash
    // doubled
    WCHAR* p = desktop_win32::commandLineAppend(cl2, cl1);
    if (hasRedirect) {
        p = desktop_win32::commandLineAppend(
            p, MY_STRING(L" \"-env:INIFILENAME=vnd.sun.star.pathname:"));
        p = desktop_win32::commandLineAppend(p, szIniDirectory);
        p = desktop_win32::commandLineAppend(p, MY_STRING(L"redirect.ini\""));
    }
    p = desktop_win32::commandLineAppend(p, MY_STRING(L" \"-env:OOO_CWD="));
    if (cwdLen == 0) {
        p = desktop_win32::commandLineAppend(p, MY_STRING(L"0"));
    }
    else {
        p = desktop_win32::commandLineAppend(p, MY_STRING(L"2"));
        p = desktop_win32::commandLineAppendEncoded(p, cwd);
    }
    desktop_win32::commandLineAppend(p, MY_STRING(L"\""));

    PROCESS_INFORMATION aProcessInfo;

    bool fSuccess = CreateProcessW(
        szTargetFileName,
        cl2,
        nullptr,
        nullptr,
        TRUE,
        bAllowConsole ? 0 : DETACHED_PROCESS,
        nullptr,
        szIniDirectory,
        &aStartupInfo,
        &aProcessInfo);

    delete[] cl2;

    if (fSuccess)
    {
        DWORD   dwWaitResult;

        do
        {
            // On Windows XP it seems as the desktop calls WaitForInputIdle after "OpenWidth" so we have to do so
            // as if we were processing any messages

            dwWaitResult = MsgWaitForMultipleObjects(1, &aProcessInfo.hProcess, FALSE, INFINITE, QS_ALLEVENTS);

            if (WAIT_OBJECT_0 + 1 == dwWaitResult)
            {
                MSG msg;

                PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE);
            }
        } while (WAIT_OBJECT_0 + 1 == dwWaitResult);

        dwExitCode = 0;
        GetExitCodeProcess(aProcessInfo.hProcess, &dwExitCode);

        CloseHandle(aProcessInfo.hProcess);
        CloseHandle(aProcessInfo.hThread);
    }

    return dwExitCode;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */