summaryrefslogtreecommitdiffstats
path: root/desktop/source/app/updater.cxx
blob: 388c45e7211ef012f840fdf2b7dff69e43b1a7e9 (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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/* -*- 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/.
 */

#include "updater.hxx"

#if UNX
#include <unistd.h>
#include <errno.h>

#endif

#include <fstream>
#include <config_folders.h>
#include <rtl/bootstrap.hxx>

#include <officecfg/Office/Update.hxx>

#include <rtl/ustring.hxx>
#include <unotools/tempfile.hxx>
#include <unotools/configmgr.hxx>
#include <osl/file.hxx>

#include <curl/curl.h>

#include <orcus/json_document_tree.hpp>
#include <orcus/config.hpp>
#include <orcus/pstring.hpp>

namespace {

class error_updater : public std::exception
{
};

#ifdef UNX
static const char kUserAgent[] = "LibreOffice UpdateChecker/1.0 (Linux)";
#else
static const char kUserAgent[] = "LibreOffice UpdateChecker/1.0 (unknown platform)";
#endif

#ifdef UNX
const char* pUpdaterName = "updater";
const char* pSofficeExeName = "soffice";
#elif defined(WNT)
const char* pUpdaterName = "updater.exe";
const char* pSofficeExeName = "soffice.exe";
#else
#error "Need implementation"
#endif

OUString normalizePath(const OUString& rPath)
{
    OUString aPath =  rPath.replaceAll("//", "/");

    // remove final /
    if (aPath.endsWith("/"))
    {
        aPath = aPath.copy(0, aPath.getLength() - 1);
    }

    while (aPath.indexOf("/..") != -1)
    {
        sal_Int32 nIndex = aPath.indexOf("/..");
        sal_Int32 i = nIndex - 1;
        for (; i > 0; --i)
        {
            if (aPath[i] == '/')
                break;
        }

        OUString aTempPath = aPath;
        aPath = aTempPath.copy(0, i) + aPath.copy(nIndex + 3);
    }

    SAL_DEBUG(aPath);

    return aPath;
}

void CopyFileToDir(const OUString& rTempDirURL, const OUString rFileName, const OUString& rOldDir)
{
    OUString aSourceURL = rOldDir + "/" + rFileName;
    OUString aDestURL = rTempDirURL + "/" + rFileName;

    osl::File::RC eError = osl::File::copy(aSourceURL, aDestURL);
    if (eError != osl::File::E_None)
    {
        SAL_WARN("desktop.updater", "could not copy the file to a temp directory: " << rFileName);
        throw std::exception();
    }
}

OUString getPathFromURL(const OUString& rURL)
{
    OUString aPath;
    osl::FileBase::getSystemPathFromFileURL(rURL, aPath);

    return normalizePath(aPath);
}

void CopyUpdaterToTempDir(const OUString& rInstallDirURL, const OUString& rTempDirURL)
{
    OUString aUpdaterName = OUString::fromUtf8(pUpdaterName);
    CopyFileToDir(rTempDirURL, aUpdaterName, rInstallDirURL);
}

void createStr(const char* pSrc, char** pArgs, size_t i)
{
    size_t nLength = std::strlen(pSrc);
    char* pFinalStr = new char[nLength + 1];
    std::strncpy(pFinalStr, pSrc, nLength);
    pFinalStr[nLength] = '\0';
    pArgs[i] = pFinalStr;
}

void createStr(const OUString& rStr, char** pArgs, size_t i)
{
    OString aStr = OUStringToOString(rStr, RTL_TEXTENCODING_UTF8);
    char* pStr = new char[aStr.getLength() + 1];
    std::strncpy(pStr, aStr.getStr(), aStr.getLength());
    pStr[aStr.getLength()] = '\0';
    pArgs[i] = pStr;
}

char** createCommandLine()
{
    OUString aLibExecDirURL( "$BRAND_BASE_DIR/" );
    rtl::Bootstrap::expandMacros(aLibExecDirURL);

    size_t nArgs = 8;
    char** pArgs = new char*[nArgs];
    {
        createStr(pUpdaterName, pArgs, 0);
    }
    {
        // directory with the patch log
        OUString aPatchDir = Updater::getPatchDirURL();
        rtl::Bootstrap::expandMacros(aPatchDir);
        OUString aTempDirPath = getPathFromURL(aPatchDir);
        createStr(aTempDirPath, pArgs, 1);
    }
    {
        // the actual update directory
        OUString aInstallPath = getPathFromURL(aLibExecDirURL);
        createStr(aInstallPath, pArgs, 2);
    }
    {
        // the temporary updated build
        OUString aUpdateDirURL = Updater::getUpdateDirURL();
        OUString aWorkingDir = getPathFromURL(aUpdateDirURL);
        createStr(aWorkingDir, pArgs, 3);
    }
    {
        const char* pPID = "/replace";
        createStr(pPID, pArgs, 4);
    }
    {
        OUString aExeDir = Updater::getExecutableDirURL();
        OUString aSofficePath = getPathFromURL(aExeDir);
        createStr(aSofficePath, pArgs, 5);
    }
    {
        // the executable to start after the successful update
        OUString aExeDir = Updater::getExecutableDirURL();
        OUString aSofficePathURL = aExeDir + OUString::fromUtf8(pSofficeExeName);
        OUString aSofficePath = getPathFromURL(aSofficePathURL);
        createStr(aSofficePath, pArgs, 6);
    }
    pArgs[nArgs - 1] = nullptr;

    return pArgs;
}

struct update_file
{
    OUString aURL;
    OUString aHash;
    size_t nSize;
};

struct language_file
{
    update_file aUpdateFile;
    OUString aLangCode;
};

struct update_info
{
    OUString aFromBuildID;
    OUString aSeeAlsoURL;
    OUString aMessage;

    update_file aUpdateFile;
    std::vector<language_file> aLanguageFiles;
};

}

void update()
{
    OUString aLibExecDirURL( "$BRAND_BASE_DIR/" LIBO_LIBEXEC_FOLDER );
    rtl::Bootstrap::expandMacros(aLibExecDirURL);

    utl::TempFile aTempDir(nullptr, true);
    OUString aTempDirURL = aTempDir.GetURL();
    CopyUpdaterToTempDir(aLibExecDirURL, aTempDirURL);

    OUString aTempDirPath = getPathFromURL(aTempDirURL);
    OString aPath = OUStringToOString(aTempDirPath + "/" + OUString::fromUtf8(pUpdaterName), RTL_TEXTENCODING_UTF8);

    char** pArgs = createCommandLine();

#if UNX
    if (execv(aPath.getStr(), pArgs))
    {
        printf("execv failed with error %d %s\n",errno,strerror(errno));
    }
#endif

    for (size_t i = 0; i < 8; ++i)
    {
        delete[] pArgs[i];
    }
    delete[] pArgs;
}

void CreateValidUpdateDir(const update_info& update_info)
{
    OUString aInstallDir("$BRAND_BASE_DIR");
    rtl::Bootstrap::expandMacros(aInstallDir);
    OUString aInstallPath = getPathFromURL(aInstallDir);
    OUString aUpdatedBuildDir("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/update_dir/");
    rtl::Bootstrap::expandMacros(aUpdatedBuildDir);
    OUString aWorkdirPath = getPathFromURL(aUpdatedBuildDir);

    OUString aPatchDirURL("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/patch/");
    rtl::Bootstrap::expandMacros(aPatchDirURL);
    OUString aPatchDir = getPathFromURL(aPatchDirURL);

    OUString aUpdaterPath = getPathFromURL(aInstallDir + "/program/" + OUString::fromUtf8(pUpdaterName));

    OUString aCommand = aUpdaterPath + " " + aPatchDir + " " + aInstallPath + " " + aWorkdirPath + " -1";

    OString aOCommand = OUStringToOString(aCommand, RTL_TEXTENCODING_UTF8);

    int nResult = std::system(aOCommand.getStr());
    if (nResult)
    {
        // TODO: remove the update directory
        SAL_WARN("desktop.updater", "failed to update");
    }
    else
    {
        OUString aUpdateInfoURL(aPatchDirURL + "/update.info");
        OUString aUpdateInfoPath = getPathFromURL(aUpdateInfoURL);
        SvFileStream aUpdateInfoFile(aUpdateInfoPath, StreamMode::WRITE | StreamMode::TRUNC);
        aUpdateInfoFile.WriteCharPtr("[UpdateInfo]\nOldBuildId=");
        aUpdateInfoFile.WriteByteStringLine(update_info.aFromBuildID, RTL_TEXTENCODING_UTF8);
    }
}

namespace {

// Callback to get the response data from server.
static size_t WriteCallback(void *ptr, size_t size,
                            size_t nmemb, void *userp)
{
  if (!userp)
    return 0;

  std::string* response = static_cast<std::string *>(userp);
  size_t real_size = size * nmemb;
  response->append(static_cast<char *>(ptr), real_size);
  return real_size;
}

// Callback to get the response data from server to a file.
static size_t WriteCallbackFile(void *ptr, size_t size,
                            size_t nmemb, void *userp)
{
  if (!userp)
    return 0;

  SvStream* response = static_cast<SvStream *>(userp);
  size_t real_size = size * nmemb;
  response->WriteBytes(static_cast<char *>(ptr), real_size);
  return real_size;
}


class invalid_update_info : public std::exception
{
};

OUString toOUString(const std::string& rStr)
{
    return OUString::fromUtf8(rStr.c_str());
}

update_file parse_update_file(const orcus::json::detail::node& rNode)
{
    if (rNode.type() != orcus::json::detail::node_t::object)
    {
        SAL_WARN("desktop.update", "invalid update or language file entry");
        throw invalid_update_info();
    }

    if (rNode.child_count() != 4)
    {
        SAL_WARN("desktop.update", "invalid update or language file entry");
        throw invalid_update_info();
    }

    orcus::json::detail::node aURLNode = rNode.child("url");
    orcus::json::detail::node aHashNode = rNode.child("hash");
    orcus::json::detail::node aHashTypeNode = rNode.child("hash_function");
    orcus::json::detail::node aSizeNode = rNode.child("size");

    if (aHashTypeNode.string_value() != "sha512")
    {
        SAL_WARN("desktop.update", "invalid hash type");
        throw invalid_update_info();
    }

    update_file aUpdateFile;
    aUpdateFile.aURL = toOUString(aURLNode.string_value().str());

    if (aUpdateFile.aURL.isEmpty())
        throw invalid_update_info();

    aUpdateFile.aHash = toOUString(aHashNode.string_value().str());
    aUpdateFile.nSize = static_cast<sal_uInt32>(aSizeNode.numeric_value());
    return aUpdateFile;
}

update_info parse_response(const std::string& rResponse)
{
    orcus::json_document_tree aJsonDoc;
    orcus::json_config aConfig;
    aJsonDoc.load(rResponse, aConfig);

    auto aDocumentRoot = aJsonDoc.get_document_root();
    if (aDocumentRoot.type() != orcus::json_node_t::object)
    {
        SAL_WARN("desktop.Update", "invalid root entries: " << rResponse);
        throw invalid_update_info();
    }

    auto aRootKeys = aDocumentRoot.keys();
    if (std::find(aRootKeys.begin(), aRootKeys.end(), "error") != aRootKeys.end())
    {
        throw invalid_update_info();
    }
    else if (std::find(aRootKeys.begin(), aRootKeys.end(), "response") != aRootKeys.end())
    {
        update_info aUpdateInfo;
        auto aMsgNode = aDocumentRoot.child("response");
        aUpdateInfo.aMessage = toOUString(aMsgNode.string_value().str());
        return aUpdateInfo;
    }

    orcus::json::detail::node aFromNode = aDocumentRoot.child("from");
    if (aFromNode.type() != orcus::json_node_t::string)
    {
        throw invalid_update_info();
    }

    orcus::json::detail::node aSeeAlsoNode = aDocumentRoot.child("see also");
    if (aSeeAlsoNode.type() != orcus::json_node_t::string)
    {
        throw invalid_update_info();
    }

    orcus::json::detail::node aUpdateNode = aDocumentRoot.child("update");
    if (aUpdateNode.type() != orcus::json_node_t::object)
    {
        throw invalid_update_info();
    }

    orcus::json::detail::node aLanguageNode = aDocumentRoot.child("languages");
    if (aUpdateNode.type() != orcus::json_node_t::object)
    {
        throw invalid_update_info();
    }

    update_info aUpdateInfo;
    aUpdateInfo.aFromBuildID = toOUString(aFromNode.string_value().str());
    aUpdateInfo.aSeeAlsoURL = toOUString(aSeeAlsoNode.string_value().str());

    aUpdateInfo.aUpdateFile = parse_update_file(aUpdateNode);

    std::vector<orcus::pstring> aLanguages = aLanguageNode.keys();
    for (auto itr = aLanguages.begin(), itrEnd = aLanguages.end(); itr != itrEnd; ++itr)
    {
        language_file aLanguageFile;
        auto aLangEntry = aLanguageNode.child(*itr);
        aLanguageFile.aLangCode = toOUString(itr->str());
        aLanguageFile.aUpdateFile = parse_update_file(aLangEntry);
        aUpdateInfo.aLanguageFiles.push_back(aLanguageFile);
    }

    return aUpdateInfo;
}

std::string download_content(const OString& rURL, bool bFile)
{
    CURL* curl = curl_easy_init();

    if (!curl)
        return std::string();

    curl_easy_setopt(curl, CURLOPT_URL, rURL.getStr());
    curl_easy_setopt(curl, CURLOPT_USERAGENT, kUserAgent);
    bool bUseProxy = false;
    if (bUseProxy)
    {
        /*
        curl_easy_setopt(curl, CURLOPT_PROXY, proxy.c_str());
        curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_user_pwd.c_str());
        */
    }

    char buf[] = "Expect:";
    curl_slist* headerlist = nullptr;
    headerlist = curl_slist_append(headerlist, buf);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); // follow redirects

    std::string response_body;
    utl::TempFile aTempFile;
    if (!bFile)
    {
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA,
                static_cast<void *>(&response_body));

        aTempFile.EnableKillingFile(true);
    }
    else
    {
        OUString aTempFileURL = aTempFile.GetURL();
        OString aTempFileURLOString = OUStringToOString(aTempFileURL, RTL_TEXTENCODING_UTF8);
        response_body.append(aTempFileURLOString.getStr(), aTempFileURLOString.getLength());

        aTempFile.EnableKillingFile(false);

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallbackFile);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA,
                static_cast<void *>(aTempFile.GetStream(StreamMode::WRITE)));
    }

    // Fail if 400+ is returned from the web server.
    curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

    CURLcode cc = curl_easy_perform(curl);
    long http_code = 0;
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    if (http_code != 200)
    {
        SAL_WARN("desktop.updater", "download did not succeed. Error code: " << http_code);
        throw error_updater();
    }

    if (cc != CURLE_OK)
    {
        SAL_WARN("desktop.updater", "curl error: " << cc);
        throw error_updater();
    }

    return response_body;
}

