ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
query.c
Go to the documentation of this file.
1
12
13/* Storage capacities in elements; text buffers include the terminating NUL. */
14#define TOOLING_QUERY_CMDLINE_BUFFER_SIZE 2048
15#define TOOLING_QUERY_PORT_BUFFER_SIZE 16
16#define TOOLING_QUERY_PID_BUFFER_SIZE 16
17
20#include <ascii-chat/common.h>
21
22#include <stdbool.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27
28#ifdef _WIN32
29#define WIN32_LEAN_AND_MEAN
30#include <windows.h>
31#include <winsock2.h>
32#pragma comment(lib, "ws2_32.lib")
33#else
34#include <arpa/inet.h>
35#include <errno.h>
36#include <netinet/in.h>
37#include <signal.h>
38#include <sys/socket.h>
39#include <sys/types.h>
40#include <sys/wait.h>
41#include <unistd.h>
42#endif
43
44// Timeouts for HTTP health check (in nanoseconds)
45#define HEALTH_CHECK_TIMEOUT_NS (10000LL * NS_PER_MS_INT)
46#define HEALTH_CHECK_INTERVAL_NS (100LL * NS_PER_MS_INT)
47#define HEALTH_CHECK_CONNECT_TIMEOUT_NS (500LL * NS_PER_MS_INT)
48
49// Global state for the query tool runtime
50static bool g_query_active = false;
51static int g_query_port = -1;
52
53#ifdef _WIN32
54static HANDLE g_controller_handle = NULL;
55static DWORD g_controller_pid = 0;
56#else
57static pid_t g_controller_pid = -1;
58#endif
59
66static bool try_http_connect(int port, int timeout_ms) {
67#ifdef _WIN32
68 SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
69 if (sock == INVALID_SOCKET) {
70 return false;
71 }
72
73 // Set non-blocking mode for timeout
74 u_long mode = 1;
75 ioctlsocket(sock, FIONBIO, &mode);
76
77 struct sockaddr_in addr;
78 memset(&addr, 0, sizeof(addr));
79 addr.sin_family = AF_INET;
80 addr.sin_port = htons((u_short)port);
81 addr.sin_addr.s_addr = inet_addr("127.0.0.1");
82
83 connect(sock, (struct sockaddr *)&addr, sizeof(addr));
84
85 // Use select for timeout
86 fd_set writefds;
87 FD_ZERO(&writefds);
88 FD_SET(sock, &writefds);
89
90 struct timeval tv;
91 tv.tv_sec = timeout_ms / 1000;
92 tv.tv_usec = (timeout_ms % 1000) * 1000;
93
94 int result = select(0, NULL, &writefds, NULL, &tv);
95 closesocket(sock);
96
97 return result > 0;
98#else
99 int sock = socket(AF_INET, SOCK_STREAM, 0);
100 if (sock < 0) {
101 return false;
102 }
103
104 // Set socket timeout
105 struct timeval tv;
106 tv.tv_sec = timeout_ms / 1000;
107 tv.tv_usec = (timeout_ms % 1000) * 1000;
108 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
109 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
110
111 struct sockaddr_in addr;
112 memset(&addr, 0, sizeof(addr));
113 addr.sin_family = AF_INET;
114 addr.sin_port = htons((uint16_t)port);
115 addr.sin_addr.s_addr = inet_addr("127.0.0.1");
116
117 int result = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
118 close(sock);
119
120 return result == 0;
121#endif
122}
123
130static bool wait_for_http_ready(int port, uint64_t timeout_ns) {
131 uint64_t elapsed_ns = 0;
132
133 while (elapsed_ns < timeout_ns) {
134 if (try_http_connect(port, (int)(HEALTH_CHECK_CONNECT_TIMEOUT_NS / NS_PER_MS_INT))) {
135 return true;
136 }
137
138// Check if controller process is still alive
139#ifdef _WIN32
140 if (g_controller_handle != NULL) {
141 DWORD exit_code;
142 if (GetExitCodeProcess(g_controller_handle, &exit_code)) {
143 if (exit_code != STILL_ACTIVE) {
144 // Controller exited unexpectedly
145 return false;
146 }
147 }
148 }
149#else
150 if (g_controller_pid > 0) {
151 int status;
152 pid_t result = waitpid(g_controller_pid, &status, WNOHANG);
153 if (result == g_controller_pid) {
154 // Controller exited unexpectedly
155 g_controller_pid = -1;
156 return false;
157 }
158 }
159#endif
160
161 // Sleep between checks
162 platform_sleep_ns(HEALTH_CHECK_INTERVAL_NS);
163 elapsed_ns += HEALTH_CHECK_INTERVAL_NS;
164 }
165
166 return false;
167}
168
175static bool find_query_server_path(char *buffer, size_t buffer_size) {
176 // Try common locations relative to the executable
177 const char *search_paths[] = {// Relative to build directory
178 ".deps-cache/query-tool/ascii-query-server", "../.deps-cache/query-tool/ascii-query-server", "../../.deps-cache/query-tool/ascii-query-server",
179 // In PATH
180 "ascii-query-server",
181 // Absolute paths for development
182 NULL};
183
184 for (int i = 0; search_paths[i] != NULL; i++) {
185#ifdef _WIN32
186 // On Windows, append .exe
187 safe_snprintf(buffer, buffer_size, "%s.exe", search_paths[i]);
188 if (GetFileAttributesA(buffer) != INVALID_FILE_ATTRIBUTES) {
189 return true;
190 }
191#else
192 safe_snprintf(buffer, buffer_size, "%s", search_paths[i]);
193 if (access(buffer, X_OK) == 0) {
194 return true;
195 }
196#endif
197 }
198
199 // Try to find via environment variable
200 const char *query_server_path = SAFE_GETENV("ASCIICHAT_QUERY_SERVER");
201 if (query_server_path != NULL) {
202 safe_snprintf(buffer, buffer_size, "%s", query_server_path);
203#ifdef _WIN32
204 if (GetFileAttributesA(buffer) != INVALID_FILE_ATTRIBUTES) {
205 return true;
206 }
207#else
208 if (access(buffer, X_OK) == 0) {
209 return true;
210 }
211#endif
212 }
213
214 return false;
215}
216
217int query_init(int preferred_port) {
218 // Already initialized?
219 if (g_query_active) {
220 return g_query_port;
221 }
222
223 // Find the query server executable
224 char server_path[PLATFORM_MAX_PATH_LENGTH];
225 if (!find_query_server_path(server_path, sizeof(server_path))) {
226 fprintf(stderr, "[query] Could not find ascii-query-server executable\n");
227 fprintf(stderr, "[query] Set ASCIICHAT_QUERY_SERVER environment variable or ensure "
228 "it's in .deps-cache/query-tool/\n");
229 return -1;
230 }
231
232#ifdef _WIN32
233 // Windows implementation using CreateProcess
234 // Winsock is already initialized by platform_init()
235
237 safe_snprintf(cmdline, sizeof(cmdline), "\"%s\" --attach %lu --port %d", server_path, (unsigned long)GetCurrentProcessId(), preferred_port);
238
239 STARTUPINFOA si;
240 PROCESS_INFORMATION pi;
241 memset(&si, 0, sizeof(si));
242 si.cb = sizeof(si);
243 memset(&pi, 0, sizeof(pi));
244
245 // Create the controller process
246 if (!CreateProcessA(NULL, // Use command line
247 cmdline, // Command line
248 NULL, // Process security attributes
249 NULL, // Thread security attributes
250 FALSE, // Don't inherit handles
251 CREATE_NEW_CONSOLE, // Creation flags
252 NULL, // Use parent's environment
253 NULL, // Use parent's directory
254 &si, &pi)) {
255 fprintf(stderr, "[query] Failed to start query server: error %lu\n", GetLastError());
256 return -1;
257 }
258
259 g_controller_handle = pi.hProcess;
260 g_controller_pid = pi.dwProcessId;
261 CloseHandle(pi.hThread); // Don't need the thread handle
262
263 fprintf(stderr, "[query] Started query server (PID %lu) on port %d\n", (unsigned long)g_controller_pid, preferred_port);
264
265#else
266 // Unix implementation using fork/exec
267 pid_t self_pid = getpid();
268
269 char port_str[TOOLING_QUERY_PORT_BUFFER_SIZE];
270 char pid_str[TOOLING_QUERY_PID_BUFFER_SIZE];
271 safe_snprintf(port_str, sizeof(port_str), "%d", preferred_port);
272 safe_snprintf(pid_str, sizeof(pid_str), "%d", self_pid);
273
274 pid_t child = fork();
275 if (child < 0) {
276 fprintf(stderr, "[query] fork() failed: %s\n", strerror(errno));
277 return -1;
278 }
279
280 if (child == 0) {
281 // Child process: exec the controller
282 // Redirect stdout/stderr to /dev/null or a log file to avoid clutter
283 // (The controller has its own logging)
284
285 execl(server_path, "ascii-query-server", "--attach", pid_str, "--port", port_str, (char *)NULL);
286
287 // If exec fails
288 fprintf(stderr, "[query] exec(%s) failed: %s\n", server_path, strerror(errno));
289 exit(1);
290 }
291
292 // Parent process
293 g_controller_pid = child;
294 fprintf(stderr, "[query] Started query server (PID %d) on port %d\n", child, preferred_port);
295#endif
296
297 // Wait for the HTTP server to become ready
298 fprintf(stderr, "[query] Waiting for HTTP server to be ready...\n");
299 if (!wait_for_http_ready(preferred_port, HEALTH_CHECK_TIMEOUT_NS)) {
300 fprintf(stderr, "[query] Timeout waiting for query server to start\n");
302 return -1;
303 }
304
305 g_query_active = true;
306 g_query_port = preferred_port;
307
308 fprintf(stderr, "[query] Query server ready at http://localhost:%d\n", preferred_port);
309 return preferred_port;
310}
311
312void query_destroy(void) {
313 if (!g_query_active && g_controller_pid <= 0) {
314 return;
315 }
316
317 fprintf(stderr, "[query] Shutting down query server...\n");
318
319#ifdef _WIN32
320 if (g_controller_handle != NULL) {
321 // Send termination signal
322 TerminateProcess(g_controller_handle, 0);
323
324 // Wait for process to exit (with timeout)
325 WaitForSingleObject(g_controller_handle, 3000);
326
327 CloseHandle(g_controller_handle);
328 g_controller_handle = NULL;
329 g_controller_pid = 0;
330 }
331
332 // Winsock cleanup handled by platform_cleanup()
333#else
334 if (g_controller_pid > 0) {
335 // Send SIGTERM for graceful shutdown
336 kill(g_controller_pid, SIGTERM);
337
338 // Wait for process to exit (with timeout)
339 int status;
340 int wait_count = 0;
341 while (wait_count < 30) { // 3 second timeout
342 pid_t result = waitpid(g_controller_pid, &status, WNOHANG);
343 if (result == g_controller_pid) {
344 break;
345 }
346 if (result < 0) {
347 break;
348 }
349 usleep(100 * US_PER_MS_INT); // 100ms
350 wait_count++;
351 }
352
353 // If still running, force kill
354 if (wait_count >= 30) {
355 kill(g_controller_pid, SIGKILL);
356 waitpid(g_controller_pid, &status, 0);
357 }
358
359 g_controller_pid = -1;
360 }
361#endif
362
363 g_query_active = false;
364 g_query_port = -1;
365
366 fprintf(stderr, "[query] Query server stopped\n");
367}
368
369bool query_is_active(void) {
370 if (!g_query_active) {
371 return false;
372 }
373
374// Verify the controller is still running
375#ifdef _WIN32
376 if (g_controller_handle != NULL) {
377 DWORD exit_code;
378 if (GetExitCodeProcess(g_controller_handle, &exit_code)) {
379 if (exit_code != STILL_ACTIVE) {
380 g_query_active = false;
381 g_controller_handle = NULL;
382 g_controller_pid = 0;
383 return false;
384 }
385 }
386 }
387#else
388 if (g_controller_pid > 0) {
389 // Check if process is still alive
390 if (kill(g_controller_pid, 0) != 0) {
391 g_query_active = false;
392 g_controller_pid = -1;
393 return false;
394 }
395 }
396#endif
397
398 return g_query_active;
399}
400
401int query_get_port(void) {
402 return g_query_port;
403}
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
int buffer_size
Size of circular buffer.
Definition grep.c:68
unsigned short uint16_t
#define SAFE_GETENV(name)
#define PLATFORM_MAX_PATH_LENGTH
unsigned long long uint64_t
#define NS_PER_MS_INT
Definition time.h:172
#define US_PER_MS_INT
Definition time.h:176
int query_init(int preferred_port)
Initialize the query tool by spawning the controller process.
Definition query.c:217
void query_destroy(void)
Shutdown the query tool and terminate the controller process.
Definition query.c:312
bool query_is_active(void)
Check if the query tool controller is currently active.
Definition query.c:369
int query_get_port(void)
Get the port number of the active query server.
Definition query.c:401
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define TOOLING_QUERY_PID_BUFFER_SIZE
Definition query.c:16
#define HEALTH_CHECK_TIMEOUT_NS
Definition query.c:45
#define TOOLING_QUERY_PORT_BUFFER_SIZE
Definition query.c:15
#define HEALTH_CHECK_INTERVAL_NS
Definition query.c:46
#define HEALTH_CHECK_CONNECT_TIMEOUT_NS
Definition query.c:47
#define TOOLING_QUERY_CMDLINE_BUFFER_SIZE
Definition query.c:14
Runtime variable query tool API for debug builds.
🔤 String Manipulation and Shell Escaping Utilities
⏱️ High-precision timing utilities using sokol_time.h and uthash