code to embed webUI server in the main executable (initial version, not yet working)

This commit is contained in:
csoler 2019-11-10 17:38:16 +01:00
parent aabba04be9
commit 6603dbd913
No known key found for this signature in database
GPG Key ID: 7BCA522266C0804C
17 changed files with 355 additions and 111 deletions

View File

@ -159,6 +159,12 @@ PUBLIC_HEADERS = retroshare/rsdisc.h \
retroshare/rsservicecontrol.h \
retroshare/rsgxsdistsync.h
rs_webui {
PUBLIC_HEADERS += retroshare/rswebui.h
SOURCES += rsserver/p3webui.cc
HEADERS += rsserver/p3webui.h
}
HEADERS += plugins/pluginmanager.h \
plugins/dlfcn_win32.h \
rsitems/rspluginitems.h \

View File

@ -0,0 +1,202 @@
/*******************************************************************************
* libretroshare/src/rsserver: p3webui.cc *
* *
* libretroshare: retroshare core library *
* *
* Copyright 2019-2019 Cyril Soler *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "p3webui.h"
#include <thread>
#include <iostream>
#include <fstream>
#include <memory>
#include <chrono>
#include <cstdlib>
#include <restbed>
#include "util/rsthreads.h"
#include "util/rsdebug.h"
#include "retroshare/rswebui.h"
#define TEXT_HTML 0
#define TEXT_CSS 1
#define TEXT_SVG 2
#define DEBUG_RS_WEBUI 1
RsWebUI *rsWebUI = new p3WebUI;
static constexpr char *mime_types[3] = {
"text/html",
"text/css",
"image/svg+xml"
};
template<int MIME_TYPE_INDEX> class handler
{
public:
static void get_handler( const std::shared_ptr< restbed::Session > session )
{
const auto request = session->get_request( );
const std::string filename = request->get_path_parameter( "filename" );
const std::string directory = request->get_path_parameter( "dir" );
std::string resource_filename = _base_directory + directory + "/" + filename;
std::cerr << "Reading file: \"" << resource_filename << "\"" << std::endl;
std::ifstream stream( resource_filename, std::ifstream::in );
if ( stream.is_open( ) )
{
const std::string body = std::string( std::istreambuf_iterator< char >( stream ), std::istreambuf_iterator< char >( ) );
std::cerr << " body length=" << body.length() << std::endl;
const std::multimap< std::string, std::string > headers
{
{ "Content-Type", mime_types[MIME_TYPE_INDEX] },
{ "Content-Length", std::to_string( body.length( ) ) }
};
session->close( restbed::OK, body, headers );
}
else
{
std::cerr << "Could not open file " << resource_filename << std::endl;
session->close( restbed::NOT_FOUND );
}
}
static std::string _base_directory ;
};
template<int MIME_TYPE_INDEX> std::string handler<MIME_TYPE_INDEX>::_base_directory = "/home/csoler/Desktop/Code/retroshare/RSNewWebUI/webui/";
static void service_ready_handler( restbed::Service& )
{
fprintf( stderr, "Hey! The service is up and running." );
}
class WebUIThread: public RsThread
{
public:
WebUIThread()
{
_service = std::make_shared<restbed::Service>();
}
void runloop() override
{
auto resource1 = std::make_shared< restbed::Resource >( );
resource1->set_paths( {
"/{filename: index.html}",
"/{filename: app.js}",
}
);
resource1->set_method_handler( "GET", handler<TEXT_HTML>::get_handler );
auto resource2 = std::make_shared< restbed::Resource >();
resource2->set_paths( {
"/{dir: css]/{filename: fontawesome.css}",
"/{dir: css}/{filename: solid.css}",
"/{filename: app.css}",
} );
resource2->set_method_handler( "GET", handler<TEXT_CSS>::get_handler );
auto resource3 = std::make_shared< restbed::Resource >();
resource3->set_paths( {
"/{filename: retroshare.svg}",
} );
resource3->set_method_handler( "GET", handler<TEXT_SVG>::get_handler );
auto settings = std::make_shared< restbed::Settings >( );
settings->set_port( 1984 );
settings->set_default_header( "Connection", "close" );
_service->publish( resource1 );
_service->publish( resource2 );
_service->publish( resource3 );
_service->set_ready_handler( service_ready_handler );
_service->start( settings );
}
void stop()
{
_service->stop();
RsThread::ask_for_stop();
while(isRunning())
sleep(1);
}
private:
std::shared_ptr<restbed::Service> _service;
};
p3WebUI::p3WebUI()
{
_webui_thread = new WebUIThread;
}
p3WebUI::~p3WebUI()
{
while(_webui_thread->isRunning())
{
stop();
std::cerr << "Deleting webUI object while webUI thread is still running. Trying shutdown...." << std::endl;
rstime::rs_usleep(1000*1000);
}
delete _webui_thread;
}
bool p3WebUI::restart()
{
RsDbg() << "Restarting web interface listening on port " << _listening_port << std::endl;
if(_webui_thread->isRunning())
_webui_thread->stop();
_webui_thread->start();
return true;
}
bool p3WebUI::stop()
{
_webui_thread->stop();
return true;
}
void p3WebUI::setHtmlFilesDirectory(const std::string& html_dir)
{
_html_files_directory = html_dir;
}
void p3WebUI::setListeningPort(uint16_t port)
{
_listening_port = port;
if(_webui_thread->isRunning())
restart();
}
int p3WebUI::status() const
{
if(_webui_thread->isRunning())
return WEBUI_STATUS_RUNNING;
else
return WEBUI_STATUS_NOT_RUNNING;
}

View File

@ -0,0 +1,49 @@
/*******************************************************************************
* libretroshare/src/rsserver: p3webui.h *
* *
* libretroshare: retroshare core library *
* *
* Copyright 2019-2019 Cyril Soler *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include <string>
#include "retroshare/rswebui.h"
class WebUIThread;
class p3WebUI: public RsWebUI
{
public:
p3WebUI();
virtual ~p3WebUI();
virtual bool restart() override;
virtual bool stop() override;
virtual void setHtmlFilesDirectory(const std::string& html_dir) override;
virtual void setListeningPort(uint16_t port) override;
virtual int status() const override;
private:
WebUIThread *_webui_thread;
std::string _html_files_directory;
uint16_t _listening_port;
};

View File

@ -23,16 +23,14 @@
#include "HelpDialog.h"
#include "rshare.h"
#include "restbed"
#include <retroshare/rsiface.h>
#include <retroshare/rsplugin.h>
#include <retroshare/rsdisc.h>
#include <retroshare/rspeers.h>
#include "settings/rsharesettings.h"
#ifdef ENABLE_WEBUI
#include <microhttpd.h>
#endif
#include <QClipboard>
#include <QSysInfo>
#include <QHBoxLayout>
@ -972,13 +970,13 @@ void AboutWidget::on_copy_button_clicked()
RsControl::instance()->getLibraries(libraries);
verInfo+=addLibraries("libretroshare", libraries);
#ifdef ENABLE_WEBUI
/* Add version numbers of RetroShare */
// Add versions here. Find a better place.
libraries.clear();
libraries.push_back(RsLibraryInfo("Libmicrohttpd", MHD_get_version()));
verInfo+=addLibraries("RetroShare", libraries);
#endif // ENABLE_WEBUI
// #ifdef RS_WEBUI
// /* Add version numbers of RetroShare */
// // Add versions here. Find a better place.
// libraries.clear();
// libraries.push_back(RsLibraryInfo("RestBed", restbed::get_version()));
// verInfo+=addLibraries("RetroShare", libraries);
// #endif
/* Add version numbers of plugins */
if (rsPlugins) {

View File

@ -25,10 +25,6 @@
#include <retroshare/rsplugin.h>
#include "rshare.h"
#ifdef ENABLE_WEBUI
#include <microhttpd.h>
#endif // ENABLE_WEBUI
#include <QFile>
#include <QTextStream>
@ -91,13 +87,13 @@ HelpDialog::HelpDialog(QWidget *parent) :
RsControl::instance()->getLibraries(libraries);
addLibraries(ui->libraryLayout, "libretroshare", libraries);
#ifdef ENABLE_WEBUI
/* Add version numbers of RetroShare */
// Add versions here. Find a better place.
libraries.clear();
libraries.push_back(RsLibraryInfo("Libmicrohttpd", MHD_get_version()));
addLibraries(ui->libraryLayout, "RetroShare", libraries);
#endif // ENABLE_WEBUI
// #ifdef RS_WEBUI
// /* Add version numbers of RetroShare */
// // Add versions here. Find a better place.
// libraries.clear();
// libraries.push_back(RsLibraryInfo("Restbed", restbed::get_version()));
// addLibraries(ui->libraryLayout, "RetroShare", libraries);
// #endif // ENABLE_WEBUI
/* Add version numbers of plugins */
if (rsPlugins) {

View File

@ -113,7 +113,7 @@
#include "common/StatusDefs.h"
#include "gui/notifyqt.h"
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
# include "settings/WebuiPage.h"
#endif
@ -605,9 +605,9 @@ void MainWindow::createTrayIcon()
trayMenu->addAction(QIcon(IMAGE_MESSENGER), tr("Open Messenger"), this, SLOT(showMessengerWindow()));
#endif
trayMenu->addAction(QIcon(IMAGE_MESSAGES), tr("Open Messages"), this, SLOT(showMess()));
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
trayMenu->addAction(QIcon(":/images/emblem-web.png"), tr("Show web interface"), this, SLOT(showWebinterface()));
#endif // ENABLE_WEBUI
#endif
trayMenu->addAction(QIcon(IMAGE_BWGRAPH), tr("Bandwidth Graph"), this, SLOT(showBandwidthGraph()));
trayMenu->addAction(QIcon(IMAGE_DHT), tr("Statistics"), this, SLOT(showStatisticsWindow()));
@ -1116,7 +1116,7 @@ void MainWindow::showStatisticsWindow()
StatisticsWindow::showYourself();
}
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
void MainWindow::showWebinterface()
{
WebuiPage::showWebui();

View File

@ -230,7 +230,7 @@ private slots:
void showMessengerWindow();
#endif
void showStatisticsWindow();
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
void showWebinterface();
#endif
//void servicePermission();

View File

@ -27,11 +27,7 @@
#include <QSpinBox>
#include "util/misc.h"
#include "api/ApiServer.h"
#include "api/ApiServerMHD.h"
#include "api/ApiServerLocal.h"
#include "api/RsControlModule.h"
#include "api/GetPluginInterfaces.h"
#include "retroshare/rswebui.h"
#include "rsharesettings.h"
@ -51,6 +47,7 @@ WebuiPage::WebuiPage(QWidget */*parent*/, Qt::WindowFlags /*flags*/)
connect(ui.port_SB, SIGNAL(valueChanged(int)), this, SLOT(onPortValueChanged(int)));
connect(ui.allIp_CB, SIGNAL(clicked(bool)), this, SLOT(onAllIPCBClicked(bool)));
connect(ui.applyStartBrowser_PB, SIGNAL(clicked()), this, SLOT(onApplyClicked()));
connect(ui.webInterfaceFiles_LE, SIGNAL(clicked()), this, SLOT(selectWebInterfaceDirectory()));
}
WebuiPage::~WebuiPage()
@ -58,6 +55,11 @@ WebuiPage::~WebuiPage()
}
void WebuiPage::selectWebInterfaceDirectory()
{
QString dirname = QFileDialog::getExistingDirectory(NULL,tr("Please select the directory were to find retroshare webinterface files"),ui.webInterfaceFiles_LE->text());
}
bool WebuiPage::updateParams(QString &errmsg)
{
std::cerr << "WebuiPage::save()" << std::endl;
@ -90,6 +92,7 @@ void WebuiPage::load()
std::cerr << "WebuiPage::load()" << std::endl;
whileBlocking(ui.enableWebUI_CB)->setChecked(Settings->getWebinterfaceEnabled());
whileBlocking(ui.port_SB)->setValue(Settings->getWebinterfacePort());
whileBlocking(ui.webInterfaceFiles_LE)->setText(Settings->getWebinterfaceFilesDirectory());
whileBlocking(ui.allIp_CB)->setChecked(Settings->getWebinterfaceAllowAllIps());
onEnableCBClicked(Settings->getWebinterfaceEnabled());
}
@ -105,49 +108,18 @@ QString WebuiPage::helpText() const
{
if(!Settings->getWebinterfaceEnabled())
return true;
if(apiServer || apiServerMHD || controlModule)
return true;
apiServer = new resource_api::ApiServer();
controlModule = new resource_api::RsControlModule(0, 0, apiServer->getStateTokenServer(), apiServer, false);
apiServer->addResourceHandler("control", dynamic_cast<resource_api::ResourceRouter*>(controlModule), &resource_api::RsControlModule::handleRequest);
rsWebUI->setListeningPort(Settings->getWebinterfacePort());
rsWebUI->setHtmlFilesDirectory(Settings->getWebinterfaceFilesDirectory().toStdString());
RsPlugInInterfaces ifaces;
resource_api::getPluginInterfaces(ifaces);
apiServer->loadMainModules(ifaces);
rsWebUI->restart();
apiServerMHD = new resource_api::ApiServerMHD(apiServer);
bool ok = apiServerMHD->configure(resource_api::getDefaultDocroot(),
Settings->getWebinterfacePort(),
"",
Settings->getWebinterfaceAllowAllIps());
apiServerMHD->start();
// TODO: LIBRESAPI_LOCAL_SERVER Move in appropriate place
#ifdef LIBRESAPI_LOCAL_SERVER
apiServerLocal = new resource_api::ApiServerLocal(apiServer, resource_api::ApiServerLocal::serverPath());
#endif
return ok;
return true;
}
/*static*/ void WebuiPage::checkShutdownWebui()
{
if(apiServer || apiServerMHD)
{
apiServerMHD->stop();
delete apiServerMHD;
apiServerMHD = 0;
// TODO: LIBRESAPI_LOCAL_SERVER Move in appropriate place
#ifdef LIBRESAPI_LOCAL_SERVER
delete apiServerLocal;
apiServerLocal = 0;
#endif
delete apiServer;
apiServer = 0;
delete controlModule;
controlModule = 0;
}
rsWebUI->stop();
}
/*static*/ void WebuiPage::showWebui()

