49 mg_websocket_write(
fWSconn, MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE,
nullptr, 0);
53 void Send(
const void *buf,
int len)
override
56 mg_websocket_write(
fWSconn, MG_WEBSOCKET_OPCODE_BINARY, (
const char *)buf,
len);
66 mg_websocket_write(
fWSconn, MG_WEBSOCKET_OPCODE_TEXT, hdr, strlen(hdr));
67 mg_websocket_write(
fWSconn, MG_WEBSOCKET_OPCODE_BINARY, (
const char *)buf,
len);
74 mg_websocket_write(
fWSconn, MG_WEBSOCKET_OPCODE_TEXT, str, strlen(str));
84 if (longpoll) num_avail++;
86 if ((num_avail <= 0.1 * engine->GetNumThreads()) || (num_avail <= 2)) {
87 const char *cfg = engine->
IsWebGui() ?
"WebGui.HttpThreads parameter in rootrc" :
"thrds=N parameter in config URL";
88 const char *place = longpoll ?
"TCivetweb::LongpollHandler" :
"TCivetweb::WebSocketHandler";
89 ::Error(place,
"Only %d threads are available, reject connection request for %s. Increase %s, now it is %d", num_avail, uri, cfg, engine->
GetNumThreads());
100 const struct mg_request_info *request_info = mg_get_request_info(conn);
111 auto arg = std::make_shared<THttpCallArg>();
112 arg->SetPathAndFileName(request_info->local_uri);
113 arg->SetQuery(request_info->query_string);
116 arg->SetMethod(
"WS_CONNECT");
123 return execres && !arg->Is404() ? 0 : 1;
130 const struct mg_request_info *request_info = mg_get_request_info(conn);
141 auto arg = std::make_shared<THttpCallArg>();
142 arg->SetPathAndFileName(request_info->local_uri);
143 arg->SetQuery(request_info->query_string);
145 arg->SetMethod(
"WS_READY");
158 const struct mg_request_info *request_info = mg_get_request_info(conn);
161 if (mg_get_user_connection_data(conn) == (
void *) conn)
171 auto arg = std::make_shared<THttpCallArg>();
172 arg->SetPathAndFileName(request_info->local_uri);
173 arg->SetQuery(request_info->query_string);
176 arg->SetMethod(
"WS_CLOSE");
187 const struct mg_request_info *request_info = mg_get_request_info(conn);
190 std::string *conn_data = (std::string *) mg_get_user_connection_data(conn);
191 if ((
void *) conn_data == (
void *) conn)
195 int fin = code & 0x80, opcode = code & 0x0F;
198 enum { OP_CONTINUE = 0, OP_TEXT = 1, OP_BINARY = 2, OP_CLOSE = 8 };
201 if (fin && (opcode == OP_CLOSE)) {
202 if (conn_data)
delete conn_data;
204 mg_set_user_connection_data(conn, conn);
213 if ((opcode != OP_CONTINUE) && (opcode != OP_TEXT) && (opcode != OP_BINARY)) {
214 if (conn_data)
delete conn_data;
216 mg_set_user_connection_data(conn, conn);
230 conn_data =
new std::string(
data,
len);
231 mg_set_user_connection_data(conn, conn_data);
238 auto arg = std::make_shared<THttpCallArg>();
239 arg->SetPathAndFileName(request_info->local_uri);
240 arg->SetQuery(request_info->query_string);
243 arg->SetMethod(
"WS_DATA");
246 mg_set_user_connection_data(conn,
nullptr);
248 arg->SetPostData(std::move(*conn_data));
251 arg->SetPostData(std::string(
data,
len));
264 const struct mg_context *ctx = mg_get_context(conn);
272 if ((
gDebug > 0) || strstr(message,
"cannot bind to"))
273 fprintf(stderr,
"Error in <TCivetweb::Log> %s\n", message);
293 if (strcmp(arg->GetFileName(),
"root.longpoll") != 0)
296 const char *
q = arg->GetQuery();
300 if ((strstr(
q,
"raw_connect") !=
q) && (strstr(
q,
"txt_connect") !=
q))
310 const struct mg_request_info *request_info = mg_get_request_info(conn);
321 auto arg = std::make_shared<THttpCallArg>();
334 arg->SetContent(std::move(buf));
338 arg->AddNoCacheHeader();
345 arg->SetPathAndFileName(request_info->local_uri);
346 arg->SetQuery(request_info->query_string);
348 arg->SetMethod(request_info->request_method);
349 if (request_info->remote_user)
350 arg->SetUserName(request_info->remote_user);
353 for (
int n = 0;
n < request_info->num_headers;
n++)
355 TString::Format(
"%s: %s\r\n", request_info->http_headers[
n].name, request_info->http_headers[
n].value));
356 arg->SetRequestHeader(header);
358 const char *
len = mg_get_header(conn,
"Content-Length");
364 Int_t iread = mg_read(conn, (
void *) buf.data(), ilen);
366 arg->SetPostData(std::move(buf));
371 cont.
Append(
"<title>Civetweb echo</title>");
372 cont.
Append(
"<h1>Civetweb echo</h1>\n");
374 static int count = 0;
382 if (arg->GetUserName())
385 cont.
Append(
"</pre><p>\n");
387 cont.
Append(
"Environment:<br/>\n<pre>\n");
388 for (
int n = 0;
n < request_info->num_headers;
n++)
390 TString::Format(
" %s = %s\n", request_info->http_headers[
n].name, request_info->http_headers[
n].value));
391 cont.
Append(
"</pre><p>\n");
393 arg->SetContentType(
"text/html");
395 arg->SetContent(cont);
405 if (!execres || arg->Is404()) {
406 std::string hdr = arg->FillHttpHeader(
"HTTP/1.1");
407 mg_printf(conn,
"%s", hdr.c_str());
408 }
else if (arg->IsFile()) {
409 filename = (
const char *)arg->GetContent();
413 auto hFile = CreateFile(
filename.Data(),
418 FILE_ATTRIBUTE_NORMAL,
424 auto dwRet = GetFinalPathNameByHandle( hFile, Path,
BUFSIZE, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS );
427 if (dwRet > 4 && Path[0] ==
'\\' && Path[1] ==
'\\' && Path[2] ==
'?' && Path[3] ==
'\\')
438 mg_send_mime_file(conn,
filename.Data(), mime_type);
440 mg_send_file(conn,
filename.Data());
444 switch (arg->GetZipping()) {
447 if (arg->GetContentLength() < 10000)
break;
450 for (
int n = 0;
n < request_info->num_headers;
n++) {
464 arg->CompressWithGzip();
466 std::string hdr = arg->FillHttpHeader(
"HTTP/1.1");
467 mg_printf(conn,
"%s", hdr.c_str());
469 if (arg->IsChunked()) {
472 unsigned last_send = arg->GetContentLength();
473 mg_send_chunk(conn, (
const char *)arg->GetContent(), last_send);
475 while (arg->IsChunked() && last_send) {
481 last_send = arg->GetContentLength();
483 mg_send_chunk(conn, (
const char *)arg->GetContent(), last_send);
488 mg_send_chunk(conn,
"", 0);
490 }
else if (arg->GetContentLength() > 0)
491 mg_write(conn, arg->GetContent(), (
size_t)arg->GetContentLength());
538 :
THttpEngine(
"civetweb",
"compact embedded http server"),
539 fOnlySecured(only_secured)
559 if ((
gDebug > 0) || strstr(message,
"cannot bind to"))
560 Error(
"Log",
"%s", message);
570 std::lock_guard<std::mutex> guard(
fMutex);
579 std::lock_guard<std::mutex> guard(
fMutex);
619 memset(&
fCallbacks, 0,
sizeof(
struct mg_callbacks));
624 websocket_timeout =
"300000",
625 dir_listening =
"no",
631 Int_t socket_mode = 0700;
632 bool use_ws =
kTRUE, is_socket =
false;
640 is_socket = *args ==
'x';
642 while ((*args != 0) && (*args !=
'?') && (is_socket || (*args !=
'/')))
648 while ((*args != 0) && (*args !=
'?'))
677 auth_domain = adomain;
687 websocket_timeout.Format(
"%d", wtmout * 1000);
702 if (dls && (!strcmp(dls,
"no") || !strcmp(dls,
"yes")))
707 socket_mode = std::stoi(smode,
nullptr, *smode==
'0' ? 8 : 10);
710 sport =
TString(
"127.0.0.1:") + sport;
714 if (addr && strlen(addr))
715 sport =
TString(addr) +
":" + sport;
741 const char *options[34];
744 Info(
"Create",
"Starting HTTP server on port %s", sport.
Data());
746 options[op++] =
"listening_ports";
747 options[op++] = sport.
Data();
748 options[op++] =
"num_threads";
749 options[op++] = num_threads.Data();
752 options[op++] =
"websocket_timeout_ms";
753 options[op++] = websocket_timeout.Data();
756 if ((auth_file.Length() > 0) && (auth_domain.Length() > 0)) {
757 options[op++] =
"global_auth_file";
758 options[op++] = auth_file.Data();
759 options[op++] =
"authentication_domain";
760 options[op++] = auth_domain.Data();
762 options[op++] =
"enable_auth_domain_check";
763 options[op++] =
"no";
766 if (log_file.Length() > 0) {
767 options[op++] =
"error_log_file";
768 options[op++] = log_file.Data();
771 if (ssl_cert.Length() > 0) {
772 options[op++] =
"ssl_certificate";
773 options[op++] = ssl_cert.Data();
775 Error(
"Create",
"No SSL certificate file configured");
778 if (max_age.Length() > 0) {
779 options[op++] =
"static_file_max_age";
780 options[op++] = max_age.Data();
785 options[op++] =
"access_control_allow_origin";
790 options[op++] =
"access_control_allow_credentials";
792 options[op++] =
"access_control_expose_headers";
793 options[op++] =
"Content-Range, Content-Length, Date";
794 options[op++] =
"access_control_allow_methods";
795 options[op++] =
"GET, HEAD, OPTIONS";
798 options[op++] =
"enable_directory_listing";
799 options[op++] = dir_listening.Data();
801 options[op++] =
nullptr;
803 if (is_socket && !mg_check_feature(MG_FEATURES_X_DOMAIN_SOCKET)) {
804 Error(
"Create",
"civetweb compiled without sockets binding support");
808 if (
IsSecured() && !mg_check_feature(MG_FEATURES_SSL)) {
809 Error(
"Create",
"civetweb compiled without SSL support");
813 if (!mg_check_feature(MG_FEATURES_WEBSOCKET)) {
814 Error(
"Create",
"civetweb compiled without websockets support");
820 mg_init_library(MG_FEATURES_TLS);
823 mg_init_library(MG_FEATURES_DEFAULT);
827 if (is_socket && !sport.
Contains(
","))
843 if (is_socket && !sport.
Contains(
","))
bool Bool_t
Boolean (0=false, 1=true) (bool)
int Int_t
Signed integer 4 bytes (int)
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
int websocket_connect_handler(const struct mg_connection *conn, void *)
static int begin_request_handler(struct mg_connection *conn, void *)
static int log_message_handler(const struct mg_connection *conn, const char *message)
int websocket_data_handler(struct mg_connection *conn, int code, char *data, size_t len, void *)
void websocket_close_handler(const struct mg_connection *conn, void *)
Bool_t CheckEngineThreads(TCivetweb *engine, const char *uri, Bool_t longpoll)
Check if engine has enough threads to process connect to new websocket handle.
void websocket_ready_handler(struct mg_connection *conn, void *)
Bool_t IsBadLongPollConnect(TCivetweb *engine, const std::shared_ptr< THttpCallArg > &arg)
Returns kTRUE in case of longpoll connection request - or at least looks like that.
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize 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 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
#define INVALID_HANDLE_VALUE
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
R__EXTERN TSystem * gSystem
struct mg_connection * fWSconn
UInt_t GetId() const override
void SendCharStar(const char *str) override
Envelope for sending string via the websocket.
void ClearHandle(Bool_t terminate) override
Bool_t SupportSendThrd() const override
True websocket requires extra thread to parallelize sending.
~TCivetwebWSEngine() override=default
void SendHeader(const char *hdr, const void *buf, int len) override
Special method to send binary data with text header For normal websocket it is two separated operatio...
void Send(const void *buf, int len) override
TCivetwebWSEngine(struct mg_connection *conn)
THttpEngine implementation, based on civetweb embedded server.
Int_t fNumThreads
! number of configured threads
Int_t fNumActiveThreads
! number of active threads - used in request and websocket handling
struct mg_context * fCtx
! civetweb context
std::mutex fMutex
! mutex to read/write fNumActiveThreads
Bool_t fWinSymLinks
! resolve symbolic links on Windows
Bool_t IsTerminating() const
const char * GetTopName() const
TCivetweb(Bool_t only_secured=kFALSE)
constructor
Int_t fMaxAge
! max-age parameter
Int_t ProcessLog(const char *message)
process civetweb log message, can be used to detect critical errors
TString fTopName
! name of top item
Int_t GetNumAvailableThreads()
Returns number of actively used threads.
Bool_t fTerminating
! server doing shutdown and not react on requests
Bool_t Create(const char *args) override
Creates embedded civetweb server.
Int_t GetNumThreads() const
Bool_t IsDebugMode() const
virtual ~TCivetweb()
destructor
Bool_t IsWinSymLinks() const
Bool_t fWebGui
! if server used for webgui
Bool_t fDebug
! debug mode
Int_t ChangeNumActiveThreads(int cnt=0)
Returns number of actively used threads.
struct mg_callbacks fCallbacks
! call-back table for civetweb webserver
Abstract class for implementing http protocol for THttpServer.
THttpServer * GetServer() const
Returns pointer to THttpServer associated with engine.
Online http server for arbitrary ROOT application.
Bool_t IsFileRequested(const char *uri, TString &res) const
Check if file is requested, thread safe.
const char * GetCors() const
Returns specified CORS domain.
Bool_t ExecuteWS(std::shared_ptr< THttpCallArg > &arg, Bool_t external_thrd=kFALSE, Bool_t wait_process=kFALSE)
Execute WS request.
Bool_t ExecuteHttp(std::shared_ptr< THttpCallArg > arg)
Execute HTTP request.
void SetCorsCredentials(const std::string &value="true")
Enable/disable usage Access-Control-Allow-Credentials response header.
void SetCors(const std::string &domain="*")
Enable CORS header to ProcessRequests() responses Specified location (typically "*") add as "Access-C...
const char * GetCorsCredentials() const
Returns specified CORS credentials value - if any.
static char * ReadFileContent(const char *filename, Int_t &len)
Reads content of file from the disk.
static const char * GetMimeType(const char *path)
Guess mime type base on file extension.
Internal instance used to exchange WS functionality between THttpServer and THttpWSHandler.
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Int_t Atoi() const
Return integer value of string.
const char * Data() const
UInt_t Hash(ECaseCompare cmp=kExact) const
Return hash value.
TString & Append(const char *cs)
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
virtual int Chmod(const char *file, UInt_t mode)
Set the file permission bits. Returns -1 in case or error, 0 otherwise.
virtual int Unlink(const char *name)
Unlink, i.e.
This class represents a WWW compatible URL.
const char * GetValueFromOptions(const char *key) const
Return a value for a given key from the URL options.
Int_t GetIntValueFromOptions(const char *key) const
Return a value for a given key from the URL options as an Int_t, a missing key returns -1.
void ParseOptions() const
Parse URL options into a key/value map.
Bool_t HasOption(const char *key) const
Returns true if the given key appears in the URL options list.
TEngineHolder(TCivetweb *engine)