OUString generateHash(const OUString& /*rURL*/)
{
    return OUString();
}

void handle_file_error(osl::FileBase::RC eError)
{
    switch (eError)
    {
        case osl::FileBase::E_None:
        break;
        default:
            SAL_WARN("desktop.updater", "file error code: " << eError);
            throw error_updater();
    }
}

void download_file(const OUString& rURL, size_t nFileSize, const OUString& rHash, const OUString& aFileName)
{
    OString aURL = OUStringToOString(rURL, RTL_TEXTENCODING_UTF8);
    std::string temp_file = download_content(aURL, true);
    if (temp_file.empty())
        throw error_updater();

    OUString aTempFile = OUString::fromUtf8(temp_file.c_str());
    osl::File aDownloadedFile(aTempFile);
    osl::FileBase::RC eError = aDownloadedFile.open(1);
    handle_file_error(eError);

    sal_uInt64 nSize = 0;
    eError = aDownloadedFile.getSize(nSize);
    handle_file_error(eError);
    if (nSize != nFileSize)
    {
        SAL_WARN("desktop.updater", "File sizes don't match. File might be corrupted.");
    }

    OUString aHash = generateHash(aTempFile);
    if (aHash != rHash)
    {
        SAL_WARN("desktop.updater", "File hash don't match. File might be corrupted.");
    }

    OUString aPatchDirURL("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/patch/");
    rtl::Bootstrap::expandMacros(aPatchDirURL);
    osl::Directory::create(aPatchDirURL);

    OUString aDestFile = aPatchDirURL + aFileName;
    eError = osl::File::move(aTempFile, aDestFile);
    handle_file_error(eError);
}

}