View File

@ -58,6 +58,7 @@ public:
static void showWebui();
public slots:
void selectWebInterfaceDirectory();
void onEnableCBClicked(bool checked);
void onPortValueChanged(int value);
void onAllIPCBClicked(bool checked);

View File

@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>497</width>
<height>404</height>
<width>960</width>
<height>717</height>
</rect>
</property>
<property name="windowTitle">
@ -29,25 +29,42 @@
<property name="title">
<string>Web parameters</string>
</property>
<layout class="QGridLayout" name="params_GBGLayout">
<item row="0" column="1">
<widget class="QSpinBox" name="port_SB">
<property name="minimum">
<number>1024</number>
</property>
<property name="maximum">
<number>65535</number>
</property>
</widget>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="port_Label">
<property name="text">
<string>Listening port:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="port_SB">
<property name="minimum">
<number>1024</number>
</property>
<property name="maximum">
<number>65535</number>
</property>
<property name="value">
<number>1984</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Web interface directory:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="webInterfaceFiles_LE"/>
</item>
</layout>
</item>
<item row="0" column="0">
<widget class="QLabel" name="port_Label">
<property name="text">
<string>Port:</string>
</property>
</widget>
</item>
<item row="1" column="0">
<item>
<widget class="QCheckBox" name="allIp_CB">
<property name="text">
<string>Allow access from all IP addresses (Default: localhost only)</string>
@ -67,7 +84,7 @@
<item>
<widget class="QLabel" name="noteLabel">
<property name="text">
<string>Note: these settings do not affect retroshare-nogui. Retroshare-nogui has a command line switch to activate the web interface.</string>
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Note: these settings do not affect retroshare-service, which has a command line switch to activate the web interface and select the listening port.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="wordWrap">
<bool>true</bool>

