Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
THttpServer.cxx
Go to the documentation of this file.
1// $Id$
2// Author: Sergey Linev 21/12/2013
3
4/*************************************************************************
5 * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12#include "THttpServer.h"
13
14#include "TThread.h"
15#include "TTimer.h"
16#include "TSystem.h"
17#include "TROOT.h"
18#include "TUrl.h"
19#include "TEnv.h"
20#include "TError.h"
21#include "TClass.h"
22#include "RConfigure.h"
23#include "TRegexp.h"
24#include "TObjArray.h"
25
26#include "THttpEngine.h"
27#include "THttpLongPollEngine.h"
28#include "THttpWSHandler.h"
29#include "TRootSniffer.h"
30#include "TRootSnifferStore.h"
31#include "TCivetweb.h"
32#include "TFastCgi.h"
33
34#include <chrono>
35#include <cstdlib>
36#include <cstring>
37#include <filesystem>
38#include <fstream>
39#include <memory>
40#include <string>
41#include <thread>
42
43class THttpTimer : public TTimer {
44
45public:
46 THttpServer &fServer; ///!< server processing requests
47
48 /// constructor
49 THttpTimer(Long_t milliSec, Bool_t mode, THttpServer &serv) : TTimer(milliSec, mode), fServer(serv) {}
50
51
52 /// timeout handler
53 /// used to process http requests in main ROOT thread
54 void Timeout() override
55 {
57 }
58};
59
60/**
61\class THttpServer
62\brief Online http server for arbitrary ROOT application
63\note This class provides HTTP access to ROOT objects. The user is entirely responsible for the security of the server.
64It is strongly recommended to use the server only within an isolated network
65or to enable proper authentication to prevent unauthorized remote access.
66
67Idea of THttpServer - provide remote http access to running
68ROOT application and enable HTML/JavaScript user interface.
69Any registered object can be requested and displayed in the browser.
70There are many benefits of such approach:
71
721. standard http interface to ROOT application
732. no any temporary ROOT files when access data
743. user interface running in all browsers
75
76To start http server simply create instance
77of the THttpServer class like:
78
79 serv = new THttpServer("http:8080");
80
81This will starts civetweb-based http server with http port 8080.
82Than one should be able to open address "http://localhost:8080"
83in any modern web browser (Firefox, Chrome, Opera, ...) and browse objects,
84created in ROOT application. By default, server can access files,
85canvases and histograms via `gROOT` pointer. All such objects
86can be displayed with JSROOT graphics.
87
88At any time one could register other objects with the command:
89
90 TGraph* gr = new TGraph(10);
91 gr->SetName("gr1");
92 serv->Register("graphs/subfolder", gr);
93
94If objects content is changing in the application, one could
95enable monitoring flag in the browser - than objects view
96will be regularly updated.
97
98More information: https://root.cern/root/htmldoc/guides/HttpServer/HttpServer.html
99*/
100
101
102////////////////////////////////////////////////////////////////////////////////
103/// constructor
104///
105/// As argument, one specifies engine kind which should be
106/// created like "http:8080". One could specify several engines
107/// at once, separating them with semicolon (";"). Following engines are supported:
108///
109/// http - TCivetweb, civetweb-based implementation of http protocol
110/// socket - TCivetweb bound to unix socket
111/// fastcgi - TFastCgi, special protocol for communicating with web servers
112///
113/// For each created engine one should provide socket port number like "http:8080" or "fastcgi:9000".
114/// Additional engine-specific options can be supplied with URL syntax like "http:8080?thrds=10".
115/// Full list of supported options should be checked in engines docu.
116///
117/// One also can configure following options, separated by semicolon:
118///
119/// readonly, ro - set read-only mode (default)
120/// readwrite, rw - allows methods execution of registered objects
121/// global - scans global ROOT lists for existing objects (default)
122/// noglobal - disable scan of global lists
123/// cors - enable CORS header with origin="*"
124/// cors=domain - enable CORS header with origin="domain"
125/// basic_sniffer - use basic sniffer without support of hist, gpad, graph classes
126///
127/// For example, create http server, which allows cors headers and disable scan of global lists,
128/// one should provide "http:8080;cors;noglobal" as parameter
129///
130/// THttpServer uses JavaScript ROOT (https://root.cern/js) to implement web clients UI.
131/// Normally JSROOT sources are used from $ROOTSYS/js directory,
132/// but one could set JSROOTSYS shell variable to specify alternative location
133
134THttpServer::THttpServer(const char *engine) : TNamed("http", "ROOT http server")
135{
136 const char *jsrootsys = gSystem->Getenv("JSROOTSYS");
137 if (!jsrootsys)
138 jsrootsys = gEnv->GetValue("HttpServ.JSRootPath", jsrootsys);
139
140 if (jsrootsys && *jsrootsys) {
141 if ((strncmp(jsrootsys, "http://", 7)==0) || (strncmp(jsrootsys, "https://", 8)==0))
142 fJSROOT = jsrootsys;
143 else
144 fJSROOTSYS = jsrootsys;
145 }
146
147 if (fJSROOTSYS.Length() == 0) {
148 TString jsdir = TString::Format("%s/js", TROOT::GetDataDir().Data());
149 if (gSystem->ExpandPathName(jsdir)) {
150 ::Warning("THttpServer::THttpServer", "problems resolving '%s', set JSROOTSYS to proper JavaScript ROOT location",
151 jsdir.Data());
152 fJSROOTSYS = ".";
153 } else {
154 fJSROOTSYS = jsdir;
155 }
156 }
157
158 Bool_t basic_sniffer = strstr(engine, "basic_sniffer") != nullptr;
159
160 AddLocation("jsrootsys/", fJSROOTSYS.Data());
161
162 if (basic_sniffer) {
163 AddLocation("rootsys_fonts/", TString::Format("%s/fonts", TROOT::GetDataDir().Data()));
164 } else {
165 AddLocation("currentdir/", ".");
166 AddLocation("rootsys/", TROOT::GetRootSys());
167 }
168
169 fDefaultPage = fJSROOTSYS + "/files/online.htm";
170 fDrawPage = fJSROOTSYS + "/files/draw.htm";
171
172 TRootSniffer *sniff = nullptr;
173 if (!basic_sniffer) {
174 static const TClass *snifferClass = TClass::GetClass("TRootSnifferFull");
175 if (snifferClass && snifferClass->IsLoaded())
176 sniff = (TRootSniffer *)snifferClass->New();
177 else
178 ::Warning("THttpServer::THttpServer", "Fail to load TRootSnifferFull class, use basic functionality");
179 }
180
181 if (!sniff) {
182 sniff = new TRootSniffer();
183 sniff->SetScanGlobalDir(kFALSE);
184 sniff->CreateOwnTopFolder(); // use dedicated folder
185 }
186
187 SetSniffer(sniff);
188
189 // start timer
190 SetTimer(20, kTRUE);
191
192 if (strchr(engine, ';') == 0) {
193 CreateEngine(engine);
194 } else {
195 TObjArray *lst = TString(engine).Tokenize(";");
196
197 for (Int_t n = 0; n <= lst->GetLast(); n++) {
198 const char *opt = lst->At(n)->GetName();
199 if ((strcmp(opt, "readonly") == 0) || (strcmp(opt, "ro") == 0)) {
201 } else if ((strcmp(opt, "readwrite") == 0) || (strcmp(opt, "rw") == 0)) {
203 } else if (strcmp(opt, "global") == 0) {
205 } else if (strcmp(opt, "noglobal") == 0) {
207 } else if (strncmp(opt, "cors=", 5) == 0) {
208 SetCors(opt + 5);
209 } else if (strcmp(opt, "cors") == 0) {
210 SetCors("*");
211 } else
212 CreateEngine(opt);
213 }
214
215 delete lst;
216 }
217}
218
219////////////////////////////////////////////////////////////////////////////////
220/// destructor
221///
222/// delete all http engines and sniffer
223
225{
227
228 if (fTerminated) {
229 TIter iter(&fEngines);
230 while (auto engine = dynamic_cast<THttpEngine *>(iter()))
231 engine->Terminate();
232 }
233
235
236 SetSniffer(nullptr);
237
238 SetTimer(0);
239}
240
241////////////////////////////////////////////////////////////////////////////////
242/// Set TRootSniffer to the server
243///
244/// Server takes ownership over sniffer
245
247{
248 fSniffer.reset(sniff);
249}
250
251////////////////////////////////////////////////////////////////////////////////
252/// Set termination flag,
253///
254/// No any further requests will be processed, server only can be destroyed afterwards
255
260
261////////////////////////////////////////////////////////////////////////////////
262/// returns read-only mode
263
265{
266 return fSniffer ? fSniffer->IsReadOnly() : kTRUE;
267}
268
269////////////////////////////////////////////////////////////////////////////////
270/// Set read-only mode for the server (default on)
271///
272/// In read-only server is not allowed to change any ROOT object, registered to the server
273/// Server also cannot execute objects method via exe.json request
274
276{
277 if (fSniffer)
278 fSniffer->SetReadOnly(readonly);
279}
280
281////////////////////////////////////////////////////////////////////////////////
282/// Returns true if server accept object content in POST reequests
283
285{
286 return fSniffer ? fSniffer->IsAllowPostObject() : kFALSE;
287}
288
289////////////////////////////////////////////////////////////////////////////////
290/// Set flag to allow receive and desereilize objects in POST requests
291///
292/// When object methods are executed via exe.json request,
293/// one can supply object as binary/json/xml in the body of POST request
294/// To allow creation of such object, one need to enable this flag
295/// Use of exe.json only possible in not-readonly mode
296///
297/// CAUTION! This is sensitive functionality and therefore should be
298/// used only when server not exposed to publicaly-accessed netowork.
299
301{
302 if (fSniffer)
303 fSniffer->SetAllowPostObject(allow_post_obj);
304}
305
306////////////////////////////////////////////////////////////////////////////////
307/// returns true if only websockets are handled by the server
308///
309/// Typically used by WebGui
310
312{
313 return fWSOnly;
314}
315
316////////////////////////////////////////////////////////////////////////////////
317/// Set websocket-only mode.
318///
319/// If true, server will only handle websockets connection
320/// plus serving file requests to access jsroot/ui5 scripts
321
326
327////////////////////////////////////////////////////////////////////////////////
328/// Add files location, which could be used in the server
329///
330/// One could map some system folder to the server like
331///
332/// serv->AddLocation("mydir/", "/home/user/specials");
333///
334/// Than files from this directory could be addressed via server like `http://localhost:8080/mydir/myfile.root`
335///
336/// The directory replaces all directories of the prefix, also those added with
337/// AppendLocation(). A null `path` removes the prefix.
338
339void THttpServer::AddLocation(const char *prefix, const char *path)
340{
341 if (!prefix || (*prefix == 0))
342 return;
343
344 if (!path)
345 fLocations.erase(prefix);
346 else
347 fLocations[prefix] = {path};
348}
349
350////////////////////////////////////////////////////////////////////////////////
351/// Append a directory to the files location of `prefix`, creating the location
352/// if there is none.
353///
354/// A file requested under a prefix with several directories is served from the
355/// first directory, in the order of AddLocation() and AppendLocation(), that has
356/// it. For example, with
357///
358/// serv->AddLocation("mydir/", "/home/user/specials");
359/// serv->AppendLocation("mydir/", "/usr/share/specials");
360///
361/// `http://localhost:8080/mydir/myfile.root` is served from `/home/user/specials`
362/// if the file is there, else from `/usr/share/specials`.
363
364void THttpServer::AppendLocation(const char *prefix, const char *path)
365{
366 if (!prefix || (*prefix == 0) || !path || (*path == 0))
367 return;
368
369 fLocations[prefix].emplace_back(path);
370}
371
372////////////////////////////////////////////////////////////////////////////////
373/// Set location of JSROOT to use with the server
374///
375/// One could specify address like:
376///
377/// * https://root.cern/js/7.12.0/
378/// * https://jsroot.gsi.de/7.12.0/
379///
380/// This allows to get new JSROOT features with old server,
381/// reduce load on THttpServer instance, also startup time can be improved
382/// When empty string specified (default), local copy of JSROOT is used (distributed with ROOT)
383
384void THttpServer::SetJSROOT(const char *location)
385{
386 fJSROOT = location ? location : "";
387}
388
389////////////////////////////////////////////////////////////////////////////////
390/// Set default HTML page
391///
392/// Sets file name, delivered by the server when http address is opened in the browser.
393///
394/// By default, $ROOTSYS/js/files/online.htm page is used
395/// When empty filename is specified, default page will be used
396
397void THttpServer::SetDefaultPage(const std::string &filename)
398{
399 if (!filename.empty())
401 else
402 fDefaultPage = fJSROOTSYS + "/files/online.htm";
403
404 // force to read page content next time again
405 fDefaultPageCont.clear();
406}
407
408////////////////////////////////////////////////////////////////////////////////
409/// Set drawing HTML page
410///
411/// Set file name of HTML page, delivered by the server when
412/// objects drawing page is requested from the browser
413/// By default, $ROOTSYS/js/files/draw.htm page is used
414/// When empty filename is specified, default page will be used
415
416void THttpServer::SetDrawPage(const std::string &filename)
417{
418 if (!filename.empty())
420 else
421 fDrawPage = fJSROOTSYS + "/files/draw.htm";
422
423 // force to read page content next time again
424 fDrawPageCont.clear();
425}
426
427////////////////////////////////////////////////////////////////////////////////
428/// Factory method to create different http engines
429///
430/// At the moment two engine kinds are supported:
431///
432/// * civetweb or http (default)
433/// * fastcgi
434///
435/// Examples:
436///
437/// // creates civetweb web server with http port 8080
438/// serv->CreateEngine("http:8080");
439/// serv->CreateEngine("civetweb:8080");
440/// serv->CreateEngine(":8080");
441/// // creates civetweb web server bound with unix socket
442/// serv->CreateEngine("socket:/home/user/server.socket?socket_mode=0700");
443/// // creates fastcgi server with port 9000
444/// serv->CreateEngine("fastcgi:9000");
445///
446/// One could apply additional parameters, using URL syntax:
447///
448/// serv->CreateEngine("http:8080?thrds=10");
449
451{
452 if (!engine)
453 return kFALSE;
454
455 const char *arg = strchr(engine, ':');
456 if (!arg)
457 return kFALSE;
458
459 TString clname, sarg;
460 if (arg != engine)
461 clname.Append(engine, arg - engine);
462 arg++; // skip first :
463
464 THttpEngine *eng = nullptr;
465
466 if ((clname.Length() == 0) || (clname == "http") || (clname == "civetweb")) {
467 eng = new TCivetweb(kFALSE);
468#ifndef R__WIN32
469 } else if (clname == "socket") {
470 eng = new TCivetweb(kFALSE);
471 sarg = "x"; // civetweb require x before socket name
472 sarg.Append(arg);
473 arg = sarg.Data();
474#endif
475 } else if (clname == "https") {
476 eng = new TCivetweb(kTRUE);
477 } else if (clname == "fastcgi") {
478 eng = new TFastCgi();
479 }
480
481 if (!eng) {
482 // ensure that required engine class exists before we try to create it
483 TClass *engine_class = gROOT->LoadClass(clname.Data());
484 if (!engine_class)
485 return kFALSE;
486
487 eng = (THttpEngine *)engine_class->New();
488 if (!eng)
489 return kFALSE;
490 }
491
492 eng->SetServer(this);
493
494 if (!eng->Create(arg)) {
495 delete eng;
496 return kFALSE;
497 }
498
499 fEngines.Add(eng);
500
501 return kTRUE;
502}
503
504////////////////////////////////////////////////////////////////////////////////
505/// Create timer which will invoke ProcessRequests() function periodically
506///
507/// Timer is required to perform all actions in main ROOT thread
508/// Method arguments are the same as for TTimer constructor
509/// By default, sync timer with 100 ms period is created
510///
511/// It is recommended to always use sync timer mode and only change period to
512/// adjust server reaction time. Use of async timer requires, that application regularly
513/// calls gSystem->ProcessEvents(). It happens automatically in ROOT interactive shell.
514/// If milliSec == 0, no timer will be created.
515/// In this case application should regularly call ProcessRequests() method.
516///
517/// Async timer allows to use THttpServer in applications, which does not have explicit
518/// gSystem->ProcessEvents() calls. But be aware, that such timer can interrupt any system call
519/// (like malloc) and can lead to dead locks, especially in multi-threaded applications.
520
522{
523 if (fTimer) {
524 fTimer->Stop();
525 fTimer.reset();
526 }
527 if (milliSec > 0) {
528 if (fOwnThread) {
529 Error("SetTimer", "Server runs already in special thread, therefore no any timer can be created");
530 } else {
531 fTimer = std::make_unique<THttpTimer>(milliSec, mode, *this);
532 fTimer->TurnOn();
533 }
534 }
535}
536
537////////////////////////////////////////////////////////////////////////////////
538/// Creates special thread to process all requests, directed to http server
539///
540/// Should be used with care - only dedicated instance of TRootSniffer is allowed
541/// By default THttpServer allows to access global lists pointers gROOT or gFile.
542/// To be on the safe side, all kind of such access performed from the main thread.
543/// Therefore usage of specialized thread means that no any global pointers will
544/// be accessible by THttpServer
545
547{
548 if (fOwnThread)
549 return;
550
551 SetTimer(0);
552 fMainThrdId = 0;
553 fOwnThread = true;
554
555 std::thread thrd([this] {
556 int nempty = 0;
557 while (fOwnThread && !fTerminated) {
558 int nprocess = ProcessRequests();
559 if (nprocess > 0)
560 nempty = 0;
561 else
562 nempty++;
563 if (nempty > 1000) {
564 nempty = 0;
565 std::this_thread::sleep_for(std::chrono::milliseconds(1));
566 }
567 }
568 });
569
570 fThrd = std::move(thrd);
571}
572
573////////////////////////////////////////////////////////////////////////////////
574/// Stop server thread
575///
576/// Normally called shortly before http server destructor
577
579{
580 if (!fOwnThread)
581 return;
582
583 fOwnThread = false;
584 fThrd.join();
585 fMainThrdId = 0;
586}
587
588////////////////////////////////////////////////////////////////////////////////
589/// Checked that filename does not contains relative path below current directory
590///
591/// Used to prevent access to files below current directory
592
594{
595 if (!fname || (*fname == 0))
596 return kFALSE;
597
598 Int_t level = 0;
599
600 while (*fname) {
601
602 // find next slash or backslash
603 const char *next = strpbrk(fname, "/\\");
604 if (next == 0)
605 return kTRUE;
606
607 // most important - change to parent dir
608 if ((next == fname + 2) && (*fname == '.') && (*(fname + 1) == '.')) {
609 fname += 3;
610 level--;
611 if (level < 0)
612 return kFALSE;
613 continue;
614 }
615
616 // ignore current directory
617 if ((next == fname + 1) && (*fname == '.')) {
618 fname += 2;
619 continue;
620 }
621
622 // ignore slash at the front
623 if (next == fname) {
624 fname++;
625 continue;
626 }
627
628 fname = next + 1;
629 level++;
630 }
631
632 return kTRUE;
633}
634
635////////////////////////////////////////////////////////////////////////////////
636/// Verifies that request is just file name
637///
638/// File names typically contains prefix like "jsrootsys/"
639/// If true, method returns real name of the file,
640/// which should be delivered to the client
641/// Method is thread safe and can be called from any thread
642
643Bool_t THttpServer::IsFileRequested(const char *uri, TString &res) const
644{
645 if (!uri || (*uri == 0))
646 return kFALSE;
647
648 TString fname(uri);
649
650 auto file_in_dir = [&fname](const std::string &dir) {
651 TString path = dir.c_str();
652 if ((fname[0] == '/') && (path[path.Length() - 1] == '/'))
653 path.Resize(path.Length() - 1);
654 path.Append(fname);
655 return path;
656 };
657
658 for (auto &entry : fLocations) {
659 Ssiz_t pos = fname.Index(entry.first.c_str());
660 if (pos == kNPOS)
661 continue;
662 fname.Remove(0, pos + (entry.first.length() - 1));
663 if (!VerifyFilePath(fname.Data()))
664 return kFALSE;
665 // With several directories, the first one having the file; when none has
666 // it, the first one, which then fails as a single directory would.
667 // TSystem::AccessPathName() is not used: its helper lookup is thread safe
668 // only after ROOT::EnableThreadSafety().
669 if (entry.second.size() > 1) {
670 for (auto &dir : entry.second) {
671 res = file_in_dir(dir);
672 std::error_code ec;
673 if (std::filesystem::exists(res.Data(), ec))
674 return kTRUE;
675 }
676 }
677 res = file_in_dir(entry.second.front());
678 return kTRUE;
679 }
680
681 return kFALSE;
682}
683
684////////////////////////////////////////////////////////////////////////////////
685/// Executes http request, specified in THttpCallArg structure
686///
687/// Method can be called from any thread
688/// Actual execution will be done in main ROOT thread, where analysis code is running.
689
690Bool_t THttpServer::ExecuteHttp(std::shared_ptr<THttpCallArg> arg)
691{
692 if (fTerminated)
693 return kFALSE;
694
695 if ((fMainThrdId != 0) && (fMainThrdId == TThread::SelfId())) {
696 // should not happen, but one could process requests directly without any signaling
697
698 ProcessRequest(arg);
699
700 return kTRUE;
701 }
702
703 // add call arg to the list
704 std::unique_lock<std::mutex> lk(fMutex);
705 arg->fNotifyFlag = kFALSE;
706 fArgs.push(arg);
707 // and now wait until request is processed
708 arg->fCond.wait(lk);
709
710 return kTRUE;
711}
712
713////////////////////////////////////////////////////////////////////////////////
714/// Submit http request, specified in THttpCallArg structure
715///
716/// Contrary to ExecuteHttp, it will not block calling thread.
717/// User should implement THttpCallArg::HttpReplied() method
718/// to react when HTTP request is executed.
719
720/// Method can be called from any thread
721/// Actual execution will be done in main ROOT thread, where analysis code is running.
722/// When called from main thread and can_run_immediately==kTRUE, will be
723/// executed immediately.
724///
725/// Returns kTRUE when was executed.
726
727Bool_t THttpServer::SubmitHttp(std::shared_ptr<THttpCallArg> arg, Bool_t can_run_immediately)
728{
729 if (fTerminated)
730 return kFALSE;
731
732 if (can_run_immediately && (fMainThrdId != 0) && (fMainThrdId == TThread::SelfId())) {
733 ProcessRequest(arg);
734 arg->NotifyCondition();
735 return kTRUE;
736 }
737
738 // add call arg to the list
739 std::unique_lock<std::mutex> lk(fMutex);
740 fArgs.push(arg);
741 return kFALSE;
742}
743
744////////////////////////////////////////////////////////////////////////////////
745/// Process requests, submitted for execution
746///
747/// Returns number of processed requests
748///
749/// Normally invoked by THttpTimer, when somewhere in the code
750/// gSystem->ProcessEvents() is called.
751/// User can call serv->ProcessRequests() directly, but only from main thread.
752/// If special server thread is created, called from that thread
753
755{
756 auto id = TThread::SelfId();
757
758 if (fMainThrdId != id) {
759 if (gDebug > 0 && fMainThrdId)
760 Warning("ProcessRequests", "Changing main thread to %ld", (long)id);
761 fMainThrdId = id;
762 }
763
764 Bool_t recursion = kFALSE;
765
766 if (fProcessingThrdId) {
767 if (fProcessingThrdId == id) {
768 recursion = kTRUE;
769 } else {
770 Error("ProcessRequests", "Processing already running from %ld thread", (long) fProcessingThrdId);
771 return 0;
772 }
773 }
774
775 if (!recursion)
777
778 Int_t cnt = 0;
779
780 std::unique_lock<std::mutex> lk(fMutex, std::defer_lock);
781
782 // first process requests in the queue
783 while (true) {
784 std::shared_ptr<THttpCallArg> arg;
785
786 lk.lock();
787 if (!fArgs.empty()) {
788 arg = fArgs.front();
789 fArgs.pop();
790 }
791 lk.unlock();
792
793 if (!arg)
794 break;
795
796 if (arg->fFileName == "root_batch_holder.js") {
798 continue;
799 }
800
801 auto prev = fSniffer->SetCurrentCallArg(arg.get());
802
803 try {
804 cnt++;
805 ProcessRequest(arg);
806 fSniffer->SetCurrentCallArg(prev);
807 } catch (...) {
808 fSniffer->SetCurrentCallArg(prev);
809 }
810
811 arg->NotifyCondition();
812 }
813
814 // regularly call Process() method of engine to let perform actions in ROOT context
815 TIter iter(&fEngines);
816 while (auto engine = static_cast<THttpEngine *>(iter())) {
817 if (fTerminated)
818 engine->Terminate();
819 engine->Process();
820 }
821
822 if (!recursion)
824
825 return cnt;
826}
827
828////////////////////////////////////////////////////////////////////////////////
829/// Method called when THttpServer cannot process request
830///
831/// By default such requests replied with 404 code
832/// One could overwrite with method in derived class to process all kinds of such non-standard requests
833
835{
836 arg->Set404();
837}
838
839////////////////////////////////////////////////////////////////////////////////
840/// Process special http request for root_batch_holder.js script
841///
842/// This kind of requests used to hold web browser running in headless mode
843/// Intentionally requests does not replied immediately
844
845void THttpServer::ProcessBatchHolder(std::shared_ptr<THttpCallArg> &arg)
846{
847 auto wsptr = FindWS(arg->GetPathName());
848
849 if (!wsptr || !wsptr->ProcessBatchHolder(arg)) {
850 arg->Set404();
851 arg->NotifyCondition();
852 }
853}
854
855////////////////////////////////////////////////////////////////////////////////
856/// Create summary page with active WS handlers
857
859{
860
861 std::string arr = "[";
862
863 {
864 std::lock_guard<std::mutex> grd(fWSMutex);
865 for (auto &ws : fWSHandlers) {
866 if (arr.length() > 1)
867 arr.append(", ");
868
869 arr.append(TString::Format("{ name: \"%s\", title: \"%s\" }", ws->GetName(), ws->GetTitle()).Data());
870 }
871 }
872
873 arr.append("]");
874
875 std::string res = ReadFileContent((TROOT::GetDataDir() + "/js/files/wslist.htm").Data());
876
877 std::string arg = "\"$$$wslist$$$\"";
878
879 auto pos = res.find(arg);
880 if (pos != std::string::npos)
881 res.replace(pos, arg.length(), arr);
882
883 return res;
884}
885
886////////////////////////////////////////////////////////////////////////////////
887/// Replaces all references like "jsrootsys/..." or other pre-configured pathes
888///
889/// Either using pre-configured JSROOT installation from web or
890/// redirect to jsrootsys from the main server path to benefit from browser caching
891/// Creates appropriate importmap instead of <!--jsroot_importmap--> placeholder
892
893void THttpServer::ReplaceJSROOTLinks(std::shared_ptr<THttpCallArg> &arg, const std::string &version)
894{
895 const std::string place_holder = "<!--jsroot_importmap-->";
896
897 auto p = arg->fContent.find(place_holder);
898
899 bool old_format = (p == std::string::npos);
900
901 // count slashes to handler relative paths to jsroot
902 Int_t slash_cnt = 0;
903 if (arg->fPathName.Length() > 0)
904 slash_cnt++;
905 for (Int_t n = 1; n < arg->fPathName.Length()-1; ++n)
906 if (arg->fPathName[n] == '/') {
907 if (arg->fPathName[n-1] != '/') {
908 slash_cnt++; // normal slash in the middle, count it
909 } else {
910 slash_cnt = 0; // double slash, do not touch such path
911 break;
912 }
913 }
914
915
916 if (old_format) {
917 // old functionality
918
919 if (!version.empty()) {
920 // replace link to JSROOT modules in import statements emulating new version for browser
921 std::string search = "from './jsrootsys/";
922 std::string replace = "from './" + version + "/jsrootsys/";
923 arg->ReplaceAllinContent(search, replace);
924 // replace link to ROOT ui5 modules in import statements emulating new version for browser
925 search = "from './rootui5sys/";
926 replace = "from './" + version + "/rootui5sys/";
927 arg->ReplaceAllinContent(search, replace);
928 // replace link on old JSRoot.core.js script - if still appears
929 search = "jsrootsys/scripts/JSRoot.core.";
930 replace = version + "/jsrootsys/scripts/JSRoot.core.";
931 arg->ReplaceAllinContent(search, replace, true);
932 arg->AddNoCacheHeader();
933 }
934
935 std::string repl;
936
937 if (fJSROOT.Length() > 0) {
938 repl = "=\"";
939 repl.append(fJSROOT.Data());
940 if (repl.back() != '/')
941 repl.append("/");
942 } else {
943 if (slash_cnt > 0) {
944 repl = "=\"";
945 while (slash_cnt-- > 0) repl.append("../");
946 repl.append("jsrootsys/");
947 }
948 }
949
950 if (!repl.empty()) {
951 arg->ReplaceAllinContent("=\"jsrootsys/", repl);
952 arg->ReplaceAllinContent("from './jsrootsys/", TString::Format("from '%s", repl.substr(2).c_str()).Data());
953 }
954 } else {
955 // new functionality creating importmap
956
957 std::string path_prefix, jsroot_prefix;
958 if (slash_cnt > 0) {
959 path_prefix = "";
960 while (slash_cnt-- > 0)
961 path_prefix.append("../");
962 } else {
963 path_prefix = "./";
964 }
965
966 if (!version.empty())
967 path_prefix.append(version + "/");
968
969 if (fJSROOT.Length() > 0) {
970 jsroot_prefix = fJSROOT.Data();
971 if (jsroot_prefix.back() != '/')
972 jsroot_prefix.append("/");
973 } else {
974 jsroot_prefix = path_prefix + "jsrootsys/";
975 }
976
977 static std::map<std::string, std::string> modules = {
978 {"jsroot", "main.mjs"}, {"jsroot/core", "core.mjs"},
979 {"jsroot/io", "io.mjs"}, {"jsroot/tree", "tree.mjs"},
980 {"jsroot/draw", "draw.mjs"}, {"jsroot/gui", "gui.mjs"},
981 {"jsroot/d3", "d3.mjs"}, {"jsroot/three", "three.mjs"}, {"jsroot/three_addons", "three_addons.mjs"},
982 {"jsroot/geom", "geom/TGeoPainter.mjs"}, {"jsroot/hpainter", "gui/HierarchyPainter.mjs"},
983 {"jsroot/webwindow", "webwindow.mjs"}
984 };
985
986 TString space_prefix;
987 auto pspace = p;
988 while ((--pspace > 0) && (arg->fContent[pspace] == ' ') && (space_prefix.Length() < 20))
989 space_prefix.Append(" ");
990
991 bool first = true;
992 TString importmap = "<script type=\"importmap\">\n";
993 importmap += space_prefix + "{\n";
994 importmap += space_prefix + " \"imports\": ";
995 for (auto &entry : modules) {
996 importmap.Append(TString::Format("%s\n%s \"%s\": \"%smodules/%s\"", first ? "{" : ",", space_prefix.Data(), entry.first.c_str(), jsroot_prefix.c_str(), entry.second.c_str()));
997 first = false;
998 }
999 importmap.Append(TString::Format(",\n%s \"jsrootsys/\": \"%s\"", space_prefix.Data(), jsroot_prefix.c_str()));
1000
1001 for (auto &entry : fLocations)
1002 if (entry.first != "jsrootsys/")
1003 importmap.Append(TString::Format(",\n%s \"%s\": \"%s%s\"", space_prefix.Data(), entry.first.c_str(), path_prefix.c_str(), entry.first.c_str()));
1004 importmap.Append("\n");
1005 importmap.Append(space_prefix + " }\n");
1006 importmap.Append(space_prefix + "}\n");
1007 importmap.Append(space_prefix + "</script>\n");
1008
1009 arg->fContent.erase(p, place_holder.length());
1010
1011 arg->fContent.insert(p, importmap.Data());
1012 }
1013}
1014
1015////////////////////////////////////////////////////////////////////////////////
1016/// Process single http request
1017///
1018/// Depending from requested path and filename different actions will be performed.
1019/// In most cases information is provided by TRootSniffer class
1020
1021void THttpServer::ProcessRequest(std::shared_ptr<THttpCallArg> arg)
1022{
1023 if (fTerminated) {
1024 arg->Set404();
1025 return;
1026 }
1027
1028 if ((arg->fFileName == "root.websocket") || (arg->fFileName == "root.longpoll")) {
1029 ExecuteWS(arg);
1030 return;
1031 }
1032
1033 if (arg->fFileName.IsNull() || (arg->fFileName == "index.htm") || (arg->fFileName == "default.htm")) {
1034
1035 std::string version;
1036
1037 if (arg->fFileName == "default.htm") {
1038
1039 if (!IsWSOnly())
1040 arg->fContent = ReadFileContent((fJSROOTSYS + "/files/online.htm").Data());
1041
1042 } else {
1043 auto wsptr = FindWS(arg->GetPathName());
1044
1045 auto handler = wsptr.get();
1046
1047 if (!handler)
1048 handler = dynamic_cast<THttpWSHandler *>(fSniffer->FindTObjectInHierarchy(arg->fPathName.Data()));
1049
1050 if (handler) {
1051
1052 arg->fContent = handler->GetDefaultPageContent().Data();
1053
1054 if (arg->fContent.find("file:") == 0) {
1055 const char *fname = arg->fContent.c_str() + 5;
1056 TString resolve;
1057 if (!IsFileRequested(fname, resolve)) resolve = fname;
1058 arg->fContent = ReadFileContent(resolve.Data());
1059 }
1060
1061 version = handler->GetCodeVersion();
1062
1063 handler->VerifyDefaultPageContent(arg);
1064 }
1065 }
1066
1067 if (arg->fContent.empty() && arg->fFileName.IsNull() && arg->fPathName.IsNull() && IsWSOnly()) {
1068 // Creating page with list of available widgets is disabled now for security reasons
1069 // Later one can provide functionality back only if explicitly desired by the user
1070 // BuildWSEntryPage();
1071
1072 arg->SetContent("refused");
1073 arg->Set404();
1074 }
1075
1076 if (arg->fContent.empty() && !IsWSOnly()) {
1077
1078 if (fDefaultPageCont.empty())
1080
1081 arg->fContent = fDefaultPageCont;
1082 }
1083
1084 if (arg->fContent.empty()) {
1085
1086 arg->Set404();
1087 } else if (!arg->Is404()) {
1088
1089 ReplaceJSROOTLinks(arg, version);
1090
1091 const char *hjsontag = "\"$$$h.json$$$\"";
1092
1093 // add h.json caching
1094 if (arg->fContent.find(hjsontag) != std::string::npos) {
1095 TString h_json;
1096 TRootSnifferStoreJson store(h_json, kTRUE);
1097 const char *topname = fTopName.Data();
1098 if (arg->fTopName.Length() > 0)
1099 topname = arg->fTopName.Data();
1100 fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store);
1101
1102 arg->ReplaceAllinContent(hjsontag, h_json.Data());
1103
1104 arg->AddNoCacheHeader();
1105
1106 if (arg->fQuery.Index("nozip") == kNPOS)
1107 arg->SetZipping();
1108 }
1109 arg->SetContentType("text/html");
1110 }
1111 return;
1112 }
1113
1114 if ((arg->fFileName == "draw.htm") && !IsWSOnly()) {
1115 if (fDrawPageCont.empty())
1117
1118 if (fDrawPageCont.empty()) {
1119 arg->Set404();
1120 } else {
1121 const char *rootjsontag = "\"$$$root.json$$$\"";
1122 const char *hjsontag = "\"$$$h.json$$$\"";
1123
1124 arg->fContent = fDrawPageCont;
1125
1126 ReplaceJSROOTLinks(arg);
1127
1128 if ((arg->fQuery.Index("no_h_json") == kNPOS) && (arg->fQuery.Index("webcanvas") == kNPOS) &&
1129 (arg->fContent.find(hjsontag) != std::string::npos)) {
1130 TString h_json;
1131 TRootSnifferStoreJson store(h_json, kTRUE);
1132 const char *topname = fTopName.Data();
1133 if (arg->fTopName.Length() > 0)
1134 topname = arg->fTopName.Data();
1135 fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store, kTRUE);
1136
1137 arg->ReplaceAllinContent(hjsontag, h_json.Data());
1138 }
1139
1140 if ((arg->fQuery.Index("no_root_json") == kNPOS) && (arg->fQuery.Index("webcanvas") == kNPOS) &&
1141 (arg->fContent.find(rootjsontag) != std::string::npos)) {
1142 std::string str;
1143 if (fSniffer->Produce(arg->fPathName.Data(), "root.json", "compact=23", str))
1144 arg->ReplaceAllinContent(rootjsontag, str);
1145 }
1146 arg->AddNoCacheHeader();
1147 if (arg->fQuery.Index("nozip") == kNPOS)
1148 arg->SetZipping();
1149 arg->SetContentType("text/html");
1150 }
1151 return;
1152 }
1153
1154 if ((arg->fFileName == "favicon.ico") && arg->fPathName.IsNull()) {
1155 arg->SetFile(fJSROOTSYS + "/img/RootIcon.ico");
1156 return;
1157 }
1158
1160 if (IsFileRequested(arg->fFileName.Data(), filename)) {
1161 arg->SetFile(filename);
1162 return;
1163 }
1164
1165 // check if websocket handler may serve file request
1166 if (!arg->fPathName.IsNull() && !arg->fFileName.IsNull()) {
1167 TString wsname = arg->fPathName, fname;
1168 auto pos = wsname.First('/');
1169 if (pos == kNPOS) {
1170 wsname = arg->fPathName;
1171 } else {
1172 wsname = arg->fPathName(0, pos);
1173 fname = arg->fPathName(pos + 1, arg->fPathName.Length() - pos);
1174 fname.Append("/");
1175 }
1176
1177 fname.Append(arg->fFileName);
1178
1179 if (VerifyFilePath(fname.Data())) {
1180
1181 auto ws = FindWS(wsname.Data());
1182
1183 if (ws && ws->CanServeFiles()) {
1184 TString fdir = ws->GetDefaultPageContent();
1185 // only when file is specified, can take directory, append prefix and file name
1186 if (fdir.Index("file:") == 0) {
1187 fdir.Remove(0, 5);
1188 auto separ = fdir.Last('/');
1189 if (separ != kNPOS)
1190 fdir.Resize(separ + 1);
1191 else
1192 fdir = "./";
1193
1194 fdir.Append(fname);
1195 arg->SetFile(fdir);
1196 return;
1197 }
1198 }
1199 }
1200 }
1201
1202 filename = arg->fFileName;
1203
1204 Bool_t iszip = kFALSE;
1205 if (filename.EndsWith(".gz")) {
1206 filename.Resize(filename.Length() - 3);
1207 iszip = kTRUE;
1208 }
1209
1210 if (IsWSOnly()) {
1211 if (arg->fContent.empty())
1212 arg->Set404();
1213 } else if ((filename == "h.xml") || (filename == "get.xml")) {
1214 Bool_t compact = arg->fQuery.Index("compact") != kNPOS,
1215 processed = kFALSE;
1216 TString res;
1217
1218 res.Form("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
1219 if (!compact)
1220 res.Append("\n");
1221 res.Append("<root>");
1222 if (!compact)
1223 res.Append("\n");
1224 {
1225 TRootSnifferStoreXml store(res, compact);
1226 auto len0 = res.Length();
1227 const char *topname = fTopName.Data();
1228 if (arg->fTopName.Length() > 0)
1229 topname = arg->fTopName.Data();
1230 fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store, filename == "get.xml");
1231 processed = res.Length() > len0;
1232 }
1233
1234 res.Append("</root>");
1235 if (!compact)
1236 res.Append("\n");
1237 if (processed) {
1238 arg->SetContent(std::string(res.Data()));
1239 arg->SetXml();
1240 } else
1241 MissedRequest(arg.get());
1242 } else if (filename == "h.json") {
1243 TString res;
1244 TRootSnifferStoreJson store(res, arg->fQuery.Index("compact") != kNPOS);
1245 const char *topname = fTopName.Data();
1246 if (arg->fTopName.Length() > 0)
1247 topname = arg->fTopName.Data();
1248 fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store);
1249
1250 if (res.Length() > 0) {
1251 arg->SetContent(std::string(res.Data()));
1252 arg->SetJson();
1253 } else
1254 MissedRequest(arg.get());
1255 } else if (fSniffer->Produce(arg->fPathName.Data(), filename.Data(), arg->fQuery.Data(), arg->fContent)) {
1256 // define content type base on extension
1257 arg->SetContentType(GetMimeType(filename.Data()));
1258 } else {
1259 // miss request, user may process
1260 MissedRequest(arg.get());
1261 }
1262
1263 if (arg->Is404())
1264 return;
1265
1266 if (iszip)
1267 arg->SetZipping(THttpCallArg::kZipAlways);
1268
1269 if (filename == "root.bin") {
1270 // only for binary data master version is important
1271 // it allows to detect if streamer info was modified
1272 const char *parname = fSniffer->IsStreamerInfoItem(arg->fPathName.Data()) ? "BVersion" : "MVersion";
1273 arg->AddHeader(parname, TString::Format("%u", (unsigned)fSniffer->GetStreamerInfoHash()).Data());
1274 }
1275
1276 // try to avoid caching on the browser
1277 arg->AddNoCacheHeader();
1278
1279 // potentially add cors headers
1280 if (IsCors())
1281 arg->AddHeader("Access-Control-Allow-Origin", GetCors());
1282 if (IsCorsCredentials()) {
1283 arg->AddHeader("Access-Control-Allow-Credentials", GetCorsCredentials());
1284 arg->AddHeader("Access-Control-Expose-Headers", "Content-Range, Content-Length, Date");
1285 arg->AddHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
1286 }
1287}
1288
1289////////////////////////////////////////////////////////////////////////////////
1290/// Register object in folders hierarchy
1291///
1292/// See TRootSniffer::RegisterObject() for more details
1293
1294Bool_t THttpServer::Register(const char *subfolder, TObject *obj)
1295{
1296 return fSniffer->RegisterObject(subfolder, obj);
1297}
1298
1299////////////////////////////////////////////////////////////////////////////////
1300/// Unregister object in folders hierarchy
1301///
1302/// See TRootSniffer::UnregisterObject() for more details
1303
1305{
1306 return fSniffer->UnregisterObject(obj);
1307}
1308
1309////////////////////////////////////////////////////////////////////////////////
1310/// Register WS handler to the THttpServer
1311///
1312/// Only such handler can be used in multi-threaded processing of websockets
1313
1314void THttpServer::RegisterWS(std::shared_ptr<THttpWSHandler> ws)
1315{
1316 std::lock_guard<std::mutex> grd(fWSMutex);
1317 fWSHandlers.emplace_back(ws);
1318}
1319
1320////////////////////////////////////////////////////////////////////////////////
1321/// Unregister WS handler to the THttpServer
1322
1323void THttpServer::UnregisterWS(std::shared_ptr<THttpWSHandler> ws)
1324{
1325 std::lock_guard<std::mutex> grd(fWSMutex);
1326 for (int n = (int)fWSHandlers.size(); n > 0; --n)
1327 if ((fWSHandlers[n - 1] == ws) || fWSHandlers[n - 1]->IsDisabled())
1328 fWSHandlers.erase(fWSHandlers.begin() + n - 1);
1329}
1330
1331////////////////////////////////////////////////////////////////////////////////
1332/// Search WS handler with given name
1333///
1334/// Handler must be registered with RegisterWS() method
1335
1336std::shared_ptr<THttpWSHandler> THttpServer::FindWS(const char *name)
1337{
1338 std::lock_guard<std::mutex> grd(fWSMutex);
1339 for (auto &ws : fWSHandlers) {
1340 if (strcmp(name, ws->GetName()) == 0)
1341 return ws;
1342 }
1343
1344 return nullptr;
1345}
1346
1347////////////////////////////////////////////////////////////////////////////////
1348/// Execute WS related operation
1349
1350Bool_t THttpServer::ExecuteWS(std::shared_ptr<THttpCallArg> &arg, Bool_t external_thrd, Bool_t wait_process)
1351{
1352 if (fTerminated) {
1353 arg->Set404();
1354 return kFALSE;
1355 }
1356
1357 auto wsptr = FindWS(arg->GetPathName());
1358
1359 auto handler = wsptr.get();
1360
1361 if (!handler && !external_thrd)
1362 handler = dynamic_cast<THttpWSHandler *>(fSniffer->FindTObjectInHierarchy(arg->fPathName.Data()));
1363
1364 if (external_thrd && (!handler || !handler->AllowMTProcess())) {
1365
1366 std::unique_lock<std::mutex> lk(fMutex);
1367 fArgs.push(arg);
1368 // and now wait until request is processed
1369 if (wait_process)
1370 arg->fCond.wait(lk);
1371
1372 return kTRUE;
1373 }
1374
1375 if (!handler) {
1376 arg->Set404();
1377 return kFALSE;
1378 }
1379
1380 Bool_t process = kFALSE;
1381
1382 if (arg->fFileName == "root.websocket") {
1383 // handling of web socket
1384 process = handler->HandleWS(arg);
1385 } else if (arg->fFileName == "root.longpoll") {
1386 // ROOT emulation of websocket with polling requests
1387 if (arg->fQuery.BeginsWith("raw_connect") || arg->fQuery.BeginsWith("txt_connect")) {
1388 // try to emulate websocket connect
1389 // if accepted, reply with connection id, which must be used in the following communications
1390 arg->SetMethod("WS_CONNECT");
1391
1392 bool israw = arg->fQuery.BeginsWith("raw_connect");
1393
1394 // automatically assign engine to arg
1395 arg->CreateWSEngine<THttpLongPollEngine>(israw);
1396
1397 if (handler->HandleWS(arg)) {
1398 arg->SetMethod("WS_READY");
1399
1400 if (handler->HandleWS(arg))
1401 arg->SetTextContent(std::string(israw ? "txt:" : "") + std::to_string(arg->GetWSId()));
1402 } else {
1403 arg->TakeWSEngine(); // delete handle
1404 }
1405
1406 process = arg->IsText();
1407 } else {
1408 TUrl url;
1409 url.SetOptions(arg->fQuery);
1410 url.ParseOptions();
1411 const char *connid = url.GetValueFromOptions("connection");
1412 if (connid)
1413 arg->SetWSId(std::stoul(connid));
1414 if (url.HasOption("close")) {
1415 arg->SetMethod("WS_CLOSE");
1416 arg->SetTextContent("OK");
1417 } else {
1418 arg->SetMethod("WS_DATA");
1419 }
1420
1421 process = handler->HandleWS(arg);
1422 }
1423 }
1424
1425 if (!process)
1426 arg->Set404();
1427
1428 return process;
1429}
1430
1431////////////////////////////////////////////////////////////////////////////////
1432/// Restrict access to specified object
1433///
1434/// See TRootSniffer::Restrict() for more details
1435
1436void THttpServer::Restrict(const char *path, const char *options)
1437{
1438 fSniffer->Restrict(path, options);
1439}
1440
1441////////////////////////////////////////////////////////////////////////////////
1442/// Register command which can be executed from web interface
1443///
1444/// As method one typically specifies string, which is executed with
1445/// gROOT->ProcessLine() method. For instance:
1446///
1447/// serv->RegisterCommand("Invoke","InvokeFunction()");
1448///
1449/// Or one could specify any method of the object which is already registered
1450/// to the server. For instance:
1451///
1452/// serv->Register("/", hpx);
1453/// serv->RegisterCommand("/ResetHPX", "/hpx/->Reset()");
1454///
1455/// Here symbols '/->' separates item name from method to be executed
1456///
1457/// One could specify additional arguments in the command with
1458/// syntax like %arg1%, %arg2% and so on. For example:
1459///
1460/// serv->RegisterCommand("/ResetHPX", "/hpx/->SetTitle(\"%arg1%\")");
1461/// serv->RegisterCommand("/RebinHPXPY", "/hpxpy/->Rebin2D(%arg1%,%arg2%)");
1462///
1463/// Such parameter(s) will be requested when command clicked in the browser.
1464///
1465/// Once command is registered, one could specify icon which will appear in the browser:
1466///
1467/// serv->SetIcon("/ResetHPX", "rootsys/icons/ed_execute.png");
1468///
1469/// One also can set extra property '_fastcmd', that command appear as
1470/// tool button on the top of the browser tree:
1471///
1472/// serv->SetItemField("/ResetHPX", "_fastcmd", "true");
1473///
1474/// Or it is equivalent to specifying extra argument when register command:
1475///
1476/// serv->RegisterCommand("/ResetHPX", "/hpx/->Reset()", "button;rootsys/icons/ed_delete.png");
1477
1478Bool_t THttpServer::RegisterCommand(const char *cmdname, const char *method, const char *icon)
1479{
1480 return fSniffer->RegisterCommand(cmdname, method, icon);
1481}
1482
1483////////////////////////////////////////////////////////////////////////////////
1484/// Hides folder or element from web gui
1485
1486Bool_t THttpServer::Hide(const char *foldername, Bool_t hide)
1487{
1488 return SetItemField(foldername, "_hidden", hide ? "true" : (const char *)0);
1489}
1490
1491////////////////////////////////////////////////////////////////////////////////
1492/// Set name of icon, used in browser together with the item
1493///
1494/// One could use images from $ROOTSYS directory like:
1495/// serv->SetIcon("/ResetHPX","/rootsys/icons/ed_execute.png");
1496
1497Bool_t THttpServer::SetIcon(const char *fullname, const char *iconname)
1498{
1499 return SetItemField(fullname, "_icon", iconname);
1500}
1501
1502////////////////////////////////////////////////////////////////////////////////
1503/// Create item in sniffer
1504
1505Bool_t THttpServer::CreateItem(const char *fullname, const char *title)
1506{
1507 return fSniffer->CreateItem(fullname, title);
1508}
1509
1510////////////////////////////////////////////////////////////////////////////////
1511/// Set item field in sniffer
1512
1513Bool_t THttpServer::SetItemField(const char *fullname, const char *name, const char *value)
1514{
1515 return fSniffer->SetItemField(fullname, name, value);
1516}
1517
1518////////////////////////////////////////////////////////////////////////////////
1519/// Get item field from sniffer
1520
1521const char *THttpServer::GetItemField(const char *fullname, const char *name)
1522{
1523 return fSniffer->GetItemField(fullname, name);
1524}
1525
1526////////////////////////////////////////////////////////////////////////////////
1527/// Returns MIME type base on file extension
1528
1529const char *THttpServer::GetMimeType(const char *path)
1530{
1531 static const struct {
1532 const char *extension;
1533 int ext_len;
1534 const char *mime_type;
1535 } builtin_mime_types[] = {{".xml", 4, "text/xml"},
1536 {".json", 5, "application/json"},
1537 {".bin", 4, "application/x-binary"},
1538 {".gif", 4, "image/gif"},
1539 {".jpg", 4, "image/jpeg"},
1540 {".png", 4, "image/png"},
1541 {".html", 5, "text/html"},
1542 {".htm", 4, "text/html"},
1543 {".shtm", 5, "text/html"},
1544 {".shtml", 6, "text/html"},
1545 {".css", 4, "text/css"},
1546 {".js", 3, "application/x-javascript"},
1547 {".mjs", 4, "text/javascript"},
1548 {".ico", 4, "image/x-icon"},
1549 {".jpeg", 5, "image/jpeg"},
1550 {".svg", 4, "image/svg+xml"},
1551 {".txt", 4, "text/plain"},
1552 {".torrent", 8, "application/x-bittorrent"},
1553 {".wav", 4, "audio/x-wav"},
1554 {".mp3", 4, "audio/x-mp3"},
1555 {".mid", 4, "audio/mid"},
1556 {".m3u", 4, "audio/x-mpegurl"},
1557 {".ogg", 4, "application/ogg"},
1558 {".ram", 4, "audio/x-pn-realaudio"},
1559 {".xslt", 5, "application/xml"},
1560 {".xsl", 4, "application/xml"},
1561 {".ra", 3, "audio/x-pn-realaudio"},
1562 {".doc", 4, "application/msword"},
1563 {".exe", 4, "application/octet-stream"},
1564 {".zip", 4, "application/x-zip-compressed"},
1565 {".xls", 4, "application/excel"},
1566 {".tgz", 4, "application/x-tar-gz"},
1567 {".tar", 4, "application/x-tar"},
1568 {".gz", 3, "application/x-gunzip"},
1569 {".arj", 4, "application/x-arj-compressed"},
1570 {".rar", 4, "application/x-arj-compressed"},
1571 {".rtf", 4, "application/rtf"},
1572 {".pdf", 4, "application/pdf"},
1573 {".swf", 4, "application/x-shockwave-flash"},
1574 {".mpg", 4, "video/mpeg"},
1575 {".webm", 5, "video/webm"},
1576 {".mpeg", 5, "video/mpeg"},
1577 {".mov", 4, "video/quicktime"},
1578 {".mp4", 4, "video/mp4"},
1579 {".m4v", 4, "video/x-m4v"},
1580 {".asf", 4, "video/x-ms-asf"},
1581 {".avi", 4, "video/x-msvideo"},
1582 {".bmp", 4, "image/bmp"},
1583 {".ttf", 4, "application/x-font-ttf"},
1584 {".woff", 5, "font/woff"},
1585 {".woff2", 6, "font/woff2"},
1586 {NULL, 0, NULL}};
1587
1588 int path_len = strlen(path);
1589
1590 for (int i = 0; builtin_mime_types[i].extension != NULL; i++) {
1591 if (path_len <= builtin_mime_types[i].ext_len)
1592 continue;
1593 const char *ext = path + (path_len - builtin_mime_types[i].ext_len);
1594 if (strcmp(ext, builtin_mime_types[i].extension) == 0) {
1595 return builtin_mime_types[i].mime_type;
1596 }
1597 }
1598
1599 return "text/plain";
1600}
1601
1602////////////////////////////////////////////////////////////////////////////////
1603/// Reads file content
1604///
1605/// @deprecated
1606
1608{
1609 len = 0;
1610
1611 std::ifstream is(filename, std::ios::in | std::ios::binary);
1612 if (!is)
1613 return nullptr;
1614
1615 is.seekg(0, is.end);
1616 len = is.tellg();
1617 is.seekg(0, is.beg);
1618
1619 char *buf = (char *)malloc(len);
1620 is.read(buf, len);
1621 if (!is) {
1622 free(buf);
1623 len = 0;
1624 return nullptr;
1625 }
1626
1627 return buf;
1628}
1629
1630////////////////////////////////////////////////////////////////////////////////
1631/// Reads file content, using std::string as container
1632
1633std::string THttpServer::ReadFileContent(const std::string &filename)
1634{
1635 std::ifstream is(filename, std::ios::in | std::ios::binary);
1636 std::string res;
1637 if (is) {
1638 is.seekg(0, std::ios::end);
1639 res.resize(is.tellg());
1640 is.seekg(0, std::ios::beg);
1641 is.read((char *)res.data(), res.length());
1642 if (!is)
1643 res.clear();
1644 }
1645 return res;
1646}
free(fBuffer)
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:69
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:132
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
R__EXTERN TEnv * gEnv
Definition TEnv.h:126
winID h TVirtualViewer3D TVirtualGLPainter p
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 filename
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 on
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
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 mode
char name[80]
Definition TGX11.cxx:142
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:792
#define gROOT
Definition TROOT.h:417
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
THttpEngine implementation, based on civetweb embedded server.
Definition TCivetweb.h:21
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition TClass.cxx:5107
static TClass * LoadClass(const char *requestedname, Bool_t silent)
Helper function used by TClass::GetClass().
Definition TClass.cxx:5922
Bool_t IsLoaded() const
Return true if the shared library of this class is currently in the a process's memory.
Definition TClass.cxx:6088
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2999
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:511
THttpEngine implementation, based on fastcgi package.
Definition TFastCgi.h:20
Contains arguments for single HTTP call.
void Set404()
mark reply as 404 error - page/request not exists or refused
Abstract class for implementing http protocol for THttpServer.
Definition THttpEngine.h:19
void SetServer(THttpServer *serv)
Definition THttpEngine.h:27
virtual Bool_t Create(const char *)
Method to create all components of engine.
Definition THttpEngine.h:37
Emulation of websocket with long poll requests.
Online http server for arbitrary ROOT application.
Definition THttpServer.h:31
Bool_t IsReadOnly() const
returns read-only mode
Bool_t RegisterCommand(const char *cmdname, const char *method, const char *icon=nullptr)
Register command which can be executed from web interface.
TString fJSROOT
! location of external JSROOT files
Definition THttpServer.h:46
virtual void ProcessRequest(std::shared_ptr< THttpCallArg > arg)
Process single http request.
std::shared_ptr< THttpWSHandler > FindWS(const char *name)
Find web-socket handler with given name.
std::unique_ptr< TRootSniffer > fSniffer
! sniffer provides access to ROOT objects hierarchy
Definition THttpServer.h:36
void SetTimer(Long_t milliSec=100, Bool_t mode=kTRUE)
Create timer which will invoke ProcessRequests() function periodically.
virtual void ProcessBatchHolder(std::shared_ptr< THttpCallArg > &arg)
Process special http request for root_batch_holder.js script.
std::vector< std::shared_ptr< THttpWSHandler > > fWSHandlers
! list of WS handlers
Definition THttpServer.h:61
virtual ~THttpServer()
destructor
void SetTerminate()
set termination flag, no any further requests will be processed
virtual void MissedRequest(THttpCallArg *arg)
Method called when THttpServer cannot process request.
Bool_t fOwnThread
! true when specialized thread allocated for processing requests
Definition THttpServer.h:40
void SetSniffer(TRootSniffer *sniff)
Set TRootSniffer to the server.
Bool_t IsFileRequested(const char *uri, TString &res) const
Check if file is requested, thread safe.
void SetReadOnly(Bool_t readonly=kTRUE)
Set read-only mode for the server (default on)
const char * GetItemField(const char *fullname, const char *name)
Get item field from sniffer.
const char * GetCors() const
Returns specified CORS domain.
std::thread fThrd
! own thread
Definition THttpServer.h:41
void StopServerThread()
Stop server thread.
Int_t ProcessRequests()
Process submitted requests, must be called from appropriate thread.
Bool_t ExecuteWS(std::shared_ptr< THttpCallArg > &arg, Bool_t external_thrd=kFALSE, Bool_t wait_process=kFALSE)
Execute WS request.
void RegisterWS(std::shared_ptr< THttpWSHandler > ws)
Register WS handler.
void AppendLocation(const char *prefix, const char *path)
Append a directory to the files location of prefix, creating the location if there is none.
Long_t fProcessingThrdId
! id of the thread where events are recently processing
Definition THttpServer.h:39
TString fTopName
! name of top folder, default - "ROOT"
Definition THttpServer.h:45
void SetDrawPage(const std::string &filename="")
Set drawing HTML page.
Bool_t CreateItem(const char *fullname, const char *title)
Create item in sniffer.
Bool_t ExecuteHttp(std::shared_ptr< THttpCallArg > arg)
Execute HTTP request.
Bool_t Hide(const char *fullname, Bool_t hide=kTRUE)
Hides folder or element from web gui.
Bool_t IsCorsCredentials() const
Returns kTRUE if Access-Control-Allow-Credentials header should be used.
void AddLocation(const char *prefix, const char *path)
Add files location, which could be used in the server.
Bool_t SubmitHttp(std::shared_ptr< THttpCallArg > arg, Bool_t can_run_immediately=kFALSE)
Submit HTTP request.
Long_t fMainThrdId
! id of the thread for processing requests
Definition THttpServer.h:38
TString fJSROOTSYS
! location of local JSROOT files
Definition THttpServer.h:44
std::unique_ptr< THttpTimer > fTimer
! timer used to access main thread
Definition THttpServer.h:35
Bool_t fWSOnly
! when true, handle only websockets / longpoll engine
Definition THttpServer.h:42
Bool_t Register(const char *subfolder, TObject *obj)
Register object in subfolder.
TList fEngines
! engines which runs http server
Definition THttpServer.h:34
void SetCors(const std::string &domain="*")
Enable CORS header to ProcessRequests() responses Specified location (typically "*") add as "Access-C...
Bool_t IsCors() const
Returns kTRUE if CORS was configured.
const char * GetCorsCredentials() const
Returns specified CORS credentials value - if any.
std::queue< std::shared_ptr< THttpCallArg > > fArgs
! submitted arguments
Definition THttpServer.h:58
void SetDefaultPage(const std::string &filename="")
Set default HTML page.
THttpServer(const THttpServer &)=delete
static char * ReadFileContent(const char *filename, Int_t &len)
Reads content of file from the disk.
void CreateServerThread()
Creates special thread to process all requests, directed to http server.
std::string fDrawPageCont
! content of draw html page
Definition THttpServer.h:53
Bool_t Unregister(TObject *obj)
Unregister object.
void SetWSOnly(Bool_t on=kTRUE)
Set websocket-only mode.
std::string BuildWSEntryPage()
Create summary page with active WS handlers.
Bool_t IsWSOnly() const
returns true if only websockets are handled by the server
std::mutex fWSMutex
! mutex to protect WS handler lists
Definition THttpServer.h:60
virtual Bool_t CreateEngine(const char *engine)
Factory method to create different http engines.
Bool_t SetIcon(const char *fullname, const char *iconname)
Set name of icon, used in browser together with the item.
std::string fDrawPage
! file name for drawing of single element
Definition THttpServer.h:52
std::string fDefaultPageCont
! content of default html page
Definition THttpServer.h:51
static Bool_t VerifyFilePath(const char *fname)
Checked that filename does not contains relative path below current directory.
Bool_t IsAllowPostObject() const
Returns true if server accept object content in POST reequests.
Bool_t SetItemField(const char *fullname, const char *name, const char *value)
Set item field in sniffer.
void SetAllowPostObject(Bool_t allow_post_obj)
Set flag to allow receive and desereilize objects in POST requests.
void SetJSROOT(const char *location)
Set location of JSROOT to use with the server.
std::mutex fMutex
! mutex to protect list with arguments
Definition THttpServer.h:57
std::string fDefaultPage
! file name for default page name
Definition THttpServer.h:50
void UnregisterWS(std::shared_ptr< THttpWSHandler > ws)
Unregister WS handler.
std::map< std::string, std::vector< std::string > > fLocations
! local directories served, per prefix
Definition THttpServer.h:48
static const char * GetMimeType(const char *path)
Guess mime type base on file extension.
TRootSniffer * GetSniffer() const
returns pointer on objects sniffer
Definition THttpServer.h:89
void ReplaceJSROOTLinks(std::shared_ptr< THttpCallArg > &arg, const std::string &version="")
Replaces all references like "jsrootsys/..." or other pre-configured pathes.
Bool_t fTerminated
! termination flag, disables all requests processing
Definition THttpServer.h:37
void Restrict(const char *path, const char *options)
Restrict access to specified object.
void Timeout() override
timeout handler used to process http requests in main ROOT thread
THttpServer & fServer
THttpTimer(Long_t milliSec, Bool_t mode, THttpServer &serv)
!< server processing requests
Class for user-side handling of websocket with THttpServer.
void Add(TObject *obj) override
Definition TList.h:81
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:600
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
An array of TObjects.
Definition TObjArray.h:31
TObject * At(Int_t idx) const override
Definition TObjArray.h:170
Int_t GetLast() const override
Return index of last object in array.
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1082
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1096
static const TString & GetRootSys()
Get the rootsys directory in the installation. Static utility function.
Definition TROOT.cxx:3155
static const TString & GetDataDir()
Get the data directory in the installation. Static utility function.
Definition TROOT.cxx:3406
Storage of hierarchy scan in TRootSniffer in JSON format.
Storage of hierarchy scan in TRootSniffer in XML format.
Sniffer of ROOT objects, data provider for THttpServer.
void CreateOwnTopFolder()
Create own TFolder structures independent from gROOT This allows to have many independent TRootSniffe...
void SetReadOnly(Bool_t on=kTRUE)
When readonly on (default), sniffer is not allowed to change ROOT structures For instance,...
void SetScanGlobalDir(Bool_t on=kTRUE)
When enabled (default), sniffer scans gROOT for files, canvases, histograms.
Basic string class.
Definition TString.h:137
Ssiz_t Length() const
Definition TString.h:426
Ssiz_t First(char c) const
Find first occurrence of a character c.
Definition TString.cxx:546
const char * Data() const
Definition TString.h:385
void Resize(Ssiz_t n)
Resize the string. Truncate or add blanks as necessary.
Definition TString.cxx:1160
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition TString.cxx:939
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition TString.cxx:2345
TString & Remove(Ssiz_t pos)
Definition TString.h:695
TString & Append(const char *cs)
Definition TString.h:582
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:2460
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2438
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:661
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1296
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1687
static Long_t SelfId()
Static method returning the id for the current thread.
Definition TThread.cxx:554
Handles synchronous and a-synchronous timer events.
Definition TTimer.h:51
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:662
void SetOptions(const char *opt)
Definition TUrl.h:87
void ParseOptions() const
Parse URL options into a key/value map.
Definition TUrl.cxx:628
Bool_t HasOption(const char *key) const
Returns true if the given key appears in the URL options list.
Definition TUrl.cxx:685
const Int_t n
Definition legend1.C:16