1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
|
/* Copyright (C) 2025 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "lib/precompiled.h"
#include "DapInterface.h"
#include "lib/debug.h"
#include "lib/path.h"
#include "lib/posix/posix_types.h"
#include "lib/sysdep/os.h"
#include "ps/CLogger.h"
#include "ps/Filesystem.h"
#include "scriptinterface/FunctionWrapper.h"
#include "scriptinterface/JSON.h"
#include "scriptinterface/ModuleLoader.h"
#include "scriptinterface/Object.h"
#include "scriptinterface/ScriptContext.h"
#include "scriptinterface/ScriptExceptions.h"
#include "scriptinterface/ScriptInterface.h"
#include "scriptinterface/ScriptRequest.h"
#include <cstddef>
#include <fmt/format.h>
#include <js/Debug.h>
#include <jsapi.h>
#include <memory>
#include <thread>
#include <utility>
#if OS_WIN
#include <WinSock2.h>
#include <ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
namespace DAP
{
class Interface::SocketHandler {
public:
SocketHandler(Interface* callbackData)
: m_CallbackData(callbackData)
{
ENSURE(m_CallbackData && "Callback data must not be null");
}
~SocketHandler()
{
m_Running = false;
CloseSocket();
if (m_ServerThread.joinable())
m_ServerThread.join();
}
NONCOPYABLE(SocketHandler);
bool BindAndListen(const std::string server_address, int port)
{
#if OS_WIN
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
LOGERROR("Failed to start WSA");
return false;
}
#endif
m_ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
#if OS_WIN
if (m_ServerSocket == INVALID_SOCKET)
#else
if (m_ServerSocket < 0)
#endif
{
LOGERROR("Failed to create socket");
return false;
}
#if OS_WIN
const int i{1};
setsockopt(m_ServerSocket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char*>(&i), sizeof(i));
#else
const int i{1};
setsockopt(m_ServerSocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&i), sizeof(i));
#endif
sockaddr_in serverAddr{};
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
if (server_address.empty())
serverAddr.sin_addr.s_addr = INADDR_ANY;
else
{
serverAddr.sin_addr.s_addr = inet_addr(server_address.c_str());
if (!inet_pton(AF_INET, server_address.c_str(), &serverAddr.sin_addr))
{
LOGERROR("Invalid server address: %s", server_address.c_str());
CloseSocket();
return false;
}
}
if (bind(m_ServerSocket, reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)) == -1)
{
LOGERROR("Failed to bind socket");
CloseSocket();
return false;
}
if (listen(m_ServerSocket, 1) == -1)
{
LOGERROR("Failed to listen on socket");
return false;
}
return true;
}
void StartServerThread()
{
m_ServerThread = std::thread(&Interface::SocketHandler::AcceptConnections, this);
}
void AcceptConnections()
{
while (m_Running)
{
sockaddr_in clientAddr{};
#if OS_WIN
int clientAddrLen{sizeof(clientAddr)};
m_ClientSocket = accept(m_ServerSocket, reinterpret_cast<sockaddr*>(&clientAddr), &clientAddrLen);
if (m_ClientSocket == INVALID_SOCKET)
#else
socklen_t clientAddrLen = sizeof(clientAddr);
m_ClientSocket = accept(m_ServerSocket, reinterpret_cast<sockaddr*>(&clientAddr), reinterpret_cast<socklen_t*>(&clientAddrLen));
if (m_ClientSocket < 0)
#endif
{
if (m_Running)
LOGERROR("Failed to accept connection");
else
LOGMESSAGE("Server stopped accepting connections");
continue;
}
LOGMESSAGE("Accepted connection from %s", inet_ntoa(clientAddr.sin_addr));
std::lock_guard<std::mutex> lock{m_ConnectionLock};
this->HandleClient();
LOGMESSAGE("Client Disconnected");
}
}
void HandleClient()
{
char buffer[1024] = {0};
std::string message{};
while (true)
{
// TODO: Validation if need more than one recv.
const int bytesRead{static_cast<int>(recv(m_ClientSocket, buffer, sizeof(buffer), 0))};
if (bytesRead <= 0)
break;
message.append(buffer, static_cast<unsigned int>(bytesRead));
LOGMESSAGE("Received message: %s", message.c_str());
while (!message.empty())
{
// Parse Content-Length get DAP Body.
const std::size_t pos{message.find("Content-Length: ")};
if (pos == std::string::npos)
{
LOGERROR("Invalid DAP message");
break;
}
const std::size_t endPos{message.find("\r\n\r\n", pos)};
if (endPos == std::string::npos)
{
LOGERROR("Invalid DAP message");
break;
}
const std::size_t length{static_cast<size_t>(std::stoi(message.substr(pos + 16, endPos - pos - 16)))};
// Should wait for more data?.
if (endPos + 4 + length > message.size())
break;
const std::string dapMessage{message.substr(endPos + 4, length)};
const std::string response{this->m_CallbackData->SendDapMessage(dapMessage)};
if (response.empty())
{
LOGERROR("Failed to process message");
break;
}
// Return DAP message with protocol headers.
const std::string dapResponse{"Content-Length: " + std::to_string(response.size()) + "\r\n\r\n" + response};
LOGMESSAGE("Sending response to client: %s", dapResponse.c_str());
send(m_ClientSocket, dapResponse.c_str(), dapResponse.size(), 0);
// Validate if there more messages.
message = message.substr(endPos + 4 + length);
}
}
#if OS_WIN
closesocket(m_ClientSocket);
m_ClientSocket = INVALID_SOCKET;
#else
close(m_ClientSocket);
m_ClientSocket = -1;
#endif
}
void SendToClient(const std::string& message)
{
#if OS_WIN
ENSURE(m_ClientSocket != INVALID_SOCKET && "Client socket is not connected");
#else
ENSURE(m_ClientSocket != -1 && "Client socket is not connected");
#endif
send(m_ClientSocket, message.c_str(), message.size(), 0);
}
void CloseSocket()
{
#if OS_WIN
if (m_ClientSocket != INVALID_SOCKET)
{
closesocket(m_ClientSocket);
m_ClientSocket = INVALID_SOCKET;
}
if (m_ServerSocket != INVALID_SOCKET)
{
closesocket(m_ServerSocket);
m_ServerSocket = INVALID_SOCKET;
}
WSACleanup();
#else
if (m_ClientSocket != -1)
{
close(m_ClientSocket);
m_ClientSocket = -1;
}
if (m_ServerSocket != -1)
{
shutdown(m_ServerSocket, SHUT_RDWR);
close(m_ServerSocket);
m_ServerSocket = -1;
}
#endif
}
private:
#if OS_WIN
SOCKET m_ServerSocket{INVALID_SOCKET};
SOCKET m_ClientSocket{INVALID_SOCKET};
#else
int m_ServerSocket{-1};
int m_ClientSocket{-1};
#endif
std::thread m_ServerThread;
std::mutex m_ConnectionLock;
Interface* m_CallbackData{nullptr};
bool m_Running{true};
};
Interface::Interface(const std::string serverAddress, int port, ScriptContext& scriptContext)
: m_SocketImpl{std::make_unique<SocketHandler>(this)},
m_ModuleValue{scriptContext.GetGeneralJSContext()}
{
LOGMESSAGERENDER("Starting DAP interface server");
if (!m_SocketImpl->BindAndListen(serverAddress, port))
throw DapInterfaceException{fmt::format("Failed to bind and listen on port {}", port)};
const VfsPath fntPath{L"tools/dap/entry.js"};
if (!VfsFileExists(fntPath))
throw DapInterfaceNoJSDebuggerException{ fmt::format("DAP entry script not found at {}", fntPath.string8().c_str())};
m_ScriptInterface = std::make_unique<ScriptInterface>("Engine", "Debugger", scriptContext, [](const VfsPath& path) {
return path.string8().find("tools/dap/") == 0;
});
m_ScriptInterface->SetCallbackData(this);
ScriptRequest rq(m_ScriptInterface.get());
if (!JS_DefineDebuggerObject(rq.cx, rq.glob))
{
ScriptException::CatchPending(rq);
throw DapInterfaceNoJSDebuggerException{"Failed to define debugger object"};
}
// Register methods.
constexpr ScriptFunction::ObjectGetter<DAP::Interface> Getter{&ScriptInterface::ObjectFromCBData<DAP::Interface>};
ScriptFunction::Register<&DAP::Interface::WaitForMessage, Getter>(rq, "WaitForMessage");
ScriptFunction::Register<&DAP::Interface::EndWaitingForMessage, Getter>(rq, "EndWaitingForMessage");
auto result{m_ScriptInterface->GetModuleLoader().LoadModule(rq, fntPath)};
scriptContext.RunJobs();
auto& future{*result.begin()};
JS::RootedObject ns{rq.cx, future.Get()};
m_ModuleValue = {rq.cx, JS::ObjectValue(*ns)};
// Validate that message handler function is defined in the script.
if (!this->isJSHandlerDefined())
throw DapInterfaceNoJSDebuggerException{"Message handler function not defined in the script"};
// Now its time to start the server thread.
m_SocketImpl->StartServerThread();
}
Interface::~Interface() = default;
bool Interface::isJSHandlerDefined()
{
ScriptRequest rq{m_ScriptInterface.get()};
JS::RootedValue handler{rq.cx};
if (!Script::GetProperty(rq, m_ModuleValue, "handleMessage", &handler))
{
ScriptException::CatchPending(rq);
return false;
}
if (!handler.isObject())
return false;
JS::RootedObject obj{rq.cx, &handler.toObject()};
return JS_ObjectIsFunction(obj);
}
std::string Interface::SendDapMessage(const std::string& message)
{
std::unique_lock<std::mutex> msgLock{m_MsgLock};
ENSURE(m_DapRequest.empty());
m_DapRequest = std::move(message);
m_MsgApplied.notify_all();
m_MsgApplied.wait(msgLock, [this] { return m_DapRequest.empty(); });
return m_DapResponse;
}
std::string Interface::OnMessage(const std::string& message)
{
ScriptRequest rq{m_ScriptInterface.get()};
JS::RootedValue msg{rq.cx};
if (!Script::ParseJSON(rq, message, &msg))
{
LOGERROR("Failed to parse JSON message");
return "";
}
JS::RootedValue rval{rq.cx};
if (!ScriptFunction::Call(rq, m_ModuleValue, "handleMessage", &rval, msg))
{
LOGERROR("Failed to call message handler");
return "";
}
return Script::StringifyJSON(rq, &rval, false);
}
void Interface::SendEventToClient()
{
ScriptRequest rq{m_ScriptInterface.get()};
JS::RootedValue global{rq.cx, rq.globalValue()};
JS::RootedValue rval{rq.cx};
while (true)
{
if (!ScriptFunction::Call(rq, m_ModuleValue, "sendEventToClient", &rval))
{
LOGERROR("Failed to call sendEventToClient");
return;
}
// Nothing to send.
if (rval.isUndefined() || rval.isNull())
return;
const std::string ret{Script::StringifyJSON(rq, &rval, false)};
// Send to socket client.
const std::string dapResponse{"Content-Length: " + std::to_string(ret.size()) + "\r\n\r\n" + ret};
LOGMESSAGE("Sending event to client: %s", ret.c_str());
m_SocketImpl->SendToClient(dapResponse);
}
}
void Interface::TryHandleMessage()
{
std::lock_guard<std::mutex> waitingLock{m_WaitingLock};
if (!m_DapRequest.empty())
{
m_DapResponse = OnMessage(m_DapRequest);
m_DapRequest.clear();
m_MsgApplied.notify_all();
}
// Handle Events from the script.
SendEventToClient();
}
void Interface::WaitForMessage()
{
std::unique_lock<std::mutex> waitingLock{m_MsgLock};
m_IsWaiting = true;
// Handle Events from the script.
do
{
SendEventToClient();
m_MsgApplied.wait(waitingLock, [this] { return !m_DapRequest.empty(); });
m_DapResponse = OnMessage(m_DapRequest);
m_DapRequest.clear();
m_MsgApplied.notify_all();
} while (m_IsWaiting);
}
void Interface::EndWaitingForMessage()
{
if (!m_IsWaiting)
return;
std::lock_guard<std::mutex> waitingLock{m_WaitingLock};
m_IsWaiting = false;
}
}
|