Added WebSocket support.
This commit is contained in:
727
src/modules/Workers/WebSocket/WebSocket.cpp
Normal file
727
src/modules/Workers/WebSocket/WebSocket.cpp
Normal file
@@ -0,0 +1,727 @@
|
||||
/*++
|
||||
|
||||
Program name:
|
||||
|
||||
dm
|
||||
|
||||
Module Name:
|
||||
|
||||
WebSocket.cpp
|
||||
|
||||
Notices:
|
||||
|
||||
Module: WebSocket
|
||||
|
||||
Author:
|
||||
|
||||
Copyright (c) Prepodobny Alen
|
||||
|
||||
mailto: alienufo@inbox.ru
|
||||
mailto: ufocomp@gmail.com
|
||||
|
||||
--*/
|
||||
|
||||
//----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
#include "Core.hpp"
|
||||
#include "WebSocket.hpp"
|
||||
//----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
#include <random>
|
||||
//----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
#define BPS_PGP_HASH "SHA512"
|
||||
#define BM_PREFIX "BM-"
|
||||
//----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
#define SYSTEM_PROVIDER_NAME "system"
|
||||
#define SERVICE_APPLICATION_NAME "service"
|
||||
#define CONFIG_SECTION_NAME "module"
|
||||
//----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
extern "C++" {
|
||||
|
||||
namespace Apostol {
|
||||
|
||||
namespace Module {
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
//-- CWebSocketModule ------------------------------------------------------------------------------------------
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
CWebSocketModule::CWebSocketModule(CModuleProcess *AProcess) : CApostolModule(AProcess, "web socket", "module/WebSocket") {
|
||||
m_SyncPeriod = BPS_DEFAULT_SYNC_PERIOD;
|
||||
m_Headers.Add("Authorization");
|
||||
|
||||
CWebSocketModule::InitMethods();
|
||||
|
||||
InitServerList();
|
||||
Reload();
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::InitMethods() {
|
||||
#if defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE >= 9)
|
||||
m_pMethods->AddObject(_T("GET") , (CObject *) new CMethodHandler(true , [this](auto && Connection) { DoGet(Connection); }));
|
||||
m_pMethods->AddObject(_T("POST") , (CObject *) new CMethodHandler(true , [this](auto && Connection) { DoPost(Connection); }));
|
||||
m_pMethods->AddObject(_T("HEAD") , (CObject *) new CMethodHandler(true , [this](auto && Connection) { DoHead(Connection); }));
|
||||
m_pMethods->AddObject(_T("OPTIONS"), (CObject *) new CMethodHandler(true , [this](auto && Connection) { DoOptions(Connection); }));
|
||||
m_pMethods->AddObject(_T("PUT") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); }));
|
||||
m_pMethods->AddObject(_T("DELETE") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); }));
|
||||
m_pMethods->AddObject(_T("TRACE") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); }));
|
||||
m_pMethods->AddObject(_T("PATCH") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); }));
|
||||
m_pMethods->AddObject(_T("CONNECT"), (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); }));
|
||||
#else
|
||||
m_pMethods->AddObject(_T("GET") , (CObject *) new CMethodHandler(true, std::bind(&CWebSocketModule::DoGet, this, _1)));
|
||||
m_pMethods->AddObject(_T("POST") , (CObject *) new CMethodHandler(true, std::bind(&CWebSocketModule::DoPost, this, _1)));
|
||||
m_pMethods->AddObject(_T("HEAD") , (CObject *) new CMethodHandler(true, std::bind(&CWebSocketModule::DoHead, this, _1)));
|
||||
m_pMethods->AddObject(_T("OPTIONS"), (CObject *) new CMethodHandler(true, std::bind(&CWebSocketModule::DoOptions, this, _1)));
|
||||
m_pMethods->AddObject(_T("PUT") , (CObject *) new CMethodHandler(false, std::bind(&CWebSocketModule::MethodNotAllowed, this, _1)));
|
||||
m_pMethods->AddObject(_T("DELETE") , (CObject *) new CMethodHandler(false, std::bind(&CWebSocketModule::MethodNotAllowed, this, _1)));
|
||||
m_pMethods->AddObject(_T("TRACE") , (CObject *) new CMethodHandler(false, std::bind(&CWebSocketModule::MethodNotAllowed, this, _1)));
|
||||
m_pMethods->AddObject(_T("PATCH") , (CObject *) new CMethodHandler(false, std::bind(&CWebSocketModule::MethodNotAllowed, this, _1)));
|
||||
m_pMethods->AddObject(_T("CONNECT"), (CObject *) new CMethodHandler(false, std::bind(&CWebSocketModule::MethodNotAllowed, this, _1)));
|
||||
#endif
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::InitServerList() {
|
||||
m_DefaultServer.Value().Name() = m_DefaultServer.Name();
|
||||
m_DefaultServer.Value().PGP().Name = "PUBLIC";
|
||||
|
||||
if (m_Servers.Count() == 0) {
|
||||
#ifdef _DEBUG
|
||||
int index = m_Servers.AddPair(BPS_BM_DEBUG_ADDRESS, CClientContext(CLocation(BPS_SERVER_URL)));
|
||||
m_Servers[index].Value().Name() = m_Servers[index].Name();
|
||||
m_Servers[index].Value().PGP().Name = "PUBLIC";
|
||||
#else
|
||||
m_Servers.Add(m_DefaultServer);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::UpdateServerList(const CString &Key) {
|
||||
CStringPairs ServerList;
|
||||
CStringList Keys;
|
||||
|
||||
ParsePGPKey(Key, ServerList, Keys);
|
||||
|
||||
if (ServerList.Count() != 0) {
|
||||
CStringPairs::ConstEnumerator em(ServerList);
|
||||
while (em.MoveNext()) {
|
||||
const auto ¤t = em.Current();
|
||||
if (m_Servers.IndexOfName(current.Name()) == -1) {
|
||||
m_Servers.AddPair(current.Name(), CClientContext(CLocation(current.Value())));
|
||||
auto &Context = m_Servers.Last().Value();
|
||||
Context.Name() = current.Name();
|
||||
Context.PGP().Name = "PUBLIC";
|
||||
Context.PGP().Key = Key;
|
||||
Context.BTCKeys() = Keys;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::UpdateOAuth2() {
|
||||
const auto &oauth2 = Config()->IniFile().ReadString(CONFIG_SECTION_NAME, "oauth2", "oauth2/service.json");
|
||||
const auto &provider = CString(SYSTEM_PROVIDER_NAME);
|
||||
const auto &application = CString(SERVICE_APPLICATION_NAME);
|
||||
|
||||
for (int i = 0; i < m_Servers.Count(); i++) {
|
||||
auto &Context = m_Servers[i].Value();
|
||||
if (!oauth2.empty() && Context.Status() == Context::csInitialization) {
|
||||
LoadOAuth2(oauth2, provider, application, Context.Providers());
|
||||
Context.SetStatus(Context::csInitialized);
|
||||
}
|
||||
Context.SetCheckDate(0);
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::LoadOAuth2(const CString &FileName, const CString &ProviderName, const CString &ApplicationName, CProviders &Providers) {
|
||||
CString ConfigFile(FileName);
|
||||
|
||||
if (!path_separator(ConfigFile.front())) {
|
||||
ConfigFile = Config()->Prefix() + ConfigFile;
|
||||
}
|
||||
|
||||
if (FileExists(ConfigFile.c_str())) {
|
||||
CJSONObject Json;
|
||||
Json.LoadFromFile(ConfigFile.c_str());
|
||||
|
||||
int index = Providers.IndexOfName(ProviderName);
|
||||
if (index == -1)
|
||||
index = Providers.AddPair(ProviderName, CProvider(ProviderName));
|
||||
auto& Provider = Providers[index].Value();
|
||||
Provider.Applications().AddPair(ApplicationName, Json);
|
||||
} else {
|
||||
Log()->Error(APP_LOG_WARN, 0, APP_FILE_NOT_FOUND, ConfigFile.c_str());
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
bool CWebSocketModule::FindURLInLine(const CString &Line, CStringList &List) {
|
||||
CString URL;
|
||||
|
||||
TCHAR ch;
|
||||
int length = 0;
|
||||
size_t startPos, pos;
|
||||
|
||||
pos = 0;
|
||||
while ((startPos = Line.Find(HTTP_PREFIX, pos)) != CString::npos) {
|
||||
|
||||
URL.Clear();
|
||||
|
||||
pos = startPos + HTTP_PREFIX_SIZE;
|
||||
if (Line.Length() < 5)
|
||||
return false;
|
||||
|
||||
URL.Append(HTTP_PREFIX);
|
||||
ch = Line.at(pos);
|
||||
if (ch == 's') {
|
||||
URL.Append(ch);
|
||||
pos++;
|
||||
}
|
||||
|
||||
if (Line.Length() < 7 || Line.at(pos++) != ':' || Line.at(pos++) != '/' || Line.at(pos++) != '/')
|
||||
return false;
|
||||
|
||||
URL.Append("://");
|
||||
|
||||
length = 0;
|
||||
ch = Line.at(pos);
|
||||
while (ch != 0 && (IsChar(ch) || IsNumeral(ch) || ch == ':' || ch == '.' || ch == '-')) {
|
||||
URL.Append(ch);
|
||||
length++;
|
||||
ch = Line.at(++pos);
|
||||
}
|
||||
|
||||
if (length < 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (startPos == 0) {
|
||||
List.Add(URL);
|
||||
} else {
|
||||
ch = Line.at(startPos - 1);
|
||||
switch (ch) {
|
||||
case ' ':
|
||||
case ',':
|
||||
case ';':
|
||||
List.Add(URL);
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
CWebSocketClient *CWebSocketModule::GetWebSocketClient(CClientContext &Context) {
|
||||
auto pClient = Context.ClientManager().Add(&Context, CLocation(Context.URL().Origin() + "/session/" + Context.Session()));
|
||||
|
||||
pClient->Session() = Context.Session();
|
||||
|
||||
pClient->ClientName() = GApplication->Title();
|
||||
pClient->AutoConnect(false);
|
||||
pClient->AllocateEventHandlers(Server());
|
||||
|
||||
#if defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE >= 9)
|
||||
pClient->OnVerbose([this](auto && Sender, auto && AConnection, auto && AFormat, auto && args) { DoVerbose(Sender, AConnection, AFormat, args); });
|
||||
pClient->OnException([this](auto && AConnection, auto && AException) { DoException(AConnection, AException); });
|
||||
pClient->OnEventHandlerException([this](auto && AHandler, auto && AException) { DoEventHandlerException(AHandler, AException); });
|
||||
pClient->OnNoCommandHandler([this](auto && Sender, auto && AData, auto && AConnection) { DoNoCommandHandler(Sender, AData, AConnection); });
|
||||
pClient->OnWebSocketError([this](auto && AConnection) { DoWebSocketError(AConnection); });
|
||||
pClient->OnConnected([this](auto && Sender) { DoClientConnected(Sender); });
|
||||
pClient->OnDisconnected([this](auto && Sender) { DoClientDisconnected(Sender); });
|
||||
pClient->OnMessage([this](auto && Sender, auto && Message) { DoClientMessage(Sender, Message); });
|
||||
pClient->OnError([this](auto && Sender, int Code, auto && Message) { DoClientError(Sender, Code, Message); });
|
||||
pClient->OnHeartbeat([this](auto && Sender) { DoClientHeartbeat(Sender); });
|
||||
pClient->OnTimeOut([this](auto && Sender) { DoClientTimeOut(Sender); });
|
||||
pClient->OnAuthorize([this](auto && Sender, auto && Request, auto && Response) { DoAuthorizeEvent(Sender, Request, Response); });
|
||||
pClient->OnSubscribe([this](auto && Sender, auto && Request, auto && Response) { DoSubscribeEvent(Sender, Request, Response); });
|
||||
pClient->OnKey([this](auto && Sender, auto && Request, auto && Response) { DoKeyEvent(Sender, Request, Response); });
|
||||
pClient->OnWebSocketEvent([this](auto && Sender, auto && Request, auto && Response) { DoWebSocketClientEvent(Sender, Request, Response); });
|
||||
#else
|
||||
pClient->OnVerbose(std::bind(&CWebSocketModule::DoVerbose, this, _1, _2, _3, _4));
|
||||
pClient->OnException(std::bind(&CWebSocketModule::DoException, this, _1, _2));
|
||||
pClient->OnEventHandlerException(std::bind(&CWebSocketModule::DoEventHandlerException, this, _1, _2));
|
||||
pClient->OnNoCommandHandler(std::bind(&CWebSocketModule::DoNoCommandHandler, this, _1, _2, _3));
|
||||
pClient->OnWebSocketError(std::bind(&CWebSocketModule::DoWebSocketError, this, _1));
|
||||
pClient->OnConnected(std::bind(&CWebSocketModule::DoClientConnected, this, _1));
|
||||
pClient->OnDisconnected(std::bind(&CWebSocketModule::DoClientDisconnected, this, _1));
|
||||
pClient->OnMessage(std::bind(&CWebSocketModule::DoClientMessage, this, _1, _2));
|
||||
pClient->OnError(std::bind(&CWebSocketModule::DoClientError, this, _1, _2, _3));
|
||||
pClient->OnHeartbeat(std::bind(&CWebSocketModule::DoClientHeartbeat, this, _1));
|
||||
pClient->OnTimeOut(std::bind(&CWebSocketModule::DoClientTimeOut, this, _1));
|
||||
pClient->OnAuthorize(std::bind(&CWebSocketModule::DoAuthorizeEvent, this, _1, _2, _3));
|
||||
pClient->OnSubscribe(std::bind(&CWebSocketModule::DoSubscribeEvent, this, _1, _2, _3));
|
||||
pClient->OnKey(std::bind(&CWebSocketModule::DoKeyEvent, this, _1, _2, _3));
|
||||
pClient->OnWebSocketEvent(std::bind(&CWebSocketModule::DoWebSocketClientEvent, this, _1, _2, _3));
|
||||
#endif
|
||||
return pClient;
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::CreateWebSocketClient(CClientContext &Context) {
|
||||
auto pClient = GetWebSocketClient(Context);
|
||||
try {
|
||||
pClient->Active(true);
|
||||
|
||||
Context.SetFixedDate(0);
|
||||
Context.SetStatus(csRunning);
|
||||
} catch (std::exception &e) {
|
||||
Log()->Error(APP_LOG_ERR, 0, e.what());
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::ParsePGPKey(const CString &Key, CStringPairs &ServerList, CStringList &BTCKeys) {
|
||||
if (Key.IsEmpty())
|
||||
return;
|
||||
|
||||
const Apostol::PGP::Key pgp(Key.c_str());
|
||||
if (!pgp.meaningful())
|
||||
return;
|
||||
|
||||
CStringList Data;
|
||||
CPGPUserIdList List;
|
||||
CStringList KeyList;
|
||||
|
||||
pgp.ExportUID(List);
|
||||
|
||||
for (int i = 0; i < List.Count(); i++) {
|
||||
|
||||
const auto& uid = List[i];
|
||||
|
||||
DebugMessage("%s (%s)\n", uid.Name.c_str(), uid.Desc.c_str());
|
||||
|
||||
const auto& name = uid.Name.Lower();
|
||||
const auto& data = uid.Desc.Lower();
|
||||
|
||||
if (name == "technical_data") {
|
||||
SplitColumns(data, Data, ';');
|
||||
|
||||
if (Data.Count() == 3) {
|
||||
m_SyncPeriod = StrToIntDef(Data[1].Trim().c_str(), BPS_DEFAULT_SYNC_PERIOD);
|
||||
} else if (Data.Count() == 2) {
|
||||
m_SyncPeriod = StrToIntDef(Data[0].Trim().c_str(), BPS_DEFAULT_SYNC_PERIOD);
|
||||
} else if (Data.Count() == 1) {
|
||||
m_SyncPeriod = StrToIntDef(Data[0].Trim().c_str(), BPS_DEFAULT_SYNC_PERIOD);
|
||||
}
|
||||
} if (uid.Name.Length() >= 35 && uid.Name.SubString(0, 3) == BM_PREFIX) {
|
||||
CStringList urlList;
|
||||
if (FindURLInLine(uid.Desc, urlList)) {
|
||||
for (int l = 0; l < urlList.Count(); l++) {
|
||||
ServerList.AddPair(uid.Name, urlList[l]);
|
||||
}
|
||||
}
|
||||
} else if (name.Find("bitcoin_key") != CString::npos) {
|
||||
const auto& key = wallet::ec_public(data.c_str());
|
||||
if (verify(key))
|
||||
KeyList.AddPair(name, key.encoded());
|
||||
}
|
||||
}
|
||||
|
||||
CString Name;
|
||||
for (int i = 1; i <= KeyList.Count(); i++) {
|
||||
Name = "bitcoin_key";
|
||||
Name << i;
|
||||
const auto& key = KeyList[Name];
|
||||
if (!key.IsEmpty()) {
|
||||
BTCKeys.Add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::CreateAccessToken(const CProvider &Provider, const CString &Application, CClientContext &Context) {
|
||||
|
||||
auto OnDone = [&Context](CTCPConnection *Sender) {
|
||||
|
||||
auto pConnection = dynamic_cast<CHTTPClientConnection *> (Sender);
|
||||
auto pReply = pConnection->Reply();
|
||||
|
||||
DebugReply(pReply);
|
||||
|
||||
if (pReply->Status == CHTTPReply::ok) {
|
||||
const CJSON Json(pReply->Content);
|
||||
|
||||
Context.SetStatus(csAuthorized);
|
||||
|
||||
Context.Session() = Json["session"].AsString();
|
||||
Context.Secret() = Json["secret"].AsString();
|
||||
|
||||
Context.SetFixedDate(0);
|
||||
Context.SetCheckDate(Now() + (CDateTime) 55 / MinsPerDay); // 55 min
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
auto OnHTTPClient = [this](const CLocation &URI) {
|
||||
return GetClient(URI.hostname, URI.port);
|
||||
};
|
||||
|
||||
CString server_uri(Context.URL().Origin());
|
||||
|
||||
const auto &token_uri = Provider.TokenURI(Application);
|
||||
const auto &service_token = CToken::CreateToken(Provider, Application);
|
||||
|
||||
Context.Tokens().Values("service_token", service_token);
|
||||
|
||||
if (!token_uri.IsEmpty()) {
|
||||
CToken::FetchAccessToken(token_uri.front() == '/' ? server_uri + token_uri : token_uri, service_token, OnHTTPClient, OnDone);
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::FetchProviders(CDateTime Now, CClientContext &Context) {
|
||||
for (int i = 0; i < Context.Providers().Count(); i++) {
|
||||
auto &Provider = Context.Providers()[i].Value();
|
||||
for (int j = 0; j < Provider.Applications().Count(); ++j) {
|
||||
const auto &app = Provider.Applications().Members(j);
|
||||
if (app["type"].AsString() == "service_account") {
|
||||
if (Provider.KeyStatus() == ksUnknown) {
|
||||
CreateAccessToken(Provider, app.String(), Context);
|
||||
Provider.KeyStatusTime(Now);
|
||||
Provider.KeyStatus(ksSuccess);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::CheckProviders(CDateTime Now, CClientContext &Context) {
|
||||
for (int i = 0; i < Context.Providers().Count(); i++) {
|
||||
auto& Provider = Context.Providers()[i].Value();
|
||||
if (Provider.KeyStatus() != ksUnknown) {
|
||||
Provider.KeyStatusTime(Now);
|
||||
Provider.KeyStatus(ksUnknown);
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoClientConnected(CObject *Sender) {
|
||||
auto pConnection = dynamic_cast<CWebSocketClientConnection *>(Sender);
|
||||
if (pConnection != nullptr) {
|
||||
auto pBinding = pConnection->Socket()->Binding();
|
||||
if (pBinding != nullptr) {
|
||||
Log()->Notice(_T("[%s:%d] [%s] WebSocket client connected."),
|
||||
pConnection->Socket()->Binding()->IP(),
|
||||
pConnection->Socket()->Binding()->Port(),
|
||||
pConnection->Session().c_str());
|
||||
} else {
|
||||
Log()->Notice(_T("[%s] WebSocket client connected."),
|
||||
pConnection->Session().c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoClientDisconnected(CObject *Sender) {
|
||||
auto pConnection = dynamic_cast<CWebSocketClientConnection *>(Sender);
|
||||
if (pConnection != nullptr) {
|
||||
auto pBinding = pConnection->Socket()->Binding();
|
||||
if (pBinding != nullptr) {
|
||||
Log()->Notice(_T("[%s:%d] [%s] WebSocket client disconnected."),
|
||||
pConnection->Socket()->Binding()->IP(),
|
||||
pConnection->Socket()->Binding()->Port(),
|
||||
pConnection->Session().c_str());
|
||||
} else {
|
||||
Log()->Notice(_T("[%s] WebSocket client disconnected."),
|
||||
pConnection->Session().c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoClientHeartbeat(CObject *Sender) {
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (Sender);
|
||||
chASSERT(pClient);
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoClientTimeOut(CObject *Sender) {
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (Sender);
|
||||
chASSERT(pClient);
|
||||
auto pContext = pClient->Context();
|
||||
chASSERT(pContext);
|
||||
pClient->SwitchConnection(nullptr);
|
||||
pClient->Reload();
|
||||
pContext->SetFixedDate(0);
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoClientMessage(CObject *Sender, const CWSMessage &Message) {
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (Sender);
|
||||
chASSERT(pClient);
|
||||
Log()->Message("[%s] [%s] [%s] [%s] %s", pClient->Session().c_str(),
|
||||
Message.UniqueId.c_str(),
|
||||
Message.Action.IsEmpty() ? "Unknown" : Message.Action.c_str(),
|
||||
CWSMessage::MessageTypeIdToString(Message.MessageTypeId).c_str(),
|
||||
Message.Payload.IsNull() ? "{}" : Message.Payload.ToString().c_str());
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoClientError(CObject *Sender, int Code, const CString &Message) {
|
||||
Log()->Error(APP_LOG_ERR, 0, "[%d] %s", Code, Message.c_str());
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoAuthorizeEvent(CObject *Sender, const CWSMessage &Request, const CWSMessage &Response) {
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (Sender);
|
||||
chASSERT(pClient);
|
||||
auto pContext = pClient->Context();
|
||||
chASSERT(pContext);
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoSubscribeEvent(CObject *Sender, const CWSMessage &Request, const CWSMessage &Response) {
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (Sender);
|
||||
chASSERT(pClient);
|
||||
auto pContext = pClient->Context();
|
||||
chASSERT(pContext);
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoKeyEvent(CObject *Sender, const CWSMessage &Request, const CWSMessage &Response) {
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (Sender);
|
||||
chASSERT(pClient);
|
||||
auto pContext = pClient->Context();
|
||||
chASSERT(pContext);
|
||||
|
||||
pContext->PGP().StatusTime = Now();
|
||||
pContext->PGP().Status = CKeyContext::ksSuccess;
|
||||
pContext->PGP().RunTime = GetRandomDate(10 * 60, m_SyncPeriod * 60, pContext->PGP().StatusTime); // 10..m_SyncPeriod min
|
||||
|
||||
if (Response.Payload.HasOwnProperty("data")) {
|
||||
UpdateServerList(Response.Payload["data"].AsString());
|
||||
UpdateOAuth2();
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoWebSocketClientEvent(CObject *Sender, const CWSMessage &Request, const CWSMessage &Response) {
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (Sender);
|
||||
chASSERT(pClient);
|
||||
auto pContext = pClient->Context();
|
||||
chASSERT(pContext);
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoWebSocketError(CTCPConnection *AConnection) {
|
||||
auto pConnection = dynamic_cast<CWebSocketClientConnection *> (AConnection);
|
||||
auto pClient = dynamic_cast<CWebSocketClient *> (pConnection->Client());
|
||||
chASSERT(pClient);
|
||||
auto pContext = pClient->Context();
|
||||
chASSERT(pContext);
|
||||
auto pReply = pConnection->Reply();
|
||||
|
||||
if (pReply->Status == CHTTPReply::moved_permanently || pReply->Status == CHTTPReply::moved_temporarily) {
|
||||
const auto &caLocation = pReply->Headers["Location"];
|
||||
if (!caLocation.IsEmpty()) {
|
||||
pClient->SetURI(CLocation(caLocation));
|
||||
Log()->Notice(_T("[%s] Redirect to %s."), pClient->Session().c_str(), pClient->URI().href().c_str());
|
||||
}
|
||||
pContext->SetFixedDate(0);
|
||||
} else {
|
||||
auto pBinding = pConnection->Socket()->Binding();
|
||||
if (pBinding != nullptr) {
|
||||
Log()->Warning(_T("[%s:%d] [%s] WebSocket client failed to establish connection"),
|
||||
pConnection->Socket()->Binding()->IP(),
|
||||
pConnection->Socket()->Binding()->Port(),
|
||||
pConnection->Session().c_str());
|
||||
} else {
|
||||
Log()->Warning(_T("[%s] WebSocket client failed to establish connection."),
|
||||
pConnection->Session().c_str());
|
||||
}
|
||||
pContext->SetFixedDate(Now() + (CDateTime) 1 / MinsPerDay); // 1 min
|
||||
}
|
||||
|
||||
pConnection->CloseConnection(true);
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoUser(CHTTPServerConnection *AConnection, const CString &Method, const CString &URI) {
|
||||
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoDeal(CHTTPServerConnection *AConnection, const CString &Method, const CString &URI, const CString &Action) {
|
||||
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoSignature(CHTTPServerConnection *AConnection) {
|
||||
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoAPI(CHTTPServerConnection *AConnection) {
|
||||
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoGet(CHTTPServerConnection *AConnection) {
|
||||
|
||||
auto pRequest = AConnection->Request();
|
||||
|
||||
CString sPath(pRequest->Location.pathname);
|
||||
|
||||
// Request sPath must be absolute and not contain "..".
|
||||
if (sPath.empty() || sPath.front() != '/' || sPath.find(_T("..")) != CString::npos) {
|
||||
AConnection->SendStockReply(CHTTPReply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sPath.SubString(0, 5) == "/api/") {
|
||||
DoAPI(AConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
SendResource(AConnection, sPath);
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::DoPost(CHTTPServerConnection *AConnection) {
|
||||
|
||||
auto pRequest = AConnection->Request();
|
||||
auto pReply = AConnection->Reply();
|
||||
|
||||
pReply->ContentType = CHTTPReply::json;
|
||||
|
||||
CStringList slRouts;
|
||||
SplitColumns(pRequest->Location.pathname, slRouts, '/');
|
||||
|
||||
if (slRouts.Count() < 3) {
|
||||
AConnection->SendStockReply(CHTTPReply::not_found);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& caService = slRouts[0].Lower();
|
||||
const auto& caVersion = slRouts[1].Lower();
|
||||
const auto& caCommand = slRouts[2].Lower();
|
||||
const auto& caAction = slRouts.Count() == 4 ? slRouts[3].Lower() : "";
|
||||
|
||||
if (caService != "api") {
|
||||
AConnection->SendStockReply(CHTTPReply::not_found);
|
||||
return;
|
||||
}
|
||||
|
||||
if (caVersion != "v1") {
|
||||
AConnection->SendStockReply(CHTTPReply::not_found);
|
||||
return;
|
||||
}
|
||||
|
||||
CString sRoute;
|
||||
for (int i = 0; i < slRouts.Count(); ++i) {
|
||||
sRoute.Append('/');
|
||||
sRoute.Append(slRouts[i]);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
if (caCommand == "account") {
|
||||
|
||||
DoUser(AConnection, "POST", sRoute);
|
||||
|
||||
} else if (caCommand == "deal") {
|
||||
|
||||
DoDeal(AConnection, "POST", sRoute, caAction);
|
||||
|
||||
} else if (caCommand == "signature") {
|
||||
|
||||
DoSignature(AConnection);
|
||||
|
||||
} else {
|
||||
|
||||
AConnection->SendStockReply(CHTTPReply::not_found);
|
||||
|
||||
}
|
||||
|
||||
} catch (std::exception &e) {
|
||||
ExceptionToJson(0, e, pReply->Content);
|
||||
|
||||
AConnection->SendReply(CHTTPReply::internal_server_error);
|
||||
Log()->Error(APP_LOG_EMERG, 0, e.what());
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::Heartbeat(CDateTime Now) {
|
||||
for (int i = 0; i < m_Servers.Count(); i++) {
|
||||
auto &Context = m_Servers[i].Value();
|
||||
|
||||
if ((Now >= Context.CheckDate())) {
|
||||
Context.SetCheckDate(Now + (CDateTime) 30 / SecsPerDay); // 30 sec
|
||||
if (Context.Status() == Context::csInitialized) {
|
||||
Context.SetStatus(Context::csAuthorization);
|
||||
|
||||
CheckProviders(Now, Context);
|
||||
FetchProviders(Now, Context);
|
||||
}
|
||||
}
|
||||
|
||||
if (Context.Status() == Context::csAuthorized) {
|
||||
if ((Now >= Context.FixedDate())) {
|
||||
Context.SetFixedDate(Now + (CDateTime) 30 / SecsPerDay); // 30 sec
|
||||
Context.SetStatus(Context::csInProgress);
|
||||
CreateWebSocketClient(Context);
|
||||
}
|
||||
}
|
||||
|
||||
if (Context.Status() == Context::csRunning) {
|
||||
if ((Now >= Context.FixedDate())) {
|
||||
Context.SetFixedDate(Now + (CDateTime) 30 / SecsPerDay); // 30 sec
|
||||
|
||||
for (int j = 0; j < Context.ClientManager().Count(); ++j) {
|
||||
auto pClient = Context.ClientManager()[j];
|
||||
|
||||
if (!pClient->Active())
|
||||
pClient->Active(true);
|
||||
|
||||
if (!pClient->Connected() && !pClient->Session().IsEmpty()) {
|
||||
Log()->Notice(_T("[%s] Trying connect to %s."), pClient->Session().c_str(), pClient->URI().href().c_str());
|
||||
pClient->ConnectStart();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
void CWebSocketModule::Reload() {
|
||||
const auto& caPublicKey = Config()->IniFile().ReadString("pgp", "public", "dm.pub");
|
||||
|
||||
if (FileExists(caPublicKey.c_str())) {
|
||||
CString Key;
|
||||
Key.LoadFromFile(caPublicKey.c_str());
|
||||
|
||||
UpdateServerList(Key);
|
||||
UpdateOAuth2();
|
||||
} else {
|
||||
Log()->Error(APP_LOG_WARN, 0, APP_FILE_NOT_FOUND, caPublicKey.c_str());
|
||||
}
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
|
||||
bool CWebSocketModule::Enabled() {
|
||||
if (m_ModuleStatus == msUnknown)
|
||||
m_ModuleStatus = Config()->IniFile().ReadBool(SectionName().c_str(), "enable", false) ? msEnabled: msDisabled;
|
||||
return m_ModuleStatus == msEnabled;
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------------------------
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user