Logo ROOT   6.08/02
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
THttpServer.cxx
Go to the documentation of this file.
1 // $Id$
2 // Author: Sergey Linev 21/12/2013
3 
4 #include "THttpServer.h"
5 
6 #include "TThread.h"
7 #include "TTimer.h"
8 #include "TSystem.h"
9 #include "TImage.h"
10 #include "TROOT.h"
11 #include "TClass.h"
12 #include "TCanvas.h"
13 #include "TFolder.h"
14 #include "RVersion.h"
15 #include "RConfigure.h"
16 
17 #include "THttpEngine.h"
18 #include "TRootSniffer.h"
19 #include "TRootSnifferStore.h"
20 
21 #include <string>
22 #include <cstdlib>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <fstream>
26 
27 
28 //////////////////////////////////////////////////////////////////////////
29 // //
30 // THttpTimer //
31 // //
32 // Specialized timer for THttpServer //
33 // Provides regular call of THttpServer::ProcessRequests() method //
34 // //
35 //////////////////////////////////////////////////////////////////////////
36 
37 
38 ////////////////////////////////////////////////////////////////////////////////
39 
40 class THttpTimer : public TTimer {
41 public:
42 
43  THttpServer *fServer; //!
44 
45  THttpTimer(Long_t milliSec, Bool_t mode, THttpServer *serv) :
46  TTimer(milliSec, mode), fServer(serv)
47  {
48  // construtor
49  }
50  virtual ~THttpTimer()
51  {
52  // destructor
53  }
54  virtual void Timeout()
55  {
56  // timeout handler
57  // used to process http requests in main ROOT thread
58 
59  if (fServer) fServer->ProcessRequests();
60  }
61 };
62 
63 // =======================================================
64 
65 //////////////////////////////////////////////////////////////////////////
66 // //
67 // THttpServer //
68 // //
69 // Online http server for arbitrary ROOT application //
70 // //
71 // Idea of THttpServer - provide remote http access to running //
72 // ROOT application and enable HTML/JavaScript user interface. //
73 // Any registered object can be requested and displayed in the browser. //
74 // There are many benefits of such approach: //
75 // * standard http interface to ROOT application //
76 // * no any temporary ROOT files when access data //
77 // * user interface running in all browsers //
78 // //
79 // Starting HTTP server //
80 // //
81 // To start http server, at any time create instance //
82 // of the THttpServer class like: //
83 // serv = new THttpServer("http:8080"); //
84 // //
85 // This will starts civetweb-based http server with http port 8080. //
86 // Than one should be able to open address "http://localhost:8080" //
87 // in any modern browser (IE, Firefox, Chrome) and browse objects, //
88 // created in application. By default, server can access files, //
89 // canvases and histograms via gROOT pointer. All such objects //
90 // can be displayed with JSROOT graphics. //
91 // //
92 // At any time one could register other objects with the command: //
93 // //
94 // TGraph* gr = new TGraph(10); //
95 // gr->SetName("gr1"); //
96 // serv->Register("graphs/subfolder", gr); //
97 // //
98 // If objects content is changing in the application, one could //
99 // enable monitoring flag in the browser - than objects view //
100 // will be regularly updated. //
101 // //
102 // More information: http://root.cern.ch/drupal/content/users-guide //
103 // //
104 //////////////////////////////////////////////////////////////////////////
105 
107 
108 ////////////////////////////////////////////////////////////////////////////////
109 /// constructor
110 
111 THttpServer::THttpServer(const char *engine) :
112  TNamed("http", "ROOT http server"),
113  fEngines(),
114  fTimer(0),
115  fSniffer(0),
116  fMainThrdId(0),
117  fJSROOTSYS(),
118  fTopName("ROOT"),
119  fJSROOT(),
120  fLocations(),
121  fDefaultPage(),
122  fDefaultPageCont(),
123  fDrawPage(),
124  fDrawPageCont(),
125  fCallArgs()
126 {
127  // As argument, one specifies engine kind which should be
128  // created like "http:8080". One could specify several engines
129  // at once, separating them with ; like "http:8080;fastcgi:9000"
130  // One also can configure readonly flag for sniffer like
131  // "http:8080;readonly" or "http:8080;readwrite"
132  //
133  // Also searches for JavaScript ROOT sources, which are used in web clients
134  // Typically JSROOT sources located in $ROOTSYS/etc/http directory,
135  // but one could set JSROOTSYS variable to specify alternative location
136 
137  fLocations.SetOwner(kTRUE);
138 
139  // Info("THttpServer", "Create %p in thrd %ld", this, (long) fMainThrdId);
140 
141 #ifdef COMPILED_WITH_DABC
142  const char *dabcsys = gSystem->Getenv("DABCSYS");
143  if (dabcsys != 0)
144  fJSROOTSYS = TString::Format("%s/plugins/root/js", dabcsys);
145 #endif
146 
147  const char *jsrootsys = gSystem->Getenv("JSROOTSYS");
148  if (jsrootsys != 0) fJSROOTSYS = jsrootsys;
149 
150  if (fJSROOTSYS.Length() == 0) {
151  TString jsdir = TString::Format("%s/http", TROOT::GetEtcDir().Data());
152  if (gSystem->ExpandPathName(jsdir)) {
153  Warning("THttpServer", "problems resolving '%s', use JSROOTSYS to specify $ROOTSYS/etc/http location", jsdir.Data());
154  fJSROOTSYS = ".";
155  } else {
156  fJSROOTSYS = jsdir;
157  }
158  }
159 
160  AddLocation("currentdir/", ".");
161  AddLocation("jsrootsys/", fJSROOTSYS);
162  AddLocation("rootsys/", TROOT::GetRootSys());
163 
164  fDefaultPage = fJSROOTSYS + "/files/online.htm";
165  fDrawPage = fJSROOTSYS + "/files/draw.htm";
166 
167  SetSniffer(new TRootSniffer("sniff"));
168 
169  // start timer
170  SetTimer(20, kTRUE);
171 
172  if (strchr(engine, ';') == 0) {
173  CreateEngine(engine);
174  } else {
175  TObjArray *lst = TString(engine).Tokenize(";");
176 
177  for (Int_t n = 0; n <= lst->GetLast(); n++) {
178  const char *opt = lst->At(n)->GetName();
179  if ((strcmp(opt, "readonly") == 0) || (strcmp(opt, "ro") == 0)) {
180  GetSniffer()->SetReadOnly(kTRUE);
181  } else if ((strcmp(opt, "readwrite") == 0) || (strcmp(opt, "rw") == 0)) {
182  GetSniffer()->SetReadOnly(kFALSE);
183  } else
184  CreateEngine(opt);
185  }
186 
187  delete lst;
188  }
189 }
190 
191 ////////////////////////////////////////////////////////////////////////////////
192 /// destructor
193 /// delete all http engines and sniffer
194 
196 {
197  fEngines.Delete();
198 
199  SetSniffer(0);
200 
201  SetTimer(0);
202 }
203 
204 ////////////////////////////////////////////////////////////////////////////////
205 /// Set TRootSniffer to the server
206 /// Server takes ownership over sniffer
207 
209 {
210  if (fSniffer) delete fSniffer;
211  fSniffer = sniff;
212 }
213 
214 ////////////////////////////////////////////////////////////////////////////////
215 /// returns read-only mode
216 
218 {
219  return fSniffer ? fSniffer->IsReadOnly() : kTRUE;
220 }
221 
222 ////////////////////////////////////////////////////////////////////////////////
223 /// Set read-only mode for the server (default on)
224 /// In read-only server is not allowed to change any ROOT object, registered to the server
225 /// Server also cannot execute objects method via exe.json request
226 
228 {
229  if (fSniffer) fSniffer->SetReadOnly(readonly);
230 }
231 
232 ////////////////////////////////////////////////////////////////////////////////
233 /// add files location, which could be used in the server
234 /// one could map some system folder to the server like AddLocation("mydir/","/home/user/specials");
235 /// Than files from this directory could be addressed via server like
236 /// http://localhost:8080/mydir/myfile.root
237 
238 void THttpServer::AddLocation(const char *prefix, const char *path)
239 {
240  if ((prefix==0) || (*prefix==0)) return;
241 
242  TNamed *obj = dynamic_cast<TNamed*> (fLocations.FindObject(prefix));
243  if (obj != 0) {
244  obj->SetTitle(path);
245  } else {
246  fLocations.Add(new TNamed(prefix, path));
247  }
248 }
249 
250 ////////////////////////////////////////////////////////////////////////////////
251 /// Set location of JSROOT to use with the server
252 /// One could specify address like:
253 /// https://root.cern.ch/js/3.3/
254 /// http://web-docs.gsi.de/~linev/js/3.3/
255 /// This allows to get new JSROOT features with old server,
256 /// reduce load on THttpServer instance, also startup time can be improved
257 /// When empty string specified (default), local copy of JSROOT is used (distributed with ROOT)
258 
259 void THttpServer::SetJSROOT(const char* location)
260 {
261  fJSROOT = location ? location : "";
262 }
263 
264 ////////////////////////////////////////////////////////////////////////////////
265 /// Set file name of HTML page, delivered by the server when
266 /// http address is opened in the browser.
267 /// By default, $ROOTSYS/etc/http/files/online.htm page is used
268 /// When empty filename is specified, default page will be used
269 
270 void THttpServer::SetDefaultPage(const char* filename)
271 {
272  if ((filename!=0) && (*filename!=0))
273  fDefaultPage = filename;
274  else
275  fDefaultPage = fJSROOTSYS + "/files/online.htm";
276 
277  // force to read page content next time again
279 }
280 
281 ////////////////////////////////////////////////////////////////////////////////
282 /// Set file name of HTML page, delivered by the server when
283 /// objects drawing page is requested from the browser
284 /// By default, $ROOTSYS/etc/http/files/draw.htm page is used
285 /// When empty filename is specified, default page will be used
286 
287 void THttpServer::SetDrawPage(const char* filename)
288 {
289  if ((filename!=0) && (*filename!=0))
290  fDrawPage = filename;
291  else
292  fDrawPage = fJSROOTSYS + "/files/draw.htm";
293 
294  // force to read page content next time again
296 }
297 
298 ////////////////////////////////////////////////////////////////////////////////
299 /// factory method to create different http engines
300 /// At the moment two engine kinds are supported:
301 /// civetweb (default) and fastcgi
302 /// Examples:
303 /// "civetweb:8080" or "http:8080" or ":8080" - creates civetweb web server with http port 8080
304 /// "fastcgi:9000" - creates fastcgi server with port 9000
305 /// "dabc:1237" - create DABC server with port 1237 (only available with DABC installed)
306 /// "dabc:master_host:port" - attach to DABC master, running on master_host:port (only available with DABC installed)
307 
309 {
310  if (engine == 0) return kFALSE;
311 
312  const char *arg = strchr(engine, ':');
313  if (arg == 0) return kFALSE;
314 
315  TString clname;
316  if (arg != engine) clname.Append(engine, arg - engine);
317 
318  if ((clname.Length() == 0) || (clname == "http") || (clname == "civetweb"))
319  clname = "TCivetweb";
320  else if (clname == "fastcgi")
321  clname = "TFastCgi";
322  else if (clname == "dabc")
323  clname = "TDabcEngine";
324 
325  // ensure that required engine class exists before we try to create it
326  TClass *engine_class = gROOT->LoadClass(clname.Data());
327  if (engine_class == 0) return kFALSE;
328 
329  THttpEngine *eng = (THttpEngine *) engine_class->New();
330  if (eng == 0) return kFALSE;
331 
332  eng->SetServer(this);
333 
334  if (!eng->Create(arg + 1)) {
335  delete eng;
336  return kFALSE;
337  }
338 
339  fEngines.Add(eng);
340 
341  return kTRUE;
342 }
343 
344 ////////////////////////////////////////////////////////////////////////////////
345 /// create timer which will invoke ProcessRequests() function periodically
346 /// Timer is required to perform all actions in main ROOT thread
347 /// Method arguments are the same as for TTimer constructor
348 /// By default, sync timer with 100 ms period is created
349 ///
350 /// If milliSec == 0, no timer will be created.
351 /// In this case application should regularly call ProcessRequests() method.
352 
353 void THttpServer::SetTimer(Long_t milliSec, Bool_t mode)
354 {
355  if (fTimer) {
356  fTimer->Stop();
357  delete fTimer;
358  fTimer = 0;
359  }
360  if (milliSec > 0) {
361  fTimer = new THttpTimer(milliSec, mode, this);
362  fTimer->TurnOn();
363  }
364 }
365 
366 ////////////////////////////////////////////////////////////////////////////////
367 /// Checked that filename does not contains relative path below current directory
368 /// Used to prevent access to files below current directory
369 
371 {
372  if ((fname == 0) || (*fname == 0)) return kFALSE;
373 
374  Int_t level = 0;
375 
376  while (*fname != 0) {
377 
378  // find next slash or backslash
379  const char *next = strpbrk(fname, "/\\");
380  if (next == 0) return kTRUE;
381 
382  // most important - change to parent dir
383  if ((next == fname + 2) && (*fname == '.') && (*(fname + 1) == '.')) {
384  fname += 3;
385  level--;
386  if (level < 0) return kFALSE;
387  continue;
388  }
389 
390  // ignore current directory
391  if ((next == fname + 1) && (*fname == '.')) {
392  fname += 2;
393  continue;
394  }
395 
396  // ignore slash at the front
397  if (next == fname) {
398  fname ++;
399  continue;
400  }
401 
402  fname = next + 1;
403  level++;
404  }
405 
406  return kTRUE;
407 }
408 
409 ////////////////////////////////////////////////////////////////////////////////
410 /// Verifies that request is just file name
411 /// File names typically contains prefix like "jsrootsys/"
412 /// If true, method returns real name of the file,
413 /// which should be delivered to the client
414 /// Method is thread safe and can be called from any thread
415 
416 Bool_t THttpServer::IsFileRequested(const char *uri, TString &res) const
417 {
418  if ((uri == 0) || (strlen(uri) == 0)) return kFALSE;
419 
420  TString fname = uri;
421 
422  TIter iter(&fLocations);
423  TObject *obj(0);
424  while ((obj=iter()) != 0) {
425  Ssiz_t pos = fname.Index(obj->GetName());
426  if (pos == kNPOS) continue;
427  fname.Remove(0, pos + (strlen(obj->GetName()) - 1));
428  if (!VerifyFilePath(fname.Data())) return kFALSE;
429  res = obj->GetTitle();
430  if ((fname[0]=='/') && (res[res.Length()-1]=='/')) res.Resize(res.Length()-1);
431  res.Append(fname);
432  return kTRUE;
433  }
434 
435  return kFALSE;
436 }
437 
438 ////////////////////////////////////////////////////////////////////////////////
439 /// Executes http request, specified in THttpCallArg structure
440 /// Method can be called from any thread
441 /// Actual execution will be done in main ROOT thread, where analysis code is running.
442 
444 {
445  if ((fMainThrdId!=0) && (fMainThrdId == TThread::SelfId())) {
446  // should not happen, but one could process requests directly without any signaling
447 
448  ProcessRequest(arg);
449 
450  return kTRUE;
451  }
452 
453  // add call arg to the list
454  std::unique_lock<std::mutex> lk(fMutex);
455  fCallArgs.Add(arg);
456  // and now wait until request is processed
457  arg->fCond.wait(lk);
458 
459  return kTRUE;
460 }
461 
462 ////////////////////////////////////////////////////////////////////////////////
463 /// Process requests, submitted for execution
464 /// Regularly invoked by THttpTimer, when somewhere in the code
465 /// gSystem->ProcessEvents() is called.
466 /// User can call serv->ProcessRequests() directly, but only from main analysis thread.
467 
469 {
471 
472  if (fMainThrdId != TThread::SelfId()) {
473  Error("ProcessRequests", "Should be called only from main ROOT thread");
474  return;
475  }
476 
477  std::unique_lock<std::mutex> lk(fMutex, std::defer_lock);
478  while (true) {
479  THttpCallArg *arg = 0;
480 
481  lk.lock();
482  if (fCallArgs.GetSize() > 0) {
483  arg = (THttpCallArg *) fCallArgs.First();
485  }
486  lk.unlock();
487 
488  if (arg == 0) break;
489 
491 
492  try {
493  ProcessRequest(arg);
495  } catch (...) {
497  }
498 
499  arg->fCond.notify_one();
500  }
501 
502  // regularly call Process() method of engine to let perform actions in ROOT context
503  TIter iter(&fEngines);
504  THttpEngine *engine = 0;
505  while ((engine = (THttpEngine *)iter()) != 0)
506  engine->Process();
507 }
508 
509 ////////////////////////////////////////////////////////////////////////////////
510 /// Process single http request
511 /// Depending from requested path and filename different actions will be performed.
512 /// In most cases information is provided by TRootSniffer class
513 
515 {
516 
517  if (arg->fFileName.IsNull() || (arg->fFileName == "index.htm")) {
518 
519  if (fDefaultPageCont.Length() == 0) {
520  Int_t len = 0;
521  char *buf = ReadFileContent(fDefaultPage.Data(), len);
522  if (len > 0) fDefaultPageCont.Append(buf, len);
523  delete buf;
524  }
525 
526  if (fDefaultPageCont.Length() == 0) {
527  arg->Set404();
528  } else {
529  arg->fContent = fDefaultPageCont;
530 
531  // replace all references on JSROOT
532  if (fJSROOT.Length() > 0) {
533  TString repl = TString("=\"") + fJSROOT;
534  if (!repl.EndsWith("/")) repl+="/";
535  arg->fContent.ReplaceAll("=\"jsrootsys/", repl);
536  }
537 
538  const char *hjsontag = "\"$$$h.json$$$\"";
539 
540  // add h.json caching
541  if (arg->fContent.Index(hjsontag) != kNPOS) {
542  TString h_json;
543  TRootSnifferStoreJson store(h_json, kTRUE);
544  const char *topname = fTopName.Data();
545  if (arg->fTopName.Length() > 0) topname = arg->fTopName.Data();
546  fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store);
547 
548  arg->fContent.ReplaceAll(hjsontag, h_json);
549 
550  arg->AddHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0");
551  if (arg->fQuery.Index("nozip") == kNPOS) arg->SetZipping(2);
552  }
553  arg->SetContentType("text/html");
554  }
555  return;
556  }
557 
558  if (arg->fFileName == "draw.htm") {
559  if (fDrawPageCont.Length() == 0) {
560  Int_t len = 0;
561  char *buf = ReadFileContent(fDrawPage.Data(), len);
562  if (len > 0) fDrawPageCont.Append(buf, len);
563  delete buf;
564  }
565 
566  if (fDrawPageCont.Length() == 0) {
567  arg->Set404();
568  } else {
569  const char *rootjsontag = "\"$$$root.json$$$\"";
570  const char *hjsontag = "\"$$$h.json$$$\"";
571 
572  arg->fContent = fDrawPageCont;
573 
574  // replace all references on JSROOT
575  if (fJSROOT.Length() > 0) {
576  TString repl = TString("=\"") + fJSROOT;
577  if (!repl.EndsWith("/")) repl+="/";
578  arg->fContent.ReplaceAll("=\"jsrootsys/", repl);
579  }
580 
581  if (arg->fContent.Index(hjsontag) != kNPOS) {
582  TString h_json;
583  TRootSnifferStoreJson store(h_json, kTRUE);
584  const char *topname = fTopName.Data();
585  if (arg->fTopName.Length() > 0) topname = arg->fTopName.Data();
586  fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store, kTRUE);
587 
588  arg->fContent.ReplaceAll(hjsontag, h_json);
589  }
590 
591  if (arg->fContent.Index(rootjsontag) != kNPOS) {
592  TString str;
593  void *bindata = 0;
594  Long_t bindatalen = 0;
595  if (fSniffer->Produce(arg->fPathName.Data(), "root.json", "compact=3", bindata, bindatalen, str)) {
596  arg->fContent.ReplaceAll(rootjsontag, str);
597  }
598  }
599  arg->AddHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0");
600  if (arg->fQuery.Index("nozip") == kNPOS) arg->SetZipping(2);
601  arg->SetContentType("text/html");
602  }
603  return;
604  }
605 
606  TString filename;
607  if (IsFileRequested(arg->fFileName.Data(), filename)) {
608  arg->SetFile(filename);
609  return;
610  }
611 
612  filename = arg->fFileName;
613  Bool_t iszip = kFALSE;
614  if (filename.EndsWith(".gz")) {
615  filename.Resize(filename.Length() - 3);
616  iszip = kTRUE;
617  }
618 
619  void* bindata(0);
620  Long_t bindatalen(0);
621 
622  if ((filename == "h.xml") || (filename == "get.xml")) {
623 
624  Bool_t compact = arg->fQuery.Index("compact") != kNPOS;
625 
626  arg->fContent.Form("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
627  if (!compact) arg->fContent.Append("\n");
628  arg->fContent.Append("<root>");
629  if (!compact) arg->fContent.Append("\n");
630  {
631  TRootSnifferStoreXml store(arg->fContent, compact);
632 
633  const char *topname = fTopName.Data();
634  if (arg->fTopName.Length() > 0) topname = arg->fTopName.Data();
635  fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store, filename == "get.xml");
636  }
637 
638  arg->fContent.Append("</root>");
639  if (!compact) arg->fContent.Append("\n");
640 
641  arg->SetXml();
642  } else
643 
644  if (filename == "h.json") {
645  TRootSnifferStoreJson store(arg->fContent, arg->fQuery.Index("compact") != kNPOS);
646  const char *topname = fTopName.Data();
647  if (arg->fTopName.Length() > 0) topname = arg->fTopName.Data();
648  fSniffer->ScanHierarchy(topname, arg->fPathName.Data(), &store);
649  arg->SetJson();
650  } else
651 
652  if (filename == "root.websocket") {
653  // handling of web socket
654 
655  TCanvas* canv = dynamic_cast<TCanvas*> (fSniffer->FindTObjectInHierarchy(arg->fPathName.Data()));
656 
657  if (canv == 0) {
658  // for the moment only TCanvas is used for web sockets
659  arg->Set404();
660  } else
661  if (strcmp(arg->GetMethod(),"WS_CONNECT")==0) {
662 
663  if (canv->GetPrimitive("websocket")) {
664  // websocket already exists, ignore all other requests
665  arg->Set404();
666  }
667  } else
668  if (strcmp(arg->GetMethod(),"WS_READY")==0) {
669  THttpWSEngine* wshandle = dynamic_cast<THttpWSEngine*> (arg->TakeWSHandle());
670 
671  if (gDebug>0) Info("ProcessRequest","Set WebSocket handle %p", wshandle);
672 
673  if (wshandle) wshandle->AssignCanvas(canv);
674 
675  // connection is established
676  } else
677  if (strcmp(arg->GetMethod(),"WS_DATA")==0) {
678  // process received data
679 
680  THttpWSEngine* wshandle = dynamic_cast<THttpWSEngine*> (canv->GetPrimitive("websocket"));
681  if (wshandle) wshandle->ProcessData(arg);
682 
683  } else
684  if (strcmp(arg->GetMethod(),"WS_CLOSE")==0) {
685  // connection is closed, one can remove handle
686 
687  THttpWSEngine* wshandle = dynamic_cast<THttpWSEngine*> (canv->GetPrimitive("websocket"));
688 
689  if (wshandle) {
690  if (gDebug>0) Info("ProcessRequest","Clear WebSocket handle");
691  wshandle->ClearHandle();
692  wshandle->AssignCanvas(0);
693  delete wshandle;
694  }
695  } else {
696  arg->Set404();
697  }
698 
699  return;
700 
701  } else
702 
703  if (fSniffer->Produce(arg->fPathName.Data(), filename.Data(), arg->fQuery.Data(), bindata, bindatalen, arg->fContent)) {
704  if (bindata != 0) arg->SetBinData(bindata, bindatalen);
705 
706  // define content type base on extension
707  arg->SetContentType(GetMimeType(filename.Data()));
708  } else {
709  // request is not processed
710  arg->Set404();
711  }
712 
713  if (arg->Is404()) return;
714 
715  if (iszip) arg->SetZipping(3);
716 
717  if (filename == "root.bin") {
718  // only for binary data master version is important
719  // it allows to detect if streamer info was modified
720  const char *parname = fSniffer->IsStreamerInfoItem(arg->fPathName.Data()) ? "BVersion" : "MVersion";
721  arg->AddHeader(parname, Form("%u", (unsigned) fSniffer->GetStreamerInfoHash()));
722  }
723 
724  // try to avoid caching on the browser
725  arg->AddHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0");
726 }
727 
728 ////////////////////////////////////////////////////////////////////////////////
729 /// Register object in folders hierarchy
730 ///
731 /// See TRootSniffer::RegisterObject() for more details
732 
733 Bool_t THttpServer::Register(const char *subfolder, TObject *obj)
734 {
735  return fSniffer->RegisterObject(subfolder, obj);
736 }
737 
738 ////////////////////////////////////////////////////////////////////////////////
739 /// Unregister object in folders hierarchy
740 ///
741 /// See TRootSniffer::UnregisterObject() for more details
742 
744 {
745  return fSniffer->UnregisterObject(obj);
746 }
747 
748 ////////////////////////////////////////////////////////////////////////////////
749 /// Restrict access to specified object
750 ///
751 /// See TRootSniffer::Restrict() for more details
752 
753 void THttpServer::Restrict(const char *path, const char* options)
754 {
755  fSniffer->Restrict(path, options);
756 }
757 
758 ////////////////////////////////////////////////////////////////////////////////
759 /// Register command which can be executed from web interface
760 ///
761 /// As method one typically specifies string, which is executed with
762 /// gROOT->ProcessLine() method. For instance
763 /// serv->RegisterCommand("Invoke","InvokeFunction()");
764 ///
765 /// Or one could specify any method of the object which is already registered
766 /// to the server. For instance:
767 /// serv->Register("/", hpx);
768 /// serv->RegisterCommand("/ResetHPX", "/hpx/->Reset()");
769 /// Here symbols '/->' separates item name from method to be executed
770 ///
771 /// One could specify additional arguments in the command with
772 /// syntax like %arg1%, %arg2% and so on. For example:
773 /// serv->RegisterCommand("/ResetHPX", "/hpx/->SetTitle(\"%arg1%\")");
774 /// serv->RegisterCommand("/RebinHPXPY", "/hpxpy/->Rebin2D(%arg1%,%arg2%)");
775 /// Such parameter(s) will be requested when command clicked in the browser.
776 ///
777 /// Once command is registered, one could specify icon which will appear in the browser:
778 /// serv->SetIcon("/ResetHPX", "rootsys/icons/ed_execute.png");
779 ///
780 /// One also can set extra property '_fastcmd', that command appear as
781 /// tool button on the top of the browser tree:
782 /// serv->SetItemField("/ResetHPX", "_fastcmd", "true");
783 /// Or it is equivalent to specifying extra argument when register command:
784 /// serv->RegisterCommand("/ResetHPX", "/hpx/->Reset()", "button;rootsys/icons/ed_delete.png");
785 
786 Bool_t THttpServer::RegisterCommand(const char *cmdname, const char *method, const char *icon)
787 {
788  return fSniffer->RegisterCommand(cmdname, method, icon);
789 }
790 
791 ////////////////////////////////////////////////////////////////////////////////
792 /// hides folder or element from web gui
793 
794 Bool_t THttpServer::Hide(const char *foldername, Bool_t hide)
795 {
796  return SetItemField(foldername, "_hidden", hide ? "true" : (const char *) 0);
797 }
798 
799 ////////////////////////////////////////////////////////////////////////////////
800 /// set name of icon, used in browser together with the item
801 ///
802 /// One could use images from $ROOTSYS directory like:
803 /// serv->SetIcon("/ResetHPX","/rootsys/icons/ed_execute.png");
804 
805 Bool_t THttpServer::SetIcon(const char *fullname, const char *iconname)
806 {
807  return SetItemField(fullname, "_icon", iconname);
808 }
809 
810 ////////////////////////////////////////////////////////////////////////////////
811 
812 Bool_t THttpServer::CreateItem(const char *fullname, const char *title)
813 {
814  return fSniffer->CreateItem(fullname, title);
815 }
816 
817 ////////////////////////////////////////////////////////////////////////////////
818 
819 Bool_t THttpServer::SetItemField(const char *fullname, const char *name, const char *value)
820 {
821  return fSniffer->SetItemField(fullname, name, value);
822 }
823 
824 ////////////////////////////////////////////////////////////////////////////////
825 
826 const char *THttpServer::GetItemField(const char *fullname, const char *name)
827 {
828  return fSniffer->GetItemField(fullname, name);
829 }
830 
831 ////////////////////////////////////////////////////////////////////////////////
832 /// Returns MIME type base on file extension
833 
834 const char *THttpServer::GetMimeType(const char *path)
835 {
836  static const struct {
837  const char *extension;
838  int ext_len;
839  const char *mime_type;
840  } builtin_mime_types[] = {
841  {".xml", 4, "text/xml"},
842  {".json", 5, "application/json"},
843  {".bin", 4, "application/x-binary"},
844  {".gif", 4, "image/gif"},
845  {".jpg", 4, "image/jpeg"},
846  {".png", 4, "image/png"},
847  {".html", 5, "text/html"},
848  {".htm", 4, "text/html"},
849  {".shtm", 5, "text/html"},
850  {".shtml", 6, "text/html"},
851  {".css", 4, "text/css"},
852  {".js", 3, "application/x-javascript"},
853  {".ico", 4, "image/x-icon"},
854  {".jpeg", 5, "image/jpeg"},
855  {".svg", 4, "image/svg+xml"},
856  {".txt", 4, "text/plain"},
857  {".torrent", 8, "application/x-bittorrent"},
858  {".wav", 4, "audio/x-wav"},
859  {".mp3", 4, "audio/x-mp3"},
860  {".mid", 4, "audio/mid"},
861  {".m3u", 4, "audio/x-mpegurl"},
862  {".ogg", 4, "application/ogg"},
863  {".ram", 4, "audio/x-pn-realaudio"},
864  {".xslt", 5, "application/xml"},
865  {".xsl", 4, "application/xml"},
866  {".ra", 3, "audio/x-pn-realaudio"},
867  {".doc", 4, "application/msword"},
868  {".exe", 4, "application/octet-stream"},
869  {".zip", 4, "application/x-zip-compressed"},
870  {".xls", 4, "application/excel"},
871  {".tgz", 4, "application/x-tar-gz"},
872  {".tar", 4, "application/x-tar"},
873  {".gz", 3, "application/x-gunzip"},
874  {".arj", 4, "application/x-arj-compressed"},
875  {".rar", 4, "application/x-arj-compressed"},
876  {".rtf", 4, "application/rtf"},
877  {".pdf", 4, "application/pdf"},
878  {".swf", 4, "application/x-shockwave-flash"},
879  {".mpg", 4, "video/mpeg"},
880  {".webm", 5, "video/webm"},
881  {".mpeg", 5, "video/mpeg"},
882  {".mov", 4, "video/quicktime"},
883  {".mp4", 4, "video/mp4"},
884  {".m4v", 4, "video/x-m4v"},
885  {".asf", 4, "video/x-ms-asf"},
886  {".avi", 4, "video/x-msvideo"},
887  {".bmp", 4, "image/bmp"},
888  {".ttf", 4, "application/x-font-ttf"},
889  {NULL, 0, NULL}
890  };
891 
892  int path_len = strlen(path);
893 
894  for (int i = 0; builtin_mime_types[i].extension != NULL; i++) {
895  if (path_len <= builtin_mime_types[i].ext_len) continue;
896  const char *ext = path + (path_len - builtin_mime_types[i].ext_len);
897  if (strcmp(ext, builtin_mime_types[i].extension) == 0) {
898  return builtin_mime_types[i].mime_type;
899  }
900  }
901 
902  return "text/plain";
903 }
904 
905 ////////////////////////////////////////////////////////////////////////////////
906 /// reads file content
907 
908 char *THttpServer::ReadFileContent(const char *filename, Int_t &len)
909 {
910  len = 0;
911 
912  std::ifstream is(filename);
913  if (!is) return 0;
914 
915  is.seekg(0, is.end);
916  len = is.tellg();
917  is.seekg(0, is.beg);
918 
919  char *buf = (char *) malloc(len);
920  is.read(buf, len);
921  if (!is) {
922  free(buf);
923  len = 0;
924  return 0;
925  }
926 
927  return buf;
928 }
void SetZipping(Int_t kind)
Definition: THttpCallArg.h:277
Bool_t RegisterObject(const char *subfolder, TObject *obj)
Register object in subfolder structure subfolder parameter can have many levels like: ...
An array of TObjects.
Definition: TObjArray.h:39
virtual void Delete(Option_t *option="")
Remove all objects from the list AND delete all heap based objects.
Definition: TList.cxx:405
virtual TObject * GetPrimitive(const char *name) const
Get primitive.
Definition: TPad.cxx:2770
Bool_t Produce(const char *path, const char *file, const char *options, void *&ptr, Long_t &length, TString &str)
Method produce different kind of data out of object Parameter &#39;path&#39; specifies object or object membe...
Bool_t IsStreamerInfoItem(const char *itemname)
Return true if it is streamer info item name.
virtual void Process()
Method regularly called in main ROOT context.
Definition: THttpEngine.h:30
const char * mime_type
Definition: civetweb.c:5007
Ssiz_t Length() const
Definition: TString.h:390
Int_t GetLast() const
Return index of last object in array.
Definition: TObjArray.cxx:528
Storage of hierarchy scan in TRootSniffer in JSON format.
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:635
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:899
const char * GetItemField(const char *fullname, const char *name)
Bool_t Is404() const
Definition: THttpCallArg.h:310
virtual void ProcessData(THttpCallArg *arg)
process data received from the client
#define gROOT
Definition: TROOT.h:379
TString fQuery
authenticated user name (if any)
Definition: THttpCallArg.h:30
Basic string class.
Definition: TString.h:137
TString fTopName
location of local JSROOT files
Definition: THttpServer.h:41
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
const Bool_t kFALSE
Definition: Rtypes.h:92
static const TString & GetRootSys()
Get the rootsys directory in the installation. Static utility function.
Definition: TROOT.cxx:2671
virtual TObject * FindObject(const char *name) const
Find an object in this list using its name.
Definition: TList.cxx:497
void Restrict(const char *path, const char *options)
Restrict access to the specified location.
Bool_t UnregisterObject(TObject *obj)
unregister (remove) object from folders structures folder itself will remain even when it will be emp...
TList fEngines
Definition: THttpServer.h:34
void SetServer(THttpServer *serv)
Definition: THttpEngine.h:24
virtual void AssignCanvas(TCanvas *canv)
assign canvas to the web socket connects with CanvasModified signal
#define malloc
Definition: civetweb.c:818
void SetContentType(const char *typ)
Definition: THttpCallArg.h:207
Bool_t CreateItem(const char *fullname, const char *title)
create item element
void ProcessRequests()
Process submitted requests, must be called from main thread.
Bool_t CreateItem(const char *fullname, const char *title)
const char * GetMethod() const
Definition: THttpCallArg.h:149
const char * Data() const
Definition: TString.h:349
TRootSniffer * fSniffer
timer used to access main thread
Definition: THttpServer.h:36
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:2335
Bool_t SetItemField(const char *fullname, const char *name, const char *value)
set field for specified item
Bool_t IsReadOnly() const
Definition: TRootSniffer.h:177
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:33
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition: TClass.cxx:4692
void Clear()
Clear string without changing its capacity.
Definition: TString.cxx:1140
THttpTimer * fTimer
engines which runs http server
Definition: THttpServer.h:35
virtual const char * Getenv(const char *env)
Get environment variable.
Definition: TSystem.cxx:1627
TString fPathName
request method like GET or POST
Definition: THttpCallArg.h:27
TString & Append(const char *cs)
Definition: TString.h:492
std::vector< std::vector< double > > Data
static Long_t SelfId()
Static method returning the id for the current thread.
Definition: TThread.cxx:538
void SetTimer(Long_t milliSec=100, Bool_t mode=kTRUE)
create timer which will invoke ProcessRequests() function periodically Timer is required to perform a...
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:925
TList fLocations
location of external JSROOT files
Definition: THttpServer.h:43
TString fJSROOTSYS
id of the main ROOT process
Definition: THttpServer.h:40
Storage of hierarchy scan in TRootSniffer in XML format.
Bool_t Register(const char *subfolder, TObject *obj)
Register object in subfolder.
void SetReadOnly(Bool_t readonly)
Set read-only mode for the server (default on) In read-only server is not allowed to change any ROOT ...
TString fTopName
Definition: THttpCallArg.h:25
void SetBinData(void *data, Long_t length)
set binary data, which will be returned as reply body
void SetJson()
Definition: THttpCallArg.h:236
Bool_t CreateEngine(const char *engine)
factory method to create different http engines At the moment two engine kinds are supported: civetwe...
size_t ext_len
Definition: civetweb.c:5006
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
Definition: TString.cxx:2221
R__EXTERN TSystem * gSystem
Definition: TSystem.h:549
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2322
virtual ~THttpServer()
destructor delete all http engines and sniffer
Bool_t RegisterCommand(const char *cmdname, const char *method, const char *icon)
Register command which can be executed from web interface.
char * Form(const char *fmt,...)
Bool_t IsFileRequested(const char *uri, TString &res) const
Check if file is requested, thread safe.
TString fDefaultPage
list of local directories, which could be accessed via server
Definition: THttpServer.h:45
Bool_t IsReadOnly() const
returns read-only mode
virtual Bool_t Create(const char *)
Method to create all components of engine.
Definition: THttpEngine.h:36
Handles synchronous and a-synchronous timer events.
Definition: TTimer.h:57
The ROOT global object gROOT contains a list of all defined classes.
Definition: TClass.h:81
Bool_t IsNull() const
Definition: TString.h:387
void Warning(const char *location, const char *msgfmt,...)
void SetSniffer(TRootSniffer *sniff)
Set TRootSniffer to the server Server takes ownership over sniffer.
static struct @163 builtin_mime_types[]
void ScanHierarchy(const char *topname, const char *path, TRootSnifferStore *store, Bool_t only_fields=kFALSE)
Method scans normal objects, registered in ROOT.
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition: TString.cxx:2241
Bool_t ExecuteHttp(THttpCallArg *arg)
Execute HTTP request.
const char * extension
Definition: civetweb.c:5005
TString fDrawPage
content of the file content
Definition: THttpServer.h:47
TString & Remove(Ssiz_t pos)
Definition: TString.h:616
long Long_t
Definition: RtypesCore.h:50
int Ssiz_t
Definition: RtypesCore.h:63
std::condition_variable fCond
web-socket handle, derived from TNamed class
Definition: THttpCallArg.h:37
The Canvas class.
Definition: TCanvas.h:41
void AddLocation(const char *prefix, const char *path)
add files location, which could be used in the server one could map some system folder to the server ...
virtual Int_t GetSize() const
Definition: TCollection.h:95
Bool_t Hide(const char *fullname, Bool_t hide=kTRUE)
hides folder or element from web gui
#define ClassImp(name)
Definition: Rtypes.h:279
std::mutex fMutex
content of draw page
Definition: THttpServer.h:50
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:416
virtual void ProcessRequest(THttpCallArg *arg)
submitted arguments
TString fDrawPageCont
file name for drawing of single element
Definition: THttpServer.h:48
TNamed()
Definition: TNamed.h:40
#define free
Definition: civetweb.c:821
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition: TROOT.cxx:2755
TString fDefaultPageCont
file name for default page name
Definition: THttpServer.h:46
TNamed * TakeWSHandle()
takeout websocket handle with HTTP call can be done only once
Bool_t RegisterCommand(const char *cmdname, const char *method, const char *icon=0)
Register command which can be executed from web interface.
Mother of all ROOT objects.
Definition: TObject.h:37
static const char * GetMimeType(const char *path)
Guess mime type base on file extension.
Bool_t Unregister(TObject *obj)
Unregister object.
TString fContent
response header like ContentEncoding, Cache-Control and so on
Definition: THttpCallArg.h:42
virtual TObject * First() const
Return the first object in the list. Returns 0 when list is empty.
Definition: TList.cxx:557
Long_t fMainThrdId
sniffer provides access to ROOT objects hierarchy
Definition: THttpServer.h:38
void AddHeader(const char *name, const char *value)
Set name: value pair to reply header Content-Type field handled separately - one should use SetConten...
static char * ReadFileContent(const char *filename, Int_t &len)
Reads content of file from the disk.
void SetReadOnly(Bool_t on=kTRUE)
Definition: TRootSniffer.h:169
virtual void Add(TObject *obj)
Definition: TList.h:81
const Ssiz_t kNPOS
Definition: Rtypes.h:115
void SetFile(const char *filename=0)
Definition: THttpCallArg.h:221
Bool_t SetIcon(const char *fullname, const char *iconname)
set name of icon, used in browser together with the item
virtual void Timeout()
Definition: TTimer.h:102
#define NULL
Definition: Rtypes.h:82
R__EXTERN Int_t gDebug
Definition: Rtypes.h:128
TList fCallArgs
mutex to protect list with arguments
Definition: THttpServer.h:51
virtual void ClearHandle()=0
static Bool_t VerifyFilePath(const char *fname)
Checked that filename does not contains relative path below current directory Used to prevent access ...
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition: TSystem.cxx:1243
TString fJSROOT
name of top folder, default - &quot;ROOT&quot;
Definition: THttpServer.h:42
TObject * At(Int_t idx) const
Definition: TObjArray.h:167
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:582
const Bool_t kTRUE
Definition: Rtypes.h:91
void SetCurrentCallArg(THttpCallArg *arg)
set current http arguments, which then used in different process methods For instance, if user authorized with some user name, depending from restrictions some objects will be invisible or user get full access to the element
virtual const char * GetTitle() const
Returns title of object.
Definition: TObject.cxx:460
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:155
void SetDrawPage(const char *filename)
Set file name of HTML page, delivered by the server when objects drawing page is requested from the b...
const Int_t n
Definition: legend1.C:16
TString fFileName
item path
Definition: THttpCallArg.h:28
Bool_t SetItemField(const char *fullname, const char *name, const char *value)
const char * GetItemField(TFolder *parent, TObject *item, const char *name)
return field for specified item
char name[80]
Definition: TGX11.cxx:109
void Restrict(const char *path, const char *options)
Restrict access to specified object.
void Resize(Ssiz_t n)
Resize the string. Truncate or add blanks as necessary.
Definition: TString.cxx:1059
ULong_t GetStreamerInfoHash()
Returns hash value for streamer infos At the moment - just number of items in streamer infos list...
void SetDefaultPage(const char *filename)
Set file name of HTML page, delivered by the server when http address is opened in the browser...
TObject * FindTObjectInHierarchy(const char *path)
Search element in hierarchy, derived from TObject.
virtual void RemoveFirst()
void SetJSROOT(const char *location)
Set location of JSROOT to use with the server One could specify address like: https://root.cern.ch/js/3.3/ http://web-docs.gsi.de/~linev/js/3.3/ This allows to get new JSROOT features with old server, reduce load on THttpServer instance, also startup time can be improved When empty string specified (default), local copy of JSROOT is used (distributed with ROOT)