Cuberite
A lightweight, fast and extensible game server for Minecraft
WebAdmin.cpp
Go to the documentation of this file.
1 
2 #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
3 
4 #include "WebAdmin.h"
5 
6 #include "World.h"
7 #include "Entities/Player.h"
8 #include "Server.h"
9 #include "Root.h"
10 
12 #include "HTTP/HTTPFormParser.h"
13 
14 
15 
16 
17 
18 static const char DEFAULT_WEBADMIN_PORTS[] = "8080";
19 
20 
21 
22 
23 
25 // cWebadminRequestData
26 
31 {
32 public:
34 
35 
37  m_Form(a_Request, *this)
38  {
39  }
40 
41  // cHTTPFormParser::cCallbacks overrides. Files are ignored:
42  virtual void OnFileStart(cHTTPFormParser &, const AString & a_FileName) override
43  {
44  UNUSED(a_FileName);
45  }
46  virtual void OnFileData(cHTTPFormParser &, const char * a_Data, size_t a_Size) override
47  {
48  UNUSED(a_Data);
49  UNUSED(a_Size);
50  }
51  virtual void OnFileEnd(cHTTPFormParser &) override {}
52 } ;
53 
54 
55 
56 
57 
59 // cWebAdmin:
60 
62  m_TemplateScript("<webadmin_template>"),
63  m_IsInitialized(false),
64  m_IsRunning(false)
65 {
66 }
67 
68 
69 
70 
71 
73 {
74  ASSERT(!m_IsRunning); // Was the HTTP server stopped properly?
75 }
76 
77 
78 
79 
80 
81 bool cWebAdmin::Init(void)
82 {
83  if (!LoadIniFile())
84  {
85  // WebAdmin is disabled, bail out faking a success
86  return true;
87  }
88 
89  LOGD("Initialising WebAdmin...");
90 
91  Reload();
92 
93  // Read the ports to be used:
94  // Note that historically the ports were stored in the "Port" and "PortsIPv6" values
95  m_Ports = ReadUpgradeIniPorts(m_IniFile, "WebAdmin", "Ports", "Port", "PortsIPv6", DEFAULT_WEBADMIN_PORTS);
96 
97  if (!m_HTTPServer.Initialize())
98  {
99  return false;
100  }
101  m_IsInitialized = true;
102  m_IniFile.WriteFile("webadmin.ini");
103  return true;
104 }
105 
106 
107 
108 
109 
111 {
112  if (!m_IsInitialized)
113  {
114  // Not initialized
115  return false;
116  }
117 
118  LOGD("Starting WebAdmin...");
119 
121  return m_IsRunning;
122 }
123 
124 
125 
126 
127 
128 void cWebAdmin::Stop(void)
129 {
130  if (!m_IsRunning)
131  {
132  return;
133  }
134 
135  LOGD("Stopping WebAdmin...");
136  m_HTTPServer.Stop();
137  m_IsRunning = false;
138 }
139 
140 
141 
142 
143 
145 {
146  cFile File(FILE_IO_PREFIX "webadmin/login_template.html", cFile::fmRead);
147  if (!File.IsOpen())
148  {
149  return false;
150  }
151 
152  AString TemplateContent;
153  if (File.ReadRestOfFile(TemplateContent) == -1)
154  {
155  return false;
156  }
157 
158  cCSLock Lock(m_CS);
159  m_LoginPage = TemplateContent;
160  return true;
161 }
162 
163 
164 
165 
166 
167 void cWebAdmin::RemoveAllPluginWebTabs(const AString & a_PluginName)
168 {
169  cCSLock lock(m_CS);
170  m_WebTabs.erase(std::remove_if(m_WebTabs.begin(), m_WebTabs.end(), [=](cWebTabPtr a_CBWebTab)
171  {
172  return (a_CBWebTab->m_PluginName == a_PluginName);
173  }),
174  m_WebTabs.end()
175  );
176 }
177 
178 
179 
180 
181 
183 {
184  cCSLock lock(m_CS);
185  if (!LoadIniFile())
186  {
187  // We are asked to disable the webadmin, cannot do that, so warn the admin:
188  LOGWARNING(
189  "WebAdmin was previously enabled and now the settings say to disable it."
190  " This will not take effect until you restart the server."
191  );
192  }
193 
194  // Initialize the WebAdmin template script and reload the file:
196  {
198  }
201  if (!m_TemplateScript.LoadFile(FILE_IO_PREFIX "webadmin/template.lua"))
202  {
203  LOGWARN("Could not load WebAdmin template \"%s\". WebAdmin will not work properly!", FILE_IO_PREFIX "webadmin/template.lua");
205  }
206 
207  // Load the login template, provide a fallback default if not found:
208  if (!LoadLoginPage())
209  {
210  LOGWARN("Could not load WebAdmin login page \"%s\", using fallback template.", FILE_IO_PREFIX "webadmin/login_template.html");
211 
212  // Set the fallback:
213  m_LoginPage = \
214  "<h1>Cuberite WebAdmin</h1>" \
215  "<center>" \
216  "<form method='get' action='webadmin/'>" \
217  "<input type='submit' value='Log in'>" \
218  "</form>" \
219  "</center>";
220  }
221 }
222 
223 
224 
225 
226 
228 {
229  m_IniFile.Clear();
230  if (!m_IniFile.ReadFile("webadmin.ini"))
231  {
232  LOGWARN("Regenerating webadmin.ini, all settings will be reset");
233  m_IniFile.AddHeaderComment(" This file controls the webadmin feature of Cuberite");
234  m_IniFile.AddHeaderComment(" It specifies whether webadmin is enabled, and what logins are allowed. ");
235  m_IniFile.AddHeaderComment(" Username format: [User:*username*]");
236  m_IniFile.AddHeaderComment(" Password format: Password=*password*; for example:");
237  m_IniFile.AddHeaderComment(" [User:admin]");
238  m_IniFile.AddHeaderComment(" Password=admin");
239  m_IniFile.AddHeaderComment(" Please restart Cuberite to apply changes made in this file!");
240  m_IniFile.SetValue("WebAdmin", "Ports", DEFAULT_WEBADMIN_PORTS);
241  m_IniFile.WriteFile("webadmin.ini");
242  }
243 
244  return m_IniFile.GetValueSetB("WebAdmin", "Enabled", true);
245 }
246 
247 
248 
249 
250 
252 {
253  if (!a_Request.HasAuth())
254  {
255  a_Connection.SendNeedAuth("Cuberite WebAdmin");
256  return;
257  }
258 
259  // Check auth:
260  {
261  cCSLock Lock(m_CS);
262  AString UserPassword = m_IniFile.GetValue("User:" + a_Request.GetAuthUsername(), "Password", "");
263  if ((UserPassword == "") || (a_Request.GetAuthPassword() != UserPassword))
264  {
265  a_Connection.SendNeedAuth("Cuberite WebAdmin - bad username or password");
266  return;
267  }
268  }
269 
270  // Check if the contents should be wrapped in the template:
271  auto BareURL = a_Request.GetURLPath();
272  ASSERT(BareURL.length() > 0);
273  bool ShouldWrapInTemplate = (!BareURL.empty() && (BareURL[1] != '~'));
274 
275  // Retrieve the request data:
276  auto Data = std::static_pointer_cast<cWebadminRequestData>(a_Request.GetUserData());
277  if (Data == nullptr)
278  {
279  a_Connection.SendStatusAndReason(500, "Bad UserData");
280  return;
281  }
282 
283  // Wrap it all up for the Lua call:
284  AString Template;
285  HTTPTemplateRequest TemplateRequest;
286  TemplateRequest.Request.URL = a_Request.GetURL();
287  TemplateRequest.Request.Username = a_Request.GetAuthUsername();
288  TemplateRequest.Request.Method = a_Request.GetMethod();
289  TemplateRequest.Request.Path = BareURL.substr(1);
290 
291  if (Data->m_Form.Finish())
292  {
293  for (cHTTPFormParser::const_iterator itr = Data->m_Form.begin(), end = Data->m_Form.end(); itr != end; ++itr)
294  {
295  HTTPFormData HTTPfd;
296  HTTPfd.Value = itr->second;
297  HTTPfd.Type = "";
298  HTTPfd.Name = itr->first;
299  TemplateRequest.Request.FormData[itr->first] = HTTPfd;
300  TemplateRequest.Request.PostParams[itr->first] = itr->second;
301  } // for itr - Data->m_Form[]
302 
303  // Parse the URL into individual params:
304  const AString & URL = a_Request.GetURL();
305  size_t idxQM = URL.find('?');
306  if (idxQM != AString::npos)
307  {
308  cHTTPFormParser URLParams(cHTTPFormParser::fpkURL, URL.c_str() + idxQM + 1, URL.length() - idxQM - 1, *Data);
309  URLParams.Finish();
310  for (cHTTPFormParser::const_iterator itr = URLParams.begin(), end = URLParams.end(); itr != end; ++itr)
311  {
312  TemplateRequest.Request.Params[itr->first] = itr->second;
313  } // for itr - URLParams[]
314  }
315  }
316 
317  // Try to get the template from the Lua template script
318  if (ShouldWrapInTemplate)
319  {
320  cCSLock LockSelf(m_CS);
321  cLuaState::cLock LockTemplate(m_TemplateScript);
322  if (m_TemplateScript.Call("ShowPage", this, &TemplateRequest, cLuaState::Return, Template))
323  {
325  Resp.SetContentType("text/html");
326  a_Connection.Send(Resp);
327  a_Connection.Send(Template.c_str(), Template.length());
328  a_Connection.FinishResponse();
329  return;
330  }
331  a_Connection.SendStatusAndReason(500, "m_TemplateScript failed");
332  return;
333  }
334 
335  // Send the un-decorated page content:
336  auto page = GetPage(TemplateRequest.Request);
338  resp.SetContentType(page.ContentType);
339  a_Connection.Send(resp);
340  a_Connection.Send(page.Content.c_str(), page.Content.length());
341  a_Connection.FinishResponse();
342 }
343 
344 
345 
346 
347 
349 {
350  UNUSED(a_Request);
351 
353  Resp.SetContentType("text/html");
354  a_Connection.Send(Resp);
355  a_Connection.Send(m_LoginPage);
356  a_Connection.FinishResponse();
357 }
358 
359 
360 
361 
362 
364 {
365  AString FileURL = a_Request.GetURL();
366  std::replace(FileURL.begin(), FileURL.end(), '\\', '/');
367 
368  // Remove all leading backslashes:
369  if (!FileURL.empty() && (FileURL[0] == '/'))
370  {
371  size_t FirstCharToRead = FileURL.find_first_not_of('/');
372  if (FirstCharToRead != AString::npos)
373  {
374  FileURL = FileURL.substr(FirstCharToRead);
375  }
376  }
377 
378  // Read the file contents and guess its mime-type, based on the extension:
379  AString Content = "<h2>404 Not Found</h2>";
380  AString ContentType = "text/html";
381  AString Path = Printf(FILE_IO_PREFIX "webadmin/files/%s", FileURL.c_str());
382 
383  // Return 404 if the file is not found, or the URL contains '../' (for security reasons)
384  if ((FileURL.find("../") == AString::npos) && cFile::IsFile(Path))
385  {
386  cFile File(Path, cFile::fmRead);
387  AString FileContent;
388  if (File.IsOpen() && (File.ReadRestOfFile(FileContent) != -1))
389  {
390  std::swap(Content, FileContent);
391  size_t LastPointPosition = Path.find_last_of('.');
392  if (LastPointPosition != AString::npos)
393  {
394  ContentType = GetContentTypeFromFileExt(Path.substr(LastPointPosition + 1));
395  }
396  }
397  if (ContentType.empty())
398  {
399  ContentType = "application/unknown";
400  }
401  }
402 
403  // Send the response:
405  Resp.SetContentType(ContentType);
406  a_Connection.Send(Resp);
407  a_Connection.Send(Content);
408  a_Connection.FinishResponse();
409 }
410 
411 
412 
413 
414 
416 {
417  static bool IsInitialized = false;
418  static AStringMap ContentTypeMap;
419  if (!IsInitialized)
420  {
421  // Initialize the ContentTypeMap:
422  ContentTypeMap["png"] = "image/png";
423  ContentTypeMap["fif"] = "image/fif";
424  ContentTypeMap["gif"] = "image/gif";
425  ContentTypeMap["jpeg"] = "image/jpeg";
426  ContentTypeMap["jpg"] = "image/jpeg";
427  ContentTypeMap["jpe"] = "image/jpeg";
428  ContentTypeMap["tiff"] = "image/tiff";
429  ContentTypeMap["ico"] = "image/ico";
430  ContentTypeMap["csv"] = "text/csv";
431  ContentTypeMap["css"] = "text/css";
432  ContentTypeMap["js"] = "text/javascript";
433  ContentTypeMap["txt"] = "text/plain";
434  ContentTypeMap["rtx"] = "text/richtext";
435  ContentTypeMap["rtf"] = "text/richtext";
436  ContentTypeMap["xml"] = "text/xml";
437  ContentTypeMap["html"] = "text/html";
438  ContentTypeMap["htm"] = "text/html";
439  ContentTypeMap["xhtml"] = "application/xhtml+xml"; // Not recomended for IE6, but no-one uses that anymore
440  }
441 
442  auto itr = ContentTypeMap.find(StrToLower(a_FileExtension));
443  if (itr == ContentTypeMap.end())
444  {
445  return AString();
446  }
447  return itr->second;
448 }
449 
450 
451 
452 
453 
455 {
456  sWebAdminPage page;
457  auto split = StringSplit(a_Request.Path, "/");
458 
459  // If no specific page was requested, return an empty object:
460  if (split.size() <= 2)
461  {
462  return page;
463  }
464 
465  // Find the WebTab handler responsible for the request:
466  cWebTabPtr tab;
467  {
468  cCSLock Lock(m_CS);
469  for (auto & wt: m_WebTabs)
470  {
471  if (
472  (wt->m_PluginName == split[1]) &&
473  (wt->m_UrlPath == split[2])
474  )
475  {
476  tab = wt;
477  break;
478  }
479  } // for wt - m_WebTabs[]
480  }
481 
482  // If a WebTab handler was found, call it:
483  if (tab != nullptr)
484  {
485  page.ContentType = "text/html"; // Default to HTML content type, unless overridden by a plugin
486  if (!tab->m_Callback->Call(a_Request, split[1], page.Content, page.ContentType))
487  {
489  "WebTab callback for plugin %s, page %s has failed.",
490  tab->m_PluginName.c_str(), tab->m_Title.c_str()
491  ));
492  }
493  page.PluginName = tab->m_PluginName;
494  page.TabTitle = tab->m_Title;
495  page.TabUrlPath = split[1];
496  }
497 
498  return page;
499 }
500 
501 
502 
503 
504 
506 {
507  return GetBaseURL(StringSplit(a_URL, "/"));
508 }
509 
510 
511 
512 
513 
515  const AString & a_Title,
516  const AString & a_UrlPath,
517  const AString & a_PluginName,
518  std::shared_ptr<cWebAdmin::cWebTabCallback> a_Callback
519 )
520 {
521  cCSLock lock(m_CS);
522  m_WebTabs.emplace_back(std::make_shared<cWebTab>(a_Title, a_UrlPath, a_PluginName, a_Callback));
523 }
524 
525 
526 
527 
528 
529 bool cWebAdmin::DelWebTab(const AString & a_UrlPath)
530 {
531  cCSLock lock(m_CS);
532  for (auto itr = m_WebTabs.begin(), end = m_WebTabs.end(); itr != end; ++itr)
533  {
534  if ((*itr)->m_UrlPath == a_UrlPath)
535  {
536  m_WebTabs.erase(itr);
537  return true;
538  }
539  } // for itr - m_WebTabs[]
540 
541  // Not found:
542  return false;
543 }
544 
545 
546 
547 
548 
550 {
551  AString dst;
552  dst.reserve(a_Input.length());
553 
554  // Loop over input and substitute HTML characters for their alternatives:
555  size_t len = a_Input.length();
556  for (size_t i = 0; i < len; i++)
557  {
558  switch (a_Input[i])
559  {
560  case '&': dst.append("&amp;"); break;
561  case '\'': dst.append("&apos;"); break;
562  case '"': dst.append("&quot;"); break;
563  case '<': dst.append("&lt;"); break;
564  case '>': dst.append("&gt;"); break;
565  default:
566  {
567  dst.push_back(a_Input[i]);
568  break;
569  }
570  } // switch (a_Input[i])
571  } // for i - a_Input[]
572 
573  return dst;
574 }
575 
576 
577 
578 
579 
581 {
582  return URLEncode(a_Input);
583 }
584 
585 
586 
587 
588 
590 {
591  AString BaseURL = "./";
592  if (a_URLSplit.size() > 1)
593  {
594  for (unsigned int i = 0; i < a_URLSplit.size(); i++)
595  {
596  BaseURL += "../";
597  }
598  BaseURL += "webadmin/";
599  }
600  return BaseURL;
601 }
602 
603 
604 
605 
606 
608 {
609  UNUSED(a_Connection);
610  const AString & URL = a_Request.GetURL();
611  if (
612  (strncmp(URL.c_str(), "/webadmin", 9) == 0) ||
613  (strncmp(URL.c_str(), "/~webadmin", 10) == 0)
614  )
615  {
616  a_Request.SetUserData(std::make_shared<cWebadminRequestData>(a_Request));
617  return;
618  }
619  if (URL == "/")
620  {
621  // The root needs no body handler and is fully handled in the OnRequestFinished() call
622  return;
623  }
624  // TODO: Handle other requests
625 }
626 
627 
628 
629 
630 
631 void cWebAdmin::OnRequestBody(cHTTPServerConnection & a_Connection, cHTTPIncomingRequest & a_Request, const char * a_Data, size_t a_Size)
632 {
633  UNUSED(a_Connection);
634  auto Data = std::static_pointer_cast<cWebadminRequestData>(a_Request.GetUserData());
635  if (Data == nullptr)
636  {
637  return;
638  }
639  Data->m_Form.Parse(a_Data, a_Size);
640 }
641 
642 
643 
644 
645 
647 {
648  const AString & URL = a_Request.GetURL();
649  if (
650  (strncmp(URL.c_str(), "/webadmin", 9) == 0) ||
651  (strncmp(URL.c_str(), "/~webadmin", 10) == 0)
652  )
653  {
654  HandleWebadminRequest(a_Connection, a_Request);
655  }
656  else if (URL == "/")
657  {
658  // The root needs no body handler and is fully handled in the OnRequestFinished() call
659  HandleRootRequest(a_Connection, a_Request);
660  }
661  else
662  {
663  HandleFileRequest(a_Connection, a_Request);
664  }
665 }
666 
667 
668 
669 
670 
HTTPRequest Request
Definition: WebAdmin.h:76
const AString & GetMethod(void) const
Returns the method used in the request.
Definition: HTTPMessage.h:104
void Stop(void)
Stops the server, drops all current connections.
Definition: HTTPServer.cpp:176
void HandleRootRequest(cHTTPServerConnection &a_Connection, cHTTPIncomingRequest &a_Request)
Handles requests for the root page.
Definition: WebAdmin.cpp:348
AString URL
The entire URL presented to the HTTP server.
Definition: WebAdmin.h:46
AString PluginName
Definition: WebAdmin.h:87
bool Call(const FnT &a_Function, Args &&...args)
Call the specified Lua function.
Definition: LuaState.h:744
static AString GetURLEncodedString(const AString &a_Input)
Escapes the string for use in an URL Exported to Lua in ManualBindings.cpp.
Definition: WebAdmin.cpp:580
StringStringMap PostParams
Parameters posted as a part of a form - either in the URL (GET method) or in the body (POST method) ...
Definition: WebAdmin.h:63
Provides storage for an incoming HTTP request.
Definition: HTTPMessage.h:85
#define FILE_IO_PREFIX
Definition: Globals.h:196
#define LOGWARN
Definition: LoggerSimple.h:43
void Parse(const char *a_Data, size_t a_Size)
Adds more data into the parser, as the request body is received.
Stores outgoing response headers and serializes them to an HTTP data stream.
Definition: HTTPMessage.h:67
Base class for anything that can be used as the UserData for the request.
Definition: HTTPMessage.h:91
static AString GetHTMLEscapedString(const AString &a_Input)
Escapes text passed into it, so it can be embedded into html.
Definition: WebAdmin.cpp:549
void SetUserData(cUserDataPtr a_UserData)
Attaches any kind of data to this request, to be later retrieved by GetUserData().
Definition: HTTPMessage.h:124
The form has been transmitted as parameters to a GET request.
cWebadminRequestData(const cHTTPIncomingRequest &a_Request)
Definition: WebAdmin.cpp:36
int ReadRestOfFile(AString &a_Contents)
Reads the file from current position till EOF into an AString; returns the number of bytes read or -1...
Definition: File.cpp:262
void Reload(void)
Reloads m_IniFile, m_LoginPage and m_TemplateScript.
Definition: WebAdmin.cpp:182
static AString GetContentTypeFromFileExt(const AString &a_FileExtension)
Returns the content type from the file extension.
Definition: WebAdmin.cpp:415
void HandleFileRequest(cHTTPServerConnection &a_Connection, cHTTPIncomingRequest &a_Request)
Handles requests for a file.
Definition: WebAdmin.cpp:363
AString TabUrlPath
Definition: WebAdmin.h:89
AString Username
Name of the logged-in user.
Definition: WebAdmin.h:55
cIniFile m_IniFile
The webadmin.ini file, used for the settings and allowed logins.
Definition: WebAdmin.h:243
bool IsOpen(void) const
Definition: File.cpp:116
AString Method
HTTP method used for the request ("GET", "POST" etc.)
Definition: WebAdmin.h:49
bool ReadFile(const AString &a_FileName, bool a_AllowExampleRedirect=true)
Reads the contents of the specified ini file If the file doesn&#39;t exist and a_AllowExampleRedirect is ...
Definition: IniFile.cpp:50
const AString & GetURL(void) const
Returns the URL used in the request.
Definition: HTTPMessage.h:107
virtual void OnFileEnd(cHTTPFormParser &) override
Called when the current file part has ended in the form data.
Definition: WebAdmin.cpp:51
cUserDataPtr GetUserData(void)
Returns the data attached to this request by the class client.
Definition: HTTPMessage.h:127
void SendStatusAndReason(int a_StatusCode, const AString &a_Reason)
Sends HTTP status code together with a_Reason (used for HTTP errors).
std::vector< AString > AStringVector
Definition: StringUtils.h:14
bool Initialize(void)
Initializes the server - reads the cert files etc.
Definition: HTTPServer.cpp:85
static bool IsFile(const AString &a_Path)
Returns true if the specified path is a regular file.
Definition: File.cpp:425
bool WriteFile(const AString &a_FileName) const
Writes data stored in class to the specified ini file.
Definition: IniFile.cpp:189
cWebTabPtrs m_WebTabs
All registered WebTab handlers.
Definition: WebAdmin.h:231
Definition: File.h:37
virtual ~cWebAdmin() override
Definition: WebAdmin.cpp:72
void AddWebTab(const AString &a_Title, const AString &a_UrlPath, const AString &a_PluginName, std::shared_ptr< cWebTabCallback > a_Callback)
Adds a new WebTab handler.
Definition: WebAdmin.cpp:514
void Stop(void)
Stops the HTTP server, if it was started.
Definition: WebAdmin.cpp:128
bool SetValue(const int keyID, const int valueID, const AString &value)
Definition: IniFile.cpp:393
AString GetURLPath(void) const
Returns the path part of the URL.
static const char DEFAULT_WEBADMIN_PORTS[]
Definition: WebAdmin.cpp:18
virtual void OnRequestBody(cHTTPServerConnection &a_Connection, cHTTPIncomingRequest &a_Request, const char *a_Data, size_t a_Size) override
Called when another part of request body has arrived.
Definition: WebAdmin.cpp:631
cWebAdmin(void)
Definition: WebAdmin.cpp:61
void HandleWebadminRequest(cHTTPServerConnection &a_Connection, cHTTPIncomingRequest &a_Request)
Handles requests coming to the "/webadmin" or "/~webadmin" URLs.
Definition: WebAdmin.cpp:251
virtual void OnFileData(cHTTPFormParser &, const char *a_Data, size_t a_Size) override
Called when more file data has come for the current file in the form data.
Definition: WebAdmin.cpp:46
AString & Printf(AString &str, const char *format, fmt::ArgList args)
Output the formatted text into the string.
Definition: StringUtils.cpp:55
void AddHeaderComment(const AString &comment)
Adds a header comment.
Definition: IniFile.cpp:675
void SendNeedAuth(const AString &a_Realm)
Sends the "401 unauthorized" reply together with instructions on authorizing, using the specified rea...
void FinishResponse(void)
Indicates that the current response is finished, gets ready for receiving another request (HTTP 1...
#define ASSERT(x)
Definition: Globals.h:335
std::map< AString, AString > AStringMap
A string dictionary, used for key-value pairs.
Definition: StringUtils.h:18
cLuaState m_TemplateScript
The Lua template script to provide templates.
Definition: WebAdmin.h:235
void LOGWARNING(const char *a_Format, fmt::ArgList a_ArgList)
Definition: Logger.cpp:174
#define LOGD(...)
Definition: LoggerSimple.h:40
void SetContentType(const AString &a_ContentType)
Definition: HTTPMessage.h:39
void Clear(void)
Deletes all stored ini data (but doesn&#39;t touch the file)
Definition: IniFile.cpp:646
std::string Type
Definition: WebAdmin.h:32
AString TabTitle
Definition: WebAdmin.h:88
AString ContentType
Definition: WebAdmin.h:90
#define UNUSED
Definition: Globals.h:152
std::string Name
Definition: WebAdmin.h:30
bool Finish(void)
Notifies that there&#39;s no more data incoming and the parser should finish its parsing.
static const cRet Return
Definition: LuaState.h:446
const AString & GetAuthUsername(void) const
Returns the username that the request presented.
Definition: HTTPMessage.h:116
AString URLEncode(const AString &a_Text)
URL-encodes the given string.
cHTTPServer m_HTTPServer
The HTTP server which provides the underlying HTTP parsing, serialization and events.
Definition: WebAdmin.h:255
bool DelWebTab(const AString &a_UrlPath)
Removes the WebTab with the specified URL path.
Definition: WebAdmin.cpp:529
void Close(void)
Closes the m_LuaState, if not closed already.
Definition: LuaState.cpp:536
std::shared_ptr< cWebTab > cWebTabPtr
Definition: WebAdmin.h:147
std::string AString
Definition: StringUtils.h:13
virtual void OnRequestBegun(cHTTPServerConnection &a_Connection, cHTTPIncomingRequest &a_Request) override
Called when a new request arrives over a connection and all its headers have been parsed...
Definition: WebAdmin.cpp:607
AString Content
Definition: WebAdmin.h:86
The form parser callbacks for requests in the "/webadmin" and "/~webadmin" paths. ...
Definition: WebAdmin.cpp:28
void Send(const cHTTPOutgoingResponse &a_Response)
Sends the headers contained in a_Response.
bool LoadIniFile(void)
Loads webadmin.ini into m_IniFile.
Definition: WebAdmin.cpp:227
FormDataMap FormData
Same as PostParams.
Definition: WebAdmin.h:66
Provides a RAII-style locking for the LuaState.
Definition: LuaState.h:146
void Create(void)
Creates the m_LuaState, if not created already.
Definition: LuaState.cpp:487
sWebAdminPage GetPage(const HTTPRequest &a_Request)
Returns the (inner) page contents for the specified request.
Definition: WebAdmin.cpp:454
AString Path
The Path part of the request&#39;s URL (excluding GET params).
Definition: WebAdmin.h:52
bool LoadFile(const AString &a_FileName, bool a_LogWarnings=true)
Loads the specified file Returns false and optionally logs a warning to the console if not successful...
Definition: LuaState.cpp:644
AStringVector StringSplit(const AString &str, const AString &delim)
Split the string at any of the listed delimiters.
Definition: StringUtils.cpp:76
RAII for cCriticalSection - locks the CS on creation, unlocks on destruction.
void RegisterAPILibs(void)
Registers all the API libraries that MCS provides into m_LuaState.
Definition: LuaState.cpp:505
static AString GetBaseURL(const AString &a_URL)
Returns the prefix needed for making a link point to the webadmin root from the given URL ("...
Definition: WebAdmin.cpp:505
virtual void OnRequestFinished(cHTTPServerConnection &a_Connection, cHTTPIncomingRequest &a_Request) override
Called when the request body has been fully received in previous calls to OnRequestBody() ...
Definition: WebAdmin.cpp:646
bool IsValid(void) const
Returns true if the m_LuaState is valid.
Definition: LuaState.h:581
void RemoveAllPluginWebTabs(const AString &a_PluginName)
Removes all WebTabs registered by the specified plugin.
Definition: WebAdmin.cpp:167
bool m_IsRunning
Set to true if Start() succeeds in starting the server, reset back to false in Stop().
Definition: WebAdmin.h:249
bool Init(void)
Initializes the object.
Definition: WebAdmin.cpp:81
AStringVector ReadUpgradeIniPorts(cSettingsRepositoryInterface &a_Settings, const AString &a_KeyName, const AString &a_PortsValueName, const AString &a_OldIPv4ValueName, const AString &a_OldIPv6ValueName, const AString &a_DefaultValue)
Reads the list of ports from the INI file, possibly upgrading from IPv4 / IPv6-specific values into n...
Definition: IniFile.cpp:924
AString m_LoginPage
The HTML page that provides the login.
Definition: WebAdmin.h:239
bool GetValueSetB(const AString &keyname, const AString &valuename, const bool defValue=false) override
Definition: IniFile.h:145
virtual void OnFileStart(cHTTPFormParser &, const AString &a_FileName) override
Called when a new file part is encountered in the form data.
Definition: WebAdmin.cpp:42
bool Start(cCallbacks &a_Callbacks, const AStringVector &a_Ports)
Starts the server and assigns the callbacks to use for incoming requests.
Definition: HTTPServer.cpp:134
bool m_IsInitialized
Set to true if Init() succeeds and the webadmin isn&#39;t to be disabled.
Definition: WebAdmin.h:246
AString GetValue(const AString &keyname, const AString &valuename, const AString &defValue="") const override
Get the value at the specified key and value, returns defValue on failure.
Definition: IniFile.cpp:481
bool Start(void)
Starts the HTTP server taking care of the webadmin.
Definition: WebAdmin.cpp:110
AString StrToLower(const AString &s)
Returns a lower-cased copy of the string.
StringStringMap Params
Parameters given in the URL, after the questionmark.
Definition: WebAdmin.h:60
cHTTPFormParser m_Form
Definition: WebAdmin.cpp:33
const AString & GetAuthPassword(void) const
Returns the password that the request presented.
Definition: HTTPMessage.h:119
cCriticalSection m_CS
Protects m_WebTabs, m_TemplateScript, m_LoginTemplate and m_IniFile against multithreaded access...
Definition: WebAdmin.h:227
bool HasAuth(void) const
Returns true if the request has had the Auth header present.
Definition: HTTPMessage.h:113
std::string Value
Definition: WebAdmin.h:31
AStringVector m_Ports
The ports on which the webadmin is running.
Definition: WebAdmin.h:252
bool LoadLoginPage(void)
Loads the login template into m_LoginPage.
Definition: WebAdmin.cpp:144