forked from LibreOffice/online
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKit.cpp
2699 lines (2330 loc) · 94.9 KB
/
Kit.cpp
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 -*- */
/*
* 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/.
*/
/*
* The main entry point for the LibreOfficeKit process serving
* a document editing session.
*/
#include <config.h>
#include <dlfcn.h>
#ifdef __linux
#include <ftw.h>
#include <sys/capability.h>
#include <sys/sysmacros.h>
#endif
#include <unistd.h>
#include <utime.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <atomic>
#include <cassert>
#include <climits>
#include <condition_variable>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <sstream>
#include <thread>
#define LOK_USE_UNSTABLE_API
#include <LibreOfficeKit/LibreOfficeKitInit.h>
#include <LibreOfficeKit/LibreOfficeKit.hxx>
#include <Poco/Exception.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Parser.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/NetException.h>
#include <Poco/Net/Socket.h>
#include <Poco/Process.h>
#include <Poco/Runnable.h>
#include <Poco/StringTokenizer.h>
#include <Poco/Thread.h>
#include <Poco/URI.h>
#include <Poco/Util/Application.h>
#include "ChildSession.hpp"
#include <Common.hpp>
#include <IoUtil.hpp>
#include "KitHelper.hpp"
#include "Kit.hpp"
#include <Protocol.hpp>
#include <Log.hpp>
#include <Png.hpp>
#include <Rectangle.hpp>
#include <TileDesc.hpp>
#include <Unit.hpp>
#include <UserMessages.hpp>
#include <Util.hpp>
#include "Delta.hpp"
#ifndef MOBILEAPP
#include <common/SigUtil.hpp>
#include <common/Seccomp.hpp>
#endif
#ifdef FUZZER
#include <kit/DummyLibreOfficeKit.hpp>
#include <wsd/LOOLWSD.hpp>
#endif
#ifdef MOBILEAPP
#include "LOOLWSD.hpp"
#endif
#ifdef IOS
#include "ios.h"
#endif
#define LIB_SOFFICEAPP "lib" "sofficeapp" ".so"
#define LIB_MERGED "lib" "mergedlo" ".so"
using Poco::Exception;
using Poco::File;
using Poco::JSON::Array;
using Poco::JSON::Object;
using Poco::JSON::Parser;
using Poco::Runnable;
using Poco::StringTokenizer;
using Poco::Thread;
using Poco::Timestamp;
using Poco::URI;
using Poco::Util::Application;
#ifndef BUILDING_TESTS
using Poco::Path;
using Poco::Process;
#endif
using namespace LOOLProtocol;
using std::size_t;
// We only host a single document in our lifetime.
class Document;
static std::shared_ptr<Document> document;
#ifndef BUILDING_TESTS
static bool AnonymizeFilenames = false;
static bool AnonymizeUsernames = false;
static std::string ObfuscatedFileId;
#endif
#if ENABLE_DEBUG
# define ADD_DEBUG_RENDERID(s) ((s)+ " renderid=" + Util::UniqueId())
#else
# define ADD_DEBUG_RENDERID(s) (s)
#endif
#ifndef MOBILEAPP
static LokHookFunction2* initFunction = nullptr;
namespace
{
#ifndef BUILDING_TESTS
enum class LinkOrCopyType { All, LO, NoUsr };
LinkOrCopyType linkOrCopyType;
std::string sourceForLinkOrCopy;
Path destinationForLinkOrCopy;
std::chrono::time_point<std::chrono::steady_clock> linkOrCopyStartTime;
bool linkOrCopyVerboseLogging = false;
unsigned slowLinkOrCopyLimitInSecs = 10; // after this much seconds, start spamming the logs
bool shouldCopyDir(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::NoUsr:
// bind mounted.
return strcmp(path,"usr") != 0;
case LinkOrCopyType::LO:
return
strcmp(path, "program/wizards") != 0 &&
strcmp(path, "sdk") != 0 &&
strcmp(path, "share/basic") != 0 &&
strcmp(path, "share/Scripts/java") != 0 &&
strcmp(path, "share/Scripts/javascript") != 0 &&
strcmp(path, "share/template") != 0 &&
strcmp(path, "share/config/wizard") != 0 &&
strcmp(path, "share/config/wizard") != 0;
default: // LinkOrCopyType::All
return true;
}
}
bool shouldLinkFile(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::LO:
{
const char *dot = strrchr(path, '.');
if (!dot)
return true;
if (!strcmp(dot, ".dbg") ||
!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;
}
case LinkOrCopyType::NoUsr:
default: // LinkOrCopyType::All
return true;
}
}
void linkOrCopyFile(const char *fpath, const Path& newPath)
{
if (linkOrCopyVerboseLogging)
LOG_INF("Linking file \"" << fpath << "\" to \"" << newPath.toString() << "\"");
if (link(fpath, newPath.toString().c_str()) == -1)
{
LOG_INF("link(\"" << fpath << "\", \"" <<
newPath.toString() << "\") failed. Will copy.");
try
{
File(fpath).copyTo(newPath.toString());
}
catch (const std::exception& exc)
{
LOG_FTL("Copying of '" << fpath << "' to " << newPath.toString() <<
" failed: " << exc.what() << ". Exiting.");
Log::shutdown();
std::_Exit(Application::EXIT_SOFTWARE);
}
}
}
int linkOrCopyFunction(const char *fpath,
const struct stat* /*sb*/,
int typeflag,
struct FTW* /*ftwbuf*/)
{
if (strcmp(fpath, sourceForLinkOrCopy.c_str()) == 0)
return 0;
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 at information level.");
linkOrCopyVerboseLogging = true;
}
}
assert(fpath[strlen(sourceForLinkOrCopy.c_str())] == '/');
const char *relativeOldPath = fpath + strlen(sourceForLinkOrCopy.c_str()) + 1;
Path newPath(destinationForLinkOrCopy, Path(relativeOldPath));
switch (typeflag)
{
case FTW_F:
case FTW_SLN:
File(newPath.parent()).createDirectories();
if (shouldLinkFile(relativeOldPath))
linkOrCopyFile(fpath, newPath);
break;
case FTW_D:
{
struct stat st;
if (stat(fpath, &st) == -1)
{
LOG_SYS("stat(\"" << std::string(fpath) << "\") failed.");
return 1;
}
if (!shouldCopyDir(relativeOldPath))
{
LOG_TRC("skip redundant paths " << relativeOldPath);
return FTW_SKIP_SUBTREE;
}
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("utime(\"" << newPath.toString() << "\") failed.");
return 1;
}
}
break;
case FTW_DNR:
LOG_ERR("Cannot read directory '" << fpath << "'");
return 1;
case FTW_NS:
LOG_ERR("nftw: stat failed for '" << fpath << "'");
return 1;
default:
LOG_FTL("nftw: unexpected type: '" << typeflag);
assert(false);
break;
}
return 0;
}
void linkOrCopy(const std::string& source,
const Path& destination,
LinkOrCopyType type)
{
linkOrCopyType = type;
sourceForLinkOrCopy = source;
if (sourceForLinkOrCopy.back() == '/')
sourceForLinkOrCopy.pop_back();
destinationForLinkOrCopy = destination;
linkOrCopyStartTime = std::chrono::steady_clock::now();
if (nftw(source.c_str(), linkOrCopyFunction, 10, FTW_ACTIONRETVAL) == -1)
{
LOG_ERR("linkOrCopy: nftw() failed for '" << source << "'");
}
if (linkOrCopyVerboseLogging)
{
LOG_INF("Linking/Copying of files to " << destinationForLinkOrCopy.toString() << " finished.");
linkOrCopyVerboseLogging = false;
}
}
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.");
Log::shutdown();
std::_Exit(1);
}
char *capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities first: " << capText);
cap_free(capText);
if (cap_set_flag(caps, CAP_EFFECTIVE, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1 ||
cap_set_flag(caps, CAP_PERMITTED, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1)
{
LOG_SFL("cap_set_flag() failed.");
Log::shutdown();
std::_Exit(1);
}
if (cap_set_proc(caps) == -1)
{
LOG_SFL("cap_set_proc() failed.");
Log::shutdown();
std::_Exit(1);
}
capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities now: " << capText);
cap_free(capText);
cap_free(caps);
}
void symlinkPathToJail(const Path& jailPath, const std::string &loTemplate,
const std::string &loSubPath)
{
Path symlinkSource(jailPath, Path(loTemplate.substr(1)));
File(symlinkSource.parent()).createDirectories();
std::string symlinkTarget;
for (int i = 0; i < Path(loTemplate).depth(); i++)
symlinkTarget += "../";
symlinkTarget += loSubPath;
LOG_DBG("symlink(\"" << symlinkTarget << "\",\"" << symlinkSource.toString() << "\")");
if (symlink(symlinkTarget.c_str(), symlinkSource.toString().c_str()) == -1)
{
LOG_SYS("symlink(\"" << symlinkTarget << "\",\"" << symlinkSource.toString() << "\") failed");
throw Exception("symlink() failed");
}
}
#endif
}
#endif
/// A quick & dirty cache of the last few PNGs
/// and their hashes to avoid re-compression
/// wherever possible.
class PngCache
{
typedef std::shared_ptr< std::vector< char > > CacheData;
struct CacheEntry {
private:
size_t _hitCount;
TileWireId _wireId;
CacheData _data;
public:
CacheEntry(size_t defaultSize, TileWireId id) :
_hitCount(1), // Every entry is used at least once; prevent removal at birth.
_wireId(id),
_data( new std::vector< char >() )
{
_data->reserve( defaultSize );
}
size_t getHitCount() const
{
return _hitCount;
}
void incrementHitCount()
{
++_hitCount;
}
void decrementHitCount()
{
--_hitCount;
}
const CacheData& getData() const
{
return _data;
}
TileWireId getWireId() const
{
return _wireId;
}
} ;
size_t _cacheSize;
static const size_t CacheSizeSoftLimit = (1024 * 4 * 32); // 128k of cache
static const size_t CacheSizeHardLimit = CacheSizeSoftLimit * 2;
size_t _cacheHits;
size_t _cacheTests;
TileWireId _nextId;
DeltaGenerator _deltaGen;
std::map< TileBinaryHash, CacheEntry > _cache;
std::map< TileWireId, TileBinaryHash > _wireToHash;
void clearCache(bool logStats = false)
{
if (logStats)
LOG_DBG("cache clear " << _cache.size() << " items total size " <<
_cacheSize << " current hits " << _cacheHits);
_cache.clear();
_cacheSize = 0;
_cacheHits = 0;
_cacheTests = 0;
_nextId = 1;
}
// Keep these ids small and wrap them.
TileWireId createNewWireId()
{
TileWireId id = ++_nextId;
// FIXME: if we wrap - we should flush the clients too really ...
if (id < 1)
clearCache(true);
return id;
}
void balanceCache()
{
// A normalish PNG image size for text in a writer document is
// around 4k for a content tile, and sub 1k for a background one.
if (_cacheSize > CacheSizeHardLimit)
{
size_t avgHits = 0;
for (auto it = _cache.begin(); it != _cache.end(); ++it)
avgHits += it->second.getHitCount();
LOG_DBG("cache " << _cache.size() << " items total size " <<
_cacheSize << " current hits " << avgHits << ", total hit rate " <<
(_cacheHits * 100. / _cacheTests) << "% at balance start");
avgHits /= _cache.size();
for (auto it = _cache.begin(); it != _cache.end();)
{
if ((_cacheSize > CacheSizeSoftLimit && it->second.getHitCount() == 0) ||
(_cacheSize > CacheSizeHardLimit && it->second.getHitCount() > 0 && it->second.getHitCount() <= avgHits))
{
// Shrink cache when we exceed the size to maximize
// the chance of hitting these entries in the future.
_cacheSize -= it->second.getData()->size();
auto wIt = _wireToHash.find(it->second.getWireId());
assert(wIt != _wireToHash.end());
_wireToHash.erase(wIt);
it = _cache.erase(it);
}
else
{
if (it->second.getHitCount() > 0)
it->second.decrementHitCount();
++it;
}
}
LOG_DBG("cache " << _cache.size() << " items total size " <<
_cacheSize << " after balance");
}
}
/// Lookup an entry in the cache and store the data in output.
/// Returns true on success, otherwise false.
bool cacheTest(const uint64_t hash, std::vector<char>& output)
{
if (hash)
{
++_cacheTests;
auto it = _cache.find(hash);
if (it != _cache.end())
{
++_cacheHits;
LOG_DBG("PNG cache with hash " << hash << " hit.");
output.insert(output.end(),
it->second.getData()->begin(),
it->second.getData()->end());
it->second.incrementHitCount();
return true;
}
}
return false;
}
bool cacheEncodeSubBufferToPNG(unsigned char* pixmap, size_t startX, size_t startY,
int width, int height,
int bufferWidth, int bufferHeight,
std::vector<char>& output, LibreOfficeKitTileMode mode,
TileBinaryHash hash, TileWireId wid, TileWireId /*oldWid*/)
{
LOG_DBG("PNG cache with hash " << hash << " missed.");
/*
*Disable for now - pushed in error.
*
if (_deltaGen.createDelta(pixmap, startX, startY, width, height,
bufferWidth, bufferHeight,
output, wid, oldWid))
return true;
*/
LOG_DBG("Encode a new png for this tile.");
CacheEntry newEntry(bufferWidth * bufferHeight * 1, wid);
if (Png::encodeSubBufferToPNG(pixmap, startX, startY, width, height,
bufferWidth, bufferHeight,
*newEntry.getData(), mode))
{
if (hash)
{
newEntry.getData()->shrink_to_fit();
_cache.emplace(hash, newEntry);
_cacheSize += newEntry.getData()->size();
}
output.insert(output.end(),
newEntry.getData()->begin(),
newEntry.getData()->end());
balanceCache();
return true;
}
else
return false;
}
public:
PngCache()
{
clearCache();
}
TileWireId hashToWireId(TileBinaryHash id)
{
TileWireId wid;
if (id == 0)
return 0;
auto it = _cache.find(id);
if (it != _cache.end())
wid = it->second.getWireId();
else
{
wid = createNewWireId();
_wireToHash.emplace(wid, id);
}
return wid;
}
bool encodeBufferToPNG(unsigned char* pixmap, int width, int height,
std::vector<char>& output, LibreOfficeKitTileMode mode,
TileBinaryHash hash, TileWireId wid, TileWireId oldWid)
{
if (cacheTest(hash, output))
return true;
return cacheEncodeSubBufferToPNG(pixmap, 0, 0, width, height,
width, height, output, mode,
hash, wid, oldWid);
}
bool encodeSubBufferToPNG(unsigned char* pixmap, size_t startX, size_t startY,
int width, int height,
int bufferWidth, int bufferHeight,
std::vector<char>& output, LibreOfficeKitTileMode mode,
TileBinaryHash hash, TileWireId wid, TileWireId oldWid)
{
if (cacheTest(hash, output))
return true;
return cacheEncodeSubBufferToPNG(pixmap, startX, startY, width, height,
bufferWidth, bufferHeight, output, mode,
hash, wid, oldWid);
}
};
class Watermark
{
public:
Watermark(const std::shared_ptr<lok::Document>& loKitDoc, const std::string& text)
: _loKitDoc(loKitDoc)
, _text(text)
, _font("Liberation Sans")
, _width(0)
, _height(0)
, _alphaLevel(0.2)
{
}
~Watermark()
{
}
void blending(unsigned char* tilePixmap,
int offsetX, int offsetY,
int tilesPixmapWidth, int tilesPixmapHeight,
int tileWidth, int tileHeight,
LibreOfficeKitTileMode /*mode*/)
{
// set requested watermark size a little bit smaller than tile size
int width = tileWidth * 0.9;
int height = tileHeight * 0.9;
const std::vector<unsigned char>* pixmap = getPixmap(width, height);
if (pixmap && tilePixmap)
{
// center watermark
const int maxX = std::min(tileWidth, _width);
const int maxY = std::min(tileHeight, _height);
offsetX += (tileWidth - maxX) / 2;
offsetY += (tileHeight - maxY) / 2;
alphaBlend(*pixmap, _width, _height, offsetX, offsetY, tilePixmap, tilesPixmapWidth, tilesPixmapHeight);
}
}
private:
/// Alpha blend pixels from 'from' over the 'to'.
void alphaBlend(const std::vector<unsigned char>& from, int from_width, int from_height, int from_offset_x, int from_offset_y,
unsigned char* to, int to_width, int to_height)
{
for (int to_y = from_offset_y, from_y = 0; (to_y < to_height) && (from_y < from_height) ; ++to_y, ++from_y)
for (int to_x = from_offset_x, from_x = 0; (to_x < to_width) && (from_x < from_width); ++to_x, ++from_x)
{
const unsigned char* f = from.data() + 4 * (from_y * from_width + from_x);
double src_r = f[0];
double src_g = f[1];
double src_b = f[2];
double src_a = f[3] / 255.0;
unsigned char* t = to + 4 * (to_y * to_width + to_x);
double dst_r = t[0];
double dst_g = t[1];
double dst_b = t[2];
double dst_a = t[3] / 255.0;
double out_a = src_a + dst_a * (1.0 - src_a);
unsigned char out_r = src_r + dst_r * (1.0 - src_a);
unsigned char out_g = src_g + dst_g * (1.0 - src_a);
unsigned char out_b = src_b + dst_b * (1.0 - src_a);
t[0] = out_r;
t[1] = out_g;
t[2] = out_b;
t[3] = static_cast<unsigned char>(out_a * 255.0);
}
}
/// Create bitmap that we later use as the watermark for every tile.
const std::vector<unsigned char>* getPixmap(int width, int height)
{
if (!_pixmap.empty() && width == _width && height == _height)
return &_pixmap;
_pixmap.clear();
_width = width;
_height = height;
if (!_loKitDoc)
{
LOG_ERR("Watermark rendering requested without a valid document.");
return nullptr;
}
// renderFont returns a buffer based on RGBA mode, where r, g, b
// are always set to 0 (black) and the alpha level is 0 everywhere
// except on the text area; the alpha level take into account of
// performing anti-aliasing over the text edges.
unsigned char* textPixels = _loKitDoc->renderFont(_font.c_str(), _text.c_str(), &_width, &_height);
if (!textPixels)
{
LOG_ERR("Watermark: rendering failed.");
}
const unsigned int pixel_count = width * height * 4;
std::vector<unsigned char> text(textPixels, textPixels + pixel_count);
// No longer needed.
std::free(textPixels);
_pixmap.reserve(pixel_count);
// Create the white blurred background
// Use box blur, it's enough for our purposes
const int r = 2;
const double weight = (r+1) * (r+1);
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
double t = 0;
for (int ky = std::max(y - r, 0); ky <= std::min(y + r, height - 1); ++ky)
{
for (int kx = std::max(x - r, 0); kx <= std::min(x + r, width - 1); ++kx)
{
// Pre-multiplied alpha; the text is black, so all the
// information is only in the alpha channel
t += text[4 * (ky * width + kx) + 3];
}
}
// Clamp the result.
double avg = t / weight;
if (avg > 255.0)
avg = 255.0;
// Pre-multiplied alpha, but use white for the resulting color
const double alpha = avg / 255.0;
_pixmap[4 * (y * width + x) + 0] = 0xff * alpha;
_pixmap[4 * (y * width + x) + 1] = 0xff * alpha;
_pixmap[4 * (y * width + x) + 2] = 0xff * alpha;
_pixmap[4 * (y * width + x) + 3] = avg;
}
}
// Now copy the (black) text over the (white) blur
alphaBlend(text, _width, _height, 0, 0, _pixmap.data(), _width, _height);
// Make the resulting pixmap semi-transparent
for (unsigned char* p = _pixmap.data(); p < _pixmap.data() + pixel_count; p++)
{
*p = static_cast<unsigned char>(*p * _alphaLevel);
}
return &_pixmap;
}
private:
std::shared_ptr<lok::Document> _loKitDoc;
std::string _text;
std::string _font;
int _width;
int _height;
double _alphaLevel;
std::vector<unsigned char> _pixmap;
};
#ifndef MOBILEAPP
static FILE* ProcSMapsFile = nullptr;
#endif
/// A document container.
/// Owns LOKitDocument instance and connections.
/// Manages the lifetime of a document.
/// Technically, we can host multiple documents
/// per process. But for security reasons don't.
/// However, we could have a loolkit instance
/// per user or group of users (a trusted circle).
class Document : public Runnable, public DocumentManagerInterface
{
public:
/// We have two types of password protected documents
/// 1) Documents which require password to view
/// 2) Document which require password to modify
enum class PasswordType { ToView, ToModify };
public:
Document(const std::shared_ptr<lok::Office>& loKit,
const std::string& jailId,
const std::string& docKey,
const std::string& docId,
const std::string& url,
std::shared_ptr<TileQueue> tileQueue,
SocketPoll& socketPoll,
const std::shared_ptr<WebSocketHandler>& websocketHandler)
: _loKit(loKit),
_jailId(jailId),
_docKey(docKey),
_docId(docId),
_url(url),
_obfuscatedFileId(Util::getFilenameFromURL(docKey)),
_tileQueue(std::move(tileQueue)),
_socketPoll(socketPoll),
_websocketHandler(websocketHandler),
_docPassword(""),
_haveDocPassword(false),
_isDocPasswordProtected(false),
_docPasswordType(PasswordType::ToView),
_stop(false),
_isLoading(0),
_editorId(-1),
_editorChangeWarning(false)
{
LOG_INF("Document ctor for [" << _docKey <<
"] url [" << anonymizeUrl(_url) << "] on child [" << _jailId <<
"] and id [" << _docId << "].");
assert(_loKit);
_callbackThread.start(*this);
}
~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;
_tileQueue->put("eof");
_callbackThread.join();
}
const std::string& getUrl() const { return _url; }
/// Post the message in the correct thread.
bool postMessage(const std::shared_ptr<std::vector<char>>& message, const WSOpCode code) const
{
LOG_TRC("postMessage called with: " << getAbbreviatedMessage(message->data(), message->size()));
if (!_websocketHandler)
{
LOG_ERR("Child Doc: Bad socket while sending [" << getAbbreviatedMessage(message->data(), message->size()) << "].");
return false;
}
_socketPoll.addCallback([=]{
_websocketHandler->sendMessage(message->data(), message->size(), code);
});
return true;
}
bool createSession(const std::string& sessionId)
{
std::unique_lock<std::mutex> lock(_mutex);
try
{
if (_sessions.find(sessionId) != _sessions.end())
{
LOG_WRN("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>(sessionId, _jailId, *this);
_sessions.emplace(sessionId, session);
int viewId = session->getViewId();
_lastUpdatedAt[viewId] = std::chrono::steady_clock::now();
_speedCount[viewId] = 0;
LOG_DBG("Sessions: " << _sessions.size());
return true;
}
catch (const std::exception& ex)
{
LOG_ERR("Exception while creating session [" << sessionId <<
"] on url [" << anonymizeUrl(_url) << "] - '" << ex.what() << "'.");
return false;
}
}
/// Purges dead connections and returns
/// the remaining number of clients.
/// Returns -1 on failure.
size_t purgeSessions()
{
std::vector<std::shared_ptr<ChildSession>> deadSessions;
size_t num_sessions = 0;
{
std::unique_lock<std::mutex> lock(_mutex, std::defer_lock);
if (!lock.try_lock())
{
// Not a good time, try later.
return -1;
}
// 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())
{
deadSessions.push_back(it->second);
it = _sessions.erase(it);
}
else
{
++it;
}
}
num_sessions = _sessions.size();
#ifndef MOBILEAPP
if (num_sessions == 0)
{
LOG_FTL("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
Log::shutdown();
std::_Exit(Application::EXIT_OK);
}
#endif
}
// 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 setDocumentPassword(int passwordType)
{
LOG_INF("setDocumentPassword: passwordProtected=" << _isDocPasswordProtected <<
" passwordProvided=" << _haveDocPassword <<
" password='" << _docPassword << "'");
Util::assertIsLocked(_documentMutex);
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 = PasswordType::ToView;
else if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY)
_docPasswordType = PasswordType::ToModify;
LOG_INF("Calling _loKit->setDocumentPassword");
if (_haveDocPassword)
_loKit->setDocumentPassword(_jailedUrl.c_str(), _docPassword.c_str());
else
_loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr);
LOG_INF("setDocumentPassword returned");
}
void renderTile(const std::vector<std::string>& tokens)
{
TileDesc tile = TileDesc::parse(tokens);
size_t pixmapDataSize = 4 * tile.getWidth() * tile.getHeight();
std::vector<unsigned char> pixmap;
pixmap.resize(pixmapDataSize);
std::unique_lock<std::mutex> lock(_documentMutex);
if (!_loKitDocument)
{
LOG_ERR("Tile rendering requested before loading document.");