-
Notifications
You must be signed in to change notification settings - Fork 982
Expand file tree
/
Copy pathKit.cpp
More file actions
4470 lines (3830 loc) · 153 KB
/
Kit.cpp
File metadata and controls
4470 lines (3830 loc) · 153 KB
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
* Copyright the Collabora Online contributors.
*
* SPDX-License-Identifier: MPL-2.0
*
* 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/.
*/
/*
* The main entry point for the LibreOfficeKit process serving
* a document editing session.
*/
#include <config.h>
#include "Kit.hpp"
#include <common/Anonymizer.hpp>
#include <wsd/TileDesc.hpp>
#include <csignal>
#include <limits>
#if !MOBILEAPP
#include <dlfcn.h>
#endif
#ifdef __linux__
#include <ftw.h>
#include <sys/vfs.h>
#include <linux/magic.h>
#include <sys/sysmacros.h>
#endif
#if HAVE_LIBCAP
#include <sys/capability.h>
#endif
#if defined(__FreeBSD__) || defined(MACOS) || (defined(__linux__) && !defined(__GLIBC__))
#include <ftw.h>
// FTW_CONTINUE, FTW_STOP, FTW_SKIP_SUBTREE, FTW_ACTIONRETVAL are glibc extensions
#define FTW_CONTINUE 0
#define FTW_STOP (-1)
#define FTW_SKIP_SUBTREE 0
#define FTW_ACTIONRETVAL 0
#endif
#ifndef _WIN32
#include <unistd.h>
#include <utime.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sysexits.h>
#endif
#include <atomic>
#include <cassert>
#include <chrono>
#include <climits>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#define LOK_USE_UNSTABLE_API
#include <LibreOfficeKit/LibreOfficeKitInit.h>
#include <Poco/File.h>
#include <Poco/Exception.h>
#include <Poco/URI.h>
#include <ChildSession.hpp>
#include <Common.hpp>
#include <MobileApp.hpp>
#include <common/FileUtil.hpp>
#include <common/JsonUtil.hpp>
#include <KitHelper.hpp>
#include <Protocol.hpp>
#include <common/Log.hpp>
#include <Png.hpp>
#include <Rectangle.hpp>
#include <Unit.hpp>
#include <UserMessages.hpp>
#include <common/Util.hpp>
#include <common/JsonUtil.hpp>
#include <RenderTiles.hpp>
#include <KitWebSocket.hpp>
#include <common/ConfigUtil.hpp>
#include <common/Uri.hpp>
#if !MOBILEAPP
#include <common/JailUtil.hpp>
#include <common/security.h>
#include <common/Seccomp.hpp>
#include <common/SigUtil.hpp>
#include <common/Syscall.hpp>
#include <common/TraceEvent.hpp>
#include <common/Watchdog.hpp>
#include <BgSaveWatchDog.hpp>
#endif
#if MOBILEAPP
#include <COOLWSD.hpp>
#ifndef IOS
#include <SetupKitEnvironment.hpp>
#endif
#endif
#ifdef QTAPP
#include "SetupKitEnvironment.hpp"
#include "DocumentBroker.hpp"
#include <future>
#endif
#ifdef IOS
#include <ios.h>
#include <DocumentBroker.hpp>
#elif defined(MACOS) && MOBILEAPP
#include <macos.h>
#include <DocumentBroker.hpp>
#endif
#ifdef _WIN32
#include "windows.hpp"
#endif
using Poco::Exception;
using Poco::File;
using Poco::JSON::Object;
using Poco::JSON::Parser;
#ifndef BUILDING_TESTS
using Poco::Path;
#endif
using namespace COOLProtocol;
using JsonUtil::makePropertyValue;
extern "C" { void dump_kit_state(void); /* easy for gdb */ }
#if MOBILEAPP
extern std::map<std::string, std::shared_ptr<DocumentBroker>> DocBrokers;
extern std::mutex DocBrokersMutex;
#endif
#if !MOBILEAPP
// A Kit process hosts only a single document in its lifetime.
class Document;
static Document *singletonDocument = nullptr;
static std::unique_ptr<Util::ThreadCounter> threadCounter;
static std::unique_ptr<Util::FDCounter> fdCounter;
int getCurrentThreadCount()
{
if (threadCounter)
return threadCounter->count();
return -1;
}
#endif
LibreOfficeKit* loKitPtr = nullptr;
static bool EnableWebsocketURP = false;
#if !MOBILEAPP
static int URPStartCount = 0;
#endif
bool isURPEnabled() { return EnableWebsocketURP; }
/// When chroot is enabled, this is blank as all
/// the paths inside the jail, relative to it's jail.
/// E.g. /tmp/user/docs/...
/// However, without chroot, the jail path is
/// absolute in the system root.
/// I.e. ChildRoot/JailId/tmp/user/docs/...
/// We need to know where the jail really is
/// because WSD doesn't know if chroot will succeed
/// or fail, but it assumes the document path to
/// be relative to the root of the jail (i.e. chroot
/// expected to succeed). If it fails, or when caps
/// are disabled, file paths would be relative to the
/// system root, not the jail.
static std::string JailRoot;
#if !MOBILEAPP
static int URPtoLoFDs[2] { -1, -1 };
static int URPfromLoFDs[2] { -1, -1 };
#endif
// Abnormally we get LOK events from another thread, which must be
// push safely into our main poll loop to process to keep all
// socket buffer & event processing in a single, thread.
static bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char* p, void* data);
[[maybe_unused]]
static LokHookFunction2* initFunction = nullptr;
#if !MOBILEAPP
BackgroundSaveWatchdog::BackgroundSaveWatchdog(unsigned mobileAppDocId, int savingTid)
: _saveCompleted(false)
, _watchdogThread(
// mobileAppDocId is on the stack, so capture it by value.
[mobileAppDocId, savingTid, this]()
{
Util::setThreadName("kitbgsv_" + Util::encodeId(mobileAppDocId, 3) + "_wdg");
const auto timeout = std::chrono::seconds(
ConfigUtil::getInt("per_document.bgsave_timeout_secs", 120));
const auto saveStart = std::chrono::steady_clock::now();
std::unique_lock<std::mutex> lock(_watchdogMutex);
LOG_TRC("Starting bgsave watchdog with " << timeout << " timeout");
if (_watchdogCV.wait_for(lock, timeout,
[this]() { return _saveCompleted.load(); }))
{
// Done!
LOG_TRC("BgSave finished in time");
}
else
{
auto saveDuration = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - saveStart);
// Failed!
LOG_WRN("BgSave timed out and will self-destroy process " << getpid() <<
" (config timeout: " << timeout << ", real timeout: " << saveDuration << ")");
Log::shutdown(); // Flush logs.
// this attempts to get the saving-thread to generate a backtrace
Util::killThreadById(savingTid, SIGABRT);
// It is possible that this process will not exit cleanly after
// handling SIGABRT, so instead after some time fall-back to this:
// raise(3) will exit the current thread, not the process.
// coverity[sleep : SUPPRESS] - don't report sleep with lock held
sleep(30); // long enough for a trace ?
std::cerr << "BgSave failed to terminate after SIGABRT - will hard self-destroy process " << getpid() << std::endl;
::kill(0, SIGKILL); // kill(2) is trapped by seccomp.
}
})
{
}
BackgroundSaveWatchdog::~BackgroundSaveWatchdog()
{
if (!_saveCompleted)
{
LOG_WRN("BgSave watchdog for " << getpid()
<< " is destroyed while save hadn't yet completed");
complete(); // Clean up.
}
}
void BackgroundSaveWatchdog::complete()
{
_saveCompleted = true;
_watchdogCV.notify_all();
if (_watchdogThread.joinable())
_watchdogThread.join();
}
void Document::shutdownBackgroundWatchdog()
{
if (BackgroundSaveWatchdog::Instance)
BackgroundSaveWatchdog::Instance->complete();
}
#endif // !MOBILEAPP
namespace
{
// for later consistency checking.
static std::string UserDirPath;
static std::string InstDirPath;
std::string pathFromFileURL(const std::string &uri)
{
const std::string decoded = Uri::decode(uri);
if (decoded.rfind("file://", 0) != 0)
{
LOG_ERR("Asked to load a very unusual file path: '" << uri << "' -> '" << decoded << "'");
return std::string();
}
return decoded.substr(7);
}
[[maybe_unused]]
void consistencyCheckFileExists(const std::string &uri)
{
std::string path = pathFromFileURL(uri);
if (path.empty())
return;
FileUtil::Stat stat(path);
if (!stat.good() && stat.isFile())
LOG_ERR("Fatal system error: created file passed into document doesn't exist: '" << path << "'");
else
LOG_TRC("File path '" << path << "' exists of length " << stat.size());
consistencyCheckJail();
}
#if !defined(BUILDING_TESTS) && !MOBILEAPP
enum class LinkOrCopyType: std::uint8_t
{
All,
LO
};
LinkOrCopyType linkOrCopyType;
std::string sourceForLinkOrCopy;
Poco::Path destinationForLinkOrCopy;
bool forceInitialCopy; // some stackable file-systems have very slow first hard link creation
std::string linkableForLinkOrCopy; // Place to stash copies that we can hard-link from
std::chrono::time_point<std::chrono::steady_clock> linkOrCopyStartTime;
bool linkOrCopyVerboseLogging = false;
unsigned linkOrCopyFileCount = 0; // Track to help quantify the link-or-copy performance.
constexpr unsigned SlowLinkOrCopyLimitInSecs = 2; // After this many seconds, start spamming the logs.
bool detectSlowStackingFileSystem([[maybe_unused]] const std::string& directory)
{
#ifdef __linux__
#ifndef OVERLAYFS_SUPER_MAGIC
// From linux/magic.h.
#define OVERLAYFS_SUPER_MAGIC 0x794c7630
#endif
struct statfs fs;
if (::statfs(directory.c_str(), &fs) != 0)
{
LOG_SYS("statfs failed on '" << directory << "'");
return false;
}
switch (fs.f_type) {
// case FUSE_SUPER_MAGIC: ?
case OVERLAYFS_SUPER_MAGIC:
return true;
default:
return false;
}
#else
return false;
#endif
}
/// Returns the LinkOrCopyType as a human-readable string (for logging).
std::string linkOrCopyTypeString(LinkOrCopyType type)
{
switch (type)
{
case LinkOrCopyType::LO:
return "LibreOffice";
case LinkOrCopyType::All:
return "all";
default:
assert(!"Unknown LinkOrCopyType.");
return "unknown";
}
}
bool shouldCopyDir(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::LO:
return
strcmp(path, "program/wizards") != 0 &&
strcmp(path, "sdk") != 0 &&
strcmp(path, "debugsource") != 0 &&
strcmp(path, "share/basic") != 0 &&
strncmp(path, "share/extensions/dict-", // preloaded
sizeof("share/extensions/dict")) != 0 &&
strcmp(path, "share/Scripts/java") != 0 &&
strcmp(path, "share/Scripts/javascript") != 0 &&
strcmp(path, "share/config/wizard") != 0 &&
strcmp(path, "readmes") != 0 &&
strcmp(path, "help") != 0;
default: // LinkOrCopyType::All
return true;
}
}
bool shouldLinkFile(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::LO:
{
if (strstr(path, "LICENSE") || strstr(path, "EULA") || strstr(path, "CREDITS")
|| strstr(path, "NOTICE"))
return false;
const char* dot = strrchr(path, '.');
if (!dot)
return true;
if (!strcmp(dot, ".dbg"))
return false;
if (!strcmp(dot, ".so"))
{
// NSS is problematic ...
if (strstr(path, "libnspr4") || strstr(path, "libplds4") ||
strstr(path, "libplc4") || strstr(path, "libnss3") ||
strstr(path, "libnssckbi") || strstr(path, "libnsutil3") ||
strstr(path, "libssl3") || strstr(path, "libsoftokn3") ||
strstr(path, "libsqlite3") || strstr(path, "libfreeblpriv3"))
return true;
// As is Python ...
if (strstr(path, "python-core"))
return true;
// otherwise drop the rest of the code.
return false;
}
const char *vers;
if ((vers = strstr(path, ".so."))) // .so.[digit]+
{
for(int i = sizeof (".so."); vers[i] != '\0'; ++i)
if (!isdigit(vers[i]) && vers[i] != '.')
return true;
return false;
}
return true;
}
default: // LinkOrCopyType::All
return true;
}
}
void linkOrCopyFile(const char* fpath, const std::string& newPath)
{
++linkOrCopyFileCount;
if (linkOrCopyVerboseLogging)
LOG_INF("Linking file \"" << fpath << "\" to \"" << newPath << '"');
if (!forceInitialCopy)
{
// first try a simple hard-link
if (link(fpath, newPath.c_str()) == 0)
return;
}
// else always copy before linking to linkable/
// incrementally build our 'linkable/' copy nearby
static bool canChown = true; // only if we can get permissions right
if ((forceInitialCopy || errno == EXDEV) && canChown)
{
// then copy somewhere closer and hard link from there
if (!forceInitialCopy)
LOG_TRC("link(\"" << fpath << "\", \"" << newPath << "\") failed: " << strerror(errno)
<< ". Will try to link template.");
std::string linkableCopy = linkableForLinkOrCopy + fpath;
if (::link(linkableCopy.c_str(), newPath.c_str()) == 0)
return;
if (errno == ENOENT)
{
File(Path(linkableCopy).parent()).createDirectories();
if (!FileUtil::copy(fpath, linkableCopy, /*log=*/false, /*throw_on_error=*/false))
LOG_TRC("Failed to create linkable copy [" << fpath << "] to [" << linkableCopy.c_str() << "]");
else {
// Match system permissions, so a file we can write is not shared across jails.
struct stat ownerInfo;
if (::stat(fpath, &ownerInfo) != 0 ||
::chown(linkableCopy.c_str(), ownerInfo.st_uid, ownerInfo.st_gid) != 0)
{
LOG_ERR("Failed to stat or chown " << ownerInfo.st_uid << ":" << ownerInfo.st_gid <<
" " << linkableCopy << ": " << strerror(errno) << " missing cap_chown?, disabling linkable");
unlink(linkableCopy.c_str());
canChown = false;
}
else if (::link(linkableCopy.c_str(), newPath.c_str()) == 0)
return;
}
}
LOG_TRC("link(\"" << linkableCopy << "\", \"" << newPath << "\") failed: " << strerror(errno)
<< ". Cannot create linkable copy.");
}
static bool warned = false;
if (!warned)
{
LOG_ERR("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno)
<< ". Very slow copying path triggered.");
warned = true;
} else
LOG_TRC("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno)
<< ". Will copy.");
if (!FileUtil::copy(fpath, newPath, /*log=*/false, /*throw_on_error=*/false))
{
LOG_FTL("Failed to copy or link [" << fpath << "] to [" << newPath << "]. Exiting.");
Util::forcedExit(EX_SOFTWARE);
}
}
int linkOrCopyFunction(const char *fpath,
const struct stat* sb,
int typeflag,
struct FTW* /*ftwbuf*/)
{
if (strcmp(fpath, sourceForLinkOrCopy.c_str()) == 0)
{
LOG_TRC("nftw: Skipping redundant path: " << fpath);
return FTW_CONTINUE;
}
if (!linkOrCopyVerboseLogging)
{
const auto durationInSecs = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - linkOrCopyStartTime);
if (durationInSecs.count() > SlowLinkOrCopyLimitInSecs)
{
LOG_WRN("Linking/copying files from "
<< sourceForLinkOrCopy << " to " << destinationForLinkOrCopy.toString()
<< " is taking too much time. Enabling verbose link/copy logging.");
linkOrCopyVerboseLogging = true;
}
}
assert(fpath[sourceForLinkOrCopy.size()] == '/');
const char* relativeOldPath = fpath + sourceForLinkOrCopy.size() + 1;
const Poco::Path newPath(destinationForLinkOrCopy, Poco::Path(relativeOldPath));
switch (typeflag)
{
case FTW_F:
case FTW_SLN:
Poco::File(newPath.parent()).createDirectories();
if (shouldLinkFile(relativeOldPath))
linkOrCopyFile(fpath, newPath.toString());
break;
case FTW_D:
{
struct stat st;
if (stat(fpath, &st) == -1)
{
LOG_SYS("nftw: stat(\"" << fpath << "\") failed");
return FTW_STOP;
}
if (!shouldCopyDir(relativeOldPath))
{
LOG_TRC("nftw: Skipping redundant path: " << relativeOldPath);
return FTW_SKIP_SUBTREE;
}
Poco::File(newPath).createDirectories();
struct utimbuf ut;
ut.actime = st.st_atime;
ut.modtime = st.st_mtime;
if (utime(newPath.toString().c_str(), &ut) == -1)
{
LOG_SYS("nftw: utime(\"" << newPath.toString() << "\") failed");
return FTW_STOP;
}
}
break;
case FTW_SL:
{
const std::size_t size = sb->st_size;
std::vector<char> target(size + 1);
char* target_data = target.data();
const ssize_t written = readlink(fpath, target_data, size);
if (written <= 0 || static_cast<std::size_t>(written) > size)
{
LOG_SYS("nftw: readlink(\"" << fpath << "\") failed");
Util::forcedExit(EX_SOFTWARE);
}
target_data[written] = '\0';
Poco::File(newPath.parent()).createDirectories();
if (symlink(target_data, newPath.toString().c_str()) == -1)
{
LOG_SYS("nftw: symlink(\"" << target_data << "\", \"" << newPath.toString()
<< "\") failed");
return FTW_STOP;
}
}
break;
case FTW_DNR:
LOG_ERR("nftw: Cannot read directory '" << fpath << '\'');
return FTW_STOP;
case FTW_NS:
LOG_ERR("nftw: stat failed for '" << fpath << '\'');
return FTW_STOP;
default:
LOG_FTL("nftw: unexpected typeflag: '" << typeflag);
assert(!"nftw: unexpected typeflag.");
break;
}
return FTW_CONTINUE;
}
void linkOrCopy(const std::string& source, const Poco::Path& destination, const std::string& linkable,
LinkOrCopyType type)
{
std::string resolved = FileUtil::realpath(source);
if (resolved != source)
{
LOG_DBG("linkOrCopy: Using real path [" << resolved << "] instead of original link ["
<< source << "].");
}
LOG_INF("linkOrCopy " << linkOrCopyTypeString(type) << " from [" << resolved << "] to ["
<< destination.toString() << "].");
linkOrCopyType = type;
sourceForLinkOrCopy = resolved;
if (sourceForLinkOrCopy.back() == '/')
sourceForLinkOrCopy.pop_back();
destinationForLinkOrCopy = destination;
linkableForLinkOrCopy = linkable;
linkOrCopyFileCount = 0;
linkOrCopyStartTime = std::chrono::steady_clock::now();
forceInitialCopy = detectSlowStackingFileSystem(destination.toString());
if (nftw(resolved.c_str(), linkOrCopyFunction, 10, FTW_ACTIONRETVAL|FTW_PHYS) == -1)
{
LOG_ERR("linkOrCopy: nftw() failed for '" << resolved << '\'');
}
if (linkOrCopyVerboseLogging)
{
linkOrCopyVerboseLogging = false;
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - linkOrCopyStartTime).count();
const double seconds = (ms + 1) / 1000.; // At least 1ms to avoid div-by-zero.
const auto rate = linkOrCopyFileCount / seconds;
LOG_INF("Linking/Copying of " << linkOrCopyFileCount << " files from " << resolved
<< " to " << destinationForLinkOrCopy.toString()
<< " finished in " << seconds << " seconds, or " << rate
<< " files / second.");
}
}
#if CODE_COVERAGE
std::string childRootForGCDAFiles;
std::string sourceForGCDAFiles;
std::string destForGCDAFiles;
int linkGCDAFilesFunction(const char* fpath, const struct stat*, int typeflag,
struct FTW* /*ftwbuf*/)
{
const std::string path = fpath;
if (path == sourceForGCDAFiles)
{
LOG_TRC("nftw: Skipping redundant path: " << fpath);
return FTW_CONTINUE;
}
if (path.starts_with(childRootForGCDAFiles))
{
LOG_TRC("nftw: Skipping childRoot subtree: " << fpath);
return FTW_SKIP_SUBTREE;
}
assert(path.size() >= sourceForGCDAFiles.size());
assert(fpath[sourceForGCDAFiles.size()] == '/');
const char* relativeOldPath = fpath + sourceForGCDAFiles.size() + 1;
const Poco::Path newPath(destForGCDAFiles, Poco::Path(relativeOldPath));
switch (typeflag)
{
case FTW_F:
case FTW_SLN:
{
const char* dot = strrchr(relativeOldPath, '.');
if (dot && !strcmp(dot, ".gcda"))
{
Poco::File(newPath.parent()).createDirectories();
if (link(fpath, newPath.toString().c_str()) != 0)
{
LOG_SYS("nftw: Failed to link [" << fpath << "] -> [" << newPath.toString()
<< ']');
}
}
}
break;
case FTW_D:
case FTW_SL:
break;
case FTW_DNR:
LOG_ERR("nftw: Cannot read directory '" << fpath << '\'');
break;
case FTW_NS:
LOG_ERR("nftw: stat failed for '" << fpath << '\'');
break;
default:
LOG_FTL("nftw: unexpected typeflag: '" << typeflag);
assert(!"nftw: unexpected typeflag.");
break;
}
return FTW_CONTINUE;
}
/// Link .gcda (gcov) files from the src directory into the jail.
/// We need this so we can easily extract the profile data from within
/// the jail. Otherwise, we lose coverage info of the kit process.
void linkGCDAFiles(const std::string& destPath)
{
Poco::Path sourcePathInJail(destPath);
const auto sourcePath = std::string(DEBUG_ABSSRCDIR);
sourcePathInJail.append(sourcePath);
Poco::File(sourcePathInJail).createDirectories();
LOG_INF("Linking .gcda files from " << sourcePath << " -> " << sourcePathInJail.toString());
const auto childRootPtr = std::getenv("BASE_CHILD_ROOT");
if (childRootPtr == nullptr || strlen(childRootPtr) == 0)
{
LOG_ERR("Cannot collect code-coverage stats for the Kit processes. BASE_CHILD_ROOT "
"envar missing.");
return;
}
// Trim the trailing /.
const std::string childRoot = childRootPtr;
const size_t last = childRoot.find_last_not_of('/');
if (last != std::string::npos)
childRootForGCDAFiles = childRoot.substr(0, last + 1);
else
childRootForGCDAFiles = childRoot;
sourceForGCDAFiles = sourcePath;
destForGCDAFiles = sourcePathInJail.toString() + '/';
LOG_INF("nftw .gcda files from " << sourceForGCDAFiles << " -> " << destForGCDAFiles << " ("
<< childRootForGCDAFiles << ')');
if (nftw(sourcePath.c_str(), linkGCDAFilesFunction, 10, FTW_ACTIONRETVAL | FTW_PHYS) == -1)
{
LOG_ERR("linkGCDAFiles: nftw() failed for '" << sourcePath << '\'');
}
}
#endif
#if HAVE_LIBCAP
void dropCapability(cap_value_t capability)
{
cap_t caps;
cap_value_t cap_list[] = { capability };
caps = cap_get_proc();
if (caps == nullptr)
{
LOG_SFL("cap_get_proc() failed");
Util::forcedExit(EX_SOFTWARE);
}
char *capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities first: " << capText);
cap_free(capText);
if (cap_set_flag(caps, CAP_EFFECTIVE, N_ELEMENTS(cap_list), cap_list, CAP_CLEAR) == -1 ||
cap_set_flag(caps, CAP_PERMITTED, N_ELEMENTS(cap_list), cap_list, CAP_CLEAR) == -1)
{
LOG_SFL("cap_set_flag() failed");
Util::forcedExit(EX_SOFTWARE);
}
if (cap_set_proc(caps) == -1)
{
LOG_SFL("cap_set_proc() failed");
Util::forcedExit(EX_SOFTWARE);
}
capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities now: " << capText);
cap_free(capText);
cap_free(caps);
}
#endif // __FreeBSD__
#endif // BUILDING_TESTS
} // namespace
Document::Document(const std::shared_ptr<lok::Office>& loKit, const std::string& jailId,
const std::string& docKey, const std::string& docId, const std::string& url,
const std::shared_ptr<WebSocketHandler>& websocketHandler,
unsigned mobileAppDocId)
: _loKit(loKit)
, _jailId(jailId)
, _docKey(docKey)
, _docId(docId)
, _url(url)
, _obfuscatedFileId(Uri::getFilenameFromURL(Uri::decode(docKey)))
, _queue(new KitQueue(*this))
, _websocketHandler(websocketHandler)
, _modified(ModifiedState::UnModified)
, _isBgSaveProcess(false)
, _isBgSaveDisabled(false)
, _trimIfInactivePostponed(false)
, _haveDocPassword(false)
, _isDocPasswordProtected(false)
, _docPasswordType(DocumentPasswordType::ToView)
, _stop(false)
, _deltaGen(new DeltaGenerator())
, _editorId(-1)
, _editorChangeWarning(false)
, _lastMemTrimTime(std::chrono::steady_clock::now())
, _mobileAppDocId(mobileAppDocId)
, _duringLoad(0)
, _bgSavesOngoing(0)
{
LOG_INF("Document ctor for [" << _docKey <<
"] url [" << anonymizeUrl(_url) << "] on child [" << _jailId <<
"] and id [" << _docId << "].");
assert(_loKit);
#if !MOBILEAPP
assert(singletonDocument == nullptr);
singletonDocument = this;
#endif
// Open file for UI Logging
if (Log::isLogUIEnabled())
{
logUiCmd.createTmpFile(_docId);
}
}
Document::~Document()
{
LOG_INF("~Document dtor for [" << _docKey <<
"] url [" << anonymizeUrl(_url) << "] on child [" << _jailId <<
"] and id [" << _docId << "]. There are " <<
_sessions.size() << " views.");
// Wait for the callback worker to finish.
_stop = true;
for (const auto& session : _sessions)
{
session.second->resetDocManager();
}
#if defined(IOS) || defined(MACOS) || defined(_WIN32) || defined(QTAPP)
DocumentData::deallocate(_mobileAppDocId);
#endif
}
/// Post the message - in the unipoll world we're in the right thread anyway
bool Document::postMessage(const char* data, int size, const WSOpCode code) const
{
if (_isBgSaveProcess)
{
auto socket = _saveProcessParent.lock();
if (socket)
{
LOG_TRC("postMessage forwarding to parent of save process: " << getAbbreviatedMessage(data, size));
if (code != WSOpCode::Text)
{
LOG_WRN("save process unexpectedly sending binary message to parent: " << getAbbreviatedMessage(data, size));
assert(false);
return false;
}
return socket->sendMessage(data, size, code, /*flush=*/true) > 0;
}
LOG_TRC("Failed to forward to parent of save process: connection closed");
return false;
}
if (!_websocketHandler)
{
LOG_ERR("Child Doc: Bad socket while sending: " << getAbbreviatedMessage(data, size));
return false;
}
LOG_TRC("postMessage called with: " << getAbbreviatedMessage(data, size));
_websocketHandler->sendMessage(data, size, code, /*flush=*/true);
return true;
}
bool Document::createSession(const std::string& sessionId)
{
#if defined(BUILDING_TESTS)
LOG_ERR("createSession stubbed for tests for " << sessionId);
return false;
#else
try
{
if (_sessions.find(sessionId) != _sessions.end())
{
LOG_ERR("Session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "] already exists.");
return true;
}
LOG_INF("Creating " << (_sessions.empty() ? "first" : "new") <<
" session for url: " << anonymizeUrl(_url) << " for sessionId: " <<
sessionId << " on jailId: " << _jailId);
auto session = std::make_shared<ChildSession>(
_websocketHandler, sessionId,
_jailId, JailRoot, *this);
if (!Util::isMobileApp())
UnitKit::get().postKitSessionCreated(session.get());
_sessions.emplace(sessionId, session);
_deltaGen->setSessionCount(_sessions.size());
const int viewId = session->getViewId();
_lastUpdatedAt[viewId] = std::chrono::steady_clock::now();
_speedCount[viewId] = 0;
LOG_INF("New session [" << sessionId << "] created. Have " << _sessions.size()
<< " sessions now");
updateActivityHeader();
return true;
}
catch (const std::exception& ex)
{
LOG_ERR("Exception while creating session [" << sessionId <<
"] on url [" << anonymizeUrl(_url) << "] - '" << ex.what() << "'.");
return false;
}
#endif
}
std::size_t Document::purgeSessions()
{
std::vector<std::shared_ptr<ChildSession>> deadSessions;
std::size_t num_sessions = 0;
{
// If there are no live sessions, we don't need to do anything at all and can just
// bluntly exit, no need to clean up our own data structures. Also, there is a bug that
// causes the deadSessions.clear() call below to crash in some situations when the last
// session is being removed.
for (auto it = _sessions.cbegin(); it != _sessions.cend(); )
{
if (it->second->isCloseFrame())
{
LOG_DBG("Removing session [" << it->second->getId() << ']');
deadSessions.push_back(it->second);
it = _sessions.erase(it);
}
else
{
++it;
}
}
num_sessions = _sessions.size();
#if !MOBILEAPP
if (num_sessions == 0)
{
LOG_FTL("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
flushAndExit(EX_OK);
}
#endif
}
if (deadSessions.size() > 0 )
LOG_TRC("Purging " << deadSessions.size() <<
" dead sessions, with " << num_sessions <<
" active sessions.");
// Don't destroy sessions while holding our lock.
// We may deadlock if a session is waiting on us
// during callback initiated while handling a command
// and the dtor tries to take its lock (which is taken).
deadSessions.clear();
return num_sessions;
}
/// Set Document password for given URL
void Document::setDocumentPassword(int passwordType)
{
// Log whether the document is password protected and a password is provided
LOG_INF("setDocumentPassword: passwordProtected=" << _isDocPasswordProtected <<
" passwordProvided=" << _haveDocPassword);
if (_isDocPasswordProtected && _haveDocPassword)
{
// it means this is the second attempt with the wrong password; abort the load operation
_loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr);
return;
}
// One thing for sure, this is a password protected document
_isDocPasswordProtected = true;
if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD)
_docPasswordType = DocumentPasswordType::ToView;
else if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY)
_docPasswordType = DocumentPasswordType::ToModify;