fixes required by review of pr1700

This commit is contained in:
csoler 2019-11-25 22:16:32 +01:00
parent 5223ff751a
commit 7aa51423a4
No known key found for this signature in database
GPG Key ID: 7BCA522266C0804C
13 changed files with 98 additions and 154 deletions

View File

@ -117,15 +117,6 @@ JsonApiServer::corsOptionsHeaders =
return false;
}
static bool is_alphanumeric(char c) { return (c>='0' && c<'9') || (c>='a' && c<='z') || (c>='A' && c<='Z') ;}
static bool is_alphanumeric(const std::string& s)
{
for(uint32_t i=0;i<s.size();++i)
if(!is_alphanumeric(s[i]))
return false;
return true;
}
bool RsJsonAPI::parseToken(const std::string& clear_token,std::string& user,std::string& passwd)
{
uint32_t last_index=0;
@ -137,7 +128,7 @@ bool RsJsonAPI::parseToken(const std::string& clear_token,std::string& user,std:
++nb_colons;
last_index = i;
}
else if(!is_alphanumeric(clear_token[i]))
else if(!librs::util::is_alphanumeric(clear_token[i]))
return false;
if(nb_colons != 1)
@ -424,7 +415,7 @@ void JsonApiServer::registerHandler(
else session->close(rb::UNAUTHORIZED);
} );
_resources.push_back(resource);
mResources.push_back(resource);
}
void JsonApiServer::setNewAccessRequestCallback( const std::function<bool (const std::string&,std::string&)>& callback )
@ -501,8 +492,11 @@ void JsonApiServer::connectToConfigManager(p3ConfigMgr *cfgmgr)
bool JsonApiServer::authorizeUser(const std::string& user,const std::string& passwd)
{
if(!is_alphanumeric(user) || !is_alphanumeric(passwd))
if(!librs::util::is_alphanumeric(user) || !librs::util::is_alphanumeric(passwd))
{
RsErr() << "Password or username for jsonapi token is not alphanumeric." << std::endl;
return false;
}
RS_STACK_MUTEX(configMutex);
@ -516,26 +510,6 @@ bool JsonApiServer::authorizeUser(const std::string& user,const std::string& pas
return true;
}
// bool JsonApiServer::authorizeToken(const std::string& token)
// {
// std::string user,password;
//
// if(!parseToken(token,user,password))
// return false;
//
// RS_STACK_MUTEX(configMutex);
//
// std::string& p(mAuthTokenStorage.mAuthorizedTokens[user]);
//
// if(p != password)
// {
// p = password;
// IndicateConfigChanged();
// }
// return true;
// }
/*static*/ std::string JsonApiServer::decodeToken(const std::string& radix64_token)
{
std::vector<uint8_t> decodedVect(Radix64::decode(radix64_token));
@ -601,32 +575,24 @@ void JsonApiServer::handleCorsOptions(
const std::shared_ptr<restbed::Session> session )
{ session->close(rb::NO_CONTENT, corsOptionsHeaders); }
int JsonApiServer::status()
{
if(RestbedService::isRunning())
return JSONAPI_STATUS_RUNNING;
else
return JSONAPI_STATUS_NOT_RUNNING;
}
void JsonApiServer::registerResourceProvider(const JsonApiResourceProvider *rp)
{
_resource_providers.insert(rp);
mResourceProviders.insert(rp);
}
void JsonApiServer::unregisterResourceProvider(const JsonApiResourceProvider *rp)
{
_resource_providers.erase(rp);
mResourceProviders.erase(rp);
}
bool JsonApiServer::hasResourceProvider(const JsonApiResourceProvider *rp)
{
return _resource_providers.find(rp) != _resource_providers.end();
return mResourceProviders.find(rp) != mResourceProviders.end();
}
std::vector<std::shared_ptr<rb::Resource> > JsonApiServer::getResources() const
{
auto tab = _resources;
auto tab = mResources;
for(auto& rp: _resource_providers)
for(auto& rp: mResourceProviders)
for(auto r: rp->getResources())
tab.push_back(r);

View File

@ -68,8 +68,8 @@ public:
// RsJsonAPI public API
bool restart() override { return RestbedService::restart(); }
bool stop() override { return RestbedService::stop();}
int status() override;
bool stop() override { return RestbedService::fullstop();}
bool isRunning() override { return RestbedService::isRunning(); }
void setListeningPort(uint16_t port) override { return RestbedService::setListeningPort(port); }
void setBindingAddress(const std::string& bind_address) override { return RestbedService::setBindAddress(bind_address); }
@ -185,7 +185,7 @@ private:
return checkRsServicePtrReady( serviceInstance.get(), serviceName, ctx, session );
}
std::vector<std::shared_ptr<rb::Resource> > _resources;
std::set<const JsonApiResourceProvider *> _resource_providers;
std::vector<std::shared_ptr<rb::Resource> > mResources;
std::set<const JsonApiResourceProvider *> mResourceProviders;
};

View File

@ -6,7 +6,7 @@
* 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 *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
@ -15,31 +15,32 @@
* 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 *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include "retroshare/rsjsonapi.h"
#include "util/rsthreads.h"
#include "util/rsdebug.h"
#include "restbedservice.h"
RestbedService::RestbedService()
: mService(std::make_shared<restbed::Service>()), // this is a place holder, in case we request some internal values.
mListeningPort(RsJsonAPI::DEFAULT_PORT),
mBindingAddress(RsJsonAPI::DEFAULT_BINDING_ADDRESS)
{
mService = std::make_shared<restbed::Service>(); // this is a place holder, in case we request some internal values.
mListeningPort = 9092;
mBindingAddress = "127.0.0.1";
}
bool RestbedService::restart()
{
stop();
fullstop();
start("Restbed Service");
return true;
}
bool RestbedService::stop()
bool RestbedService::fullstop()
{
if(!mService->is_up())
return true;
@ -69,7 +70,7 @@ void RestbedService::runloop()
if(mService->is_up())
{
std::cerr << "(II) WebUI is already running. Killing it." << std::endl;
RsWarn() << "(II) WebUI is already running. Killing it." << std::endl;
mService->stop();
}

View File

@ -6,16 +6,16 @@
* 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 *
* it under the terms of the GNU Affero 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. *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
@ -34,7 +34,7 @@ public:
virtual ~RestbedService() = default;
bool restart();
bool stop();
bool fullstop();
void setListeningPort(uint16_t port) ;
void setBindAddress(const std::string& bind_address);

View File

@ -5,7 +5,7 @@
* Copyright (C) 2019-2019 Cyril Soler <csoler@users.sourceforge.net> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
@ -14,12 +14,13 @@
* 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 *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
*
*******************************************************************************/
#pragma once
#include <map>
#include <string>
class p3ConfigMgr;
@ -28,34 +29,52 @@ class JsonApiResourceProvider;
class RsJsonAPI
{
public:
enum {
JSONAPI_STATUS_UNKNOWN = 0x00,
JSONAPI_STATUS_RUNNING = 0x01,
JSONAPI_STATUS_NOT_RUNNING = 0x02
};
static const uint16_t DEFAULT_PORT = 9092 ;
static const std::string DEFAULT_BINDING_ADDRESS ; // 127.0.0.1
virtual bool restart() =0;
virtual bool stop() =0;
virtual void setBindingAddress(const std::string& address) =0;
virtual void setListeningPort(uint16_t port) =0;
virtual uint16_t listeningPort() const =0;
virtual void connectToConfigManager(p3ConfigMgr *cfgmgr)=0;
virtual void registerResourceProvider(const JsonApiResourceProvider *)=0;
virtual void unregisterResourceProvider(const JsonApiResourceProvider *)=0;
virtual bool hasResourceProvider(const JsonApiResourceProvider *)=0;
/**
* @brief Get status of the json api server
* @jsonapi{development}
* @return the status picked in the enum JSONAPI_STATUS_UNKNOWN/RUNNING/NOT_RUNNING
* @return Returns true if the server is running
*/
virtual int status() =0;
virtual bool isRunning() =0;
/*!
* \brief setBindingAddress
* Sets the binding address of the jsonapi server. Will only take effect after the server is restarted
* \param address
* Address in IPv4 or IPv6 format.
*/
virtual void setBindingAddress(const std::string& address) =0;
/*!
* \brief setListeningPort
* Port to use when talking to the jsonAPI server.
* \param port
* Should be a non system-reserved 16 bits port number (1024 to 65535)
*/
virtual void setListeningPort(uint16_t port) =0;
virtual uint16_t listeningPort() const =0;
/*!
* \brief connectToConfigManager
* Should be called after creating the JsonAPI object so that it publishes itself with the proper config file.
* Since JsonAPI is created *before* login, the config manager does not exist at this time.
* \param cfgmgr
*/
virtual void connectToConfigManager(p3ConfigMgr *cfgmgr)=0;
/*!
* \brief registerResourceProvider
* This is used to add/remove new web services to JsonAPI. The client should take care of not using a path range already
* used by the jsonAPI server.
*/
virtual void registerResourceProvider(const JsonApiResourceProvider *)=0;
virtual void unregisterResourceProvider(const JsonApiResourceProvider *)=0;
virtual bool hasResourceProvider(const JsonApiResourceProvider *)=0;
//=============================================================================================//
// API methods that are also accessible through http //

View File

@ -31,6 +31,7 @@
#include "util/rsthreads.h"
#include "util/rsdebug.h"
#include "retroshare/rswebui.h"
#include "rsserver/rsaccounts.h"
#include "retroshare/rsjsonapi.h"
#define TEXT_HTML 0
@ -53,12 +54,7 @@ static constexpr char *mime_types[6] = {
"application/octet-stream",
};
#ifdef WINDOWS_SYS
const std::string RsWebUI::DEFAULT_BASE_DIRECTORY = "data/webui";
#else
const std::string RsWebUI::DEFAULT_BASE_DIRECTORY = "/usr/share/retroshare/webui/";
#endif
const std::string RsWebUI::DEFAULT_BASE_DIRECTORY = RsAccountsDetail::PathDataDirectory(false); //"/usr/share/retroshare/webui/";
static std::string _base_directory = RsWebUI::DEFAULT_BASE_DIRECTORY;
@ -75,14 +71,14 @@ template<int MIME_TYPE_INDEX> class handler
directory += "/";
std::string resource_filename = _base_directory + "/" + directory + filename;
std::cerr << "Reading file: \"" << resource_filename << "\"" << std::endl;
RsDbg() << "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;
RsDbg() << " body length=" << body.length() << std::endl;
const std::multimap< std::string, std::string > headers
{
{ "Content-Type", mime_types[MIME_TYPE_INDEX] },
@ -93,7 +89,7 @@ template<int MIME_TYPE_INDEX> class handler
}
else
{
std::cerr << "Could not open file " << resource_filename << std::endl;
RsErr() << "Could not open file " << resource_filename << std::endl;
session->close( restbed::NOT_FOUND );
}
}
@ -171,7 +167,7 @@ void p3WebUI::setHtmlFilesDirectory(const std::string& html_dir)
int p3WebUI::status() const
{
if(rsJsonAPI->status()==RsJsonAPI::JSONAPI_STATUS_RUNNING && rsJsonAPI->hasResourceProvider(this))
if(rsJsonAPI->isRunning() && rsJsonAPI->hasResourceProvider(this))
return WEBUI_STATUS_RUNNING;
else
return WEBUI_STATUS_NOT_RUNNING;

View File

@ -30,7 +30,7 @@ class p3WebUI: public RsWebUI, public JsonApiResourceProvider
{
public:
p3WebUI(){}
virtual ~p3WebUI(){}
virtual ~p3WebUI() = default;
// implements RsWebUI

View File

@ -205,6 +205,19 @@ bool ConvertUtf16ToUtf8(const std::wstring& source, std::string& dest)
return true;
}
bool is_alphanumeric(char c)
{
return (c>='0' && c<'9') || (c>='a' && c<='z') || (c>='A' && c<='Z') ;
}
bool is_alphanumeric(const std::string& s)
{
for(uint32_t i=0;i<s.size();++i)
if(!is_alphanumeric(s[i]))
return false;
return true;
}
} } // librs::util
#ifdef WINDOWS_SYS

View File

@ -25,10 +25,14 @@
#include <string>
#include <stdarg.h>
namespace librs { namespace util {
namespace librs {
namespace util {
bool ConvertUtf8ToUtf16(const std::string& source, std::wstring& dest);
bool ConvertUtf16ToUtf8(const std::wstring& source, std::string& dest);
bool ConvertUtf8ToUtf16(const std::string& source, std::wstring& dest);
bool ConvertUtf16ToUtf8(const std::wstring& source, std::string& dest);
bool is_alphanumeric(char c) ;
bool is_alphanumeric(const std::string& s);
} } // librs::util

View File

@ -122,35 +122,10 @@ bool JsonApiPage::checkStartJsonApi()
/*static*/ void JsonApiPage::checkShutdownJsonApi()
{
if(RsJsonAPI::JSONAPI_STATUS_RUNNING != rsJsonAPI->status())
if(!rsJsonAPI->isRunning())
return;
rsJsonAPI->stop(); // this is a blocking call until the thread is terminated.
#ifdef SUSPENDED_CODE
/* It is important to make a copy of +jsonApiServer+ pointer so the old
* object can be deleted later, while the original pointer is
* reassigned */
QProgressDialog* pd = new QProgressDialog("Stopping JSON API Server", QString(), 0, 3000);
QTimer* prtm = new QTimer;
prtm->setInterval(16); // 60 FPS
connect( prtm, &QTimer::timeout,
pd, [=](){pd->setValue(pd->value()+16);} );
pd->show();
prtm->start();
/* Must wait for deletion because stopping of the server is async.
* It is important to capture a copy so it "survive" after
* safeStopJsonApiServer returns */
QTimer::singleShot(3*1000, [=]()
{
prtm->stop();
pd->close();
prtm->deleteLater();
pd->deleteLater();
});
#endif
}
void JsonApiPage::onApplyClicked()

View File

@ -74,8 +74,6 @@ bool WebuiPage::updateParams(QString &errmsg)
bool changed = false;
if(ui.enableWebUI_CB->isChecked() != Settings->getWebinterfaceEnabled())
changed = true;
if(ui.allIp_CB->isChecked() != Settings->getWebinterfaceAllowAllIps())
changed = true;
if(ui.webInterfaceFiles_LE->text() != Settings->getWebinterfaceFilesDirectory())
changed = true;
@ -83,7 +81,6 @@ bool WebuiPage::updateParams(QString &errmsg)
{
// store config
Settings->setWebinterfaceEnabled(ui.enableWebUI_CB->isChecked());
Settings->setWebinterfaceAllowAllIps(ui.allIp_CB->isChecked());
Settings->setWebinterfaceFilesDirectory(ui.webInterfaceFiles_LE->text());
}
return ok;
@ -118,7 +115,6 @@ void WebuiPage::load()
std::cerr << "WebuiPage::load()" << std::endl;
whileBlocking(ui.enableWebUI_CB)->setChecked(Settings->getWebinterfaceEnabled());
whileBlocking(ui.webInterfaceFiles_LE)->setText(Settings->getWebinterfaceFilesDirectory());
whileBlocking(ui.allIp_CB)->setChecked(Settings->getWebinterfaceAllowAllIps());
#ifdef RS_JSONAPI
auto smap = rsJsonAPI->getAuthorizedTokens();
@ -157,7 +153,7 @@ QString WebuiPage::helpText() const
{
if(Settings->getWebinterfaceEnabled())
{
QDesktopServices::openUrl(QUrl(QString("http://localhost:")+QString::number(Settings->getWebinterfacePort())));
QDesktopServices::openUrl(QUrl(QString("http://localhost:")+QString::number(rsJsonAPI->listeningPort())));
}
else
{

View File

@ -1167,26 +1167,6 @@ void RshareSettings::setWebinterfaceFilesDirectory(const QString& s)
}
uint16_t RshareSettings::getWebinterfacePort()
{
return valueFromGroup("Webinterface", "port", 1984).toUInt();
}
void RshareSettings::setWebinterfacePort(uint16_t port)
{
setValueToGroup("Webinterface", "port", port);
}
bool RshareSettings::getWebinterfaceAllowAllIps()
{
return valueFromGroup("Webinterface", "allowAllIps", false).toBool();
}
void RshareSettings::setWebinterfaceAllowAllIps(bool allow_all)
{
setValueToGroup("Webinterface", "allowAllIps", allow_all);
}
bool RshareSettings::getPageAlreadyDisplayed(const QString& page_name)
{
return valueFromGroup("PageAlreadyDisplayed",page_name,false).toBool();

View File

@ -331,15 +331,9 @@ public:
bool getWebinterfaceEnabled();
void setWebinterfaceEnabled(bool enabled);
uint16_t getWebinterfacePort();
void setWebinterfacePort(uint16_t port);
QString getWebinterfaceFilesDirectory();
void setWebinterfaceFilesDirectory(const QString& dirname);
bool getWebinterfaceAllowAllIps();
void setWebinterfaceAllowAllIps(bool allow_all);
// proxy function that computes the best icon size among sizes passed as array, to match the recommended size on screen.
int computeBestIconSize(int n_sizes, int *sizes, int recommended_size);