void update_checker()
{
    OUString aDownloadCheckBaseURL = officecfg::Office::Update::Update::URL::get();

    OUString aProductName = utl::ConfigManager::getProductName();
    OUString aBuildID("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("version") ":buildid}");
    rtl::Bootstrap::expandMacros(aBuildID);
    OUString aBuildTarget = "${_OS}_${_ARCH}";
    rtl::Bootstrap::expandMacros(aBuildTarget);
    OUString aChannel = officecfg::Office::Update::Update::UpdateChannel::get();

    OUString aDownloadCheckURL = aDownloadCheckBaseURL + "update/check/1/" + aProductName +
        "/" + aBuildID + "/" + aBuildTarget + "/" + "/" + aChannel;
    OString aURL = OUStringToOString(aDownloadCheckURL, RTL_TEXTENCODING_UTF8);


    try
    {
        std::string response_body = download_content(aURL, false);
        if (!response_body.empty())
        {
            update_info aUpdateInfo = parse_response(response_body);
            if (aUpdateInfo.aUpdateFile.aURL.isEmpty())
            {
                // No update currently available
                // add entry to updating.log with the message
                SAL_WARN("desktop.updater", "Message received from the updater: " << aUpdateInfo.aMessage);
            }
            else
            {
                download_file(aUpdateInfo.aUpdateFile.aURL, aUpdateInfo.aUpdateFile.nSize, aUpdateInfo.aUpdateFile.aHash, "update.mar");
                CreateValidUpdateDir(aUpdateInfo);
            }
        }
    }
    catch (const invalid_update_info&)
    {
        SAL_WARN("desktop.updater", "invalid update information");
    }
    catch (const error_updater&)
    {
        SAL_WARN("desktop.updater", "error during the update check");
    }
    catch (...)
    {
        SAL_WARN("desktop.updater", "unknown error during the update check");
    }
}

OUString Updater::getUpdateInfoURL()
{
    OUString aUpdateInfoURL("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/patch/update.info");
    rtl::Bootstrap::expandMacros(aUpdateInfoURL);

    return aUpdateInfoURL;
}

OUString Updater::getPatchDirURL()
{
    OUString aPatchDirURL("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/patch/");
    rtl::Bootstrap::expandMacros(aPatchDirURL);

    return aPatchDirURL;
}

OUString Updater::getUpdateDirURL()
{
    OUString aUpdateDirURL("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/update_dir/");
    rtl::Bootstrap::expandMacros(aUpdateDirURL);

    return aUpdateDirURL;
}

OUString Updater::getExecutableDirURL()
{
    OUString aExeDir( "$BRAND_BASE_DIR/" LIBO_BIN_FOLDER "/" );
    rtl::Bootstrap::expandMacros(aExeDir);

    return aExeDir;
}

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