forked from CollaboraOnline/online
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClientSession.cpp
2523 lines (2268 loc) · 91.7 KB
/
ClientSession.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 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 "ClientSession.hpp"
#include <fstream>
#include <ios>
#include <sstream>
#include <memory>
#include <unordered_map>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>
#include <Poco/JSON/Object.h>
#include "DocumentBroker.hpp"
#include "COOLWSD.hpp"
#include <common/Common.hpp>
#include <common/JsonUtil.hpp>
#include <common/Log.hpp>
#include <common/Protocol.hpp>
#include <common/Clipboard.hpp>
#include <common/Session.hpp>
#include <common/TraceEvent.hpp>
#include <common/Util.hpp>
#include <common/CommandControl.hpp>
#if !MOBILEAPP
#include <net/HttpHelper.hpp>
#endif
using namespace COOLProtocol;
static constexpr int SYNTHETIC_COOL_PID_OFFSET = 10000000;
using Poco::Path;
// rotates regularly
const int ClipboardTokenLengthBytes = 16;
// home-use, disabled by default.
const int ProxyAccessTokenLengthBytes = 32;
static std::mutex GlobalSessionMapMutex;
static std::unordered_map<std::string, std::weak_ptr<ClientSession>> GlobalSessionMap;
ClientSession::ClientSession(
const std::shared_ptr<ProtocolHandlerInterface>& ws,
const std::string& id,
const std::shared_ptr<DocumentBroker>& docBroker,
const Poco::URI& uriPublic,
const bool readOnly,
const RequestDetails &requestDetails) :
Session(ws, "ToClient-" + id, id, readOnly),
_docBroker(docBroker),
_uriPublic(uriPublic),
_auth(Authorization::create(uriPublic)),
_isDocumentOwner(false),
_state(SessionState::DETACHED),
_keyEvents(1),
_clientVisibleArea(0, 0, 0, 0),
_splitX(0),
_splitY(0),
_clientSelectedPart(-1),
_clientSelectedMode(0),
_tileWidthPixel(0),
_tileHeightPixel(0),
_tileWidthTwips(0),
_tileHeightTwips(0),
_kitViewId(-1),
_serverURL(requestDetails),
_isTextDocument(false)
{
const std::size_t curConnections = ++COOLWSD::NumConnections;
LOG_INF("ClientSession ctor [" << getName() << "] for URI: [" << _uriPublic.toString()
<< "], current number of connections: " << curConnections);
// populate with random values.
for (auto it : _clipboardKeys)
rotateClipboardKey(false);
// get timestamp set
setState(SessionState::DETACHED);
// Emit metadata Trace Events for the synthetic pid used for the Trace Events coming in from the
// client's cool, and for its dummy thread.
TraceEvent::emitOneRecordingIfEnabled("{\"name\":\"process_name\",\"ph\":\"M\",\"args\":{\"name\":\""
"cool-" + id
+ "\"},\"pid\":"
+ std::to_string(getpid() + SYNTHETIC_COOL_PID_OFFSET)
+ ",\"tid\":1},\n");
TraceEvent::emitOneRecordingIfEnabled("{\"name\":\"thread_name\",\"ph\":\"M\",\"args\":{\"name\":\"JS\"},\"pid\":"
+ std::to_string(getpid() + SYNTHETIC_COOL_PID_OFFSET)
+ ",\"tid\":1},\n");
}
// Can't take a reference in the constructor.
void ClientSession::construct()
{
std::unique_lock<std::mutex> lock(GlobalSessionMapMutex);
MessageHandlerInterface::initialize();
GlobalSessionMap[getId()] = client_from_this();
}
ClientSession::~ClientSession()
{
const std::size_t curConnections = --COOLWSD::NumConnections;
LOG_INF("~ClientSession dtor [" << getName() << "], current number of connections: " << curConnections);
std::unique_lock<std::mutex> lock(GlobalSessionMapMutex);
GlobalSessionMap.erase(getId());
}
void ClientSession::setState(SessionState newState)
{
LOG_TRC("transition from " << name(_state) << " to " << name(newState));
// we can get incoming messages while our disconnection is in transit.
if (_state == SessionState::WAIT_DISCONNECT)
{
if (newState != SessionState::WAIT_DISCONNECT)
LOG_WRN("Unusual race - attempts to transition from " << name(_state) << " to "
<< name(newState));
return;
}
switch (newState)
{
case SessionState::DETACHED:
assert(_state == SessionState::DETACHED);
break;
case SessionState::LOADING:
assert(_state == SessionState::DETACHED);
break;
case SessionState::LIVE:
assert(_state == SessionState::LIVE ||
_state == SessionState::LOADING);
break;
case SessionState::WAIT_DISCONNECT:
assert(_state == SessionState::LOADING ||
_state == SessionState::LIVE);
break;
}
_state = newState;
_lastStateTime = std::chrono::steady_clock::now();
}
bool ClientSession::disconnectFromKit()
{
assert(_state != SessionState::WAIT_DISCONNECT);
auto docBroker = getDocumentBroker();
if (_state == SessionState::LIVE && docBroker)
{
setState(SessionState::WAIT_DISCONNECT);
#ifndef IOS
LOG_TRC("request/rescue clipboard on disconnect for " << getId());
// rescue clipboard before shutdown.
docBroker->forwardToChild(client_from_this(), "getclipboard");
#endif
// handshake nicely; so wait for 'disconnected'
docBroker->forwardToChild(client_from_this(), "disconnect");
return false;
}
return true; // just get on with it
}
// Allow 20secs for the clipboard and disconnection to come.
bool ClientSession::staleWaitDisconnect(const std::chrono::steady_clock::time_point &now)
{
if (_state != SessionState::WAIT_DISCONNECT)
return false;
return std::chrono::duration_cast<std::chrono::seconds>(now - _lastStateTime).count() >= 20;
}
void ClientSession::rotateClipboardKey(bool notifyClient)
{
if (_state == SessionState::WAIT_DISCONNECT)
return;
_clipboardKeys[1] = _clipboardKeys[0];
_clipboardKeys[0] = Util::rng::getHardRandomHexString(
ClipboardTokenLengthBytes);
LOG_TRC("Clipboard key on [" << getId() << "] set to " << _clipboardKeys[0] <<
" last was " << _clipboardKeys[1]);
if (notifyClient)
sendTextFrame("clipboardkey: " + _clipboardKeys[0]);
}
std::string ClientSession::getClipboardURI(bool encode)
{
if (_wopiFileInfo && _wopiFileInfo->getDisableCopy())
return std::string();
return createPublicURI("clipboard", _clipboardKeys[0], encode);
}
std::string ClientSession::createPublicURI(const std::string& subPath, const std::string& tag, bool encode)
{
Poco::URI wopiSrc = getDocumentBroker()->getPublicUri();
wopiSrc.setQueryParameters(Poco::URI::QueryParameters());
const std::string encodedFrom = Util::encodeURIComponent(wopiSrc.toString());
std::string meta = _serverURL.getSubURLForEndpoint(
"/cool/" + subPath + "?WOPISrc=" + encodedFrom +
"&ServerId=" + Util::getProcessIdentifier() +
"&ViewId=" + std::to_string(getKitViewId()) +
"&Tag=" + tag);
if (!encode)
return meta;
return Util::encodeURIComponent(meta);
}
bool ClientSession::matchesClipboardKeys(const std::string &/*viewId*/, const std::string &tag)
{
if (tag.empty())
{
LOG_ERR("Invalid, empty clipboard tag");
return false;
}
// FIXME: check viewId for paranoia if we can.
return std::any_of(std::begin(_clipboardKeys), std::end(_clipboardKeys),
[&tag](const std::string& it) { return it == tag; });
}
void ClientSession::handleClipboardRequest(DocumentBroker::ClipboardRequest type,
const std::shared_ptr<StreamSocket> &socket,
const std::string &tag,
const std::shared_ptr<std::string> &data)
{
// Move the socket into our DocBroker.
auto docBroker = getDocumentBroker();
docBroker->addSocketToPoll(socket);
if (_state == SessionState::WAIT_DISCONNECT)
{
LOG_TRC("Clipboard request " << tag << " for disconnecting session");
if (docBroker->lookupSendClipboardTag(socket, tag, false))
return; // the getclipboard already completed.
if (type == DocumentBroker::CLIP_REQUEST_SET)
{
#if !MOBILEAPP
HttpHelper::sendErrorAndShutdown(400, socket);
#endif
}
else // will be handled during shutdown
{
LOG_TRC("Clipboard request " << tag << " queued for shutdown");
_clipSockets.push_back(socket);
}
}
std::string specific;
if (type == DocumentBroker::CLIP_REQUEST_GET_RICH_HTML_ONLY)
specific = " text/html";
if (type != DocumentBroker::CLIP_REQUEST_SET)
{
if (_wopiFileInfo && _wopiFileInfo->getDisableCopy())
{
// Unsupported clipboard request.
LOG_ERR("Unsupported Clipboard Request from socket #" << socket->getFD()
<< ". Terminating connection.");
std::ostringstream oss;
oss << "HTTP/1.1 403 Forbidden\r\n"
<< "Date: " << Util::getHttpTimeNow() << "\r\n"
<< "User-Agent: " << WOPI_AGENT_STRING << "\r\n"
<< "Content-Length: 0\r\n"
<< "Connection: close\r\n"
<< "\r\n";
socket->send(oss.str());
socket->closeConnection(); // Shutdown socket.
socket->ignoreInput();
return;
}
LOG_TRC("Session [" << getId() << "] sending getclipboard" + specific);
docBroker->forwardToChild(client_from_this(), "getclipboard" + specific);
_clipSockets.push_back(socket);
}
else // REQUEST_SET
{
// FIXME: manage memory more efficiently.
LOG_TRC("Session [" << getId() << "] sending setclipboard");
if (data.get())
{
preProcessSetClipboardPayload(*data);
docBroker->forwardToChild(client_from_this(), "setclipboard\n" + *data, true);
// FIXME: work harder for error detection ?
std::ostringstream oss;
oss << "HTTP/1.1 200 OK\r\n"
<< "Date: " << Util::getHttpTimeNow() << "\r\n"
<< "User-Agent: " << WOPI_AGENT_STRING << "\r\n"
<< "Content-Length: 0\r\n"
<< "Connection: close\r\n"
<< "\r\n";
socket->send(oss.str());
socket->shutdown();
}
else
{
#if !MOBILEAPP
HttpHelper::sendErrorAndShutdown(400, socket);
#endif
}
}
}
bool ClientSession::_handleInput(const char *buffer, int length)
{
LOG_TRC("handling incoming [" << getAbbreviatedMessage(buffer, length) << ']');
const std::string firstLine = getFirstLine(buffer, length);
const StringVector tokens = StringVector::tokenize(firstLine.data(), firstLine.size());
std::shared_ptr<DocumentBroker> docBroker = getDocumentBroker();
if (!docBroker || docBroker->isMarkedToDestroy())
{
LOG_ERR("No DocBroker found, or DocBroker marked to be destroyed. Terminating session " << getName());
return false;
}
if (tokens.size() < 1)
{
sendTextFrameAndLogError("error: cmd=empty kind=unknown");
return false;
}
if (tokens.equals(0, "DEBUG"))
{
LOG_DBG("From client: " << std::string(buffer, length).substr(strlen("DEBUG") + 1));
return false;
}
else if (tokens.equals(0, "ERROR"))
{
LOG_ERR("From client: " << std::string(buffer, length).substr(strlen("ERROR") + 1));
return false;
}
else if (tokens.equals(0, "TRACEEVENT"))
{
if (COOLWSD::EnableTraceEventLogging)
{
if (_performanceCounterEpoch == 0)
{
static bool warnedOnce = false;
if (!warnedOnce)
{
LOG_WRN("For some reason the _performanceCounterEpoch is still zero, ignoring TRACEEVENT from cool as the timestamp would be garbage");
warnedOnce = true;
}
return false;
} else if (_performanceCounterEpoch < 1620000000000000ull || _performanceCounterEpoch > 2000000000000000ull)
{
static bool warnedOnce = false;
if (!warnedOnce)
{
LOG_WRN("For some reason the _performanceCounterEpoch is bogus, ignoring TRACEEVENT from cool as the timestamp would be garbage");
warnedOnce = true;
}
return false;
}
if (tokens.size() >= 4)
{
// The intent is that when doing Trace Event generation, the web browser client and
// the server run on the same machine, so there is no clock skew problem.
std::string name;
std::string ph;
uint64_t ts;
if (getTokenString(tokens[1], "name", name) &&
getTokenString(tokens[2], "ph", ph) &&
getTokenUInt64(tokens[3], "ts", ts))
{
std::string args;
if (tokens.size() >= 5 && getTokenString(tokens, "args", args))
args = ",\"args\":" + args;
uint64_t id, tid;
uint64_t dur;
if (ph == "i")
{
COOLWSD::writeTraceEventRecording("{\"name\":\""
+ name
+ "\",\"ph\":\"i\""
+ args
+ ",\"ts\":"
+ std::to_string(ts + _performanceCounterEpoch)
+ ",\"pid\":"
+ std::to_string(getpid() + SYNTHETIC_COOL_PID_OFFSET)
+ ",\"tid\":1},\n");
}
else if ((ph == "S" || ph == "F") &&
getTokenUInt64(tokens[4], "id", id),
getTokenUInt64(tokens[5], "tid", tid))
{
COOLWSD::writeTraceEventRecording("{\"name\":\""
+ name
+ "\",\"ph\":\""
+ ph
+ "\""
+ args
+ ",\"ts\":"
+ std::to_string(ts + _performanceCounterEpoch)
+ ",\"pid\":"
+ std::to_string(getpid() + SYNTHETIC_COOL_PID_OFFSET)
+ ",\"tid\":"
+ std::to_string(tid)
+ ",\"id\":"
+ std::to_string(id)
+ "},\n");
}
else if (ph == "X" &&
getTokenUInt64(tokens[4], "dur", dur))
{
COOLWSD::writeTraceEventRecording("{\"name\":\""
+ name
+ "\",\"ph\":\"X\""
+ args
+ ",\"ts\":"
+ std::to_string(ts + _performanceCounterEpoch)
+ ",\"pid\":"
+ std::to_string(getpid() + SYNTHETIC_COOL_PID_OFFSET)
+ ",\"tid\":1"
",\"dur\":"
+ std::to_string(dur)
+ "},\n");
}
else
{
LOG_WRN("Unrecognized TRACEEVENT message");
}
}
}
else
LOG_WRN("Unrecognized TRACEEVENT message");
}
return false;
}
COOLWSD::dumpIncomingTrace(docBroker->getJailId(), getId(), firstLine);
if (COOLProtocol::tokenIndicatesUserInteraction(tokens[0]))
{
// Keep track of timestamps of incoming client messages that indicate user activity.
updateLastActivityTime();
docBroker->updateLastActivityTime();
if (COOLProtocol::tokenIndicatesDocumentModification(tokens[0]))
{
docBroker->updateLastModifyingActivityTime();
}
if (isEditable() && isViewLoaded())
{
assert(!inWaitDisconnected() && "A writable view can't be waiting disconnection.");
docBroker->updateEditingSessionId(getId());
}
}
if (tokens.equals(0, "coolclient"))
{
if (tokens.size() < 2)
{
sendTextFrameAndLogError("error: cmd=coolclient kind=badprotocolversion");
return false;
}
const std::tuple<int, int, std::string> versionTuple = ParseVersion(tokens[1]);
if (std::get<0>(versionTuple) != ProtocolMajorVersionNumber ||
std::get<1>(versionTuple) != ProtocolMinorVersionNumber)
{
sendTextFrameAndLogError("error: cmd=coolclient kind=badprotocolversion");
return false;
}
_performanceCounterEpoch = 0;
if (tokens.size() >= 4)
{
std::string timestamp = tokens[2];
const char* str = timestamp.c_str();
char* endptr = nullptr;
uint64_t ts = strtoull(str, &endptr, 10);
if (*endptr == '\0')
{
std::string perfcounter = tokens[3].data();
str = perfcounter.data();
endptr = nullptr;
double counter = strtod(str, &endptr);
if (*endptr == '\0' && counter > 0 &&
(counter < (double)(std::numeric_limits<uint64_t>::max() / 1000)))
{
// Now we know how to translate from the client's performance.now() values to
// microseconds since the epoch.
_performanceCounterEpoch = ts * 1000 - (uint64_t)(counter * 1000);
LOG_INF("Client timestamps: Date.now():" << ts <<
", performance.now():" << counter
<< " => " << _performanceCounterEpoch);
}
}
}
// Send COOL version information
sendTextFrame("coolserver " + Util::getVersionJSON(EnableExperimental));
// Send LOKit version information
sendTextFrame("lokitversion " + COOLWSD::LOKitVersion);
// If Trace Event generation and logging is enabled (whether it can be turned on), tell it
// to cool
if (COOLWSD::EnableTraceEventLogging)
sendTextFrame("enabletraceeventlogging yes");
#if !MOBILEAPP
// If it is not mobile, it must be Linux (for now).
sendTextFrame(std::string("osinfo ") + Util::getLinuxVersion());
#endif
// Send clipboard key
rotateClipboardKey(true);
return true;
}
if (tokens.equals(0, "infobar"))
{
#if !MOBILEAPP
std::string infobar;
{
std::lock_guard<std::mutex> lock(COOLWSD::FetchUpdateMutex);
infobar = COOLWSD::LatestVersion;
}
if (!infobar.empty())
sendTextFrame("infobar: " + infobar);
#endif
}
else if (tokens.equals(0, "jserror") || tokens.equals(0, "jsexception"))
{
LOG_ERR(std::string(buffer, length));
return true;
}
else if (tokens.equals(0, "load"))
{
if (getDocURL() != "")
{
sendTextFrameAndLogError("error: cmd=load kind=docalreadyloaded");
return false;
}
return loadDocument(buffer, length, tokens, docBroker);
}
else if (tokens.equals(0, "loadwithpassword"))
{
std::string docPassword;
if (tokens.size() > 1 && getTokenString(tokens[1], "password", docPassword))
{
if (!docPassword.empty())
{
setHaveDocPassword(true);
setDocPassword(docPassword);
}
}
return loadDocument(buffer, length, tokens, docBroker);
}
else if (getDocURL().empty())
{
sendTextFrameAndLogError("error: cmd=" + tokens[0] + " kind=nodocloaded");
return false;
}
else if (tokens.equals(0, "canceltiles"))
{
docBroker->cancelTileRequests(client_from_this());
return true;
}
else if (tokens.equals(0, "commandvalues"))
{
return getCommandValues(buffer, length, tokens, docBroker);
}
else if (tokens.equals(0, "closedocument"))
{
// If this session is the owner of the file & 'EnableOwnerTermination' feature
// is turned on by WOPI, let it close all sessions
if (isDocumentOwner() && _wopiFileInfo && _wopiFileInfo->getEnableOwnerTermination())
{
LOG_DBG("Session [" << getId() << "] requested owner termination");
docBroker->closeDocument("ownertermination");
}
else if (docBroker->isDocumentChangedInStorage())
{
LOG_DBG("Document marked as changed in storage and user ["
<< getUserId() << ", " << getUserName()
<< "] wants to refresh the document for all.");
docBroker->stop("documentconflict " + getUserName());
}
return true;
}
else if (tokens.equals(0, "versionrestore"))
{
if (tokens.size() > 1 && tokens.equals(1, "prerestore"))
{
// green signal to WOPI host to restore the version *after* saving
// any unsaved changes, if any, to the storage
docBroker->closeDocument("versionrestore: prerestore_ack");
}
}
else if (tokens.equals(0, "partpagerectangles"))
{
// We don't support partpagerectangles any more, will be removed in the
// next version
sendTextFrame("partpagerectangles: ");
return true;
}
else if (tokens.equals(0, "ping"))
{
std::string count = std::to_string(docBroker->getRenderedTileCount());
sendTextFrame("pong rendercount=" + count);
return true;
}
else if (tokens.equals(0, "renderfont"))
{
return sendFontRendering(buffer, length, tokens, docBroker);
}
else if (tokens.equals(0, "status") || tokens.equals(0, "statusupdate"))
{
assert(firstLine.size() == static_cast<std::size_t>(length));
return forwardToChild(firstLine, docBroker);
}
else if (tokens.equals(0, "tile"))
{
return sendTile(buffer, length, tokens, docBroker);
}
else if (tokens.equals(0, "tilecombine"))
{
return sendCombinedTiles(buffer, length, tokens, docBroker);
}
else if (tokens.equals(0, "save"))
{
// If we can't write to Storage, there is no point in saving.
if (!isWritable())
{
LOG_WRN("Session [" << getId() << "] on document [" << docBroker->getDocKey()
<< "] has no write permissions in Storage and cannot save.");
sendTextFrameAndLogError("error: cmd=save kind=savefailed");
}
else
{
// Don't save unmodified docs by default.
int dontSaveIfUnmodified = 1;
int dontTerminateEdit = 1;
std::string extendedData;
// We expect at most 3 arguments.
for (int i = 0; i < 3; ++i)
{
// +1 to skip the command token.
const StringVector attr = StringVector::tokenize(tokens[i + 1], '=');
if (attr.size() == 2)
{
if (attr[0] == "dontTerminateEdit")
COOLProtocol::stringToInteger(attr[1], dontTerminateEdit);
else if (attr[0] == "dontSaveIfUnmodified")
COOLProtocol::stringToInteger(attr[1], dontSaveIfUnmodified);
else if (attr[0] == "extendedData")
{
std::string decoded;
Poco::URI::decode(attr[1], decoded);
extendedData = decoded;
}
}
}
constexpr bool isAutosave = false;
constexpr bool isExitSave = false;
docBroker->sendUnoSave(client_from_this(), dontTerminateEdit != 0,
dontSaveIfUnmodified != 0, isAutosave, isExitSave, extendedData);
}
}
else if (tokens.equals(0, "savetostorage"))
{
// By default savetostorage implies forcing.
int force = 1;
if (tokens.size() > 1)
getTokenInteger(tokens[1], "force", force);
// The savetostorage command is really only used to resolve save conflicts
// and it seems to always have force=1. However, we should still honor the
// contract and do as told, not as we expect the API to be used. Use force if provided.
docBroker->uploadToStorage(client_from_this(), force);
}
else if (tokens.equals(0, "clientvisiblearea"))
{
int x;
int y;
int width;
int height;
if ((tokens.size() != 5 && tokens.size() != 7) ||
!getTokenInteger(tokens[1], "x", x) ||
!getTokenInteger(tokens[2], "y", y) ||
!getTokenInteger(tokens[3], "width", width) ||
!getTokenInteger(tokens[4], "height", height))
{
// Be forgiving and log instead of disconnecting.
// sendTextFrameAndLogError("error: cmd=clientvisiblearea kind=syntax");
LOG_WRN("Invalid syntax for '" << tokens[0] << "' message: [" << firstLine << ']');
return true;
}
else
{
if (tokens.size() == 7)
{
int splitX, splitY;
if (!getTokenInteger(tokens[5], "splitx", splitX) ||
!getTokenInteger(tokens[6], "splity", splitY))
{
LOG_WRN("Invalid syntax for '" << tokens[0] << "' message: [" << firstLine << ']');
return true;
}
_splitX = splitX;
_splitY = splitY;
}
_clientVisibleArea = Util::Rectangle(x, y, width, height);
resetWireIdMap();
return forwardToChild(std::string(buffer, length), docBroker);
}
}
else if (tokens.equals(0, "setclientpart"))
{
if(!_isTextDocument)
{
int temp;
if (tokens.size() != 2 ||
!getTokenInteger(tokens[1], "part", temp))
{
sendTextFrameAndLogError("error: cmd=setclientpart kind=syntax");
return false;
}
else
{
_clientSelectedPart = temp;
resetWireIdMap();
return forwardToChild(std::string(buffer, length), docBroker);
}
}
}
else if (tokens.equals(0, "selectclientpart"))
{
if(!_isTextDocument)
{
int part;
int how;
if (tokens.size() != 3 ||
!getTokenInteger(tokens[1], "part", part) ||
!getTokenInteger(tokens[2], "how", how))
{
sendTextFrameAndLogError("error: cmd=selectclientpart kind=syntax");
return false;
}
else
{
return forwardToChild(std::string(buffer, length), docBroker);
}
}
}
else if (tokens.equals(0, "moveselectedclientparts"))
{
if(!_isTextDocument)
{
int nPosition;
if (tokens.size() != 2 ||
!getTokenInteger(tokens[1], "position", nPosition))
{
sendTextFrameAndLogError("error: cmd=moveselectedclientparts kind=syntax");
return false;
}
else
{
return forwardToChild(std::string(buffer, length), docBroker);
}
}
}
else if (tokens.equals(0, "clientzoom"))
{
int tilePixelWidth, tilePixelHeight, tileTwipWidth, tileTwipHeight;
if (tokens.size() != 5 ||
!getTokenInteger(tokens[1], "tilepixelwidth", tilePixelWidth) ||
!getTokenInteger(tokens[2], "tilepixelheight", tilePixelHeight) ||
!getTokenInteger(tokens[3], "tiletwipwidth", tileTwipWidth) ||
!getTokenInteger(tokens[4], "tiletwipheight", tileTwipHeight))
{
// Be forgiving and log instead of disconnecting.
// sendTextFrameAndLogError("error: cmd=clientzoom kind=syntax");
LOG_WRN("Invalid syntax for '" << tokens[0] << "' message: [" << firstLine << ']');
return true;
}
else
{
_tileWidthPixel = tilePixelWidth;
_tileHeightPixel = tilePixelHeight;
_tileWidthTwips = tileTwipWidth;
_tileHeightTwips = tileTwipHeight;
resetWireIdMap();
return forwardToChild(std::string(buffer, length), docBroker);
}
}
else if (tokens.equals(0, "tileprocessed"))
{
std::string tileID;
if (tokens.size() != 2 ||
!getTokenString(tokens[1], "tile", tileID))
{
// Be forgiving and log instead of disconnecting.
// sendTextFrameAndLogError("error: cmd=tileprocessed kind=syntax");
LOG_WRN("Invalid syntax for '" << tokens[0] << "' message: [" << firstLine << ']');
return true;
}
auto iter = std::find_if(_tilesOnFly.begin(), _tilesOnFly.end(),
[&tileID](const std::pair<std::string, std::chrono::steady_clock::time_point>& curTile)
{
return curTile.first == tileID;
});
if(iter != _tilesOnFly.end())
_tilesOnFly.erase(iter);
else
LOG_INF("Tileprocessed message with an unknown tile ID '" << tileID << "' from session " << getId());
docBroker->sendRequestedTiles(client_from_this());
return true;
}
else if (tokens.equals(0, "removesession"))
{
if (tokens.size() > 1 && (_isDocumentOwner || !isReadOnly()))
{
std::string sessionId = Util::encodeId(std::stoi(tokens[1]), 4);
docBroker->broadcastMessage(firstLine);
docBroker->removeSession(client_from_this());
}
else
LOG_WRN("Readonly session '" << getId() << "' trying to kill another view");
}
else if (tokens.equals(0, "renamefile"))
{
std::string encodedWopiFilename;
if (tokens.size() < 2 || !getTokenString(tokens[1], "filename", encodedWopiFilename))
{
LOG_ERR("Bad syntax for: " << firstLine);
sendTextFrameAndLogError("error: cmd=renamefile kind=syntax");
return false;
}
std::string wopiFilename;
Poco::URI::decode(encodedWopiFilename, wopiFilename);
const std::string error =
docBroker->handleRenameFileCommand(getId(), std::move(wopiFilename));
if (!error.empty())
{
sendTextFrameAndLogError(error);
return false;
}
return true;
}
else if (tokens.equals(0, "dialogevent") ||
tokens.equals(0, "formfieldevent") ||
tokens.equals(0, "sallogoverride") ||
tokens.equals(0, "contentcontrolevent"))
{
return forwardToChild(firstLine, docBroker);
}
else if (tokens.equals(0, "loggingleveloverride"))
{
if (tokens.size() > 0)
{
// Note that these LOG_INF() messages won't necessarily show up if the current logging
// level is higher, of course.
if (tokens.equals(1, "default"))
{
LOG_INF("Thread-local logging level being set to default ["
<< Log::getLevel()
<< "]");
Log::setThreadLocalLogLevel(Log::getLevel());
}
else
{
try
{
auto leastVerboseAllowed = Poco::Logger::parseLevel(COOLWSD::LeastVerboseLogLevelSettableFromClient);
auto mostVerboseAllowed = Poco::Logger::parseLevel(COOLWSD::MostVerboseLogLevelSettableFromClient);
if (tokens.equals(1, "verbose"))
{
LOG_INF("Client sets thread-local logging level to the most verbose allowed ["
<< COOLWSD::MostVerboseLogLevelSettableFromClient
<< "]");
Log::setThreadLocalLogLevel(COOLWSD::MostVerboseLogLevelSettableFromClient);
LOG_INF("Thread-local logging level was set to ["
<< COOLWSD::MostVerboseLogLevelSettableFromClient
<< "]");
}
else if (tokens.equals(1, "terse"))
{
LOG_INF("Client sets thread-local logging level to the least verbose allowed ["
<< COOLWSD::LeastVerboseLogLevelSettableFromClient
<< "]");
Log::setThreadLocalLogLevel(COOLWSD::LeastVerboseLogLevelSettableFromClient);
LOG_INF("Thread-local logging level was set to ["
<< COOLWSD::LeastVerboseLogLevelSettableFromClient
<< "]");
}
else
{
auto level = Poco::Logger::parseLevel(tokens[1]);
// Note that numerically the higher priority levels are lower in value.
if (level >= leastVerboseAllowed && level <= mostVerboseAllowed)
{
LOG_INF("Thread-local logging level being set to ["
<< tokens[1]
<< "]");
Log::setThreadLocalLogLevel(tokens[1]);
}
else
{
LOG_WRN("Client tries to set logging level to ["
<< tokens[1]
<< "] which is outside of bounds ["
<< COOLWSD::LeastVerboseLogLevelSettableFromClient << ","
<< COOLWSD::MostVerboseLogLevelSettableFromClient << "]");
}
}
}
catch (const Poco::Exception &e)
{
LOG_WRN("Exception while handling loggingleveloverride message: " << e.message());
}
}
}
}
else if (tokens.equals(0, "traceeventrecording"))
{
if (COOLWSD::getConfigValue<bool>("trace_event[@enable]", false))
{
if (tokens.size() > 0)
{
if (tokens.equals(1, "start"))
{
TraceEvent::startRecording();
LOG_INF("Trace Event recording in this WSD process turned on (might have been on already)");
}
else if (tokens.equals(1, "stop"))
{
TraceEvent::stopRecording();
LOG_INF("Trace Event recording in this WSD process turned off (might have been off already)");
}
}
forwardToChild(firstLine, docBroker);
}
return true;
}
else if (tokens.equals(0, "completefunction"))
{
return forwardToChild(std::string(buffer, length), docBroker);
}
else if (tokens.equals(0, "resetaccesstoken"))
{
if (tokens.size() != 2)
{
LOG_ERR("Bad syntax for: " << tokens[0]);
sendTextFrameAndLogError("error: cmd=resetaccesstoken kind=syntax");
return false;
}
_auth.resetAccessToken(tokens[1]);
return true;
}
else if (tokens.equals(0, "outlinestate") ||
tokens.equals(0, "downloadas") ||
tokens.equals(0, "getchildid") ||
tokens.equals(0, "gettextselection") ||
tokens.equals(0, "paste") ||
tokens.equals(0, "insertfile") ||
tokens.equals(0, "key") ||
tokens.equals(0, "textinput") ||
tokens.equals(0, "windowkey") ||
tokens.equals(0, "mouse") ||
tokens.equals(0, "windowmouse") ||
tokens.equals(0, "windowgesture") ||