forked from CollaboraOnline/online
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DocumentBroker.cpp
4570 lines (3938 loc) · 172 KB
/
DocumentBroker.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 -*- */
/*
* 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/.
*/
#include <config.h>
#include "DocumentBroker.hpp"
#include <atomic>
#include <cassert>
#include <chrono>
#include <ctime>
#include <ios>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <string>
#include <sstream>
#include <Poco/DigestStream.h>
#include <Poco/Exception.h>
#include <Poco/Path.h>
#include <Poco/SHA1Engine.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>
#include "Admin.hpp"
#include "Authorization.hpp"
#include "ClientSession.hpp"
#include "Common.hpp"
#include "Exceptions.hpp"
#include "COOLWSD.hpp"
#include "FileServer.hpp"
#include "Socket.hpp"
#include "Storage.hpp"
#include "TileCache.hpp"
#include "TraceEvent.hpp"
#include "ProxyProtocol.hpp"
#include "Util.hpp"
#include "QuarantineUtil.hpp"
#include <common/JsonUtil.hpp>
#include <common/Log.hpp>
#include <common/Message.hpp>
#include <common/Clipboard.hpp>
#include <common/Protocol.hpp>
#include <common/Unit.hpp>
#include <common/FileUtil.hpp>
#include <CommandControl.hpp>
#if !MOBILEAPP
#include <wopi/CheckFileInfo.hpp>
#include <net/HttpHelper.hpp>
#endif
#include <sys/types.h>
#include <sys/wait.h>
using namespace COOLProtocol;
using Poco::JSON::Object;
void UrpHandler::handleIncomingMessage(SocketDisposition&)
{
std::shared_ptr<StreamSocket> socket = _socket.lock();
if (!socket)
{
LOG_ERR("Invalid socket while handling incoming client request");
return;
}
Buffer& data = socket->getInBuffer();
if (data.empty())
{
LOG_DBG("No data to process from the socket");
return;
}
ChildProcess* child = _childProcess;
std::shared_ptr<DocumentBroker> docBroker =
child && child->getPid() > 0 ? child->getDocumentBroker() : nullptr;
if (docBroker)
docBroker->onUrpMessage(data.data(), data.size());
// Remove consumed data.
data.clear();
}
void ChildProcess::setDocumentBroker(const std::shared_ptr<DocumentBroker>& docBroker)
{
assert(docBroker && "Invalid DocumentBroker instance.");
_docBroker = docBroker;
// The prisoner socket is added in 'takeSocket'
// if URP is enabled, also add its socket to the poll
if (_urpFromKit)
docBroker->addSocketToPoll(_urpFromKit);
if (_urpToKit)
docBroker->addSocketToPoll(_urpToKit);
if (UnitWSD::isUnitTesting())
{
UnitWSD::get().onDocBrokerAttachKitProcess(docBroker->getDocKey(), getPid());
}
}
void DocumentBroker::broadcastLastModificationTime(
const std::shared_ptr<ClientSession>& session) const
{
if (_storageManager.getLastModifiedTime().empty())
// No time from the storage (e.g., SharePoint 2013 and 2016) -> don't send
return;
std::ostringstream stream;
stream << "lastmodtime: " << _storageManager.getLastModifiedTime();
const std::string message = stream.str();
// While loading, the current session is not yet added to
// the sessions container, so we need to send to it directly.
if (session)
session->sendTextFrame(message);
broadcastMessage(message);
}
/// The Document Broker Poll - one of these in a thread per document
class DocumentBroker::DocumentBrokerPoll final : public TerminatingPoll
{
/// The DocumentBroker owning us.
DocumentBroker& _docBroker;
public:
DocumentBrokerPoll(const std::string &threadName, DocumentBroker& docBroker) :
TerminatingPoll(threadName),
_docBroker(docBroker)
{
}
void pollingThread() override
{
// Delegate to the docBroker.
_docBroker.pollThread();
}
};
std::atomic<unsigned> DocumentBroker::DocBrokerId(1);
DocumentBroker::DocumentBroker(ChildType type, const std::string& uri, const Poco::URI& uriPublic,
const std::string& docKey, unsigned mobileAppDocId,
std::unique_ptr<WopiStorage::WOPIFileInfo> wopiFileInfo)
: _limitLifeSeconds(std::chrono::seconds::zero())
, _uriOrig(uri)
, _type(type)
, _uriPublic(uriPublic)
, _docKey(docKey)
, _docId(Util::encodeId(DocBrokerId++, 3))
, _documentChangedInStorage(false)
, _isViewFileExtension(false)
, _saveManager(std::chrono::seconds(std::getenv("COOL_NO_AUTOSAVE") != nullptr
? 0
: COOLWSD::getConfigValueNonZero<int>(
"per_document.idlesave_duration_secs", 30)),
std::chrono::seconds(std::getenv("COOL_NO_AUTOSAVE") != nullptr
? 0
: COOLWSD::getConfigValueNonZero<int>(
"per_document.autosave_duration_secs", 300)),
std::chrono::milliseconds(COOLWSD::getConfigValueNonZero<int>(
"per_document.min_time_between_saves_ms", 500)))
, _storageManager(std::chrono::milliseconds(
COOLWSD::getConfigValueNonZero<int>("per_document.min_time_between_uploads_ms", 5000)))
, _isModified(false)
, _cursorPosX(0)
, _cursorPosY(0)
, _cursorWidth(0)
, _cursorHeight(0)
, _poll(
std::make_unique<DocumentBrokerPoll>("doc" SHARED_DOC_THREADNAME_SUFFIX + _docId, *this))
, _stop(false)
, _lockCtx(std::make_unique<LockContext>())
, _tileVersion(0)
, _debugRenderedTileCount(0)
, _loadDuration(0)
, _wopiDownloadDuration(0)
, _mobileAppDocId(mobileAppDocId)
, _alwaysSaveOnExit(COOLWSD::getConfigValue<bool>("per_document.always_save_on_exit", false))
, _backgroundAutoSave(COOLWSD::getConfigValue<bool>("per_document.background_autosave", true))
#if !MOBILEAPP
, _admin(Admin::instance())
#endif
, _unitWsd(UnitWSD::isUnitTesting() ? &UnitWSD::get() : nullptr)
{
assert(!_docKey.empty());
assert(!COOLWSD::ChildRoot.empty());
if (!Util::isMobileApp())
assert(_mobileAppDocId == 0 && "Unexpected to have mobileAppDocId in the non-mobile build");
#ifdef IOS
assert(_mobileAppDocId > 0 && "Unexpected to have no mobileAppDocId in the iOS build");
#endif
LOG_INF("DocumentBroker [" << COOLWSD::anonymizeUrl(_uriPublic.toString())
<< "] created with docKey [" << _docKey
<< "], always_save_on_exit: " << _alwaysSaveOnExit);
if (_unitWsd)
{
_unitWsd->onDocBrokerCreate(_docKey);
}
_initialWopiFileInfo = std::move(wopiFileInfo);
if (_initialWopiFileInfo)
{
LOG_DBG("Starting DocBrokerPoll thread");
_poll->startThread();
}
}
void DocumentBroker::setupPriorities()
{
if (Util::isMobileApp())
return;
if (_type == ChildType::Batch)
{
int prio = COOLWSD::getConfigValue<int>("per_document.batch_priority", 5);
Util::setProcessAndThreadPriorities(_childProcess->getPid(), prio);
}
}
void DocumentBroker::setupTransfer(SocketDisposition &disposition,
SocketDisposition::MoveFunction transferFn)
{
disposition.setTransfer(*_poll, std::move(transferFn));
}
void DocumentBroker::setupTransfer(const std::shared_ptr<StreamSocket>& socket,
const SocketDisposition::MoveFunction& transferFn)
{
// Drop pretentions of ownership before _socketMove.
socket->resetThreadOwner();
_poll->startThread();
_poll->addCallback(
[this, socket, transferFn]()
{
_poll->insertNewSocket(socket);
transferFn(socket);
});
}
void DocumentBroker::assertCorrectThread(const char* filename, int line) const
{
_poll->assertCorrectThread(filename, line);
}
// The inner heart of the DocumentBroker - our poll loop.
void DocumentBroker::pollThread()
{
_threadStart = std::chrono::steady_clock::now();
LOG_INF("Starting docBroker polling thread for docKey [" << _docKey << ']');
// Request a kit process for this doc.
do
{
static constexpr std::chrono::milliseconds timeoutMs(COMMAND_TIMEOUT_MS * 5);
_childProcess = getNewChild_Blocks(*_poll, _mobileAppDocId);
if (_childProcess
|| std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - _threadStart)
> timeoutMs)
break;
// Nominal time between retries, lest we busy-loop. getNewChild could also wait, so don't double that here.
std::this_thread::sleep_for(std::chrono::milliseconds(CHILD_REBALANCE_INTERVAL_MS / 10));
} while (!_stop && _poll->continuePolling() && !SigUtil::getShutdownRequestFlag());
if (!_childProcess)
{
// Let the client know we can't serve now.
LOG_ERR("Failed to get new child.");
// FIXME: need to notify all clients and shut this down ...
// FIXME: return something good down the websocket ...
#if 0
const std::string msg = SERVICE_UNAVAILABLE_INTERNAL_ERROR;
ws.sendMessage(msg);
// abnormal close frame handshake
ws.shutdown(WebSocketHandler::StatusCodes::ENDPOINT_GOING_AWAY);
#endif
stop("Failed to get new child.");
// Stop to mark it done and cleanup.
_poll->stop();
// Async cleanup.
COOLWSD::doHousekeeping();
LOG_INF("Finished docBroker polling thread for docKey [" << _docKey << "].");
return;
}
// We have a child process.
_childProcess->setDocumentBroker(shared_from_this());
LOG_INF("Doc [" << _docKey << "] attached to child [" << _childProcess->getPid() << "].");
setupPriorities();
// Download and load the document.
if (_initialWopiFileInfo)
{
downloadAdvance(_childProcess->getJailId(), _uriPublic, std::move(_initialWopiFileInfo));
}
#if !MOBILEAPP
static const std::size_t IdleDocTimeoutSecs
= COOLWSD::getConfigValue<int>("per_document.idle_timeout_secs", 3600);
// Used to accumulate B/W deltas.
uint64_t adminSent = 0;
uint64_t adminRecv = 0;
auto lastBWUpdateTime = std::chrono::steady_clock::now();
auto lastClipboardHashUpdateTime = std::chrono::steady_clock::now();
const int limit_load_secs =
#if ENABLE_DEBUG
// paused waiting for a debugger to attach
// ignore load time out
std::getenv("PAUSEFORDEBUGGER") ? -1 :
#endif
COOLWSD::getConfigValue<int>("per_document.limit_load_secs", 100);
auto loadDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(limit_load_secs);
#endif
const auto limStoreFailures =
COOLWSD::getConfigValue<int>("per_document.limit_store_failures", 5);
bool waitingForMigrationMsg = false;
std::chrono::time_point<std::chrono::steady_clock> migrationMsgStartTime;
static const std::chrono::microseconds migrationMsgTimeout = std::chrono::seconds(
COOLWSD::getConfigValue<int>("indirection_endpoint.migration_timeout_secs", 180));
// Main polling loop goodness.
while (!_stop && _poll->continuePolling() && !SigUtil::getTerminationFlag())
{
// Poll more frequently while unloading to cleanup sooner.
const bool unloading = isMarkedToDestroy() || _docState.isUnloadRequested();
_poll->poll(unloading ? SocketPoll::DefaultPollTimeoutMicroS / 16
: SocketPoll::DefaultPollTimeoutMicroS);
// Consolidate updates across multiple processed events.
processBatchUpdates();
if (_stop)
{
LOG_DBG("Doc [" << _docKey << "] is flagged to stop after returning from poll.");
break;
}
if (_unitWsd && _unitWsd->isFinished())
{
stop("UnitTestFinished");
break;
}
#if !MOBILEAPP
const auto now = std::chrono::steady_clock::now();
// a tile's data is ~8k, a 4k screen is ~256 256x256 tiles -
// so double that - 4Mb per view.
if (_tileCache)
_tileCache->setMaxCacheSize(8 * 1024 * 256 * 2 * _sessions.size());
if (isInteractive())
{
// It is possible to dismiss the interactive dialog,
// exit the Kit process, or even crash. We would deadlock.
if (isUnloading())
{
// We expect to have either isMarkedToDestroy() or
// isCloseRequested() in that case.
stop("abortedinteractive");
}
// Extend the deadline while we are interactiving with the user.
loadDeadline = now + std::chrono::seconds(limit_load_secs);
continue;
}
if (!isLoaded() && (limit_load_secs > 0) && (now > loadDeadline))
{
LOG_ERR("Doc [" << _docKey << "] is taking too long to load. Will kill process ["
<< _childProcess->getPid() << "]. per_document.limit_load_secs set to "
<< limit_load_secs << " secs.");
broadcastMessage("error: cmd=load kind=docloadtimeout");
// Brutal but effective.
if (_childProcess)
_childProcess->terminate();
stop("Doc lifetime expired");
continue;
}
// Check if we had a sunset time and expired.
if (_limitLifeSeconds > std::chrono::seconds::zero()
&& std::chrono::duration_cast<std::chrono::seconds>(now - _threadStart)
> _limitLifeSeconds)
{
LOG_WRN("Doc [" << _docKey << "] is taking too long to convert. Will kill process ["
<< _childProcess->getPid()
<< "]. per_document.limit_convert_secs set to "
<< _limitLifeSeconds.count() << " secs.");
broadcastMessage("error: cmd=load kind=docexpired");
// Brutal but effective.
if (_childProcess)
_childProcess->terminate();
stop("Convert-to timed out");
continue;
}
if (std::chrono::duration_cast<std::chrono::milliseconds>
(now - lastBWUpdateTime).count() >= COMMAND_TIMEOUT_MS)
{
lastBWUpdateTime = now;
uint64_t sent = 0, recv = 0;
getIOStats(sent, recv);
uint64_t deltaSent = 0, deltaRecv = 0;
// connection drop transiently reduces this.
if (sent > adminSent)
{
deltaSent = sent - adminSent;
adminSent = sent;
}
if (recv > deltaRecv)
{
deltaRecv = recv - adminRecv;
adminRecv = recv;
}
LOG_TRC("Doc [" << _docKey << "] added stats sent: +" << deltaSent << ", recv: +" << deltaRecv << " bytes to totals.");
// send change since last notification.
_admin.addBytes(getDocKey(), deltaSent, deltaRecv);
}
if (_storage && _lockCtx->needsRefresh(now))
refreshLock();
#endif
LOG_TRC("Poll: current activity: " << DocumentState::name(_docState.activity()));
switch (_docState.activity())
{
case DocumentState::Activity::None:
{
// Check if there are queued activities.
if (!_renameFilename.empty() && !_renameSessionId.empty())
{
startRenameFileCommand();
// Nothing more to do until the save is complete.
continue;
}
#if !MOBILEAPP
// Remove idle documents after 1 hour.
if (isLoaded() && getIdleTimeSecs() >= IdleDocTimeoutSecs)
{
autoSaveAndStop("idle");
}
else
#endif
if (_sessions.empty() && (isLoaded() || _docState.isMarkedToDestroy()))
{
if (!isLoaded())
{
// Nothing to do; no sessions, not loaded, marked to destroy.
stop("dead");
}
else if (_saveManager.isSaving() || isAsyncUploading())
{
LOG_DBG("Don't terminate dead DocumentBroker: async saving in progress for "
"docKey ["
<< getDocKey() << "].");
continue;
}
autoSaveAndStop("dead");
}
else if (COOLWSD::IndirectionServerEnabled && SigUtil::getShutdownRequestFlag() &&
!_migrateMsgReceived)
{
if (!waitingForMigrationMsg)
{
migrationMsgStartTime = std::chrono::steady_clock::now();
waitingForMigrationMsg = true;
break;
}
const auto timeNow = std::chrono::steady_clock::now();
const auto elapsedMicroS =
std::chrono::duration_cast<std::chrono::microseconds>(
timeNow - migrationMsgStartTime);
if (elapsedMicroS > migrationMsgTimeout)
{
LOG_WRN("Timeout waiting for migration message for docKey[" << _docKey
<< ']');
_migrateMsgReceived = true;
break;
}
LOG_DBG("Waiting for migration message to arrive before closing the document "
"for docKey["
<< _docKey << ']');
}
else if (_docState.isUnloadRequested() || SigUtil::getShutdownRequestFlag() ||
_docState.isCloseRequested())
{
if (limStoreFailures > 0 && (_saveManager.saveFailureCount() >=
static_cast<std::size_t>(limStoreFailures) ||
_storageManager.uploadFailureCount() >=
static_cast<std::size_t>(limStoreFailures)))
{
LOG_ERR("Failed to store the document and reached maximum retry count of "
<< limStoreFailures
<< ". Giving up. The document should be recoverable from the "
"quarantine. Save failures: "
<< _saveManager.saveFailureCount()
<< ", Upload failures: " << _storageManager.uploadFailureCount());
stop("storefailed");
continue;
}
const std::string reason =
SigUtil::getShutdownRequestFlag()
? "recycling"
: (!_closeReason.empty() ? _closeReason : "unloading");
autoSaveAndStop(reason);
}
else if (!_stop && _saveManager.needAutoSaveCheck())
{
LOG_TRC("Triggering an autosave by timer");
autoSave(/*force=*/false, /*dontSaveIfUnmodified=*/true);
}
else if (!isAsyncUploading() && !_storageManager.lastUploadSuccessful() &&
needToUploadToStorage() != NeedToUpload::No)
{
// Retry uploading, if the last one failed and we can try again.
const auto session = getWriteableSession();
if (session && !session->getAuthorization().isExpired())
{
checkAndUploadToStorage(session, /*justSaved=*/false);
}
}
}
break;
case DocumentState::Activity::Save:
case DocumentState::Activity::SaveAs:
{
if (_docState.isDisconnected())
{
// We will never save. No need to wait for timeout.
LOG_DBG("Doc disconnected while saving. Ending save activity.");
_saveManager.setLastSaveResult(/*success=*/false, /*newVersion=*/false);
endActivity();
}
else
if (_saveManager.hasSavingTimedOut())
{
LOG_DBG("Saving timedout. Ending save activity.");
_saveManager.setLastSaveResult(/*success=*/false, /*newVersion=*/false);
endActivity();
}
}
break;
// We have some activity ongoing.
default:
{
constexpr std::chrono::seconds postponeAutosaveDuration(30);
LOG_TRC("Postponing autosave check by " << postponeAutosaveDuration);
_saveManager.postponeAutosave(postponeAutosaveDuration);
}
break;
}
#if !MOBILEAPP
if (std::chrono::duration_cast<std::chrono::minutes>(now - lastClipboardHashUpdateTime).count() >= 2)
{
for (auto &it : _sessions)
{
if (it.second->staleWaitDisconnect(now))
{
std::string id = it.second->getId();
LOG_WRN("Unusual, Kit session " + id + " failed its disconnect handshake, killing");
finalRemoveSession(it.second);
break; // it invalid.
}
}
}
if (std::chrono::duration_cast<std::chrono::minutes>(now - lastClipboardHashUpdateTime).count() >= 5)
{
LOG_TRC("Rotating clipboard keys");
for (auto &it : _sessions)
it.second->rotateClipboardKey(true);
lastClipboardHashUpdateTime = now;
}
#endif
}
LOG_INF("Finished polling doc ["
<< _docKey << "]. stop: " << _stop << ", continuePolling: " << _poll->continuePolling()
<< ", CloseReason: [" << _closeReason << ']'
<< ", ShutdownRequestFlag: " << SigUtil::getShutdownRequestFlag()
<< ", TerminationFlag: " << SigUtil::getTerminationFlag());
if (_childProcess && _sessions.empty())
{
LOG_INF("Requesting termination of child [" << getPid() << "] for doc [" << _docKey
<< "] as there are no sessions");
_childProcess->requestTermination();
}
// Check for data-loss.
std::string reason;
#if !MOBILEAPP
bool dataLoss = false;
#endif
if (haveModifyActivityAfterSaveRequest() || !_saveManager.lastSaveSuccessful() ||
!_storageManager.lastUploadSuccessful() || isStorageOutdated())
{
// If we are exiting because the owner discarded conflict changes, don't detect data loss.
if (!(_docState.isCloseRequested() && _documentChangedInStorage))
{
#if !MOBILEAPP
dataLoss = true;
#endif
if (haveModifyActivityAfterSaveRequest())
reason = "have unsaved modifications";
else
reason = !_saveManager.lastSaveSuccessful() ? "flagged as modified"
: "not uploaded to storage";
// The test may override (if it was expected).
if (_unitWsd && !_unitWsd->onDataLoss("Data-loss detected while exiting [" + _docKey +
"]: " + reason))
reason.clear();
}
}
if (!reason.empty() || (_unitWsd && _unitWsd->isFinished() && _unitWsd->failed()))
{
std::stringstream state;
state << "DocBroker [" << _docKey << " stopped "
<< (reason.empty() ? "because of test failure" : ("although " + reason)) << ": ";
dumpState(state);
LOG_WRN(state.str());
}
// Flush socket data first, if any.
if (_poll->getSocketCount())
{
constexpr std::chrono::microseconds flushTimeoutMicroS(std::chrono::seconds(2));
LOG_INF("Flushing " << _poll->getSocketCount() << " sockets for doc [" << _docKey
<< "] for " << flushTimeoutMicroS);
const auto flushStartTime = std::chrono::steady_clock::now();
while (_poll->getSocketCount())
{
const auto now = std::chrono::steady_clock::now();
const auto elapsedMicroS =
std::chrono::duration_cast<std::chrono::microseconds>(now - flushStartTime);
if (elapsedMicroS > flushTimeoutMicroS)
break;
const std::chrono::microseconds timeoutMicroS =
std::min(flushTimeoutMicroS - elapsedMicroS, flushTimeoutMicroS/10);
if (_poll->poll(timeoutMicroS) == 0 && UnitWSD::isUnitTesting())
{
// Polling timed out, no more data to flush.
break;
}
processBatchUpdates();
}
LOG_INF("Finished flushing socket for doc [" << _docKey << ']');
}
// Terminate properly while we can.
LOG_DBG("Terminating child with reason: [" << _closeReason << ']');
terminateChild(_closeReason);
// Stop to mark it done and cleanup.
_poll->stop();
#if !MOBILEAPP
if (dataLoss || _docState.disconnected() == DocumentState::Disconnected::Unexpected)
{
// Quarantine the last copy, if different.
LOG_WRN((dataLoss ? "Data loss " : "Crash ")
<< "detected, will quarantine last version of [" << getDocKey()
<< "] if necessary. Quarantine enabled: "
<< (_quarantine && _quarantine->isEnabled())
<< ", Storage available: " << bool(_storage));
if (_storage && _quarantine)
{
const std::string uploading = _storage->getRootFilePathUploading();
if (FileUtil::Stat(uploading).exists())
{
LOG_WRN("Quarantining the .uploading file: " << uploading);
_quarantine->quarantineFile(uploading);
}
else
{
const std::string upload = _storage->getRootFilePathToUpload();
if (FileUtil::Stat(upload).exists())
{
LOG_WRN("Quarantining the .upload file: " << upload);
_quarantine->quarantineFile(upload);
}
else
{
// Fallback to quarantining the original document.
LOG_WRN("Quarantining the original document file: " << _filename);
_quarantine->quarantineFile(_storage->getRootFilePath());
}
}
}
}
// Async cleanup.
COOLWSD::doHousekeeping();
#endif
if (_tileCache)
_tileCache->clear();
LOG_INF("Finished docBroker polling thread for docKey [" << _docKey << ']');
}
bool DocumentBroker::isAlive() const
{
if (!_stop || _poll->isAlive())
return true; // Polling thread not started or still running.
// Shouldn't have live child process outside of the polling thread.
return _childProcess && _childProcess->isAlive();
}
DocumentBroker::~DocumentBroker()
{
ASSERT_CORRECT_THREAD();
LOG_INF("~DocumentBroker [" << _docKey << "] destroyed with " << _sessions.size()
<< " sessions left");
// Do this early - to avoid operating on _childProcess from two threads.
_poll->joinThread();
for (const auto& sessionIt : _sessions)
{
if (sessionIt.second->isLive())
{
LOG_WRN("Destroying DocumentBroker ["
<< _docKey << "] while having " << _sessions.size()
<< " unremoved sessions, at least one is still live");
break;
}
}
// Need to first make sure the child exited, socket closed,
// and thread finished before we are destroyed.
_childProcess.reset();
#if !MOBILEAPP
// Remove from the admin last, to avoid racing the next test.
_admin.rmDoc(_docKey);
#endif
if (_unitWsd)
{
_unitWsd->DocBrokerDestroy(_docKey);
}
}
void DocumentBroker::joinThread()
{
_poll->joinThread();
}
void DocumentBroker::stop(const std::string& reason)
{
if (_closeReason.empty() || _closeReason == reason)
{
LOG_DBG("Stopping DocumentBroker for docKey [" << _docKey << "] with reason: " << reason);
_closeReason = reason; // used later in the polling loop
}
else
{
LOG_DBG("Stopping DocumentBroker for docKey ["
<< _docKey << "] with existing close reason: " << _closeReason
<< " (ignoring requested reason: " << reason << ')');
}
_stop = true;
_poll->wakeup();
}
bool DocumentBroker::downloadAdvance(const std::string& jailId, const Poco::URI& uriPublic,
std::unique_ptr<WopiStorage::WOPIFileInfo> wopiFileInfo)
{
ASSERT_CORRECT_THREAD();
LOG_INF("Loading [" << _docKey << "] ahead-of-time in jail [" << jailId << ']');
assert(!_docState.isMarkedToDestroy() && "MarkedToDestroy while downloading ahead-of-time");
assert(_storage == nullptr &&
"Unexpected to find storage created while downloading ahead-of-time");
return download(/*session=*/nullptr, jailId, uriPublic, std::move(wopiFileInfo));
}
bool DocumentBroker::download(
const std::shared_ptr<ClientSession>& session, const std::string& jailId,
const Poco::URI& uriPublic,
[[maybe_unused]] std::unique_ptr<WopiStorage::WOPIFileInfo> wopiFileInfo)
{
ASSERT_CORRECT_THREAD();
const std::string sessionId = session ? session->getId() : "000";
LOG_INF("Loading [" << _docKey << "] for session [" << sessionId << "] in jail [" << jailId
<< ']');
if (_unitWsd)
{
bool result;
if (_unitWsd->filterLoad(sessionId, jailId, result))
return result;
}
if (_docState.isMarkedToDestroy())
{
// Tearing down.
LOG_WRN("Will not load document marked to destroy. DocKey: [" << _docKey << "].");
return false;
}
_jailId = jailId;
// The URL is the publicly visible one, not visible in the chroot jail.
// We need to map it to a jailed path and copy the file there.
// /tmp/user/docs/<dirName>, root under getJailRoot()
const Poco::Path jailPath(JAILED_DOCUMENT_ROOT, Util::rng::getFilename(16));
const std::string jailRoot = getJailRoot();
LOG_INF("JailPath for docKey [" << _docKey << "]: [" << jailPath.toString() << "], jailRoot: ["
<< jailRoot << ']');
bool firstInstance = false;
if (_storage == nullptr)
{
_docState.setStatus(DocumentState::Status::Downloading);
// Pass the public URI to storage as it needs to load using the token
// and other storage-specific data provided in the URI.
LOG_DBG("Creating new storage instance for URI ["
<< COOLWSD::anonymizeUrl(uriPublic.toString()) << ']');
try
{
_storage = StorageBase::create(uriPublic, jailRoot, jailPath.toString(),
/*takeOwnership=*/isConvertTo());
}
catch (...)
{
if (session)
session->sendMessage("loadstorage: failed");
throw;
}
if (_storage == nullptr)
{
// We should get an exception, not null.
LOG_ERR("Failed to create Storage instance for [" << _docKey << "] in "
<< jailPath.toString());
return false;
}
firstInstance = true;
}
LOG_ASSERT(_storage);
// Call the storage specific fileinfo functions
std::string templateSource;
#if !MOBILEAPP
std::chrono::milliseconds checkFileInfoCallDurationMs = std::chrono::milliseconds::zero();
WopiStorage* wopiStorage = dynamic_cast<WopiStorage*>(_storage.get());
if (wopiStorage != nullptr)
{
LOG_DBG("CheckFileInfo for docKey [" << _docKey << ']');
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
if (!wopiFileInfo)
{
auto poller = std::make_shared<TerminatingPoll>("CFISynReqPoll");
poller->startThread();
CheckFileInfo checkFileInfo(poller, session->getPublicUri(), [](CheckFileInfo&) {});
checkFileInfo.checkFileInfoSync(RedirectionLimit);
wopiFileInfo = checkFileInfo.wopiFileInfo(session->getPublicUri());
if (!wopiFileInfo)
{
throw std::runtime_error(
"CheckFileInfo failed or timed out while adding session #" + session->getId());
}
}
wopiStorage->handleWOPIFileInfo(*wopiFileInfo, *_lockCtx);
checkFileInfoCallDurationMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start);
if (session)
{
templateSource =
updateSessionWithWopiInfo(session, wopiStorage, std::move(wopiFileInfo));
}
}
else
#endif
{
LocalStorage* localStorage = dynamic_cast<LocalStorage*>(_storage.get());
if (localStorage != nullptr)
{
std::unique_ptr<LocalStorage::LocalFileInfo> localfileinfo =
localStorage->getLocalFileInfo();
_isViewFileExtension = COOLWSD::IsViewFileExtension(localStorage->getFileExtension());
if (session)
{
if (_isViewFileExtension)
{
LOG_DBG("Setting session [" << sessionId << "] as readonly");
session->setReadOnly(true);
if (_isViewFileExtension)
{
LOG_DBG("Allow session ["
<< sessionId << "] to change comments on document with extension ["
<< localStorage->getFileExtension() << ']');
session->setAllowChangeComments(true);
}
// Related to fix for issue #5887: only send a read-only
// message for "view file extension" document types
session->sendFileMode(session->isReadOnly(), session->isAllowChangeComments());
}
else if (Util::isMobileApp())
{
// Fix issue #5887 by assuming that documents are writable on iOS and Android
// The iOS and Android app saves directly to local disk so, other than for
// "view file extension" document types or other cases that
// I am missing, we can assume the document is writable until
// a write failure occurs.
LOG_DBG("Setting session [" << sessionId
<< "] to writable and allowing comments");
session->setWritable(true);
session->setReadOnly(false);
session->setAllowChangeComments(true);
}
session->setUserId(localfileinfo->getUserId());
session->setUserName(localfileinfo->getUsername());
}
}
}
if (session)
{
LOG_DBG("Setting username ["
<< COOLWSD::anonymizeUsername(session->getUserName()) << "] and userId ["
<< COOLWSD::anonymizeUsername(session->getUserId()) << "] for session ["
<< sessionId << "] with canonical id " << session->getCanonicalViewId());
}
// Basic file information was stored by the above getWOPIFileInfo() or getLocalFileInfo() calls
const StorageBase::FileInfo fileInfo = _storage->getFileInfo();
if (!fileInfo.isValid())
{
LOG_ERR("Invalid fileinfo for URI [" << uriPublic.toString() << ']');
return false;
}