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