summaryrefslogtreecommitdiff
path: root/desktop/source/app/updater.cxx
blob: d1cd07d76f1ea15d2f73b41c3d054b71e1c5d7f6 (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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
/* -*- 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

#ifdef _WIN32
#include <comphelper/windowsStart.hxx>
#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 <rtl/process.h>

#include <curl/curl.h>

#include <orcus/json_document_tree.hpp>
#include <orcus/config.hpp>
#include <orcus/pstring.hpp>
#include <comphelper/hash.hxx>

#include <com/sun/star/container/XNameAccess.hpp>

#include <officecfg/Setup.hxx>

#include <set>

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);
    }

    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);
}

#ifdef UNX
typedef char CharT;
#define tstrncpy std::strncpy
#elif _WIN32
typedef wchar_t CharT;
#define tstrncpy std::wcsncpy
#else
#error "Need an implementation"
#endif

void createStr(const OUString& rStr, CharT** pArgs, size_t i)
{
#ifdef UNX
    OString aStr = OUStringToOString(rStr, RTL_TEXTENCODING_UTF8);
#elif _WIN32
    OUString aStr = rStr;
#else
#error "Need an implementation"
#endif
    CharT* pStr = new CharT[aStr.getLength() + 1];
    tstrncpy(pStr, (CharT*)aStr.getStr(), aStr.getLength());
    pStr[aStr.getLength()] = '\0';
    pArgs[i] = pStr;
}

CharT** createCommandLine()
{
    OUString aInstallDir = Updater::getInstallationPath();

    size_t nCommandLineArgs = rtl_getAppCommandArgCount();
    size_t nArgs = 8 + nCommandLineArgs;
    CharT** pArgs = new CharT*[nArgs];
    {
        OUString aUpdaterName = OUString::fromUtf8(pUpdaterName);
        createStr(aUpdaterName, pArgs, 0);
    }
    {
        // directory with the patch log
        OUString aPatchDir = Updater::getPatchDirURL();
        rtl::Bootstrap::expandMacros(aPatchDir);
        OUString aTempDirPath = getPathFromURL(aPatchDir);
        Updater::log("Patch Dir: " + aTempDirPath);
        createStr(aTempDirPath, pArgs, 1);
    }
    {
        // the actual update directory
        Updater::log("Install Dir: " + aInstallDir);
        createStr(aInstallDir, pArgs, 2);
    }
    {
        // the temporary updated build
        Updater::log("Working Dir: " + aInstallDir);
        createStr(aInstallDir, pArgs, 3);
    }
    {
#ifdef UNX
        OUString aPID("0");
#elif _WIN32
        oslProcessInfo aInfo;
        aInfo.Size = sizeof(oslProcessInfo);
        osl_getProcessInfo(nullptr, osl_Process_IDENTIFIER, &aInfo);
        OUString aPID = OUString::number(aInfo.Ident);
#else
#error "Need an implementation"
#endif
        createStr(aPID, pArgs, 4);
    }
    {
        OUString aExeDir = Updater::getExecutableDirURL();
        OUString aSofficePath = getPathFromURL(aExeDir);
        Updater::log("soffice Path: " + aSofficePath);
        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);
    }

    // add the command line arguments from the soffice list
    for (size_t i = 0; i < nCommandLineArgs; ++i)
    {
        OUString aCommandLineArg;
        rtl_getAppCommandArg(i, &aCommandLineArg.pData);
        createStr(aCommandLineArg, pArgs, 7 + i);
    }

    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;
};

bool isUserWritable(const OUString& rFileURL)
{
    osl::FileStatus aStatus(osl_FileStatus_Mask_Attributes);
    osl::DirectoryItem aDirectoryItem;

    osl::FileBase::RC eRes = osl::DirectoryItem::get(rFileURL, aDirectoryItem);
    if (eRes != osl::FileBase::E_None)
    {
        Updater::log("Could not get the directory item for: " + rFileURL);
        return false;
    }

    osl::FileBase::RC eResult = aDirectoryItem.getFileStatus(aStatus);
    if (eResult != osl::FileBase::E_None)
    {
        Updater::log("Could not get the file status for: " + rFileURL);
        return false;
    }

    bool bReadOnly = (aStatus.getAttributes() & static_cast<sal_uInt64>(osl_File_Attribute_ReadOnly)) != 0;
    if (bReadOnly)
    {
        Updater::log("Update location as determined by: " + rFileURL + " is read-only.");
        return false;
    }

    return true;
}

}

bool update()
{
    utl::TempFile aTempDir(nullptr, true);
    OUString aTempDirURL = aTempDir.GetURL();
    CopyUpdaterToTempDir(Updater::getExecutableDirURL(), aTempDirURL);

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

    Updater::log("Calling the updater with parameters: ");
    CharT** pArgs = createCommandLine();

    bool bSuccess = true;
    const char* pUpdaterTestReplace = std::getenv("LIBO_UPDATER_TEST_REPLACE");
    if (!pUpdaterTestReplace)
    {
#if UNX
        OString aPath = OUStringToOString(aUpdaterPath, RTL_TEXTENCODING_UTF8);
        if (execv(aPath.getStr(), pArgs))
        {
            printf("execv failed with error %d %s\n",errno,strerror(errno));
            bSuccess = false;
        }
#elif _WIN32
        bSuccess = WinLaunchChild((wchar_t*)aUpdaterPath.getStr(), 8, pArgs);
#endif
    }
    else
    {
        SAL_WARN("desktop.updater", "Updater executable path: " << aUpdaterPath);
        for (size_t i = 0; i < 8 + rtl_getAppCommandArgCount(); ++i)
        {
            SAL_WARN("desktop.updater", pArgs[i]);
        }
        bSuccess = false;
    }

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

    return bSuccess;
}

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;
}



class invalid_update_info : public std::exception
{
};

class invalid_hash : public std::exception
{
    OString maMessage;
public:

    invalid_hash(const OUString& rExpectedHash, const OUString& rReceivedHash)
    {
        OUString aMsg = "Invalid hash found.\nExpected: " + rExpectedHash + ";\nReceived: " + rReceivedHash;
        maMessage = OUStringToOString(aMsg, RTL_TEXTENCODING_UTF8);
    }

    const char* what() const noexcept override
    {
        return maMessage.getStr();
    }
};

class invalid_size : public std::exception
{
    OString maMessage;
public:

    invalid_size(const size_t nExpectedSize, const size_t nReceivedSize)
    {
        OUString aMsg = "Invalid file size found.\nExpected: " + OUString::number(nExpectedSize) + ";\nReceived: " + OUString::number(nReceivedSize);
        maMessage = OUStringToOString(aMsg, RTL_TEXTENCODING_UTF8);
    }

    const char* what() const noexcept override
    {
        return maMessage.getStr();
    }
};

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.updater", "invalid update or language file entry");
        throw invalid_update_info();
    }

    if (rNode.child_count() < 4)
    {
        SAL_WARN("desktop.updater", "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.updater", "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.updater", "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;
}

struct WriteDataFile
{
    comphelper::Hash maHash;
    SvStream* mpStream;

    WriteDataFile(SvStream* pStream):
        maHash(comphelper::HashType::SHA512),
        mpStream(pStream)
    {
    }

    OUString getHash()
    {
        auto final_hash = maHash.finalize();
        std::stringstream aStrm;
        for (auto& i: final_hash)
        {
            aStrm << std::setw(2) << std::setfill('0') << std::hex << (int)i;
        }

        return toOUString(aStrm.str());
    }
};

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

  WriteDataFile* response = static_cast<WriteDataFile *>(userp);
  size_t real_size = size * nmemb;
  response->mpStream->WriteBytes(static_cast<char *>(ptr), real_size);
  response->maHash.update(static_cast<const unsigned char*>(ptr), real_size);
  return real_size;
}

std::string download_content(const OString& rURL, bool bFile, OUString& rHash)
{
    Updater::log("Download: " + rURL);
    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
    // only allow redirect to http:// and https://
    curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);

    std::string response_body;
    utl::TempFile aTempFile;
    WriteDataFile aFile(aTempFile.GetStream(StreamMode::WRITE));
    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 *>(&aFile));
    }

    // 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();
    }

    if (bFile)
        rHash = aFile.getHash();

    return response_body;
}

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);
    OUString aHash;
    std::string temp_file = download_content(aURL, true, aHash);
    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.");
        throw invalid_size(nFileSize, nSize);
    }

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

    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 aBrandBaseDir("${BRAND_BASE_DIR}");
    rtl::Bootstrap::expandMacros(aBrandBaseDir);
    bool bUserWritable = isUserWritable(aBrandBaseDir);
    if (!bUserWritable)
    {
        Updater::log("Can't update as the update location is not user writable");
        return;
    }

    OUString aDownloadCheckBaseURL = officecfg::Office::Update::Update::URL::get();
    static const char* pDownloadCheckBaseURLEnv = std::getenv("LIBO_UPDATER_URL");
    if (pDownloadCheckBaseURLEnv)
    {
        aDownloadCheckBaseURL = OUString::createFromAscii(pDownloadCheckBaseURLEnv);
    }

    OUString aProductName = utl::ConfigManager::getProductName();
    OUString aBuildID = Updater::getBuildID();
    OUString aBuildTarget = "${_OS}_${_ARCH}";
    rtl::Bootstrap::expandMacros(aBuildTarget);
    OUString aChannel = officecfg::Office::Update::Update::UpdateChannel::get();
    static const char* pUpdateChannelEnv = std::getenv("LIBO_UPDATER_CHANNEL");
    if (pUpdateChannelEnv)
    {
        aChannel = OUString::createFromAscii(pUpdateChannelEnv);
    }

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

    try
    {
        OUString aHash;
        std::string response_body = download_content(aURL, false, aHash);
        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);
                Updater::log("Server response: " + aUpdateInfo.aMessage);
            }
            else
            {
                css::uno::Sequence<OUString> aInstalledLanguages(officecfg::Setup::Office::InstalledLocales::get()->getElementNames());
                std::set<OUString> aInstalledLanguageSet(std::begin(aInstalledLanguages), std::end(aInstalledLanguages));
                download_file(aUpdateInfo.aUpdateFile.aURL, aUpdateInfo.aUpdateFile.nSize, aUpdateInfo.aUpdateFile.aHash, "update.mar");
                for (auto& lang_update : aUpdateInfo.aLanguageFiles)
                {
                    // only download the language packs for installed languages
                    if (aInstalledLanguageSet.find(lang_update.aLangCode) != aInstalledLanguageSet.end())
                    {
                        OUString aFileName = "update_" + lang_update.aLangCode + ".mar";
                        download_file(lang_update.aUpdateFile.aURL, lang_update.aUpdateFile.nSize, lang_update.aUpdateFile.aHash, aFileName);
                    }
                }
                OUString aSeeAlsoURL = aUpdateInfo.aSeeAlsoURL;
                std::shared_ptr< comphelper::ConfigurationChanges > batch(
                        comphelper::ConfigurationChanges::create());
                officecfg::Office::Update::Update::SeeAlso::set(aSeeAlsoURL, batch);
                batch->commit();
            }
        }
    }
    catch (const invalid_update_info&)
    {
        SAL_WARN("desktop.updater", "invalid update information");
        Updater::log(OString("warning: invalid update info"));
    }
    catch (const error_updater&)
    {
        SAL_WARN("desktop.updater", "error during the update check");
        Updater::log(OString("warning: error by the updater"));
    }
    catch (const invalid_size& e)
    {
        SAL_WARN("desktop.updater", e.what());
        Updater::log(OString("warning: invalid size"));
    }
    catch (const invalid_hash& e)
    {
        SAL_WARN("desktop.updater", e.what());
        Updater::log(OString("warning: invalid hash"));
    }
    catch (...)
    {
        SAL_WARN("desktop.updater", "unknown error during the update check");
        Updater::log(OString("warning: unknown exception"));
    }
}

OUString Updater::getUpdateInfoLog()
{
    OUString aUpdateInfoURL("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/patch/updating.log");
    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::getUpdateFileURL()
{
    return getPatchDirURL() + "update.mar";
}

OUString Updater::getInstallationPath()
{
    OUString aInstallDir( "$BRAND_BASE_DIR/");
    rtl::Bootstrap::expandMacros(aInstallDir);

    return getPathFromURL(aInstallDir);
}

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

    return aExeDir;
}

void Updater::log(const OUString& rMessage)
{
    SAL_INFO("updater", rMessage);
    OUString aUpdateLog = getUpdateInfoLog();
    SvFileStream aLog(aUpdateLog, StreamMode::STD_READWRITE);
    aLog.Seek(aLog.Tell() + aLog.remainingSize()); // make sure we are at the end
    aLog.WriteLine(OUStringToOString(rMessage, RTL_TEXTENCODING_UTF8));
}

void Updater::log(const OString& rMessage)
{
    SAL_INFO("updater", rMessage);
    OUString aUpdateLog = getUpdateInfoLog();
    SvFileStream aLog(aUpdateLog, StreamMode::STD_READWRITE);
    aLog.Seek(aLog.Tell() + aLog.remainingSize()); // make sure we are at the end
    aLog.WriteLine(rMessage);
}

void Updater::log(const char* pMessage)
{
    SAL_INFO("updater", pMessage);
    OUString aUpdateLog = getUpdateInfoLog();
    SvFileStream aLog(aUpdateLog, StreamMode::STD_READWRITE);
    aLog.Seek(aLog.Tell() + aLog.remainingSize()); // make sure we are at the end
    aLog.WriteCharPtr(pMessage);
}

OUString Updater::getBuildID()
{
    OUString aBuildID("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("version") ":buildid}");
    rtl::Bootstrap::expandMacros(aBuildID);

    return aBuildID;
}

void Updater::removeUpdateFiles()
{
    Updater::log("Removing: " + getUpdateFileURL());
    osl::File::remove(getUpdateFileURL());

    OUString aPatchDirURL = getPatchDirURL();
    osl::Directory aDir(aPatchDirURL);
    aDir.open();

    osl::FileBase::RC eRC;
    do
    {
        osl::DirectoryItem aItem;
        eRC = aDir.getNextItem(aItem);
        if (eRC == osl::FileBase::E_None)
        {
            osl::FileStatus aStatus(osl_FileStatus_Mask_All);
            if (aItem.getFileStatus(aStatus) != osl::FileBase::E_None)
                continue;

            if (!aStatus.isRegular())
                continue;

            OUString aURL = aStatus.getFileURL();
            if (!aURL.endsWith(".mar"))
                continue;

            Updater::log("Removing. " + aURL);
            osl::File::remove(aURL);
        }
    }
    while (eRC == osl::FileBase::E_None);
}

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