View File

@ -44,7 +44,7 @@
#include "gui/common/FloatingHelpBrowser.h"
#include "gui/common/RSElidedItemDelegate.h"
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
# include "WebuiPage.h"
#endif
@ -164,9 +164,9 @@ SettingsPage::initStackedWidget()
addPage(new AppearancePage()); // APPEARENCE
addPage(new SoundPage() ); // SOUND
addPage(new ServicePermissionsPage() ); // PERMISSIONS
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
addPage(new WebuiPage() );
#endif // ENABLE_WEBUI
#endif
#ifdef RS_JSONAPI
addPage(new JsonApiPage());

View File

@ -1152,7 +1152,15 @@ void RshareSettings::setWebinterfaceEnabled(bool enabled)
uint16_t RshareSettings::getWebinterfacePort()
{
return valueFromGroup("Webinterface", "port", 9090).toUInt();
return valueFromGroup("Webinterface", "port", 1984).toUInt();
}
QString RshareSettings::getWebinterfaceFilesDirectory()
{
#ifdef WINDOWS_SYS
return valueFromGroup("Webinterface","directory","data/webui/").toString().toStdString();
#endif
return valueFromGroup("Webinterface","directory","/usr/share/retroshare/webui/").toString();
}
void RshareSettings::setWebinterfacePort(uint16_t port)

