Commit 2e6eb5e1 authored by Pavel Vainerman's avatar Pavel Vainerman

(Http): added support "CORS" (Access-Control-Allow-Origin). Default: *

and minor fixes
parent 02995521
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
Name: libuniset2 Name: libuniset2
Version: 2.7 Version: 2.7
Release: alt6 Release: alt7
Summary: UniSet - library for building distributed industrial control systems Summary: UniSet - library for building distributed industrial control systems
License: LGPL License: LGPL
...@@ -509,6 +509,9 @@ rm -f %buildroot%_libdir/*.la ...@@ -509,6 +509,9 @@ rm -f %buildroot%_libdir/*.la
# history of current unpublished changes # history of current unpublished changes
%changelog %changelog
* Tue May 08 2018 Pavel Vainerman <pv@altlinux.ru> 2.7-alt7
- (http): added support "CORS" (Access-Control-Allow-Origin)
* Tue Apr 03 2018 Pavel Vainerman <pv@altlinux.ru> 2.7-alt6 * Tue Apr 03 2018 Pavel Vainerman <pv@altlinux.ru> 2.7-alt6
- new minor release - new minor release
......
...@@ -220,6 +220,7 @@ LogDB::LogDB( const string& name, int argc, const char* const* argv, const strin ...@@ -220,6 +220,7 @@ LogDB::LogDB( const string& name, int argc, const char* const* argv, const strin
httpHost = uniset::getArgParam("--" + prefix + "httpserver-host", argc, argv, "localhost"); httpHost = uniset::getArgParam("--" + prefix + "httpserver-host", argc, argv, "localhost");
httpPort = uniset::getArgInt("--" + prefix + "httpserver-port", argc, argv, "8080"); httpPort = uniset::getArgInt("--" + prefix + "httpserver-port", argc, argv, "8080");
httpCORS_allow = uniset::getArgParam("--" + prefix + "httpserver-cors-allow", argc, argv, httpCORS_allow);
dblog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl; dblog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl;
Poco::Net::SocketAddress sa(httpHost, httpPort); Poco::Net::SocketAddress sa(httpHost, httpPort);
...@@ -449,6 +450,7 @@ void LogDB::help_print() ...@@ -449,6 +450,7 @@ void LogDB::help_print()
cout << "--prefix-httpserver-port num - Порт на котором принимать запросы. По умолчанию: 8080" << endl; cout << "--prefix-httpserver-port num - Порт на котором принимать запросы. По умолчанию: 8080" << endl;
cout << "--prefix-httpserver-max-queued num - Размер очереди запросов к http серверу. По умолчанию: 100" << endl; cout << "--prefix-httpserver-max-queued num - Размер очереди запросов к http серверу. По умолчанию: 100" << endl;
cout << "--prefix-httpserver-max-threads num - Разрешённое количество потоков для http-сервера. По умолчанию: 3" << endl; cout << "--prefix-httpserver-max-threads num - Разрешённое количество потоков для http-сервера. По умолчанию: 3" << endl;
cout << "--prefix-httpserver-cors-allow addr - (CORS): Access-Control-Allow-Origin. Default: *" << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void LogDB::run( bool async ) void LogDB::run( bool async )
...@@ -791,6 +793,9 @@ void LogDB::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPSer ...@@ -791,6 +793,9 @@ void LogDB::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPSer
std::ostream& out = resp.send(); std::ostream& out = resp.send();
resp.setContentType("text/json"); resp.setContentType("text/json");
resp.set("Access-Control-Allow-Methods", "GET");
resp.set("Access-Control-Allow-Request-Method", "*");
resp.set("Access-Control-Allow-Origin", httpCORS_allow /* req.get("Origin") */);
try try
{ {
......
...@@ -315,6 +315,7 @@ namespace uniset ...@@ -315,6 +315,7 @@ namespace uniset
std::shared_ptr<Poco::Net::HTTPServer> httpserv; std::shared_ptr<Poco::Net::HTTPServer> httpserv;
std::string httpHost = { "" }; std::string httpHost = { "" };
int httpPort = { 0 }; int httpPort = { 0 };
std::string httpCORS_allow = { "*" };
double wsHeartbeatTime_sec = { 3.0 }; double wsHeartbeatTime_sec = { 3.0 };
double wsSendTime_sec = { 0.5 }; double wsSendTime_sec = { 0.5 };
......
...@@ -39,6 +39,7 @@ ...@@ -39,6 +39,7 @@
#include "modbus/ModbusClient.h" #include "modbus/ModbusClient.h"
#include "LogAgregator.h" #include "LogAgregator.h"
#include "LogServer.h" #include "LogServer.h"
#include "LogAgregator.h"
#include "VMonitor.h" #include "VMonitor.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef vmonit #ifndef vmonit
......
...@@ -113,7 +113,7 @@ namespace uniset ...@@ -113,7 +113,7 @@ namespace uniset
public Poco::Net::HTTPRequestHandler public Poco::Net::HTTPRequestHandler
{ {
public: public:
UHttpRequestHandler( std::shared_ptr<IHttpRequestRegistry> _registry ); UHttpRequestHandler( std::shared_ptr<IHttpRequestRegistry> _registry, const std::string& httpCORS_allow = "*");
virtual void handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) override; virtual void handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) override;
...@@ -121,6 +121,7 @@ namespace uniset ...@@ -121,6 +121,7 @@ namespace uniset
std::shared_ptr<IHttpRequestRegistry> registry; std::shared_ptr<IHttpRequestRegistry> registry;
std::shared_ptr<DebugStream> log; std::shared_ptr<DebugStream> log;
const std::string httpCORS_allow = { "*" };
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
class UHttpRequestHandlerFactory: class UHttpRequestHandlerFactory:
...@@ -132,8 +133,11 @@ namespace uniset ...@@ -132,8 +133,11 @@ namespace uniset
virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& ) override; virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& ) override;
// (CORS): Access-Control-Allow-Origin. Default: *
void setCORS_allow( const std::string& allow );
private: private:
std::shared_ptr<IHttpRequestRegistry> registry; std::shared_ptr<IHttpRequestRegistry> registry;
std::string httpCORS_allow = { "*" };
}; };
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -45,6 +45,8 @@ namespace uniset ...@@ -45,6 +45,8 @@ namespace uniset
std::shared_ptr<DebugStream> log(); std::shared_ptr<DebugStream> log();
// (CORS): Access-Control-Allow-Origin. Default: *
void setCORS_allow( const std::string& CORS_allow );
protected: protected:
UHttpServer(); UHttpServer();
......
...@@ -55,6 +55,7 @@ namespace uniset ...@@ -55,6 +55,7 @@ namespace uniset
* и перенаправление их указанным объектам. Помимо этого UniSetActivator реализует обработку команд /conf/.. * и перенаправление их указанным объектам. Помимо этого UniSetActivator реализует обработку команд /conf/..
* Для запуска http-сервера необходимо в аргументах командной строки указать --activator-run-httpserver * Для запуска http-сервера необходимо в аргументах командной строки указать --activator-run-httpserver
* Помимо этого можно задать параметры --activator-httpserver-host и --activator-httpserver-port. * Помимо этого можно задать параметры --activator-httpserver-host и --activator-httpserver-port.
* --activator-httpserver-cors-allow addr - (CORS): Access-Control-Allow-Origin. Default: *.
* *
*/ */
class UniSetActivator: class UniSetActivator:
...@@ -115,6 +116,7 @@ namespace uniset ...@@ -115,6 +116,7 @@ namespace uniset
std::shared_ptr<uniset::UHttp::UHttpServer> httpserv; std::shared_ptr<uniset::UHttp::UHttpServer> httpserv;
std::string httpHost = { "" }; std::string httpHost = { "" };
int httpPort = { 0 }; int httpPort = { 0 };
std::string httpCORS_allow = { "*" };
#endif #endif
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -28,14 +28,21 @@ namespace uniset ...@@ -28,14 +28,21 @@ namespace uniset
using namespace UHttp; using namespace UHttp;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ): UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry
registry(_registry) , const std::string& allow )
: registry(_registry)
, httpCORS_allow(allow)
{ {
log = make_shared<DebugStream>(); log = make_shared<DebugStream>();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req
, Poco::Net::HTTPServerResponse& resp )
{ {
// В этой версии API поддерживается только GET
resp.set("Access-Control-Allow-Methods", "GET");
resp.set("Access-Control-Allow-Request-Method", "*");
resp.set("Access-Control-Allow-Origin", httpCORS_allow /* req.get("Origin") */);
if( !registry ) if( !registry )
{ {
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
...@@ -159,7 +166,12 @@ namespace uniset ...@@ -159,7 +166,12 @@ namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req ) HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTPServerRequest& req )
{ {
return new UHttpRequestHandler(registry); return new UHttpRequestHandler(registry, httpCORS_allow);
}
// -------------------------------------------------------------------------
void UHttpRequestHandlerFactory::setCORS_allow( const std::string& allow )
{
httpCORS_allow = allow;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Poco::JSON::Object::Ptr IHttpRequest::httpRequest( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr IHttpRequest::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
......
...@@ -78,6 +78,11 @@ namespace uniset ...@@ -78,6 +78,11 @@ namespace uniset
return mylog; return mylog;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UHttpServer::setCORS_allow( const std::string& allow )
{
reqFactory->setCORS_allow(allow);
}
// -------------------------------------------------------------------------
} // end of namespace uniset } // end of namespace uniset
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // #ifndef DISABLE_REST_API #endif // #ifndef DISABLE_REST_API
...@@ -89,6 +89,7 @@ namespace uniset ...@@ -89,6 +89,7 @@ namespace uniset
s << (getId() == DefaultObjectId ? 8080 : getId() ); s << (getId() == DefaultObjectId ? 8080 : getId() );
httpPort = conf->getArgInt("--activator-httpserver-port", s.str()); httpPort = conf->getArgInt("--activator-httpserver-port", s.str());
ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl; ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl;
httpCORS_allow = conf->getArgParam("--activator-httpserver-cors-allow", "*");
} }
#endif #endif
...@@ -153,6 +154,7 @@ namespace uniset ...@@ -153,6 +154,7 @@ namespace uniset
{ {
auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this()); auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this());
httpserv = make_shared<UHttp::UHttpServer>(reg, httpHost, httpPort); httpserv = make_shared<UHttp::UHttpServer>(reg, httpHost, httpPort);
httpserv->setCORS_allow(httpCORS_allow);
httpserv->start(); httpserv->start();
} }
catch( std::exception& ex ) catch( std::exception& ex )
......
...@@ -128,7 +128,8 @@ uniset::IDList::IDList( const std::vector<string>& svec ): ...@@ -128,7 +128,8 @@ uniset::IDList::IDList( const std::vector<string>& svec ):
else else
id = conf->getSensorID(s); id = conf->getSensorID(s);
add(id); if( id != DefaultObjectId )
add(id);
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment