Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RWebWindow.cxx
Go to the documentation of this file.
1// Author: Sergey Linev <s.linev@gsi.de>
2// Date: 2017-10-16
3// Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!
4
5/*************************************************************************
6 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
7 * All rights reserved. *
8 * *
9 * For the licensing terms see $ROOTSYS/LICENSE. *
10 * For the list of contributors see $ROOTSYS/README/CREDITS. *
11 *************************************************************************/
12
13#include <ROOT/RWebWindow.hxx>
14
16#include <ROOT/RLogger.hxx>
17
19#include "THttpCallArg.h"
20#include "TUrl.h"
21#include "TError.h"
22#include "TROOT.h"
23#include "TSystem.h"
24
25#include <cstring>
26#include <cstdlib>
27#include <utility>
28#include <assert.h>
29#include <algorithm>
30#include <fstream>
31
32// must be here because of defines
33#include "../../../core/foundation/res/ROOT/RSha256.hxx"
34
35using namespace ROOT;
36using namespace std::string_literals;
37
38//////////////////////////////////////////////////////////////////////////////////////////
39/// Destructor for WebConn
40/// Notify special HTTP request which blocks headless browser from exit
41
43{
44 if (fHold) {
45 fHold->SetTextContent("console.log('execute holder script'); if (window) setTimeout (window.close, 1000); if (window) window.close();");
46 fHold->NotifyCondition();
47 fHold.reset();
48 }
49}
50
51
52
53/** \class ROOT::RWebWindow
54\ingroup webdisplay
55
56Represents web window, which can be shown in web browser or any other supported environment
57
58Window can be configured to run either in the normal or in the batch (headless) mode.
59In second case no any graphical elements will be created. For the normal window one can configure geometry
60(width and height), which are applied when window shown.
61
62Each window can be shown several times (if allowed) in different places - either as the
63CEF (chromium embedded) window or in the standard web browser. When started, window will open and show
64HTML page, configured with RWebWindow::SetDefaultPage() method.
65
66Typically (but not necessarily) clients open web socket connection to the window and one can exchange data,
67using RWebWindow::Send() method and call-back function assigned via RWebWindow::SetDataCallBack().
68
69*/
70
71
72//////////////////////////////////////////////////////////////////////////////////////////
73/// RWebWindow constructor
74/// Should be defined here because of std::unique_ptr<RWebWindowWSHandler>
75
77{
78 fRequireAuthKey = RWebWindowWSHandler::GetBoolEnv("WebGui.OnetimeKey", 1) == 1; // does authentication key really required
79}
80
81//////////////////////////////////////////////////////////////////////////////////////////
82/// RWebWindow destructor
83/// Closes all connections and remove window from manager
84
86{
87 StopThread();
88
89 if (fMaster) {
90 std::vector<MasterConn> lst;
91 {
92 std::lock_guard<std::mutex> grd(fConnMutex);
93 std::swap(lst, fMasterConns);
94 }
95
96 for (auto &entry : lst)
97 fMaster->RemoveEmbedWindow(entry.connid, entry.channel);
98 fMaster.reset();
99 }
100
101 if (fWSHandler)
102 fWSHandler->SetDisabled();
103
104 if (fMgr) {
105
106 // make copy of all connections
107 auto lst = GetWindowConnections();
108
109 {
110 // clear connections vector under mutex
111 std::lock_guard<std::mutex> grd(fConnMutex);
112 fConn.clear();
113 fPendingConn.clear();
114 }
115
116 for (auto &conn : lst) {
117 conn->fActive = false;
118 for (auto &elem: conn->fEmbed)
119 elem.second->RemoveMasterConnection();
120 conn->fEmbed.clear();
121 }
122
123 fMgr->Unregister(*this);
124 }
125}
126
127//////////////////////////////////////////////////////////////////////////////////////////
128/// Configure window to show some of existing JSROOT panels
129/// It uses "file:rootui5sys/panel/panel.html" as default HTML page
130/// At the moment only FitPanel is existing
131
132void RWebWindow::SetPanelName(const std::string &name)
133{
134 {
135 std::lock_guard<std::mutex> grd(fConnMutex);
136 if (!fConn.empty()) {
137 R__LOG_ERROR(WebGUILog()) << "Cannot configure panel when connection exists";
138 return;
139 }
140 }
141
143 SetDefaultPage("file:rootui5sys/panel/panel.html");
144 if (fPanelName.find("localapp.") == 0)
145 SetUseCurrentDir(true);
146}
147
148//////////////////////////////////////////////////////////////////////////////////////////
149/// Assigns manager reference, window id and creates websocket handler, used for communication with the clients
150
151std::shared_ptr<RWebWindowWSHandler>
152RWebWindow::CreateWSHandler(std::shared_ptr<RWebWindowsManager> mgr, unsigned id, double tmout)
153{
154 fMgr = mgr;
155 fId = id;
156 fOperationTmout = tmout;
157
158 fSendMT = fMgr->IsUseSenderThreads();
159 fWSHandler = std::make_shared<RWebWindowWSHandler>(*this, Form("win%u", GetId()));
160
161 return fWSHandler;
162}
163
164//////////////////////////////////////////////////////////////////////////////////////////
165/// Return URL string to connect web window
166/// URL typically includes extra parameters required for connection with the window like
167/// `http://localhost:9635/win1/?key=<connection_key>#<session_key>`
168/// When \param remote is true, real HTTP server will be started automatically and
169/// widget can be connected from the web browser. If \param remote is false,
170/// HTTP server will not be started and window can be connected only from ROOT application itself.
171/// !!! WARNING - do not invoke this method without real need, each URL consumes resources in widget and in http server
172
173std::string RWebWindow::GetUrl(bool remote)
174{
175 return fMgr->GetUrl(*this, remote);
176}
177
178//////////////////////////////////////////////////////////////////////////////////////////
179/// Return THttpServer instance serving requests to the window
180
182{
183 return fMgr->GetServer();
184}
185
186//////////////////////////////////////////////////////////////////////////////////////////
187/// Show window in specified location
188/// \see ROOT::RWebWindowsManager::Show for more info
189/// \return (future) connection id (or 0 when fails)
190
192{
193 return fMgr->ShowWindow(*this, args);
194}
195
196//////////////////////////////////////////////////////////////////////////////////////////
197/// Start headless browser for specified window
198/// Normally only single instance is used, but many can be created
199/// See ROOT::RWebWindowsManager::Show() docu for more info
200/// returns (future) connection id (or 0 when fails)
201
202unsigned RWebWindow::MakeHeadless(bool create_new)
203{
204 unsigned connid = 0;
205 if (!create_new)
206 connid = FindHeadlessConnection();
207 if (!connid) {
208 RWebDisplayArgs args;
209 args.SetHeadless(true);
210 connid = fMgr->ShowWindow(*this, args);
211 }
212 return connid;
213}
214
215//////////////////////////////////////////////////////////////////////////////////////////
216/// Returns connection id of window running in headless mode
217/// This can be special connection which may run picture production jobs in background
218/// Connection to that job may not be initialized yet
219/// If connection does not exists, returns 0
220
222{
223 std::lock_guard<std::mutex> grd(fConnMutex);
224
225 for (auto &entry : fPendingConn) {
226 if (entry->fHeadlessMode)
227 return entry->fConnId;
228 }
229
230 for (auto &conn : fConn) {
231 if (conn->fHeadlessMode)
232 return conn->fConnId;
233 }
234
235 return 0;
236}
237
238//////////////////////////////////////////////////////////////////////////////////////////
239/// Returns first connection id where window is displayed
240/// It could be that connection(s) not yet fully established - but also not timed out
241/// Batch jobs will be ignored here
242/// Returns 0 if connection not exists
243
245{
246 std::lock_guard<std::mutex> grd(fConnMutex);
247
248 for (auto &entry : fPendingConn) {
249 if (!entry->fHeadlessMode)
250 return entry->fConnId;
251 }
252
253 for (auto &conn : fConn) {
254 if (!conn->fHeadlessMode)
255 return conn->fConnId;
256 }
257
258 return 0;
259}
260
261//////////////////////////////////////////////////////////////////////////////////////////
262/// Find connection with given websocket id
263
264std::shared_ptr<RWebWindow::WebConn> RWebWindow::FindConnection(unsigned wsid)
265{
266 std::lock_guard<std::mutex> grd(fConnMutex);
267
268 for (auto &conn : fConn) {
269 if (conn->fWSId == wsid)
270 return conn;
271 }
272
273 return nullptr;
274}
275
276//////////////////////////////////////////////////////////////////////////////////////////
277/// Remove connection with given websocket id
278
279std::shared_ptr<RWebWindow::WebConn> RWebWindow::RemoveConnection(unsigned wsid)
280{
281
282 std::shared_ptr<WebConn> res;
283
284 {
285 std::lock_guard<std::mutex> grd(fConnMutex);
286
287 for (size_t n = 0; n < fConn.size(); ++n)
288 if (fConn[n]->fWSId == wsid) {
289 res = std::move(fConn[n]);
290 fConn.erase(fConn.begin() + n);
291 res->fActive = false;
292 break;
293 }
294 }
295
296 if (res) {
297 for (auto &elem: res->fEmbed)
298 elem.second->RemoveMasterConnection(res->fConnId);
299 res->fEmbed.clear();
300 }
301
302 return res;
303}
304
305
306//////////////////////////////////////////////////////////////////////////////////////////
307/// Add new master connection
308/// If there are many connections - only same master is allowed
309
310void RWebWindow::AddMasterConnection(std::shared_ptr<RWebWindow> window, unsigned connid, int channel)
311{
312 if (fMaster && fMaster != window)
313 R__LOG_ERROR(WebGUILog()) << "Cannot configure different masters at the same time";
314
315 fMaster = window;
316
317 std::lock_guard<std::mutex> grd(fConnMutex);
318
319 fMasterConns.emplace_back(connid, channel);
320}
321
322//////////////////////////////////////////////////////////////////////////////////////////
323/// Get list of master connections
324
325std::vector<RWebWindow::MasterConn> RWebWindow::GetMasterConnections(unsigned connid) const
326{
327 std::vector<MasterConn> lst;
328 if (!fMaster)
329 return lst;
330
331 std::lock_guard<std::mutex> grd(fConnMutex);
332
333 for (auto & entry : fMasterConns)
334 if (!connid || entry.connid == connid)
335 lst.emplace_back(entry);
336
337 return lst;
338}
339
340//////////////////////////////////////////////////////////////////////////////////////////
341/// Remove master connection - if any
342
344{
345 if (!fMaster) return;
346
347 bool isany = false;
348
349 {
350 std::lock_guard<std::mutex> grd(fConnMutex);
351
352 if (connid == 0) {
353 fMasterConns.clear();
354 } else {
355 for (auto iter = fMasterConns.begin(); iter != fMasterConns.end(); ++iter)
356 if (iter->connid == connid) {
357 fMasterConns.erase(iter);
358 break;
359 }
360 }
361
362 isany = fMasterConns.size() > 0;
363 }
364
365 if (!isany)
366 fMaster.reset();
367}
368
369//////////////////////////////////////////////////////////////////////////////////////////
370/// Process special http request, used to hold headless browser running
371/// Such requests should not be replied for the long time
372/// Be aware that function called directly from THttpServer thread, which is not same thread as window
373
374bool RWebWindow::ProcessBatchHolder(std::shared_ptr<THttpCallArg> &arg)
375{
376 std::string query = arg->GetQuery();
377
378 if (query.compare(0, 4, "key=") != 0)
379 return false;
380
381 std::string key = query.substr(4);
382
383 std::shared_ptr<THttpCallArg> prev;
384
385 bool found_key = false;
386
387 // use connection mutex to access hold request
388 {
389 std::lock_guard<std::mutex> grd(fConnMutex);
390 for (auto &entry : fPendingConn) {
391 if (entry->fKey == key) {
392 assert(!found_key); // indicate error if many same keys appears
393 found_key = true;
394 prev = std::move(entry->fHold);
395 entry->fHold = arg;
396 }
397 }
398
399 for (auto &conn : fConn) {
400 if (conn->fKey == key) {
401 assert(!found_key); // indicate error if many same keys appears
402 prev = std::move(conn->fHold);
403 conn->fHold = arg;
404 found_key = true;
405 }
406 }
407 }
408
409 if (prev) {
410 prev->SetTextContent("console.log('execute holder script'); if (window) window.close();");
411 prev->NotifyCondition();
412 }
413
414 return found_key;
415}
416
417//////////////////////////////////////////////////////////////////////////////////////////
418/// Provide data to user callback
419/// User callback must be executed in the window thread
420
421void RWebWindow::ProvideQueueEntry(unsigned connid, EQueueEntryKind kind, std::string &&arg)
422{
423 {
424 std::lock_guard<std::mutex> grd(fInputQueueMutex);
425 fInputQueue.emplace(connid, kind, std::move(arg));
426 }
427
428 // if special python mode is used, process events called from special thread
429 // there is no other way to get regular calls in main python thread,
430 // therefore invoke widgets callbacks directly - which potentially can be dangerous
432}
433
434//////////////////////////////////////////////////////////////////////////////////////////
435/// Invoke callbacks with existing data
436/// Must be called from appropriate thread
437
439{
440 if (fCallbacksThrdIdSet && (fCallbacksThrdId != std::this_thread::get_id()) && !force)
441 return;
442
443 while (true) {
444 unsigned connid;
445 EQueueEntryKind kind;
446 std::string arg;
447
448 {
449 std::lock_guard<std::mutex> grd(fInputQueueMutex);
450 if (fInputQueue.size() == 0)
451 return;
452 auto &entry = fInputQueue.front();
453 connid = entry.fConnId;
454 kind = entry.fKind;
455 arg = std::move(entry.fData);
456 fInputQueue.pop();
457 }
458
459 switch (kind) {
460 case kind_None: break;
461 case kind_Connect:
462 if (fConnCallback)
463 fConnCallback(connid);
464 break;
465 case kind_Data:
466 if (fDataCallback)
467 fDataCallback(connid, arg);
468 break;
469 case kind_Disconnect:
471 fDisconnCallback(connid);
472 break;
473 }
474 }
475}
476
477//////////////////////////////////////////////////////////////////////////////////////////
478/// Add display handle and associated key
479/// Key is large random string generated when starting new window
480/// When client is connected, key should be supplied to correctly identify it
481
482unsigned RWebWindow::AddDisplayHandle(bool headless_mode, const std::string &key, std::unique_ptr<RWebDisplayHandle> &handle)
483{
484 std::lock_guard<std::mutex> grd(fConnMutex);
485
486 for (auto &entry : fPendingConn) {
487 if (entry->fKey == key) {
488 entry->fHeadlessMode = headless_mode;
489 std::swap(entry->fDisplayHandle, handle);
490 return entry->fConnId;
491 }
492 }
493
494 auto conn = std::make_shared<WebConn>(++fConnCnt, headless_mode, key);
495
496 std::swap(conn->fDisplayHandle, handle);
497
498 fPendingConn.emplace_back(conn);
499
500 return fConnCnt;
501}
502
503
504//////////////////////////////////////////////////////////////////////////////////////////
505/// Check if provided hash, ntry parameters from the connection request could be accepted
506/// \param hash - provided hash value which should match with HMAC hash for generated before connection key
507/// \param ntry - connection attempt number provided together with request, must come in increasing order
508/// \param remote - boolean flag indicating if request comming from remote (via real http),
509/// for local displays like Qt5 or CEF simpler connection rules are applied
510/// \param test_first_time - true if hash/ntry tested for the first time, false appears only with
511/// websocket when connection accepted by server
512
513bool RWebWindow::_CanTrustIn(std::shared_ptr<WebConn> &conn, const std::string &hash, const std::string &ntry, bool remote, bool test_first_time)
514{
515 if (!conn)
516 return false;
517
518 int intry = ntry.empty() ? -1 : std::stoi(ntry);
519
520 auto msg = TString::Format("attempt_%s", ntry.c_str());
521 auto expected = HMAC(conn->fKey, fMgr->fUseSessionKey && remote ? fMgr->fSessionKey : ""s, msg.Data(), msg.Length());
522
523 if (!IsRequireAuthKey())
524 return (conn->fKey.empty() && hash.empty()) || (hash == conn->fKey) || (hash == expected);
525
526 // for local connection simple key can be used
527 if (!remote && ((hash == conn->fKey) || (hash == expected)))
528 return true;
529
530 if (hash == expected) {
531 if (test_first_time) {
532 if (conn->fKeyUsed >= intry) {
533 // this is indication of main in the middle, already checked hashed value was shown again!!!
534 // client sends id with increasing counter, if previous value is presented it is BAD
535 R__LOG_ERROR(WebGUILog()) << "Detect connection hash send before, possible replay attack!!!";
536 return false;
537 }
538 // remember counter, it should prevent trying previous hash values
539 conn->fKeyUsed = intry;
540 } else {
541 if (conn->fKeyUsed != intry) {
542 // this is rather error condition, should never happen
543 R__LOG_ERROR(WebGUILog()) << "Connection failure with HMAC signature check";
544 return false;
545 }
546 }
547 return true;
548 }
549
550 return false;
551}
552
553
554//////////////////////////////////////////////////////////////////////////////////////////
555/// Returns true if provided key value already exists (in processes map or in existing connections)
556/// In special cases one also can check if key value exists as newkey
557
558bool RWebWindow::HasKey(const std::string &key, bool also_newkey) const
559{
560 if (key.empty())
561 return false;
562
563 std::lock_guard<std::mutex> grd(fConnMutex);
564
565 for (auto &entry : fPendingConn) {
566 if (entry->fKey == key)
567 return true;
568 }
569
570 for (auto &conn : fConn) {
571 if (conn->fKey == key)
572 return true;
573 if (also_newkey && (conn->fNewKey == key))
574 return true;
575 }
576
577 return false;
578}
579
580//////////////////////////////////////////////////////////////////////////////////////////
581/// Removes all connections with the key
582
583void RWebWindow::RemoveKey(const std::string &key)
584{
586
587 {
588 std::lock_guard<std::mutex> grd(fConnMutex);
589
590 auto pred = [&](std::shared_ptr<WebConn> &e) {
591 if (e->fKey == key) {
592 lst.emplace_back(e);
593 return true;
594 }
595 return false;
596 };
597
598 fPendingConn.erase(std::remove_if(fPendingConn.begin(), fPendingConn.end(), pred), fPendingConn.end());
599 fConn.erase(std::remove_if(fConn.begin(), fConn.end(), pred), fConn.end());
600 }
601
602 for (auto &conn : lst)
603 if (conn->fActive)
604 ProvideQueueEntry(conn->fConnId, kind_Disconnect, ""s);
605}
606
607
608//////////////////////////////////////////////////////////////////////////////////////////
609/// Generate new unique key for the window
610
611std::string RWebWindow::GenerateKey() const
612{
613 auto key = RWebWindowsManager::GenerateKey(32);
614
615 R__ASSERT((!HasKey(key) && (key != fMgr->fSessionKey)) && "Fail to generate window connection key");
616
617 return key;
618}
619
620//////////////////////////////////////////////////////////////////////////////////////////
621/// Check if started process(es) establish connection. After timeout such processed will be killed
622/// Method invoked from http server thread, therefore appropriate mutex must be used on all relevant data
623
625{
626 if (!fMgr) return;
627
628 timestamp_t stamp = std::chrono::system_clock::now();
629
630 float tmout = fMgr->GetLaunchTmout();
631
632 ConnectionsList_t selected;
633
634 {
635 std::lock_guard<std::mutex> grd(fConnMutex);
636
637 auto pred = [&](std::shared_ptr<WebConn> &e) {
638 std::chrono::duration<double> diff = stamp - e->fSendStamp;
639
640 if (diff.count() > tmout) {
641 R__LOG_DEBUG(0, WebGUILog()) << "Remove pending connection " << e->fKey << " after " << diff.count() << " sec";
642 selected.emplace_back(e);
643 return true;
644 }
645
646 return false;
647 };
648
649 fPendingConn.erase(std::remove_if(fPendingConn.begin(), fPendingConn.end(), pred), fPendingConn.end());
650 }
651}
652
653
654//////////////////////////////////////////////////////////////////////////////////////////
655/// Check if there are connection which are inactive for longer time
656/// For instance, batch browser will be stopped if no activity for 30 sec is there
657
659{
660 timestamp_t stamp = std::chrono::system_clock::now();
661
662 double batch_tmout = 20.;
663
664 std::vector<std::shared_ptr<WebConn>> clr;
665
666 {
667 std::lock_guard<std::mutex> grd(fConnMutex);
668
669 auto pred = [&](std::shared_ptr<WebConn> &conn) {
670 std::chrono::duration<double> diff = stamp - conn->fSendStamp;
671 // introduce large timeout
672 if ((diff.count() > batch_tmout) && conn->fHeadlessMode) {
673 conn->fActive = false;
674 clr.emplace_back(conn);
675 return true;
676 }
677 return false;
678 };
679
680 fConn.erase(std::remove_if(fConn.begin(), fConn.end(), pred), fConn.end());
681 }
682
683 for (auto &entry : clr)
684 ProvideQueueEntry(entry->fConnId, kind_Disconnect, ""s);
685
686}
687
688/////////////////////////////////////////////////////////////////////////
689/// Configure maximal number of allowed connections - 0 is unlimited
690/// Will not affect already existing connections
691/// Default is 1 - the only client is allowed
692
693void RWebWindow::SetConnLimit(unsigned lmt)
694{
695 std::lock_guard<std::mutex> grd(fConnMutex);
696
697 fConnLimit = lmt;
698}
699
700/////////////////////////////////////////////////////////////////////////
701/// returns configured connections limit (0 - default)
702
704{
705 std::lock_guard<std::mutex> grd(fConnMutex);
706
707 return fConnLimit;
708}
709
710/////////////////////////////////////////////////////////////////////////
711/// Configures connection token (default none)
712/// When specified, in URL of webpage such token should be provided as &token=value parameter,
713/// otherwise web window will refuse connection
714
715void RWebWindow::SetConnToken(const std::string &token)
716{
717 std::lock_guard<std::mutex> grd(fConnMutex);
718
719 fConnToken = token;
720}
721
722/////////////////////////////////////////////////////////////////////////
723/// Returns configured connection token
724
725std::string RWebWindow::GetConnToken() const
726{
727 std::lock_guard<std::mutex> grd(fConnMutex);
728
729 return fConnToken;
730}
731
732//////////////////////////////////////////////////////////////////////////////////////////
733/// Processing of websockets call-backs, invoked from RWebWindowWSHandler
734/// Method invoked from http server thread, therefore appropriate mutex must be used on all relevant data
735
737{
738 if (arg.GetWSId() == 0)
739 return true;
740
741 bool is_longpoll = arg.GetFileName() && ("root.longpoll"s == arg.GetFileName()),
742 is_remote = arg.GetTopName() && ("remote"s == arg.GetTopName());
743
744 // do not allow longpoll requests for loopback device
745 if (is_longpoll && is_remote && RWebWindowsManager::IsLoopbackMode())
746 return false;
747
748 if (arg.IsMethod("WS_CONNECT")) {
749
750 TUrl url;
751 url.SetOptions(arg.GetQuery());
752
753 std::lock_guard<std::mutex> grd(fConnMutex);
754
755 // refuse connection when number of connections exceed limit
756 if (fConnLimit && (fConn.size() >= fConnLimit))
757 return false;
758
759 if (!fConnToken.empty()) {
760 // refuse connection which does not provide proper token
761 if (!url.HasOption("token") || (fConnToken != url.GetValueFromOptions("token"))) {
762 R__LOG_DEBUG(0, WebGUILog()) << "Refuse connection without proper token";
763 return false;
764 }
765 }
766
767 if (!IsRequireAuthKey())
768 return true;
769
770 if(!url.HasOption("key")) {
771 R__LOG_DEBUG(0, WebGUILog()) << "key parameter not provided in url";
772 return false;
773 }
774
775 std::string key, ntry;
776 key = url.GetValueFromOptions("key");
777 if(url.HasOption("ntry"))
778 ntry = url.GetValueFromOptions("ntry");
779
780 for (auto &conn : fPendingConn)
781 if (_CanTrustIn(conn, key, ntry, is_remote, true /* test_first_time */))
782 return true;
783
784 return false;
785 }
786
787 if (arg.IsMethod("WS_READY")) {
788
789 if (FindConnection(arg.GetWSId())) {
790 R__LOG_ERROR(WebGUILog()) << "WSHandle with given websocket id " << arg.GetWSId() << " already exists";
791 return false;
792 }
793
794 std::shared_ptr<WebConn> conn;
795 std::string key, ntry;
796
797 TUrl url;
798 url.SetOptions(arg.GetQuery());
799 if (url.HasOption("key"))
800 key = url.GetValueFromOptions("key");
801 if (url.HasOption("ntry"))
802 ntry = url.GetValueFromOptions("ntry");
803
804 std::lock_guard<std::mutex> grd(fConnMutex);
805
806 // check if in pending connections exactly this combination was checked
807 for (size_t n = 0; n < fPendingConn.size(); ++n)
808 if (_CanTrustIn(fPendingConn[n], key, ntry, is_remote, false /* test_first_time */)) {
809 conn = std::move(fPendingConn[n]);
810 fPendingConn.erase(fPendingConn.begin() + n);
811 break;
812 }
813
814 if (conn) {
815 conn->fWSId = arg.GetWSId();
816 conn->fActive = true;
817 conn->fRecvSeq = 0;
818 conn->fSendSeq = 1;
819 // preserve key for longpoll or when with session key used for HMAC hash of messages
820 // conn->fKey.clear();
821 conn->ResetStamps();
822 fConn.emplace_back(conn);
823 return true;
824 } else if (!IsRequireAuthKey() && (!fConnLimit || (fConn.size() < fConnLimit))) {
825 fConn.emplace_back(std::make_shared<WebConn>(++fConnCnt, arg.GetWSId()));
826 return true;
827 }
828
829 // reject connection, should not really happen
830 return false;
831 }
832
833 // special sequrity check for the longpoll requests
834 if(is_longpoll) {
835 auto conn = FindConnection(arg.GetWSId());
836 if (!conn)
837 return false;
838
839 TUrl url;
840 url.SetOptions(arg.GetQuery());
841
842 std::string key, ntry;
843 if(url.HasOption("key"))
844 key = url.GetValueFromOptions("key");
845 if(url.HasOption("ntry"))
846 ntry = url.GetValueFromOptions("ntry");
847
848 if (!_CanTrustIn(conn, key, ntry, is_remote, true /* test_first_time */))
849 return false;
850 }
851
852 if (arg.IsMethod("WS_CLOSE")) {
853 // connection is closed, one can remove handle, associated window will be closed
854
855 auto conn = RemoveConnection(arg.GetWSId());
856
857 if (conn) {
858 ProvideQueueEntry(conn->fConnId, kind_Disconnect, ""s);
859 bool do_clear_on_close = false;
860 if (!conn->fNewKey.empty()) {
861 // case when same handle want to be reused by client with new key
862 std::lock_guard<std::mutex> grd(fConnMutex);
863 conn->fKeyUsed = 0;
864 conn->fKey = conn->fNewKey;
865 conn->fNewKey.clear();
866 conn->fConnId = ++fConnCnt; // change connection id to avoid confusion
867 conn->ResetData();
868 conn->ResetStamps(); // reset stamps, after timeout connection wll be removed
869 fPendingConn.emplace_back(conn);
870 } else {
871 std::lock_guard<std::mutex> grd(fConnMutex);
872 do_clear_on_close = (fPendingConn.size() == 0) && (fConn.size() == 0);
873 }
874
875 if (do_clear_on_close)
876 fClearOnClose.reset();
877 }
878
879 return true;
880 }
881
882 if (!arg.IsMethod("WS_DATA")) {
883 R__LOG_ERROR(WebGUILog()) << "only WS_DATA request expected!";
884 return false;
885 }
886
887 auto conn = FindConnection(arg.GetWSId());
888
889 if (!conn) {
890 R__LOG_ERROR(WebGUILog()) << "Get websocket data without valid connection - ignore!!!";
891 return false;
892 }
893
894 if (arg.GetPostDataLength() <= 0)
895 return true;
896
897 // here start testing of HMAC in the begin of the message
898
899 const char *buf0 = (const char *) arg.GetPostData();
900 Long_t data_len = arg.GetPostDataLength();
901
902 const char *buf = strchr(buf0, ':');
903 if (!buf) {
904 R__LOG_ERROR(WebGUILog()) << "missing separator for HMAC checksum";
905 return false;
906 }
907
908 Int_t code_len = buf - buf0;
909 data_len -= code_len + 1;
910 buf++; // starting of normal message
911
912 if (data_len < 0) {
913 R__LOG_ERROR(WebGUILog()) << "no any data after HMAC checksum";
914 return false;
915 }
916
917 bool is_none = strncmp(buf0, "none:", 5) == 0, is_match = false;
918
919 if (!is_none) {
920 std::string hmac = HMAC(conn->fKey, fMgr->fSessionKey, buf, data_len);
921
922 is_match = (code_len == (Int_t) hmac.length()) && (strncmp(buf0, hmac.c_str(), code_len) == 0);
923 } else if (!fMgr->fUseSessionKey) {
924 // no packet signing without session key
925 is_match = true;
926 }
927
928 // IMPORTANT: final place where integrity of input message is checked!
929 if (!is_match) {
930 // mismatch of HMAC checksum
931 if (is_remote && IsRequireAuthKey())
932 return false;
933 if (!is_none) {
934 R__LOG_ERROR(WebGUILog()) << "wrong HMAC checksum provided";
935 return false;
936 }
937 }
938
939 // here processing of received data should be performed
940 // this is task for the implemented windows
941
942 char *str_end = nullptr;
943
944 unsigned long oper_seq = std::strtoul(buf, &str_end, 10);
945 if (!str_end || *str_end != ':') {
946 R__LOG_ERROR(WebGUILog()) << "missing operation sequence";
947 return false;
948 }
949
950 if (is_remote && (oper_seq <= conn->fRecvSeq)) {
951 R__LOG_ERROR(WebGUILog()) << "supply same package again - MiM attacker?";
952 return false;
953 }
954
955 conn->fRecvSeq = oper_seq;
956
957 unsigned long ackn_oper = std::strtoul(str_end + 1, &str_end, 10);
958 if (!str_end || *str_end != ':') {
959 R__LOG_ERROR(WebGUILog()) << "missing number of acknowledged operations";
960 return false;
961 }
962
963 unsigned long can_send = std::strtoul(str_end + 1, &str_end, 10);
964 if (!str_end || *str_end != ':') {
965 R__LOG_ERROR(WebGUILog()) << "missing can_send counter";
966 return false;
967 }
968
969 unsigned long nchannel = std::strtoul(str_end + 1, &str_end, 10);
970 if (!str_end || *str_end != ':') {
971 R__LOG_ERROR(WebGUILog()) << "missing channel number";
972 return false;
973 }
974
975 Long_t processed_len = (str_end + 1 - buf);
976
977 if (processed_len > data_len) {
978 R__LOG_ERROR(WebGUILog()) << "corrupted buffer";
979 return false;
980 }
981
982 std::string cdata(str_end + 1, data_len - processed_len);
983
984 timestamp_t stamp = std::chrono::system_clock::now();
985
986 {
987 std::lock_guard<std::mutex> grd(conn->fMutex);
988
989 conn->fSendCredits += ackn_oper;
990 conn->fRecvCount++;
991 conn->fClientCredits = (int)can_send;
992 conn->fRecvStamp = stamp;
993 }
994
995 if (fProtocolCnt >= 0)
996 if (!fProtocolConnId || (conn->fConnId == fProtocolConnId)) {
997 fProtocolConnId = conn->fConnId; // remember connection
998
999 // record send event only for normal channel or very first message via ch0
1000 if ((nchannel != 0) || (cdata.find("READY=") == 0)) {
1001 if (fProtocol.length() > 2)
1002 fProtocol.insert(fProtocol.length() - 1, ",");
1003 fProtocol.insert(fProtocol.length() - 1, "\"send\"");
1004
1005 std::ofstream pfs(fProtocolFileName);
1006 pfs.write(fProtocol.c_str(), fProtocol.length());
1007 pfs.close();
1008 }
1009 }
1010
1011 if (nchannel == 0) {
1012 // special system channel
1013 if ((cdata.compare(0, 6, "READY=") == 0) && !conn->fReady) {
1014
1015 std::string key = cdata.substr(6);
1016
1017 if (key.empty() && IsNativeOnlyConn()) {
1018 RemoveConnection(conn->fWSId);
1019 return false;
1020 }
1021
1022 if (!key.empty() && !conn->fKey.empty() && (conn->fKey != key)) {
1023 R__LOG_ERROR(WebGUILog()) << "Key mismatch after established connection " << key << " != " << conn->fKey;
1024 RemoveConnection(conn->fWSId);
1025 return false;
1026 }
1027
1028 if (!fPanelName.empty()) {
1029 // initialization not yet finished, appropriate panel should be started
1030 Send(conn->fConnId, "SHOWPANEL:"s + fPanelName);
1031 conn->fReady = 5;
1032 } else {
1033 ProvideQueueEntry(conn->fConnId, kind_Connect, ""s);
1034 conn->fReady = 10;
1035 }
1036 } else if (cdata.compare(0, 8, "CLOSECH=") == 0) {
1037 int channel = std::stoi(cdata.substr(8));
1038 auto iter = conn->fEmbed.find(channel);
1039 if (iter != conn->fEmbed.end()) {
1040 iter->second->ProvideQueueEntry(conn->fConnId, kind_Disconnect, ""s);
1041 conn->fEmbed.erase(iter);
1042 }
1043 } else if (cdata.compare(0, 7, "RESIZE=") == 0) {
1044 auto p = cdata.find(",");
1045 if (p != std::string::npos) {
1046 auto width = std::stoi(cdata.substr(7, p - 7));
1047 auto height = std::stoi(cdata.substr(p + 1));
1048 if ((width > 0) && (height > 0) && conn->fDisplayHandle)
1049 conn->fDisplayHandle->Resize(width, height);
1050 }
1051 } else if (cdata == "GENERATE_KEY") {
1052 if (fMaster) {
1053 R__LOG_ERROR(WebGUILog()) << "Not able to generate new key with master connections";
1054 } else {
1055 conn->fNewKey = GenerateKey();
1056 if(!conn->fNewKey.empty())
1057 SubmitData(conn->fConnId, true, "NEW_KEY="s + conn->fNewKey, -1);
1058 }
1059 }
1060 } else if (fPanelName.length() && (conn->fReady < 10)) {
1061 if (cdata == "PANEL_READY") {
1062 R__LOG_DEBUG(0, WebGUILog()) << "Get panel ready " << fPanelName;
1063 ProvideQueueEntry(conn->fConnId, kind_Connect, ""s);
1064 conn->fReady = 10;
1065 } else {
1066 ProvideQueueEntry(conn->fConnId, kind_Disconnect, ""s);
1067 RemoveConnection(conn->fWSId);
1068 }
1069 } else if (nchannel == 1) {
1070 ProvideQueueEntry(conn->fConnId, kind_Data, std::move(cdata));
1071 } else if (nchannel > 1) {
1072 // process embed window
1073 auto embed_window = conn->fEmbed[nchannel];
1074 if (embed_window)
1075 embed_window->ProvideQueueEntry(conn->fConnId, kind_Data, std::move(cdata));
1076 }
1077
1079
1080 return true;
1081}
1082
1083//////////////////////////////////////////////////////////////////////////////////////////
1084/// Complete websocket send operation
1085/// Clear "doing send" flag and check if next operation has to be started
1086
1088{
1089 auto conn = FindConnection(wsid);
1090
1091 if (!conn)
1092 return;
1093
1094 {
1095 std::lock_guard<std::mutex> grd(conn->fMutex);
1096 conn->fDoingSend = false;
1097 }
1098
1099 CheckDataToSend(conn);
1100}
1101
1102//////////////////////////////////////////////////////////////////////////////////////////
1103/// Internal method to prepare text part of send data
1104/// Should be called under locked connection mutex
1105
1106std::string RWebWindow::_MakeSendHeader(std::shared_ptr<WebConn> &conn, bool txt, const std::string &data, int chid)
1107{
1108 std::string buf;
1109
1110 if (!conn->fWSId || !fWSHandler) {
1111 R__LOG_ERROR(WebGUILog()) << "try to send text data when connection not established";
1112 return buf;
1113 }
1114
1115 if (conn->fSendCredits <= 0) {
1116 R__LOG_ERROR(WebGUILog()) << "No credits to send text data via connection";
1117 return buf;
1118 }
1119
1120 if (conn->fDoingSend) {
1121 R__LOG_ERROR(WebGUILog()) << "Previous send operation not completed yet";
1122 return buf;
1123 }
1124
1125 if (txt)
1126 buf.reserve(data.length() + 100);
1127
1128 buf.append(std::to_string(conn->fSendSeq++));
1129 buf.append(":");
1130 buf.append(std::to_string(conn->fRecvCount));
1131 buf.append(":");
1132 buf.append(std::to_string(conn->fSendCredits));
1133 buf.append(":");
1134 conn->fRecvCount = 0; // we confirm how many packages was received
1135 conn->fSendCredits--;
1136
1137 buf.append(std::to_string(chid));
1138 buf.append(":");
1139
1140 if (txt) {
1141 buf.append(data);
1142 } else if (data.length()==0) {
1143 buf.append("$$nullbinary$$");
1144 } else {
1145 buf.append("$$binary$$");
1146 if (!conn->fKey.empty() && !fMgr->fSessionKey.empty() && fMgr->fUseSessionKey)
1147 buf.append(HMAC(conn->fKey, fMgr->fSessionKey, data.data(), data.length()));
1148 }
1149
1150 return buf;
1151}
1152
1153//////////////////////////////////////////////////////////////////////////////////////////
1154/// Checks if one should send data for specified connection
1155/// Returns true when send operation was performed
1156
1157bool RWebWindow::CheckDataToSend(std::shared_ptr<WebConn> &conn)
1158{
1159 std::string hdr, data, prefix;
1160
1161 {
1162 std::lock_guard<std::mutex> grd(conn->fMutex);
1163
1164 if (!conn->fActive || (conn->fSendCredits <= 0) || conn->fDoingSend) return false;
1165
1166 if (!conn->fQueue.empty()) {
1167 QueueItem &item = conn->fQueue.front();
1168 hdr = _MakeSendHeader(conn, item.fText, item.fData, item.fChID);
1169 if (!hdr.empty() && !item.fText)
1170 data = std::move(item.fData);
1171 conn->fQueue.pop();
1172 } else if ((conn->fClientCredits < 3) && (conn->fRecvCount > 1)) {
1173 // give more credits to the client
1174 hdr = _MakeSendHeader(conn, true, "KEEPALIVE", 0);
1175 }
1176
1177 if (hdr.empty()) return false;
1178
1179 conn->fDoingSend = true;
1180 }
1181
1182 // add HMAC checksum for string send to client
1183 if (!conn->fKey.empty() && !fMgr->fSessionKey.empty() && fMgr->fUseSessionKey) {
1184 prefix = HMAC(conn->fKey, fMgr->fSessionKey, hdr.c_str(), hdr.length());
1185 } else {
1186 prefix = "none";
1187 }
1188
1189 prefix += ":";
1190 hdr.insert(0, prefix);
1191
1192 int res = 0;
1193
1194 if (data.empty()) {
1195 res = fWSHandler->SendCharStarWS(conn->fWSId, hdr.c_str());
1196 } else {
1197 res = fWSHandler->SendHeaderWS(conn->fWSId, hdr.c_str(), data.data(), data.length());
1198 }
1199
1200 // submit operation, will be processed
1201 if (res >=0) return true;
1202
1203 // failure, clear sending flag
1204 std::lock_guard<std::mutex> grd(conn->fMutex);
1205 conn->fDoingSend = false;
1206 return false;
1207}
1208
1209
1210//////////////////////////////////////////////////////////////////////////////////////////
1211/// Checks if new data can be send (internal use only)
1212/// If necessary, provide credits to the client
1213/// \param only_once if true, data sending performed once or until there is no data to send
1214
1216{
1217 // make copy of all connections to be independent later, only active connections are checked
1218 auto arr = GetWindowConnections(0, true);
1219
1220 do {
1221 bool isany = false;
1222
1223 for (auto &conn : arr)
1224 if (CheckDataToSend(conn))
1225 isany = true;
1226
1227 if (!isany) break;
1228
1229 } while (!only_once);
1230}
1231
1232///////////////////////////////////////////////////////////////////////////////////
1233/// Special method to process all internal activity when window runs in separate thread
1234
1236{
1238
1240
1242
1244}
1245
1246///////////////////////////////////////////////////////////////////////////////////
1247/// Returns window address which is used in URL
1248
1249std::string RWebWindow::GetAddr() const
1250{
1251 return fWSHandler->GetName();
1252}
1253
1254///////////////////////////////////////////////////////////////////////////////////
1255/// Returns relative URL address for the specified window
1256/// Address can be required if one needs to access data from one window into another window
1257/// Used for instance when inserting panel into canvas
1258
1259std::string RWebWindow::GetRelativeAddr(const std::shared_ptr<RWebWindow> &win) const
1260{
1261 return GetRelativeAddr(*win);
1262}
1263
1264///////////////////////////////////////////////////////////////////////////////////
1265/// Returns relative URL address for the specified window
1266/// Address can be required if one needs to access data from one window into another window
1267/// Used for instance when inserting panel into canvas
1268
1270{
1271 if (fMgr != win.fMgr) {
1272 R__LOG_ERROR(WebGUILog()) << "Same web window manager should be used";
1273 return "";
1274 }
1275
1276 std::string res("../");
1277 res.append(win.GetAddr());
1278 res.append("/");
1279 return res;
1280}
1281
1282/////////////////////////////////////////////////////////////////////////
1283/// Set client version, used as prefix in scripts URL
1284/// When changed, web browser will reload all related JS files while full URL will be different
1285/// Default is empty value - no extra string in URL
1286/// Version should be string like "1.2" or "ver1.subv2" and not contain any special symbols
1287
1288void RWebWindow::SetClientVersion(const std::string &vers)
1289{
1290 std::lock_guard<std::mutex> grd(fConnMutex);
1291 fClientVersion = vers;
1292}
1293
1294/////////////////////////////////////////////////////////////////////////
1295/// Returns current client version
1296
1298{
1299 std::lock_guard<std::mutex> grd(fConnMutex);
1300 return fClientVersion;
1301}
1302
1303/////////////////////////////////////////////////////////////////////////
1304/// Set arbitrary JSON data, which is accessible via conn.getUserArgs() method in JavaScript
1305/// This JSON code injected into main HTML document into connectWebWindow({})
1306/// Must be set before RWebWindow::Show() method is called
1307/// \param args - arbitrary JSON data which can be provided to client side
1308
1309void RWebWindow::SetUserArgs(const std::string &args)
1310{
1311 std::lock_guard<std::mutex> grd(fConnMutex);
1312 fUserArgs = args;
1313}
1314
1315/////////////////////////////////////////////////////////////////////////
1316/// Returns configured user arguments for web window
1317/// See \ref SetUserArgs method for more details
1318
1319std::string RWebWindow::GetUserArgs() const
1320{
1321 std::lock_guard<std::mutex> grd(fConnMutex);
1322 return fUserArgs;
1323}
1324
1325///////////////////////////////////////////////////////////////////////////////////
1326/// Returns current number of active clients connections
1327/// \param with_pending if true, also pending (not yet established) connection accounted
1328
1329int RWebWindow::NumConnections(bool with_pending) const
1330{
1331 bool is_master = !!fMaster;
1332
1333 std::lock_guard<std::mutex> grd(fConnMutex);
1334
1335 if (is_master)
1336 return fMasterConns.size();
1337
1338 auto sz = fConn.size();
1339 if (with_pending)
1340 sz += fPendingConn.size();
1341 return sz;
1342}
1343
1344///////////////////////////////////////////////////////////////////////////////////
1345/// Configures recording of communication data in protocol file
1346/// Provided filename will be used to store JSON array with names of written files - text or binary
1347/// If data was send from client, "send" entry will be placed. JSON file will look like:
1348///
1349/// ["send", "msg0.txt", "send", "msg1.txt", "msg2.txt"]
1350///
1351/// If empty file name is provided, data recording will be disabled
1352/// Recorded data can be used in JSROOT directly to test client code without running C++ server
1353
1354void RWebWindow::RecordData(const std::string &fname, const std::string &fprefix)
1355{
1356 fProtocolFileName = fname;
1357 fProtocolCnt = fProtocolFileName.empty() ? -1 : 0;
1359 fProtocolPrefix = fprefix;
1360 fProtocol = "[]"; // empty array
1361}
1362
1363///////////////////////////////////////////////////////////////////////////////////
1364/// Returns connection id for specified connection sequence number
1365/// Only active connections are returned - where clients confirms connection
1366/// Total number of connections can be retrieved with NumConnections() method
1367/// \param num connection sequence number
1368
1369unsigned RWebWindow::GetConnectionId(int num) const
1370{
1371 bool is_master = !!fMaster;
1372
1373 std::lock_guard<std::mutex> grd(fConnMutex);
1374
1375 if (is_master)
1376 return (num >= 0) && (num < (int)fMasterConns.size()) ? fMasterConns[num].connid : 0;
1377
1378 return ((num >= 0) && (num < (int)fConn.size()) && fConn[num]->fActive) ? fConn[num]->fConnId : 0;
1379}
1380
1381///////////////////////////////////////////////////////////////////////////////////
1382/// returns vector with all existing connections ids
1383/// One also can exclude specified connection from return result,
1384/// which can be useful to be able reply too all but this connections
1385
1386std::vector<unsigned> RWebWindow::GetConnections(unsigned excludeid) const
1387{
1388 std::vector<unsigned> res;
1389
1390 bool is_master = !!fMaster;
1391
1392 std::lock_guard<std::mutex> grd(fConnMutex);
1393
1394 if (is_master) {
1395 for (auto & entry : fMasterConns)
1396 if (entry.connid != excludeid)
1397 res.emplace_back(entry.connid);
1398 } else {
1399 for (auto & entry : fConn)
1400 if (entry->fActive && (entry->fConnId != excludeid))
1401 res.emplace_back(entry->fConnId);
1402 }
1403
1404 return res;
1405}
1406
1407///////////////////////////////////////////////////////////////////////////////////
1408/// returns true if specified connection id exists
1409/// \param connid connection id (0 - any)
1410/// \param only_active when true only active connection will be checked, otherwise also pending (not yet established) connections are checked
1411
1412bool RWebWindow::HasConnection(unsigned connid, bool only_active) const
1413{
1414 std::lock_guard<std::mutex> grd(fConnMutex);
1415
1416 for (auto &conn : fConn) {
1417 if (connid && (conn->fConnId != connid))
1418 continue;
1419 if (conn->fActive || !only_active)
1420 return true;
1421 }
1422
1423 if (!only_active)
1424 for (auto &conn : fPendingConn) {
1425 if (!connid || (conn->fConnId == connid))
1426 return true;
1427 }
1428
1429 return false;
1430}
1431
1432///////////////////////////////////////////////////////////////////////////////////
1433/// Closes all connection to clients
1434/// Normally leads to closing of all correspondent browser windows
1435/// Some browsers (like firefox) do not allow by default to close window
1436
1438{
1439 SubmitData(0, true, "CLOSE", 0);
1440}
1441
1442///////////////////////////////////////////////////////////////////////////////////
1443/// Close specified connection
1444/// \param connid connection id, when 0 - all connections will be closed
1445
1446void RWebWindow::CloseConnection(unsigned connid)
1447{
1448 if (connid)
1449 SubmitData(connid, true, "CLOSE", 0);
1450}
1451
1452///////////////////////////////////////////////////////////////////////////////////
1453/// returns connection list (or all active connections)
1454/// \param connid connection id, when 0 - all existing connections are returned
1455/// \param only_active when true, only active (already established) connections are returned
1456
1458{
1460
1461 {
1462 std::lock_guard<std::mutex> grd(fConnMutex);
1463
1464 for (auto &conn : fConn) {
1465 if ((conn->fActive || !only_active) && (!connid || (conn->fConnId == connid)))
1466 arr.push_back(conn);
1467 }
1468
1469 if (!only_active)
1470 for (auto &conn : fPendingConn)
1471 if (!connid || (conn->fConnId == connid))
1472 arr.push_back(conn);
1473 }
1474
1475 return arr;
1476}
1477
1478///////////////////////////////////////////////////////////////////////////////////
1479/// Returns true if sending via specified connection can be performed
1480/// \param connid connection id, when 0 - all existing connections are checked
1481/// \param direct when true, checks if direct sending (without queuing) is possible
1482
1483bool RWebWindow::CanSend(unsigned connid, bool direct) const
1484{
1485 auto arr = GetWindowConnections(connid, direct); // for direct sending connection has to be active
1486
1487 auto maxqlen = GetMaxQueueLength();
1488
1489 for (auto &conn : arr) {
1490
1491 std::lock_guard<std::mutex> grd(conn->fMutex);
1492
1493 if (direct && (!conn->fQueue.empty() || (conn->fSendCredits == 0) || conn->fDoingSend))
1494 return false;
1495
1496 if (conn->fQueue.size() >= maxqlen)
1497 return false;
1498 }
1499
1500 return true;
1501}
1502
1503///////////////////////////////////////////////////////////////////////////////////
1504/// Returns send queue length for specified connection
1505/// \param connid connection id, 0 - maximal value for all connections is returned
1506/// If wrong connection id specified, -1 is return
1507
1508int RWebWindow::GetSendQueueLength(unsigned connid) const
1509{
1510 int maxq = -1;
1511
1512 for (auto &conn : GetWindowConnections(connid)) {
1513 std::lock_guard<std::mutex> grd(conn->fMutex);
1514 int len = conn->fQueue.size();
1515 if (len > maxq) maxq = len;
1516 }
1517
1518 return maxq;
1519}
1520
1521///////////////////////////////////////////////////////////////////////////////////
1522/// Internal method to send data
1523/// \param connid connection id, when 0 - data will be send to all connections
1524/// \param txt is text message that should be sent
1525/// \param data data to be std-moved to SubmitData function
1526/// \param chid channel id, 1 - normal communication, 0 - internal with highest priority
1527
1528void RWebWindow::SubmitData(unsigned connid, bool txt, std::string &&data, int chid)
1529{
1530 if (fMaster) {
1531 auto lst = GetMasterConnections(connid);
1532 auto cnt = lst.size();
1533 for (auto & entry : lst)
1534 if (--cnt)
1535 fMaster->SubmitData(entry.connid, txt, std::string(data), entry.channel);
1536 else
1537 fMaster->SubmitData(entry.connid, txt, std::move(data), entry.channel);
1538 return;
1539 }
1540
1541 auto arr = GetWindowConnections(connid);
1542 auto cnt = arr.size();
1543 auto maxqlen = GetMaxQueueLength();
1544
1545 bool clear_queue = false;
1546
1547 if (chid == -1) {
1548 chid = 0;
1549 clear_queue = true;
1550 }
1551
1552 timestamp_t stamp = std::chrono::system_clock::now();
1553
1554 for (auto &conn : arr) {
1555
1556 if (fProtocolCnt >= 0)
1557 if (!fProtocolConnId || (conn->fConnId == fProtocolConnId)) {
1558 fProtocolConnId = conn->fConnId; // remember connection
1559 std::string fname = fProtocolPrefix;
1560 fname.append("msg");
1561 fname.append(std::to_string(fProtocolCnt++));
1562 if (chid > 1) {
1563 fname.append("_ch");
1564 fname.append(std::to_string(chid));
1565 }
1566 fname.append(txt ? ".txt" : ".bin");
1567
1568 std::ofstream ofs(fname);
1569 ofs.write(data.c_str(), data.length());
1570 ofs.close();
1571
1572 if (fProtocol.length() > 2)
1573 fProtocol.insert(fProtocol.length() - 1, ",");
1574 fProtocol.insert(fProtocol.length() - 1, "\""s + fname + "\""s);
1575
1576 std::ofstream pfs(fProtocolFileName);
1577 pfs.write(fProtocol.c_str(), fProtocol.length());
1578 pfs.close();
1579 }
1580
1581 conn->fSendStamp = stamp;
1582
1583 std::lock_guard<std::mutex> grd(conn->fMutex);
1584
1585 if (clear_queue) {
1586 while (!conn->fQueue.empty())
1587 conn->fQueue.pop();
1588 }
1589
1590 if (conn->fQueue.size() < maxqlen) {
1591 if (--cnt)
1592 conn->fQueue.emplace(chid, txt, std::string(data)); // make copy
1593 else
1594 conn->fQueue.emplace(chid, txt, std::move(data)); // move content
1595 } else {
1596 R__LOG_ERROR(WebGUILog()) << "Maximum queue length achieved";
1597 }
1598 }
1599
1601}
1602
1603///////////////////////////////////////////////////////////////////////////////////
1604/// Sends data to specified connection
1605/// \param connid connection id, when 0 - data will be send to all connections
1606/// \param data data to be copied to SubmitData function
1607
1608void RWebWindow::Send(unsigned connid, const std::string &data)
1609{
1610 SubmitData(connid, true, std::string(data), 1);
1611}
1612
1613///////////////////////////////////////////////////////////////////////////////////
1614/// Send binary data to specified connection
1615/// \param connid connection id, when 0 - data will be send to all connections
1616/// \param data data to be std-moved to SubmitData function
1617
1618void RWebWindow::SendBinary(unsigned connid, std::string &&data)
1619{
1620 SubmitData(connid, false, std::move(data), 1);
1621}
1622
1623///////////////////////////////////////////////////////////////////////////////////
1624/// Send binary data to specified connection
1625/// \param connid connection id, when 0 - data will be send to all connections
1626/// \param data pointer to binary data
1627/// \param len number of bytes in data
1628
1629void RWebWindow::SendBinary(unsigned connid, const void *data, std::size_t len)
1630{
1631 std::string buf;
1632 buf.resize(len);
1633 std::copy((const char *)data, (const char *)data + len, buf.begin());
1634 SubmitData(connid, false, std::move(buf), 1);
1635}
1636
1637///////////////////////////////////////////////////////////////////////////////////
1638/// Assign thread id which has to be used for callbacks
1639/// WARNING!!! only for expert use
1640/// Automatically done at the moment when any callback function is invoked
1641/// Can be invoked once again if window Run method will be invoked from other thread
1642/// Normally should be invoked before Show() method is called
1643
1645{
1646 fUseServerThreads = false;
1647 fUseProcessEvents = false;
1648 fProcessMT = false;
1649 fCallbacksThrdIdSet = true;
1650 fCallbacksThrdId = std::this_thread::get_id();
1652 fProcessMT = true;
1653 } else if (fMgr->IsUseHttpThread()) {
1654 // special thread is used by the manager, but main thread used for the canvas - not supported
1655 R__LOG_ERROR(WebGUILog()) << "create web window from main thread when THttpServer created with special thread - not supported";
1656 }
1657}
1658
1659/////////////////////////////////////////////////////////////////////////////////
1660/// Let use THttpServer threads to process requests
1661/// WARNING!!! only for expert use
1662/// Should be only used when application provides proper locking and
1663/// does not block. Such mode provides minimal possible latency
1664/// Must be called before callbacks are assigned
1665
1667{
1668 fUseServerThreads = true;
1669 fUseProcessEvents = false;
1670 fCallbacksThrdIdSet = false;
1671 fProcessMT = true;
1672}
1673
1674/////////////////////////////////////////////////////////////////////////////////
1675/// Start special thread which will be used by the window to handle all callbacks
1676/// One has to be sure, that access to global ROOT structures are minimized and
1677/// protected with ROOT::EnableThreadSafety(); call
1678
1680{
1681 if (fHasWindowThrd) {
1682 R__LOG_WARNING(WebGUILog()) << "thread already started for the window";
1683 return;
1684 }
1685
1686 fHasWindowThrd = true;
1687
1688 std::thread thrd([this] {
1690 while(fHasWindowThrd)
1691 Run(0.1);
1692 fCallbacksThrdIdSet = false;
1693 });
1694
1695 fWindowThrd = std::move(thrd);
1696}
1697
1698/////////////////////////////////////////////////////////////////////////////////
1699/// Stop special thread
1700
1702{
1703 if (!fHasWindowThrd)
1704 return;
1705
1706 fHasWindowThrd = false;
1707 fWindowThrd.join();
1708}
1709
1710
1711/////////////////////////////////////////////////////////////////////////////////
1712/// Set call-back function for data, received from the clients via websocket
1713///
1714/// Function should have signature like void func(unsigned connid, const std::string &data)
1715/// First argument identifies connection (unique for each window), second argument is received data
1716///
1717/// At the moment when callback is assigned, RWebWindow working thread is detected.
1718/// If called not from main application thread, RWebWindow::Run() function must be regularly called from that thread.
1719///
1720/// Most simple way to assign call-back - use of c++11 lambdas like:
1721/// ~~~ {.cpp}
1722/// auto win = RWebWindow::Create();
1723/// win->SetDefaultPage("file:./page.htm");
1724/// win->SetDataCallBack(
1725/// [](unsigned connid, const std::string &data) {
1726/// printf("Conn:%u data:%s\n", connid, data.c_str());
1727/// }
1728/// );
1729/// win->Show();
1730/// ~~~
1731
1733{
1736 fDataCallback = func;
1737}
1738
1739/////////////////////////////////////////////////////////////////////////////////
1740/// Set call-back function for new connection
1741
1743{
1746 fConnCallback = func;
1747}
1748
1749/////////////////////////////////////////////////////////////////////////////////
1750/// Set call-back function for disconnecting
1751
1753{
1756 fDisconnCallback = func;
1757}
1758
1759/////////////////////////////////////////////////////////////////////////////////
1760/// Set handle which is cleared when last active connection is closed
1761/// Typically can be used to destroy web-based widget at such moment
1762
1763void RWebWindow::SetClearOnClose(const std::shared_ptr<void> &handle)
1764{
1765 fClearOnClose = handle;
1766}
1767
1768/////////////////////////////////////////////////////////////////////////////////
1769/// Set call-backs function for connect, data and disconnect events
1770
1772{
1775 fConnCallback = conn;
1777 fDisconnCallback = disconn;
1778}
1779
1780/////////////////////////////////////////////////////////////////////////////////
1781/// Waits until provided check function or lambdas returns non-zero value
1782/// Check function has following signature: int func(double spent_tm)
1783/// Waiting will be continued, if function returns zero.
1784/// Parameter spent_tm is time in seconds, which already spent inside the function
1785/// First non-zero value breaks loop and result is returned.
1786/// Runs application mainloop and short sleeps in-between
1787
1789{
1790 return fMgr->WaitFor(*this, check);
1791}
1792
1793/////////////////////////////////////////////////////////////////////////////////
1794/// Waits until provided check function or lambdas returns non-zero value
1795/// Check function has following signature: int func(double spent_tm)
1796/// Waiting will be continued, if function returns zero.
1797/// Parameter spent_tm in lambda is time in seconds, which already spent inside the function
1798/// First non-zero value breaks waiting loop and result is returned (or 0 if time is expired).
1799/// Runs application mainloop and short sleeps in-between
1800/// WebGui.OperationTmout rootrc parameter defines waiting time in seconds
1801
1803{
1804 return fMgr->WaitFor(*this, check, true, GetOperationTmout());
1805}
1806
1807/////////////////////////////////////////////////////////////////////////////////
1808/// Waits until provided check function or lambdas returns non-zero value
1809/// Check function has following signature: int func(double spent_tm)
1810/// Waiting will be continued, if function returns zero.
1811/// Parameter spent_tm in lambda is time in seconds, which already spent inside the function
1812/// First non-zero value breaks waiting loop and result is returned (or 0 if time is expired).
1813/// Runs application mainloop and short sleeps in-between
1814/// duration (in seconds) defines waiting time
1815
1817{
1818 return fMgr->WaitFor(*this, check, true, duration);
1819}
1820
1821
1822/////////////////////////////////////////////////////////////////////////////////
1823/// Run window functionality for specified time
1824/// If no action can be performed - just sleep specified time
1825
1826void RWebWindow::Run(double tm)
1827{
1828 if (!fCallbacksThrdIdSet || (fCallbacksThrdId != std::this_thread::get_id())) {
1829 R__LOG_WARNING(WebGUILog()) << "Change thread id where RWebWindow is executed";
1830 fCallbacksThrdIdSet = true;
1831 fCallbacksThrdId = std::this_thread::get_id();
1832 }
1833
1834 if (tm <= 0) {
1835 Sync();
1836 } else {
1837 WaitForTimed([](double) { return 0; }, tm);
1838 }
1839}
1840
1841
1842/////////////////////////////////////////////////////////////////////////////////
1843/// Add embed window
1844
1845unsigned RWebWindow::AddEmbedWindow(std::shared_ptr<RWebWindow> window, unsigned connid, int channel)
1846{
1847 if (channel < 2)
1848 return 0;
1849
1850 auto arr = GetWindowConnections(connid, true);
1851 if (arr.size() == 0)
1852 return 0;
1853
1854 // check if channel already occupied
1855 if (arr[0]->fEmbed.find(channel) != arr[0]->fEmbed.end())
1856 return 0;
1857
1858 arr[0]->fEmbed[channel] = window;
1859
1860 return arr[0]->fConnId;
1861}
1862
1863/////////////////////////////////////////////////////////////////////////////////
1864/// Remove RWebWindow associated with the channelfEmbed
1865
1866void RWebWindow::RemoveEmbedWindow(unsigned connid, int channel)
1867{
1868 auto arr = GetWindowConnections(connid);
1869
1870 for (auto &conn : arr) {
1871 auto iter = conn->fEmbed.find(channel);
1872 if (iter != conn->fEmbed.end())
1873 conn->fEmbed.erase(iter);
1874 }
1875}
1876
1877
1878/////////////////////////////////////////////////////////////////////////////////
1879/// Create new RWebWindow
1880/// Using default RWebWindowsManager
1881
1882std::shared_ptr<RWebWindow> RWebWindow::Create()
1883{
1884 return RWebWindowsManager::Instance()->CreateWindow();
1885}
1886
1887/////////////////////////////////////////////////////////////////////////////////
1888/// Terminate ROOT session
1889/// Tries to correctly close THttpServer, associated with RWebWindowsManager
1890/// After that exit from process
1891
1893{
1894
1895 // workaround to release all connection-specific handles as soon as possible
1896 // required to work with QWebEngine
1897 // once problem solved, can be removed here
1898 ConnectionsList_t arr1, arr2;
1899
1900 {
1901 std::lock_guard<std::mutex> grd(fConnMutex);
1902 std::swap(arr1, fConn);
1903 std::swap(arr2, fPendingConn);
1904 }
1905
1906 fMgr->Terminate();
1907}
1908
1909/////////////////////////////////////////////////////////////////////////////////
1910/// Static method to show web window
1911/// Has to be used instead of RWebWindow::Show() when window potentially can be embed into other windows
1912/// Soon RWebWindow::Show() method will be done protected
1913
1914unsigned RWebWindow::ShowWindow(std::shared_ptr<RWebWindow> window, const RWebDisplayArgs &args)
1915{
1916 if (!window)
1917 return 0;
1918
1920 if (args.fMaster && window->fMaster && window->fMaster != args.fMaster) {
1921 R__LOG_ERROR(WebGUILog()) << "Cannot use different master for same RWebWindow";
1922 return 0;
1923 }
1924
1925 unsigned connid = args.fMaster ? args.fMaster->AddEmbedWindow(window, args.fMasterConnection, args.fMasterChannel) : 0;
1926
1927 if (connid > 0) {
1928
1929 window->RemoveMasterConnection(connid);
1930
1931 window->AddMasterConnection(args.fMaster, connid, args.fMasterChannel);
1932
1933 // inform client that connection is established and window initialized
1934 args.fMaster->SubmitData(connid, true, "EMBED_DONE"s, args.fMasterChannel);
1935
1936 // provide call back for window itself that connection is ready
1937 window->ProvideQueueEntry(connid, kind_Connect, ""s);
1938 }
1939
1940 return connid;
1941 }
1942
1943 return window->Show(args);
1944}
1945
1946std::function<bool(const std::shared_ptr<RWebWindow> &, unsigned, const std::string &)> RWebWindow::gStartDialogFunc = nullptr;
1947
1948/////////////////////////////////////////////////////////////////////////////////////
1949/// Configure func which has to be used for starting dialog
1950
1951
1952void RWebWindow::SetStartDialogFunc(std::function<bool(const std::shared_ptr<RWebWindow> &, unsigned, const std::string &)> func)
1953{
1954 gStartDialogFunc = func;
1955}
1956
1957/////////////////////////////////////////////////////////////////////////////////////
1958/// Check if this could be the message send by client to start new file dialog
1959/// If returns true, one can call RWebWindow::EmbedFileDialog() to really create file dialog
1960/// instance inside existing widget
1961
1962bool RWebWindow::IsFileDialogMessage(const std::string &msg)
1963{
1964 return msg.compare(0, 11, "FILEDIALOG:") == 0;
1965}
1966
1967/////////////////////////////////////////////////////////////////////////////////////
1968/// Create dialog instance to use as embedded dialog inside provided widget
1969/// Loads libROOTBrowserv7 and tries to call RFileDialog::Embedded() method
1970/// Embedded dialog started on the client side where FileDialogController.SaveAs() method called
1971/// Such method immediately send message with "FILEDIALOG:" prefix
1972/// On the server side widget should detect such message and call RFileDialog::Embedded()
1973/// providing received string as second argument.
1974/// Returned instance of shared_ptr<RFileDialog> may be used to assign callback when file is selected
1975
1976bool RWebWindow::EmbedFileDialog(const std::shared_ptr<RWebWindow> &window, unsigned connid, const std::string &args)
1977{
1978 if (!gStartDialogFunc)
1979 gSystem->Load("libROOTBrowserv7");
1980
1981 if (!gStartDialogFunc)
1982 return false;
1983
1984 return gStartDialogFunc(window, connid, args);
1985}
1986
1987/////////////////////////////////////////////////////////////////////////////////////
1988/// Calculate HMAC checksum for provided key and message
1989/// Key combained from connection key and session key
1990
1991std::string RWebWindow::HMAC(const std::string &key, const std::string &sessionKey, const char *msg, int msglen)
1992{
1993 using namespace ROOT::Internal::SHA256;
1994
1995 auto get_digest = [](sha256_t &hash, bool as_hex = false) -> std::string {
1996 std::string digest;
1997 digest.resize(32);
1998
1999 sha256_final(&hash, reinterpret_cast<unsigned char *>(digest.data()));
2000
2001 if (!as_hex) return digest;
2002
2003 static const char* digits = "0123456789abcdef";
2004 std::string hex;
2005 for (int n = 0; n < 32; n++) {
2006 unsigned char code = (unsigned char) digest[n];
2007 hex += digits[code / 16];
2008 hex += digits[code % 16];
2009 }
2010 return hex;
2011 };
2012
2013 // calculate hash of sessionKey + key;
2014 sha256_t hash1;
2015 sha256_init(&hash1);
2016 sha256_update(&hash1, (const unsigned char *) sessionKey.data(), sessionKey.length());
2017 sha256_update(&hash1, (const unsigned char *) key.data(), key.length());
2018 std::string kbis = get_digest(hash1);
2019
2020 kbis.resize(64, 0); // resize to blocksize 64 bytes required by the sha256
2021
2022 std::string ki = kbis, ko = kbis;
2023 const int opad = 0x5c;
2024 const int ipad = 0x36;
2025 for (size_t i = 0; i < kbis.length(); ++i) {
2026 ko[i] = kbis[i] ^ opad;
2027 ki[i] = kbis[i] ^ ipad;
2028 }
2029
2030 // calculate hash for ko + msg;
2031 sha256_t hash2;
2032 sha256_init(&hash2);
2033 sha256_update(&hash2, (const unsigned char *) ki.data(), ki.length());
2034 sha256_update(&hash2, (const unsigned char *) msg, msglen);
2035 std::string m2digest = get_digest(hash2);
2036
2037 // calculate hash for ki + m2_digest;
2038 sha256_t hash3;
2039 sha256_init(&hash3);
2040 sha256_update(&hash3, (const unsigned char *) ko.data(), ko.length());
2041 sha256_update(&hash3, (const unsigned char *) m2digest.data(), m2digest.length());
2042
2043 return get_digest(hash3, true);
2044}
#define R__LOG_WARNING(...)
Definition RLogger.hxx:363
#define R__LOG_ERROR(...)
Definition RLogger.hxx:362
#define R__LOG_DEBUG(DEBUGLEVEL,...)
Definition RLogger.hxx:365
#define e(i)
Definition RSha256.hxx:103
int Int_t
Definition RtypesCore.h:45
long Long_t
Definition RtypesCore.h:54
#define R__ASSERT(e)
Definition TError.h:118
winID h TVirtualViewer3D TVirtualGLPainter p
winID h direct
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t stamp
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize id
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t win
Option_t Option_t width
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t height
char name[80]
Definition TGX11.cxx:110
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
R__EXTERN TSystem * gSystem
Definition TSystem.h:555
Holds different arguments for starting browser with RWebDisplayHandle::Display() method.
EBrowserKind GetBrowserKind() const
returns configured browser kind, see EBrowserKind for supported values
unsigned fMasterConnection
! used master connection
int fMasterChannel
! used master channel
std::shared_ptr< RWebWindow > fMaster
! master window
@ kEmbedded
window will be embedded into other, no extra browser need to be started
void SetHeadless(bool on=true)
set headless mode
static int GetBoolEnv(const std::string &name, int dfl=-1)
Parse boolean gEnv variable which should be "yes" or "no".
Represents web window, which can be shown in web browser or any other supported environment.
bool CheckDataToSend(std::shared_ptr< WebConn > &conn)
Checks if one should send data for specified connection Returns true when send operation was performe...
int WaitFor(WebWindowWaitFunc_t check)
Waits until provided check function or lambdas returns non-zero value Check function has following si...
unsigned GetId() const
Returns ID for the window - unique inside window manager.
std::vector< MasterConn > GetMasterConnections(unsigned connid=0) const
Get list of master connections.
void AddMasterConnection(std::shared_ptr< RWebWindow > window, unsigned connid, int channel)
Add new master connection If there are many connections - only same master is allowed.
std::mutex fConnMutex
! mutex used to protect connection list
WebWindowDataCallback_t fDataCallback
! main callback when data over channel 1 is arrived
void CheckInactiveConnections()
Check if there are connection which are inactive for longer time For instance, batch browser will be ...
unsigned fId
! unique identifier
bool fHasWindowThrd
! indicate if special window thread was started
std::vector< MasterConn > fMasterConns
! master connections
void SetClearOnClose(const std::shared_ptr< void > &handle=nullptr)
Set handle which is cleared when last active connection is closed Typically can be used to destroy we...
void StartThread()
Start special thread which will be used by the window to handle all callbacks One has to be sure,...
unsigned fConnCnt
! counter of new connections to assign ids
unsigned fProtocolConnId
! connection id, which is used for writing protocol
ConnectionsList_t GetWindowConnections(unsigned connid=0, bool only_active=false) const
returns connection list (or all active connections)
bool fSendMT
! true is special threads should be used for sending data
std::thread::id fCallbacksThrdId
! thread id where callbacks should be invoked
void RemoveKey(const std::string &key)
Removes all connections with the key.
std::queue< QueueEntry > fInputQueue
! input queue for all callbacks
bool _CanTrustIn(std::shared_ptr< WebConn > &conn, const std::string &key, const std::string &ntry, bool remote, bool test_first_time)
Check if provided hash, ntry parameters from the connection request could be accepted.
void SetConnToken(const std::string &token="")
Configures connection token (default none) When specified, in URL of webpage such token should be pro...
unsigned MakeHeadless(bool create_new=false)
Start headless browser for specified window Normally only single instance is used,...
std::string GetUrl(bool remote=true)
Return URL string to connect web window URL typically includes extra parameters required for connecti...
void CloseConnections()
Closes all connection to clients Normally leads to closing of all correspondent browser windows Some ...
std::shared_ptr< RWebWindow > fMaster
! master window where this window is embedded
int NumConnections(bool with_pending=false) const
Returns current number of active clients connections.
bool fCallbacksThrdIdSet
! flag indicating that thread id is assigned
std::string fUserArgs
! arbitrary JSON code, which is accessible via conn.getUserArgs() method
void SetDefaultPage(const std::string &page)
Set content of default window HTML page This page returns when URL address of the window will be requ...
unsigned fConnLimit
! number of allowed active connections
void InvokeCallbacks(bool force=false)
Invoke callbacks with existing data Must be called from appropriate thread.
std::shared_ptr< WebConn > FindConnection(unsigned wsid)
Find connection with specified websocket id.
std::string GetClientVersion() const
Returns current client version.
void SetConnectCallBack(WebWindowConnectCallback_t func)
Set call-back function for new connection.
void Sync()
Special method to process all internal activity when window runs in separate thread.
void UseServerThreads()
Let use THttpServer threads to process requests WARNING!!! only for expert use Should be only used wh...
void TerminateROOT()
Terminate ROOT session Tries to correctly close THttpServer, associated with RWebWindowsManager After...
void Send(unsigned connid, const std::string &data)
Sends data to specified connection.
unsigned Show(const RWebDisplayArgs &args="")
Show window in specified location.
THttpServer * GetServer()
Return THttpServer instance serving requests to the window.
unsigned AddDisplayHandle(bool headless_mode, const std::string &key, std::unique_ptr< RWebDisplayHandle > &handle)
Add display handle and associated key Key is large random string generated when starting new window W...
std::vector< std::shared_ptr< WebConn > > ConnectionsList_t
void AssignThreadId()
Assign thread id which has to be used for callbacks WARNING!!! only for expert use Automatically done...
bool IsNativeOnlyConn() const
returns true if only native (own-created) connections are allowed
void SendBinary(unsigned connid, const void *data, std::size_t len)
Send binary data to specified connection.
static std::shared_ptr< RWebWindow > Create()
Create new RWebWindow Using default RWebWindowsManager.
std::string fClientVersion
! configured client version, used as prefix in scripts URL
bool ProcessBatchHolder(std::shared_ptr< THttpCallArg > &arg)
Process special http request, used to hold headless browser running Such requests should not be repli...
unsigned AddEmbedWindow(std::shared_ptr< RWebWindow > window, unsigned connid, int channel)
Add embed window.
void SetDisconnectCallBack(WebWindowConnectCallback_t func)
Set call-back function for disconnecting.
std::vector< unsigned > GetConnections(unsigned excludeid=0) const
returns vector with all existing connections ids One also can exclude specified connection from retur...
void SetDataCallBack(WebWindowDataCallback_t func)
Set call-back function for data, received from the clients via websocket.
float fOperationTmout
! timeout in seconds to perform synchronous operation, default 50s
bool fRequireAuthKey
! defines if authentication key always required when connect to the widget
static std::function< bool(const std::shared_ptr< RWebWindow > &, unsigned, const std::string &)> gStartDialogFunc
void SetUserArgs(const std::string &args)
Set arbitrary JSON data, which is accessible via conn.getUserArgs() method in JavaScript This JSON co...
std::string fConnToken
! value of "token" URL parameter which should be provided for connecting window
static unsigned ShowWindow(std::shared_ptr< RWebWindow > window, const RWebDisplayArgs &args="")
Static method to show web window Has to be used instead of RWebWindow::Show() when window potentially...
std::shared_ptr< RWebWindowWSHandler > fWSHandler
! specialize websocket handler for all incoming connections
void StopThread()
Stop special thread.
void SubmitData(unsigned connid, bool txt, std::string &&data, int chid=1)
Internal method to send data.
static std::string HMAC(const std::string &key, const std::string &sessionKey, const char *msg, int msglen)
Calculate HMAC checksum for provided key and message Key combained from connection key and session ke...
~RWebWindow()
RWebWindow destructor Closes all connections and remove window from manager.
static bool EmbedFileDialog(const std::shared_ptr< RWebWindow > &window, unsigned connid, const std::string &args)
Create dialog instance to use as embedded dialog inside provided widget Loads libROOTBrowserv7 and tr...
void CloseConnection(unsigned connid)
Close specified connection.
ConnectionsList_t fPendingConn
! list of pending connection with pre-assigned keys
unsigned GetConnectionId(int num=0) const
Returns connection id for specified connection sequence number Only active connections are returned -...
std::string GetConnToken() const
Returns configured connection token.
float GetOperationTmout() const
Returns timeout for synchronous WebWindow operations.
void SetConnLimit(unsigned lmt=0)
Configure maximal number of allowed connections - 0 is unlimited Will not affect already existing con...
void SetPanelName(const std::string &name)
Configure window to show some of existing JSROOT panels It uses "file:rootui5sys/panel/panel....
bool IsRequireAuthKey() const
returns true if authentication string is required
RWebWindow()
RWebWindow constructor Should be defined here because of std::unique_ptr<RWebWindowWSHandler>
std::string fProtocolPrefix
! prefix for created files names
int GetSendQueueLength(unsigned connid) const
Returns send queue length for specified connection.
std::shared_ptr< WebConn > RemoveConnection(unsigned wsid)
Remove connection with given websocket id.
std::shared_ptr< RWebWindowWSHandler > CreateWSHandler(std::shared_ptr< RWebWindowsManager > mgr, unsigned id, double tmout)
Assigns manager reference, window id and creates websocket handler, used for communication with the c...
std::string fProtocol
! protocol
bool CanSend(unsigned connid, bool direct=true) const
Returns true if sending via specified connection can be performed.
std::string GetUserArgs() const
Returns configured user arguments for web window See SetUserArgs method for more details.
void RecordData(const std::string &fname="protocol.json", const std::string &fprefix="")
Configures recording of communication data in protocol file Provided filename will be used to store J...
bool fUseProcessEvents
! all window functionality will run through process events
unsigned GetDisplayConnection() const
Returns first connection id where window is displayed It could be that connection(s) not yet fully es...
unsigned GetConnLimit() const
returns configured connections limit (0 - default)
std::string GetRelativeAddr(const std::shared_ptr< RWebWindow > &win) const
Returns relative URL address for the specified window Address can be required if one needs to access ...
static void SetStartDialogFunc(std::function< bool(const std::shared_ptr< RWebWindow > &, unsigned, const std::string &)>)
Configure func which has to be used for starting dialog.
std::string fPanelName
! panel name which should be shown in the window
void Run(double tm=0.)
Run window functionality for specified time If no action can be performed - just sleep specified time...
std::string GetAddr() const
Returns window address which is used in URL.
std::shared_ptr< RWebWindowsManager > fMgr
! display manager
std::string fProtocolFileName
! local file where communication protocol will be written
ConnectionsList_t fConn
! list of all accepted connections
WebWindowConnectCallback_t fConnCallback
! callback for connect event
void CheckPendingConnections()
Check if started process(es) establish connection.
std::shared_ptr< void > fClearOnClose
! entry which is cleared when last connection is closed
std::mutex fInputQueueMutex
! mutex to protect input queue
std::string _MakeSendHeader(std::shared_ptr< WebConn > &conn, bool txt, const std::string &data, int chid)
Internal method to prepare text part of send data Should be called under locked connection mutex.
std::chrono::time_point< std::chrono::system_clock > timestamp_t
bool ProcessWS(THttpCallArg &arg)
Processing of websockets call-backs, invoked from RWebWindowWSHandler Method invoked from http server...
bool HasConnection(unsigned connid=0, bool only_active=true) const
returns true if specified connection id exists
std::thread fWindowThrd
! special thread for that window
void ProvideQueueEntry(unsigned connid, EQueueEntryKind kind, std::string &&arg)
Provide data to user callback User callback must be executed in the window thread.
bool HasKey(const std::string &key, bool also_newkey=false) const
Returns true if provided key value already exists (in processes map or in existing connections) In sp...
void CompleteWSSend(unsigned wsid)
Complete websocket send operation Clear "doing send" flag and check if next operation has to be start...
bool fUseServerThreads
! indicates that server thread is using, no special window thread
unsigned FindHeadlessConnection()
Returns connection id of window running in headless mode This can be special connection which may run...
int WaitForTimed(WebWindowWaitFunc_t check)
Waits until provided check function or lambdas returns non-zero value Check function has following si...
bool fProcessMT
! if window event processing performed in dedicated thread
int fProtocolCnt
! counter for protocol recording
void SetClientVersion(const std::string &vers)
Set client version, used as prefix in scripts URL When changed, web browser will reload all related J...
void RemoveMasterConnection(unsigned connid=0)
Remove master connection - if any.
void RemoveEmbedWindow(unsigned connid, int channel)
Remove RWebWindow associated with the channelfEmbed.
void SetCallBacks(WebWindowConnectCallback_t conn, WebWindowDataCallback_t data, WebWindowConnectCallback_t disconn=nullptr)
Set call-backs function for connect, data and disconnect events.
std::string GenerateKey() const
Generate new unique key for the window.
void SetUseCurrentDir(bool on=true)
Configure if window can access local files via currentdir/ path of http server.
WebWindowConnectCallback_t fDisconnCallback
! callback for disconnect event
unsigned GetMaxQueueLength() const
Return maximal queue length of data which can be held by window.
static bool IsFileDialogMessage(const std::string &msg)
Check if this could be the message send by client to start new file dialog If returns true,...
static std::string GenerateKey(int keylen=32)
Static method to generate cryptographic key Parameter keylen defines length of cryptographic key in b...
static bool IsMainThrd()
Returns true when called from main process Main process recognized at the moment when library is load...
static std::shared_ptr< RWebWindowsManager > & Instance()
Returns default window manager Used to display all standard ROOT elements like TCanvas or TFitPanel.
static bool IsLoopbackMode()
Returns true if loopback mode used by THttpServer for web widgets.
Contains arguments for single HTTP call.
UInt_t GetWSId() const
get web-socket id
const char * GetTopName() const
returns engine-specific top-name
const void * GetPostData() const
return pointer on posted with request data
const char * GetQuery() const
returns request query (string after ? in request URL)
Long_t GetPostDataLength() const
return length of posted with request data
Bool_t IsMethod(const char *name) const
returns kTRUE if post method is used
const char * GetFileName() const
returns file name from request URL
Online http server for arbitrary ROOT application.
Definition THttpServer.h:31
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2378
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1857
This class represents a WWW compatible URL.
Definition TUrl.h:33
const char * GetValueFromOptions(const char *key) const
Return a value for a given key from the URL options.
Definition TUrl.cxx:660
void SetOptions(const char *opt)
Definition TUrl.h:87
Bool_t HasOption(const char *key) const
Returns true if the given key appears in the URL options list.
Definition TUrl.cxx:683
const Int_t n
Definition legend1.C:16
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
std::function< void(unsigned, const std::string &)> WebWindowDataCallback_t
function signature for call-backs from the window clients first argument is connection id,...
ROOT::Experimental::RLogChannel & WebGUILog()
Log channel for WebGUI diagnostics.
std::function< void(unsigned)> WebWindowConnectCallback_t
function signature for connect/disconnect call-backs argument is connection id
std::function< int(double)> WebWindowWaitFunc_t
function signature for waiting call-backs Such callback used when calling thread need to waits for so...
std::string fData
! text or binary data
bool fText
! is text data
std::shared_ptr< THttpCallArg > fHold
! request used to hold headless browser
~WebConn()
Destructor for WebConn Notify special HTTP request which blocks headless browser from exit.