View File

@ -334,6 +334,9 @@ public:
uint16_t getWebinterfacePort();
void setWebinterfacePort(uint16_t port);
QString getWebinterfaceFilesDirectory();
void setWebinterfaceFilesDirectory(const QString& dirname);
bool getWebinterfaceAllowAllIps();
void setWebinterfaceAllowAllIps(bool allow_all);

View File

@ -56,7 +56,7 @@ CrashStackTrace gCrashStackTrace;
#ifdef MESSENGER_WINDOW
#include "gui/MessengerWindow.h"
#endif
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
# include "gui/settings/WebuiPage.h"
#endif
@ -574,7 +574,7 @@ feenableexcept(FE_INVALID | FE_DIVBYZERO);
notify->enable() ; // enable notification system after GUI creation, to avoid data races in Qt.
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
WebuiPage::checkStartWebui();
#endif // ENABLE_WEBUI
@ -595,9 +595,9 @@ feenableexcept(FE_INVALID | FE_DIVBYZERO);
JsonApiPage::checkShutdownJsonApi();
#endif // RS_JSONAPI
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
WebuiPage::checkShutdownWebui();
#endif // ENABLE_WEBUI
#endif
/* cleanup */
ChatDialog::cleanupChat();

View File

@ -28,7 +28,7 @@ DEFINES += TARGET=\\\"$${TARGET}\\\"
DEPENDPATH *= $${PWD} $${RS_INCLUDE_DIR} retroshare-gui
INCLUDEPATH *= $${PWD} retroshare-gui
libresapihttpserver {
rs_webui {
!include("../../libresapi/src/use_libresapi.pri"):error("Including")
HEADERS *= gui/settings/WebuiPage.h
SOURCES *= gui/settings/WebuiPage.cpp

View File

@ -37,14 +37,6 @@
#include "introserver.h"
#endif
#ifdef ENABLE_WEBUI
#include <stdarg.h>
#include <csignal>
#include "api/ApiServerMHD.h"
#include "api/RsControlModule.h"
#include "TerminalApiClient.h"
#endif
/* Basic instructions for running libretroshare as background thread.
* ******************************************************************* *
* This allows your program to communicate with authenticated peers.
@ -60,7 +52,7 @@ int main(int argc, char **argv)
RsConfigOptions conf;
conf.main_executable_path = argv[0];
#ifdef ENABLE_WEBUI
#ifdef RS_WEBUI
std::string docroot = resource_api::getDefaultDocroot();
uint16_t httpPort = 0;
std::string listenAddress;

View File

@ -200,10 +200,10 @@ rs_use_native_dialogs:CONFIG -= no_rs_use_native_dialogs
CONFIG *= rs_broadcast_discovery
no_rs_broadcast_discovery:CONFIG -= rs_broadcast_discovery
# To enable webui append the following assignation to qmake
# command line "CONFIG+=rs_webui"
CONFIG *= no_rs_webui
rs_webui:CONFIG -= no_rs_webui
# To disable webui append the following assignation to qmake
# command line "CONFIG+=rs_no_webui"
CONFIG *= rs_webui
rs_no_webui:CONFIG -= rs_webui
# To enable webui append the following assignation to qmake
# command line "CONFIG+=rs_service_webui_terminal_password"