| 1 | /* |
| 2 | * plugin_netcheck - SCORPIOX BOT open-source network diagnostics from this node |
| 3 | * |
| 4 | * A single clean-room C99 binary that serves THREE modes: |
| 5 | * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata |
| 6 | * 2. ?action=ifaces | dns&host= | tcp&host=&port= | http&url= | info -> JSON node API |
| 7 | * 3. GET (default) -> responsive HTML diagnostics UI |
| 8 | * |
| 9 | * Everything it reports is about the node it runs on: the interfaces and their |
| 10 | * addresses, the configured DNS servers, a name resolution, a TCP connect |
| 11 | * latency, and a plain-HTTP reachability check (status line and headers only, |
| 12 | * body never read). The only outbound connections are the ones the node owner |
| 13 | * asks for by typing a host into the box, and every one of them sits behind |
| 14 | * node authentication, so the plugin is not a blind SSRF pivot. |
| 15 | * |
| 16 | * Interfaces come from getifaddrs(3) on Linux/macOS and from |
| 17 | * GetAdaptersAddresses on Windows. DNS uses getaddrinfo guarded by a deadline |
| 18 | * (a worker thread, because the resolver itself is blocking). TCP latency is |
| 19 | * the mean of three non-blocking connect() round trips. HTTP is a raw HEAD |
| 20 | * request over TCP - there is no TLS library anywhere in this binary, so an |
| 21 | * https:// target is reported as a TCP connect to port 443 with |
| 22 | * "tls":"not_checked". |
| 23 | * |
| 24 | * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang |
| 25 | * and x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 26 | * scorpiox-server on the node. |
| 27 | * |
| 28 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 29 | */ |
| 30 | |
| 31 | /* Must come before every include: iphlpapi.h and ws2tcpip.h gate |
| 32 | * GetAdaptersAddresses and the IPv6 helpers on it, and MinGW defaults to 0x502 |
| 33 | * (Server 2003) which hides all of them. */ |
| 34 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 35 | # define _WIN32_WINNT 0x0601 |
| 36 | #endif |
| 37 | |
| 38 | #if !defined(_WIN32) |
| 39 | # define _POSIX_C_SOURCE 200809L |
| 40 | # define _DEFAULT_SOURCE 1 |
| 41 | # if defined(__APPLE__) |
| 42 | # define _DARWIN_C_SOURCE 1 |
| 43 | # endif |
| 44 | #endif |
| 45 | |
| 46 | #include <stdio.h> |
| 47 | #include <stdlib.h> |
| 48 | #include <string.h> |
| 49 | #include <ctype.h> |
| 50 | #include <errno.h> |
| 51 | #include <time.h> |
| 52 | |
| 53 | #if defined(_WIN32) |
| 54 | # define WIN32_LEAN_AND_MEAN |
| 55 | # include <winsock2.h> |
| 56 | # include <ws2tcpip.h> |
| 57 | # include <windows.h> |
| 58 | # include <iphlpapi.h> |
| 59 | # define sx_popen _popen |
| 60 | # define sx_pclose _pclose |
| 61 | # define sx_close_socket closesocket |
| 62 | # define SX_SOCK_T SOCKET |
| 63 | # define SX_SOCK_INVALID INVALID_SOCKET |
| 64 | #else |
| 65 | # include <unistd.h> |
| 66 | # include <ifaddrs.h> |
| 67 | # include <net/if.h> |
| 68 | # include <netdb.h> |
| 69 | # include <sys/types.h> |
| 70 | # include <sys/socket.h> |
| 71 | # include <sys/select.h> |
| 72 | # include <sys/time.h> |
| 73 | # include <netinet/in.h> |
| 74 | # include <arpa/inet.h> |
| 75 | # include <fcntl.h> |
| 76 | # include <pthread.h> |
| 77 | # define sx_popen popen |
| 78 | # define sx_pclose pclose |
| 79 | # define sx_close_socket close |
| 80 | # define SX_SOCK_T int |
| 81 | # define SX_SOCK_INVALID (-1) |
| 82 | #endif |
| 83 | |
| 84 | #include "bot_theme_plugin.h" |
| 85 | #include "ui_html.h" |
| 86 | |
| 87 | #define PLUGIN_SLUG "netcheck" |
| 88 | #define PLUGIN_ID "plugin_netcheck" |
| 89 | #define PLUGIN_VER "1.0.0" |
| 90 | |
| 91 | #define MAX_IFACES 128 |
| 92 | #define MAX_LINE 1024 |
| 93 | #define MAX_HOST 256 |
| 94 | #define MAX_PATHZ 256 |
| 95 | #define MAX_SAMPLES 3 |
| 96 | #define MAX_RES 16 |
| 97 | |
| 98 | /* Hard ceilings so a typed host cannot make the plugin hang forever. Each |
| 99 | * phase (resolve, connect, read) gets its own budget. */ |
| 100 | #define DNS_MS 3000 |
| 101 | #define TCP_MS 3000 |
| 102 | #define READ_MS 2000 |
| 103 | |
| 104 | /* ------------------------------------------------------------------ */ |
| 105 | /* Small utilities */ |
| 106 | /* ------------------------------------------------------------------ */ |
| 107 | |
| 108 | static void url_decode(char *s) |
| 109 | { |
| 110 | char *o = s; |
| 111 | if (!s) return; |
| 112 | while (*s) { |
| 113 | if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { |
| 114 | int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 115 | int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 116 | *o++ = (char)((hi << 4) | lo); |
| 117 | s += 3; |
| 118 | } else if (*s == '+') { |
| 119 | *o++ = ' '; |
| 120 | s++; |
| 121 | } else { |
| 122 | *o++ = *s++; |
| 123 | } |
| 124 | } |
| 125 | *o = '\0'; |
| 126 | } |
| 127 | |
| 128 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 129 | { |
| 130 | size_t klen; |
| 131 | const char *p; |
| 132 | |
| 133 | if (!out || outsz == 0) return 0; |
| 134 | out[0] = '\0'; |
| 135 | if (!qs) return 0; |
| 136 | klen = strlen(key); |
| 137 | p = qs; |
| 138 | while (*p) { |
| 139 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 140 | const char *v = p + klen + 1; |
| 141 | size_t i = 0; |
| 142 | while (*v && *v != '&' && i + 1 < outsz) |
| 143 | out[i++] = *v++; |
| 144 | out[i] = '\0'; |
| 145 | url_decode(out); |
| 146 | return 1; |
| 147 | } |
| 148 | p = strchr(p, '&'); |
| 149 | if (!p) break; |
| 150 | p++; |
| 151 | } |
| 152 | return 0; |
| 153 | } |
| 154 | |
| 155 | static void json_str(const char *s) |
| 156 | { |
| 157 | putchar('"'); |
| 158 | for (; s && *s; s++) { |
| 159 | unsigned char c = (unsigned char)*s; |
| 160 | switch (c) { |
| 161 | case '"': fputs("\\\"", stdout); break; |
| 162 | case '\\': fputs("\\\\", stdout); break; |
| 163 | case '\n': fputs("\\n", stdout); break; |
| 164 | case '\r': fputs("\\r", stdout); break; |
| 165 | case '\t': fputs("\\t", stdout); break; |
| 166 | default: |
| 167 | if (c < 0x20) printf("\\u%04x", c); |
| 168 | else putchar(c); |
| 169 | } |
| 170 | } |
| 171 | putchar('"'); |
| 172 | } |
| 173 | |
| 174 | static void str_copy(char *dst, size_t sz, const char *src) |
| 175 | { |
| 176 | size_t n; |
| 177 | if (!dst || sz == 0) return; |
| 178 | if (!src) { dst[0] = '\0'; return; } |
| 179 | n = strlen(src); |
| 180 | if (n >= sz) n = sz - 1; |
| 181 | memcpy(dst, src, n); |
| 182 | dst[n] = '\0'; |
| 183 | } |
| 184 | |
| 185 | static void str_trim(char *s) |
| 186 | { |
| 187 | char *p; |
| 188 | size_t n; |
| 189 | if (!s) return; |
| 190 | p = s; |
| 191 | while (*p && isspace((unsigned char)*p)) p++; |
| 192 | if (p != s) memmove(s, p, strlen(p) + 1); |
| 193 | n = strlen(s); |
| 194 | while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; |
| 195 | } |
| 196 | |
| 197 | static void str_lower(char *s) |
| 198 | { |
| 199 | for (; s && *s; s++) *s = (char)tolower((unsigned char)*s); |
| 200 | } |
| 201 | |
| 202 | static long long now_ms(void) |
| 203 | { |
| 204 | #if defined(_WIN32) |
| 205 | FILETIME ft; |
| 206 | ULARGE_INTEGER u; |
| 207 | GetSystemTimeAsFileTime(&ft); |
| 208 | u.LowPart = ft.dwLowDateTime; |
| 209 | u.HighPart = ft.dwHighDateTime; |
| 210 | return (long long)(u.QuadPart / 10000ULL); |
| 211 | #else |
| 212 | struct timeval tv; |
| 213 | gettimeofday(&tv, NULL); |
| 214 | return (long long)tv.tv_sec * 1000LL + (long long)(tv.tv_usec / 1000); |
| 215 | #endif |
| 216 | } |
| 217 | |
| 218 | static void utc_stamp(time_t t, char *buf, size_t sz) |
| 219 | { |
| 220 | struct tm tmv; |
| 221 | #if defined(_WIN32) |
| 222 | gmtime_s(&tmv, &t); |
| 223 | #else |
| 224 | gmtime_r(&t, &tmv); |
| 225 | #endif |
| 226 | strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); |
| 227 | } |
| 228 | |
| 229 | /* ------------------------------------------------------------------ */ |
| 230 | /* Node authentication */ |
| 231 | /* ------------------------------------------------------------------ */ |
| 232 | |
| 233 | static void require_node_auth(void) |
| 234 | { |
| 235 | const char *np = getenv("BOT_PASSWORD"); |
| 236 | const char *xp; |
| 237 | const char *auth; |
| 238 | const char *qs; |
| 239 | char qpwd[256]; |
| 240 | |
| 241 | if (!np || !*np) return; |
| 242 | |
| 243 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 244 | if (xp && strcmp(xp, np) == 0) return; |
| 245 | |
| 246 | auth = getenv("HTTP_AUTHORIZATION"); |
| 247 | if (auth) { |
| 248 | while (*auth == ' ') auth++; |
| 249 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 250 | auth += 7; |
| 251 | while (*auth == ' ') auth++; |
| 252 | if (strcmp(auth, np) == 0) return; |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | qs = getenv("QUERY_STRING"); |
| 257 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 258 | return; |
| 259 | |
| 260 | fputs("Status: 401 Unauthorized\r\n" |
| 261 | "Content-Type: application/json; charset=utf-8\r\n" |
| 262 | "Cache-Control: no-store\r\n" |
| 263 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 264 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 265 | exit(0); |
| 266 | } |
| 267 | |
| 268 | /* ------------------------------------------------------------------ */ |
| 269 | /* Address formatting */ |
| 270 | /* ------------------------------------------------------------------ */ |
| 271 | |
| 272 | /* Render a sockaddr into a printable address string. Returns the family |
| 273 | * (AF_INET / AF_INET6) or 0 when the address cannot be rendered. */ |
| 274 | static int addr_text(const struct sockaddr *sa, char *out, size_t outsz) |
| 275 | { |
| 276 | if (!sa || !out || outsz == 0) return 0; |
| 277 | out[0] = '\0'; |
| 278 | |
| 279 | switch (sa->sa_family) { |
| 280 | case AF_INET: { |
| 281 | const struct sockaddr_in *in = (const struct sockaddr_in *)sa; |
| 282 | if (inet_ntop(AF_INET, &in->sin_addr, out, (unsigned int)outsz)) |
| 283 | return AF_INET; |
| 284 | return 0; |
| 285 | } |
| 286 | case AF_INET6: { |
| 287 | const struct sockaddr_in6 *in6 = (const struct sockaddr_in6 *)sa; |
| 288 | if (inet_ntop(AF_INET6, &in6->sin6_addr, out, (unsigned int)outsz)) |
| 289 | return AF_INET6; |
| 290 | return 0; |
| 291 | } |
| 292 | default: |
| 293 | return 0; |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | static int netmask_text(const struct sockaddr *sa, char *out, size_t outsz) |
| 298 | { |
| 299 | if (!sa || sa->sa_family != AF_INET || !out || outsz == 0) return 0; |
| 300 | return inet_ntop(AF_INET, |
| 301 | &((const struct sockaddr_in *)sa)->sin_addr, |
| 302 | out, (unsigned int)outsz) ? 1 : 0; |
| 303 | } |
| 304 | |
| 305 | /* ------------------------------------------------------------------ */ |
| 306 | /* Interface collection */ |
| 307 | /* ------------------------------------------------------------------ */ |
| 308 | typedef struct { |
| 309 | char name[64]; |
| 310 | char addr[64]; |
| 311 | char mask[64]; |
| 312 | char broad[64]; |
| 313 | int family; /* 4 or 6 */ |
| 314 | int loopback; |
| 315 | int up; |
| 316 | int running; |
| 317 | } iface_t; |
| 318 | |
| 319 | static iface_t g_ifaces[MAX_IFACES]; |
| 320 | static int g_iface_count; |
| 321 | |
| 322 | static int is_loopback_text(const char *a) |
| 323 | { |
| 324 | if (!a) return 0; |
| 325 | if (strncmp(a, "127.", 4) == 0) return 1; |
| 326 | if (strcmp(a, "::1") == 0) return 1; |
| 327 | return 0; |
| 328 | } |
| 329 | |
| 330 | static void iface_add(const char *name, const struct sockaddr *sa, |
| 331 | const struct sockaddr *mask, const struct sockaddr *broad, |
| 332 | int up, int running) |
| 333 | { |
| 334 | iface_t *f; |
| 335 | char a[64]; |
| 336 | int fam; |
| 337 | |
| 338 | if (g_iface_count >= MAX_IFACES) return; |
| 339 | fam = addr_text(sa, a, sizeof a); |
| 340 | if (!fam) return; |
| 341 | |
| 342 | f = &g_ifaces[g_iface_count++]; |
| 343 | memset(f, 0, sizeof *f); |
| 344 | str_copy(f->name, sizeof f->name, name ? name : "?"); |
| 345 | str_copy(f->addr, sizeof f->addr, a); |
| 346 | f->family = (fam == AF_INET6) ? 6 : 4; |
| 347 | f->loopback = is_loopback_text(f->addr); |
| 348 | f->up = up; |
| 349 | f->running = running; |
| 350 | if (mask) netmask_text(mask, f->mask, sizeof f->mask); |
| 351 | if (broad) addr_text(broad, f->broad, sizeof f->broad); |
| 352 | } |
| 353 | |
| 354 | #if defined(_WIN32) |
| 355 | /* ASCII-fold a wide adapter name; Windows adapter names are alphanumeric with |
| 356 | * spaces, dashes and dots, so a byte-per-wchar fold is lossless in practice. */ |
| 357 | static void wide_to_ascii(const wchar_t *w, char *out, size_t outsz) |
| 358 | { |
| 359 | size_t i = 0; |
| 360 | if (outsz) out[0] = '\0'; |
| 361 | if (!w || !out || outsz == 0) return; |
| 362 | for (i = 0; i + 1 < outsz && w[i]; i++) |
| 363 | out[i] = (char)((unsigned char)w[i]); |
| 364 | out[i] = '\0'; |
| 365 | } |
| 366 | |
| 367 | static PIP_ADAPTER_ADDRESSES fetch_adapters(ULONG flags) |
| 368 | { |
| 369 | ULONG want = 0; |
| 370 | ULONG rc; |
| 371 | PIP_ADAPTER_ADDRESSES adapters; |
| 372 | |
| 373 | rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, NULL, &want); |
| 374 | if (rc != ERROR_SUCCESS && rc != ERROR_BUFFER_OVERFLOW) return NULL; |
| 375 | if (want < 2048) want = 2048; |
| 376 | adapters = (PIP_ADAPTER_ADDRESSES)malloc(want + 1024); |
| 377 | if (!adapters) return NULL; |
| 378 | rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapters, &want); |
| 379 | if (rc != ERROR_SUCCESS) { free(adapters); return NULL; } |
| 380 | return adapters; |
| 381 | } |
| 382 | |
| 383 | static void collect_ifaces_windows(void) |
| 384 | { |
| 385 | PIP_ADAPTER_ADDRESSES adapters; |
| 386 | PIP_ADAPTER_ADDRESSES a; |
| 387 | PIP_ADAPTER_UNICAST_ADDRESS u; |
| 388 | |
| 389 | adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX | |
| 390 | GAA_FLAG_SKIP_ANYCAST | |
| 391 | GAA_FLAG_SKIP_MULTICAST | |
| 392 | GAA_FLAG_SKIP_DNS_SERVER); |
| 393 | if (!adapters) return; |
| 394 | |
| 395 | for (a = adapters; a; a = a->Next) { |
| 396 | char ascii[64]; |
| 397 | const wchar_t *friendly = a->FriendlyName ? a->FriendlyName : NULL; |
| 398 | int up = (a->OperStatus == IfOperStatusUp); |
| 399 | |
| 400 | if (friendly) wide_to_ascii(friendly, ascii, sizeof ascii); |
| 401 | else if (a->AdapterName) str_copy(ascii, sizeof ascii, a->AdapterName); |
| 402 | else str_copy(ascii, sizeof ascii, "adapter"); |
| 403 | |
| 404 | for (u = a->FirstUnicastAddress; u; u = u->Next) { |
| 405 | const struct sockaddr *sa = u->Address.lpSockaddr; |
| 406 | struct sockaddr_storage nm; |
| 407 | struct sockaddr *nmp = NULL; |
| 408 | |
| 409 | /* SOCKET_ADDRESS is {lpSockaddr, iSockaddrLength}, not an inline |
| 410 | * sockaddr, so the family has to be read through the pointer and |
| 411 | * guarded by the length the OS reported. */ |
| 412 | if (!sa || u->Address.iSockaddrLength < (int)sizeof(struct sockaddr)) |
| 413 | continue; |
| 414 | |
| 415 | /* OnLinkPrefixLength is a CIDR length, not a dotted mask. Expand it |
| 416 | * into a dotted netmask so the table has something familiar to show. */ |
| 417 | memset(&nm, 0, sizeof nm); |
| 418 | if (sa->sa_family == AF_INET && u->OnLinkPrefixLength < 32) { |
| 419 | struct sockaddr_in *in4 = (struct sockaddr_in *)&nm; |
| 420 | in4->sin_family = AF_INET; |
| 421 | in4->sin_addr.s_addr = |
| 422 | htonl(0xFFFFFFFFUL << (32 - u->OnLinkPrefixLength)); |
| 423 | nmp = (struct sockaddr *)in4; |
| 424 | } |
| 425 | iface_add(ascii, sa, nmp, NULL, up, up); |
| 426 | } |
| 427 | } |
| 428 | free(adapters); |
| 429 | } |
| 430 | #else |
| 431 | static void collect_ifaces_posix(void) |
| 432 | { |
| 433 | struct ifaddrs *list = NULL; |
| 434 | struct ifaddrs *i; |
| 435 | |
| 436 | if (getifaddrs(&list) != 0 || !list) return; |
| 437 | for (i = list; i; i = i->ifa_next) { |
| 438 | int up, running; |
| 439 | |
| 440 | if (!i->ifa_addr) continue; |
| 441 | up = (i->ifa_flags & IFF_UP) != 0; |
| 442 | running = (i->ifa_flags & IFF_RUNNING) != 0; |
| 443 | iface_add(i->ifa_name, i->ifa_addr, i->ifa_netmask, i->ifa_broadaddr, |
| 444 | up, running); |
| 445 | } |
| 446 | freeifaddrs(list); |
| 447 | } |
| 448 | #endif |
| 449 | |
| 450 | |
| 451 | /* ------------------------------------------------------------------ */ |
| 452 | /* Host validation */ |
| 453 | /* ------------------------------------------------------------------ */ |
| 454 | |
| 455 | /* A host is accepted only as a DNS hostname label sequence or a literal IPv4 / |
| 456 | * IPv6 address. That keeps typed input from smuggling a URL, a path, or a |
| 457 | * shell metacharacter into anything we do with it. */ |
| 458 | static int valid_hostname(const char *s) |
| 459 | { |
| 460 | size_t i, n = strlen(s); |
| 461 | |
| 462 | if (n == 0 || n > 253) return 0; |
| 463 | if (s[0] == '.' || s[n - 1] == '.') return 0; |
| 464 | for (i = 0; i < n; i++) { |
| 465 | unsigned char c = (unsigned char)s[i]; |
| 466 | if (c == '.') { |
| 467 | if (i == 0 || s[i - 1] == '.') return 0; |
| 468 | continue; |
| 469 | } |
| 470 | if (!isalnum(c) && c != '-' && c != '_') return 0; |
| 471 | } |
| 472 | return 1; |
| 473 | } |
| 474 | |
| 475 | static int looks_ipv4(const char *s) |
| 476 | { |
| 477 | struct sockaddr_in in; |
| 478 | return inet_pton(AF_INET, s, &in.sin_addr) == 1; |
| 479 | } |
| 480 | |
| 481 | static int looks_ipv6(const char *s) |
| 482 | { |
| 483 | struct sockaddr_in6 in6; |
| 484 | return inet_pton(AF_INET6, s, &in6.sin6_addr) == 1; |
| 485 | } |
| 486 | |
| 487 | static int valid_host(const char *s) |
| 488 | { |
| 489 | if (!s || !*s) return 0; |
| 490 | if (looks_ipv4(s) || looks_ipv6(s)) return 1; |
| 491 | return valid_hostname(s); |
| 492 | } |
| 493 | |
| 494 | /* ------------------------------------------------------------------ */ |
| 495 | /* Test hooks */ |
| 496 | /* ------------------------------------------------------------------ */ |
| 497 | |
| 498 | /* The offline suite needs deterministic, network-free answers, so three |
| 499 | * environment hooks exist. They are only consulted when the variable is set, |
| 500 | * which is never the case on a real node, and they let the suite exercise the |
| 501 | * timeout and the multi-address paths without a live resolver. |
| 502 | * |
| 503 | * NETCHECK_MOCK_IFACES "lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,eth0|..." |
| 504 | * name|address|netmask|broadcast|family|up |
| 505 | * NETCHECK_MOCK_DNS "host=addr,addr;host2=addr" (family inferred) |
| 506 | * NETCHECK_MOCK_TIMEOUT 1 -> every resolution reports a deadline miss |
| 507 | */ |
| 508 | static int mock_timeout_enabled(void) |
| 509 | { |
| 510 | const char *v = getenv("NETCHECK_MOCK_TIMEOUT"); |
| 511 | return v && v[0] == '1'; |
| 512 | } |
| 513 | |
| 514 | /* Fill *res with a synthetic addrinfo chain for host. Returns 0 on success. */ |
| 515 | static int mock_resolve(const char *host, const char *port, struct addrinfo **res) |
| 516 | { |
| 517 | const char *map = getenv("NETCHECK_MOCK_DNS"); |
| 518 | char entry[512]; |
| 519 | char addrs[512]; |
| 520 | size_t hl, el, i; |
| 521 | struct addrinfo *head = NULL, *tail = NULL; |
| 522 | int count = 0; |
| 523 | |
| 524 | int mock_port = 0; |
| 525 | |
| 526 | if (!map || !host) return -1; |
| 527 | if (port) { |
| 528 | long v = strtol(port, NULL, 10); |
| 529 | if (v >= 1 && v <= 65535) mock_port = (int)v; |
| 530 | } |
| 531 | hl = strlen(host); |
| 532 | |
| 533 | i = 0; |
| 534 | for (;;) { |
| 535 | size_t j = i; |
| 536 | char *eq; |
| 537 | size_t k, al; |
| 538 | struct addrinfo *ai; |
| 539 | |
| 540 | while (map[j] && map[j] != ';') j++; |
| 541 | el = j - i; |
| 542 | if (el > 0 && el < sizeof entry) { |
| 543 | memcpy(entry, map + i, el); |
| 544 | entry[el] = 0; |
| 545 | eq = strchr(entry, '='); |
| 546 | if (eq && (size_t)(eq - entry) == hl && strncmp(entry, host, hl) == 0) { |
| 547 | str_copy(addrs, sizeof addrs, eq + 1); |
| 548 | al = strlen(addrs); |
| 549 | k = 0; |
| 550 | while (k < al) { |
| 551 | char tok[128]; |
| 552 | size_t tl = 0; |
| 553 | struct sockaddr_in *in4; |
| 554 | struct sockaddr_in6 *in6; |
| 555 | |
| 556 | while (k < al && addrs[k] != ',') { |
| 557 | if (tl < sizeof tok - 1) tok[tl++] = addrs[k]; |
| 558 | k++; |
| 559 | } |
| 560 | tok[tl] = 0; |
| 561 | if (k < al) k++; /* skip the comma */ |
| 562 | while (tl > 0 && isspace((unsigned char)tok[tl - 1])) tok[--tl] = 0; |
| 563 | if (tl == 0) continue; |
| 564 | |
| 565 | ai = (struct addrinfo *)calloc(1, sizeof *ai); |
| 566 | if (!ai) return -2; |
| 567 | if (looks_ipv4(tok)) { |
| 568 | in4 = (struct sockaddr_in *)calloc(1, sizeof *in4); |
| 569 | if (!in4) { free(ai); return -2; } |
| 570 | in4->sin_family = AF_INET; |
| 571 | in4->sin_port = htons((unsigned short)mock_port); |
| 572 | inet_pton(AF_INET, tok, &in4->sin_addr); |
| 573 | ai->ai_family = AF_INET; |
| 574 | ai->ai_socktype = SOCK_STREAM; |
| 575 | ai->ai_addr = (struct sockaddr *)in4; |
| 576 | ai->ai_addrlen = sizeof *in4; |
| 577 | } else if (looks_ipv6(tok)) { |
| 578 | in6 = (struct sockaddr_in6 *)calloc(1, sizeof *in6); |
| 579 | if (!in6) { free(ai); return -2; } |
| 580 | in6->sin6_family = AF_INET6; |
| 581 | in6->sin6_port = htons((unsigned short)mock_port); |
| 582 | inet_pton(AF_INET6, tok, &in6->sin6_addr); |
| 583 | ai->ai_family = AF_INET6; |
| 584 | ai->ai_socktype = SOCK_STREAM; |
| 585 | ai->ai_addr = (struct sockaddr *)in6; |
| 586 | ai->ai_addrlen = sizeof *in6; |
| 587 | } else { |
| 588 | free(ai); |
| 589 | continue; |
| 590 | } |
| 591 | if (tail) tail->ai_next = ai; else head = ai; |
| 592 | tail = ai; |
| 593 | if (++count >= MAX_RES) break; |
| 594 | } |
| 595 | *res = head; |
| 596 | return 0; |
| 597 | } |
| 598 | } |
| 599 | if (map[j] == ';') { i = j + 1; continue; } |
| 600 | break; |
| 601 | } |
| 602 | return -1; |
| 603 | } |
| 604 | |
| 605 | /* Synthetic interface table for the offline suite. |
| 606 | * Format: name|address|netmask|broadcast|family|up (entries separated by ','). |
| 607 | * A pipe is used between fields because an IPv6 address is full of colons. */ |
| 608 | static int mock_ifaces(void) |
| 609 | { |
| 610 | const char *spec = getenv("NETCHECK_MOCK_IFACES"); |
| 611 | char tok[256]; |
| 612 | char *parts[6]; |
| 613 | size_t i = 0, n; |
| 614 | |
| 615 | if (!spec) return 0; |
| 616 | n = strlen(spec); |
| 617 | i = 0; |
| 618 | while (i < n) { |
| 619 | size_t tl = 0, pi; |
| 620 | iface_t *f; |
| 621 | struct sockaddr_storage sa; |
| 622 | struct sockaddr_storage nm; |
| 623 | struct sockaddr *nmp = NULL; |
| 624 | char *pp; |
| 625 | int fam = 0; |
| 626 | |
| 627 | while (i < n && spec[i] != ',') { |
| 628 | if (tl < sizeof tok - 1) tok[tl++] = spec[i]; |
| 629 | i++; |
| 630 | } |
| 631 | tok[tl] = 0; |
| 632 | if (i < n) i++; /* skip the comma */ |
| 633 | if (tl == 0) continue; |
| 634 | |
| 635 | for (pi = 0; pi < 6; pi++) parts[pi] = (char *)""; |
| 636 | parts[0] = tok; |
| 637 | pi = 1; |
| 638 | pp = tok; |
| 639 | while (pp && pi < 6) { |
| 640 | char *nx = strchr(pp, '|'); |
| 641 | if (!nx) break; |
| 642 | *nx = 0; |
| 643 | parts[pi++] = nx + 1; |
| 644 | pp = nx + 1; |
| 645 | } |
| 646 | for (; pi < 6; pi++) parts[pi] = (char *)""; |
| 647 | |
| 648 | memset(&sa, 0, sizeof sa); |
| 649 | memset(&nm, 0, sizeof nm); |
| 650 | if (looks_ipv4(parts[1])) { |
| 651 | struct sockaddr_in *in4 = (struct sockaddr_in *)&sa; |
| 652 | in4->sin_family = AF_INET; |
| 653 | inet_pton(AF_INET, parts[1], &in4->sin_addr); |
| 654 | fam = 4; |
| 655 | if (parts[2][0] && looks_ipv4(parts[2])) { |
| 656 | struct sockaddr_in *m4 = (struct sockaddr_in *)&nm; |
| 657 | m4->sin_family = AF_INET; |
| 658 | inet_pton(AF_INET, parts[2], &m4->sin_addr); |
| 659 | nmp = (struct sockaddr *)m4; |
| 660 | } |
| 661 | } else if (looks_ipv6(parts[1])) { |
| 662 | struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&sa; |
| 663 | in6->sin6_family = AF_INET6; |
| 664 | inet_pton(AF_INET6, parts[1], &in6->sin6_addr); |
| 665 | fam = 6; |
| 666 | } else { |
| 667 | continue; |
| 668 | } |
| 669 | |
| 670 | if (g_iface_count >= MAX_IFACES) break; |
| 671 | f = &g_ifaces[g_iface_count++]; |
| 672 | memset(f, 0, sizeof *f); |
| 673 | str_copy(f->name, sizeof f->name, parts[0]); |
| 674 | str_copy(f->addr, sizeof f->addr, parts[1]); |
| 675 | f->family = fam; |
| 676 | f->loopback = is_loopback_text(f->addr); |
| 677 | f->up = parts[5][0] == '1'; |
| 678 | f->running = f->up; |
| 679 | if (nmp) netmask_text(nmp, f->mask, sizeof f->mask); |
| 680 | if (parts[3][0]) str_copy(f->broad, sizeof f->broad, parts[3]); |
| 681 | } |
| 682 | return 1; |
| 683 | } |
| 684 | |
| 685 | |
| 686 | static void collect_ifaces(void) |
| 687 | { |
| 688 | g_iface_count = 0; |
| 689 | if (mock_ifaces()) return; |
| 690 | #if defined(_WIN32) |
| 691 | collect_ifaces_windows(); |
| 692 | #else |
| 693 | collect_ifaces_posix(); |
| 694 | #endif |
| 695 | } |
| 696 | |
| 697 | /* ------------------------------------------------------------------ */ |
| 698 | /* DNS server discovery */ |
| 699 | /* ------------------------------------------------------------------ */ |
| 700 | |
| 701 | #define MAX_NS 16 |
| 702 | static char g_ns[MAX_NS][64]; |
| 703 | static int g_ns_count; |
| 704 | |
| 705 | static void ns_add(const char *s) |
| 706 | { |
| 707 | char buf[64]; |
| 708 | int i; |
| 709 | |
| 710 | if (!s) return; |
| 711 | str_copy(buf, sizeof buf, s); |
| 712 | str_trim(buf); |
| 713 | if (!buf[0]) return; |
| 714 | for (i = 0; i < g_ns_count; i++) |
| 715 | if (strcmp(g_ns[i], buf) == 0) return; |
| 716 | if (g_ns_count >= MAX_NS) return; |
| 717 | str_copy(g_ns[g_ns_count++], sizeof g_ns[0], buf); |
| 718 | } |
| 719 | |
| 720 | static void discover_nameservers(void) |
| 721 | { |
| 722 | g_ns_count = 0; |
| 723 | |
| 724 | #if defined(_WIN32) |
| 725 | { |
| 726 | /* The interface query above deliberately skipped the DNS server list, |
| 727 | * so re-query with the flag left on rather than parsing a text tool. */ |
| 728 | PIP_ADAPTER_ADDRESSES adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX); |
| 729 | PIP_ADAPTER_ADDRESSES a; |
| 730 | PIP_ADAPTER_DNS_SERVER_ADDRESS_XP d; |
| 731 | |
| 732 | if (adapters) { |
| 733 | for (a = adapters; a; a = a->Next) |
| 734 | for (d = a->FirstDnsServerAddress; d; d = d->Next) { |
| 735 | char txt[64]; |
| 736 | const struct sockaddr *sa = d->Address.lpSockaddr; |
| 737 | if (!sa || d->Address.iSockaddrLength < (int)sizeof(struct sockaddr)) |
| 738 | continue; |
| 739 | if (addr_text(sa, txt, sizeof txt)) |
| 740 | ns_add(txt); |
| 741 | } |
| 742 | free(adapters); |
| 743 | } |
| 744 | } |
| 745 | #else |
| 746 | { |
| 747 | FILE *f = fopen("/etc/resolv.conf", "r"); |
| 748 | char line[MAX_LINE]; |
| 749 | if (f) { |
| 750 | while (fgets(line, sizeof line, f)) { |
| 751 | char *p = line; |
| 752 | if (*p == '#') continue; |
| 753 | if (strncmp(p, "nameserver", 10) == 0) { |
| 754 | p += 10; |
| 755 | while (*p == ' ' || *p == '\t') p++; |
| 756 | ns_add(p); |
| 757 | } |
| 758 | } |
| 759 | fclose(f); |
| 760 | } |
| 761 | } |
| 762 | #endif |
| 763 | |
| 764 | #if defined(__APPLE__) |
| 765 | /* macOS keeps /etc/resolv.conf as a symlink to a rotating stub; scutil is |
| 766 | * the authoritative source. Fixed argv - no user input reaches the shell. |
| 767 | * scutil lives in /usr/sbin on macOS (measured on the MacBook builder), so |
| 768 | * both absolute spellings are tried rather than trusting one. */ |
| 769 | { |
| 770 | static const char *SCUTIL_PATHS[] = {"/usr/sbin/scutil", "/usr/bin/scutil"}; |
| 771 | FILE *f = NULL; |
| 772 | char line[MAX_LINE]; |
| 773 | int si; |
| 774 | for (si = 0; si < 2 && !f; si++) { |
| 775 | char cmd[64]; |
| 776 | snprintf(cmd, sizeof cmd, "%s --dns", SCUTIL_PATHS[si]); |
| 777 | f = sx_popen(cmd, "r"); |
| 778 | } |
| 779 | if (f) { |
| 780 | while (fgets(line, sizeof line, f)) { |
| 781 | const char *p = strstr(line, "nameserver["); |
| 782 | char srv[64]; |
| 783 | size_t i = 0; |
| 784 | if (!p) continue; |
| 785 | p += 11; |
| 786 | while (*p && *p != ']' && i < sizeof srv - 1) srv[i++] = *p++; |
| 787 | srv[i] = '\0'; |
| 788 | str_trim(srv); |
| 789 | if (srv[0]) ns_add(srv); |
| 790 | } |
| 791 | sx_pclose(f); |
| 792 | } |
| 793 | } |
| 794 | #endif |
| 795 | } |
| 796 | |
| 797 | /* ------------------------------------------------------------------ */ |
| 798 | /* Deadline-guarded DNS */ |
| 799 | /* ------------------------------------------------------------------ */ |
| 800 | |
| 801 | /* getaddrinfo is blocking and has no timeout argument, so the deadline lives |
| 802 | * in a worker thread. On timeout the thread is left running: this process is a |
| 803 | * CGI child that exits as soon as the request is answered, so the leak is |
| 804 | * bounded by the request itself. */ |
| 805 | typedef struct { |
| 806 | const char *host; |
| 807 | const char *port; |
| 808 | struct addrinfo *res; |
| 809 | int rc; |
| 810 | int done; |
| 811 | } resolve_job; |
| 812 | |
| 813 | #if defined(_WIN32) |
| 814 | static DWORD WINAPI resolve_thread(LPVOID arg) |
| 815 | { |
| 816 | resolve_job *j = (resolve_job *)arg; |
| 817 | struct addrinfo hints; |
| 818 | |
| 819 | memset(&hints, 0, sizeof hints); |
| 820 | hints.ai_family = AF_UNSPEC; |
| 821 | hints.ai_socktype = SOCK_STREAM; |
| 822 | j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); |
| 823 | j->done = 1; |
| 824 | return 0; |
| 825 | } |
| 826 | |
| 827 | static int resolve_with_deadline(const char *host, const char *port, |
| 828 | struct addrinfo **res, int timeout_ms) |
| 829 | { |
| 830 | resolve_job job; |
| 831 | HANDLE th; |
| 832 | DWORD wait; |
| 833 | |
| 834 | if (mock_timeout_enabled()) return -1; |
| 835 | if (mock_resolve(host, port, res) == 0) return 0; |
| 836 | job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; |
| 837 | th = CreateThread(NULL, 0, resolve_thread, &job, 0, NULL); |
| 838 | if (!th) return -4; |
| 839 | wait = WaitForSingleObject(th, (DWORD)timeout_ms); |
| 840 | if (wait == WAIT_TIMEOUT) { CloseHandle(th); return -1; } |
| 841 | CloseHandle(th); |
| 842 | *res = job.res; |
| 843 | return job.rc; |
| 844 | } |
| 845 | #else |
| 846 | static void *resolve_thread(void *arg) |
| 847 | { |
| 848 | resolve_job *j = (resolve_job *)arg; |
| 849 | struct addrinfo hints; |
| 850 | |
| 851 | memset(&hints, 0, sizeof hints); |
| 852 | hints.ai_family = AF_UNSPEC; |
| 853 | hints.ai_socktype = SOCK_STREAM; |
| 854 | j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); |
| 855 | j->done = 1; |
| 856 | return NULL; |
| 857 | } |
| 858 | |
| 859 | static int resolve_with_deadline(const char *host, const char *port, |
| 860 | struct addrinfo **res, int timeout_ms) |
| 861 | { |
| 862 | resolve_job job; |
| 863 | pthread_t th; |
| 864 | long long deadline = now_ms() + timeout_ms; |
| 865 | |
| 866 | if (mock_timeout_enabled()) return -1; |
| 867 | if (mock_resolve(host, port, res) == 0) return 0; |
| 868 | job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; |
| 869 | if (pthread_create(&th, NULL, resolve_thread, &job) != 0) return -4; |
| 870 | while (!job.done) { |
| 871 | if (now_ms() >= deadline) return -1; /* thread keeps running; process exits soon */ |
| 872 | usleep(20000); |
| 873 | } |
| 874 | pthread_join(th, NULL); |
| 875 | *res = job.res; |
| 876 | return job.rc; |
| 877 | } |
| 878 | #endif |
| 879 | |
| 880 | /* ------------------------------------------------------------------ */ |
| 881 | /* TCP connect with a deadline */ |
| 882 | /* ------------------------------------------------------------------ */ |
| 883 | |
| 884 | /* Returns >=0 connect latency in ms, -1 timeout, -2 connect failed/refused, |
| 885 | * -3 resolution failed, -4 socket/thread failure. Writes the resolved address |
| 886 | * into addr_out when available. */ |
| 887 | static int tcp_connect_ms(const struct addrinfo *rp, int timeout_ms, |
| 888 | char *addr_out, size_t addr_sz) |
| 889 | { |
| 890 | SX_SOCK_T s; |
| 891 | long long start; |
| 892 | int rc; |
| 893 | |
| 894 | if (addr_out && addr_sz) addr_out[0] = '\0'; |
| 895 | |
| 896 | s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); |
| 897 | if (s == SX_SOCK_INVALID) return -4; |
| 898 | |
| 899 | /* Non-blocking so connect() returns immediately and select() enforces the |
| 900 | * deadline. A blocking connect on some stacks ignores the deadline. */ |
| 901 | #if defined(_WIN32) |
| 902 | { |
| 903 | u_long nb = 1; |
| 904 | ioctlsocket(s, FIONBIO, &nb); |
| 905 | } |
| 906 | #else |
| 907 | { |
| 908 | int fl = fcntl(s, F_GETFL, 0); |
| 909 | if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK); |
| 910 | } |
| 911 | #endif |
| 912 | |
| 913 | start = now_ms(); |
| 914 | rc = connect(s, rp->ai_addr, rp->ai_addrlen); |
| 915 | if (rc != 0) { |
| 916 | #if defined(_WIN32) |
| 917 | int inprogress = (WSAGetLastError() == WSAEINPROGRESS || |
| 918 | WSAGetLastError() == WSAEWOULDBLOCK || |
| 919 | WSAGetLastError() == WSAEALREADY); |
| 920 | #else |
| 921 | int inprogress = (errno == EINPROGRESS || errno == EALREADY || |
| 922 | errno == EWOULDBLOCK); |
| 923 | #endif |
| 924 | if (!inprogress) { sx_close_socket(s); return -2; } |
| 925 | |
| 926 | { |
| 927 | fd_set wfds; |
| 928 | struct timeval tv; |
| 929 | int sr; |
| 930 | |
| 931 | FD_ZERO(&wfds); |
| 932 | FD_SET(s, &wfds); |
| 933 | tv.tv_sec = timeout_ms / 1000; |
| 934 | tv.tv_usec = (timeout_ms % 1000) * 1000; |
| 935 | sr = select((int)s + 1, NULL, &wfds, NULL, &tv); |
| 936 | if (sr <= 0) { sx_close_socket(s); return -1; } |
| 937 | { |
| 938 | int soerr = 0; |
| 939 | #if defined(_WIN32) |
| 940 | int sl = sizeof soerr; |
| 941 | #else |
| 942 | socklen_t sl = sizeof soerr; |
| 943 | #endif |
| 944 | if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &sl) != 0 || soerr != 0) { |
| 945 | sx_close_socket(s); |
| 946 | return -2; |
| 947 | } |
| 948 | } |
| 949 | } |
| 950 | } |
| 951 | |
| 952 | rc = (int)(now_ms() - start); |
| 953 | if (rc < 0) rc = 0; |
| 954 | addr_text(rp->ai_addr, addr_out, addr_sz); |
| 955 | sx_close_socket(s); |
| 956 | return rc; |
| 957 | } |
| 958 | |
| 959 | /* ------------------------------------------------------------------ */ |
| 960 | /* URL parsing for the http action */ |
| 961 | /* ------------------------------------------------------------------ */ |
| 962 | |
| 963 | typedef struct { |
| 964 | char scheme[8]; |
| 965 | char host[MAX_HOST]; /* bracketed when it is an IPv6 literal */ |
| 966 | char host_plain[MAX_HOST];/* bare address, for getaddrinfo */ |
| 967 | int port; |
| 968 | char path[MAX_PATHZ]; |
| 969 | int tls; |
| 970 | } url_t; |
| 971 | |
| 972 | static int parse_url(const char *in, url_t *u) |
| 973 | { |
| 974 | const char *p = in; |
| 975 | const char *hs, *he, *ps; |
| 976 | size_t n; |
| 977 | |
| 978 | memset(u, 0, sizeof *u); |
| 979 | if (!in || !*in) return 0; |
| 980 | |
| 981 | if (strncmp(p, "http://", 7) == 0) { |
| 982 | str_copy(u->scheme, sizeof u->scheme, "http"); |
| 983 | u->tls = 0; |
| 984 | p += 7; |
| 985 | } else if (strncmp(p, "https://", 8) == 0) { |
| 986 | str_copy(u->scheme, sizeof u->scheme, "https"); |
| 987 | u->tls = 1; |
| 988 | p += 8; |
| 989 | } else { |
| 990 | return 0; |
| 991 | } |
| 992 | |
| 993 | hs = p; |
| 994 | he = p; |
| 995 | while (*he && *he != '/' && *he != '?' && *he != '#') he++; |
| 996 | ps = he; /* the path starts at the first '/', not at the port */ |
| 997 | |
| 998 | /* strip userinfo */ |
| 999 | { |
| 1000 | const char *at = NULL, *q; |
| 1001 | for (q = hs; q < he; q++) if (*q == '@') at = q; |
| 1002 | if (at) hs = at + 1; |
| 1003 | } |
| 1004 | |
| 1005 | /* split an optional :port. Scan right-to-left for the last colon outside |
| 1006 | * IPv6 brackets: an unbracketed IPv6 literal (127.0.0.1:80 style aside) |
| 1007 | * contains several colons, and the port is always the final one. */ |
| 1008 | { |
| 1009 | const char *col = NULL; |
| 1010 | intptr_t qi = (intptr_t)(he - hs) - 1; |
| 1011 | while (qi >= 0) { |
| 1012 | char c = hs[qi]; |
| 1013 | if (c == ']') { qi--; continue; } |
| 1014 | if (c == '[') break; /* bracketed IPv6, no plain port colon */ |
| 1015 | if (c == ':') { col = hs + qi; break; } |
| 1016 | if (c == '/' || c == '?' || c == '#') break; |
| 1017 | qi--; |
| 1018 | } |
| 1019 | if (col) { |
| 1020 | long v; |
| 1021 | char pbuf[16]; |
| 1022 | size_t pn = (size_t)(he - col - 1); |
| 1023 | size_t k; |
| 1024 | if (pn == 0 || pn >= sizeof pbuf) return 0; |
| 1025 | memcpy(pbuf, col + 1, pn); |
| 1026 | pbuf[pn] = '\0'; |
| 1027 | for (k = 0; k < pn; k++) if (!isdigit((unsigned char)pbuf[k])) return 0; |
| 1028 | v = strtol(pbuf, NULL, 10); |
| 1029 | if (v < 1 || v > 65535) return 0; |
| 1030 | u->port = (int)v; |
| 1031 | he = col; |
| 1032 | } else { |
| 1033 | u->port = u->tls ? 443 : 80; |
| 1034 | } |
| 1035 | } |
| 1036 | |
| 1037 | n = (size_t)(he - hs); |
| 1038 | if (n == 0 || n >= sizeof u->host) return 0; |
| 1039 | memcpy(u->host, hs, n); |
| 1040 | u->host[n] = '\0'; |
| 1041 | |
| 1042 | /* bare address for the resolver */ |
| 1043 | if (u->host[0] == '[' && u->host[n - 1] == ']') { |
| 1044 | if (n < 3 || n - 2 >= sizeof u->host_plain) return 0; |
| 1045 | memcpy(u->host_plain, u->host + 1, n - 2); |
| 1046 | u->host_plain[n - 2] = '\0'; |
| 1047 | if (!looks_ipv6(u->host_plain)) return 0; |
| 1048 | } else { |
| 1049 | str_copy(u->host_plain, sizeof u->host_plain, u->host); |
| 1050 | if (!valid_host(u->host_plain)) return 0; |
| 1051 | } |
| 1052 | |
| 1053 | /* path */ |
| 1054 | { |
| 1055 | const char *e = ps; |
| 1056 | while (*e && *e != '?' && *e != '#') e++; |
| 1057 | n = (size_t)(e - ps); |
| 1058 | if (n == 0) { str_copy(u->path, sizeof u->path, "/"); } |
| 1059 | else { |
| 1060 | if (n >= sizeof u->path) n = sizeof u->path - 1; |
| 1061 | memcpy(u->path, ps, n); |
| 1062 | u->path[n] = '\0'; |
| 1063 | if (u->path[0] != '/') return 0; |
| 1064 | } |
| 1065 | } |
| 1066 | return 1; |
| 1067 | } |
| 1068 | |
| 1069 | /* ------------------------------------------------------------------ */ |
| 1070 | /* JSON helpers */ |
| 1071 | /* ------------------------------------------------------------------ */ |
| 1072 | |
| 1073 | static void emit_json_head(void) |
| 1074 | { |
| 1075 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 1076 | "Cache-Control: no-store\r\n" |
| 1077 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1078 | } |
| 1079 | |
| 1080 | static void err_json(int status, const char *msg) |
| 1081 | { |
| 1082 | printf("Status: %d %s\r\n" |
| 1083 | "Content-Type: application/json; charset=utf-8\r\n" |
| 1084 | "Cache-Control: no-store\r\n" |
| 1085 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 1086 | "{\"ok\":false,\"error\":", |
| 1087 | status, status == 400 ? "Bad Request" : "Internal Error"); |
| 1088 | json_str(msg); |
| 1089 | puts("}"); |
| 1090 | } |
| 1091 | |
| 1092 | /* ------------------------------------------------------------------ */ |
| 1093 | /* action=ifaces */ |
| 1094 | /* ------------------------------------------------------------------ */ |
| 1095 | |
| 1096 | static void action_ifaces(void) |
| 1097 | { |
| 1098 | int i; |
| 1099 | char stamp[32]; |
| 1100 | |
| 1101 | collect_ifaces(); |
| 1102 | discover_nameservers(); |
| 1103 | |
| 1104 | emit_json_head(); |
| 1105 | utc_stamp(time(NULL), stamp, sizeof stamp); |
| 1106 | printf("{\"ok\":true,\"action\":\"ifaces\",\"generated_at\":"); |
| 1107 | json_str(stamp); |
| 1108 | printf(",\"count\":%d,\"interfaces\":[", g_iface_count); |
| 1109 | for (i = 0; i < g_iface_count; i++) { |
| 1110 | const iface_t *f = &g_ifaces[i]; |
| 1111 | if (i) putchar(','); |
| 1112 | printf("{\"name\":"); |
| 1113 | json_str(f->name); |
| 1114 | printf(",\"address\":"); |
| 1115 | json_str(f->addr); |
| 1116 | printf(",\"family\":%d,\"netmask\":", f->family); |
| 1117 | if (f->mask[0]) json_str(f->mask); else fputs("null", stdout); |
| 1118 | printf(",\"broadcast\":"); |
| 1119 | if (f->broad[0]) json_str(f->broad); else fputs("null", stdout); |
| 1120 | printf(",\"loopback\":%s,\"up\":%s,\"running\":%s}", |
| 1121 | f->loopback ? "true" : "false", |
| 1122 | f->up ? "true" : "false", |
| 1123 | f->running ? "true" : "false"); |
| 1124 | } |
| 1125 | printf("],\"nameservers\":["); |
| 1126 | for (i = 0; i < g_ns_count; i++) { |
| 1127 | if (i) putchar(','); |
| 1128 | json_str(g_ns[i]); |
| 1129 | } |
| 1130 | printf("],\"nameserver_count\":%d}", g_ns_count); |
| 1131 | } |
| 1132 | |
| 1133 | /* ------------------------------------------------------------------ */ |
| 1134 | /* action=dns */ |
| 1135 | /* ------------------------------------------------------------------ */ |
| 1136 | |
| 1137 | static void action_dns(const char *host_in) |
| 1138 | { |
| 1139 | struct addrinfo *res = NULL; |
| 1140 | struct addrinfo *rp; |
| 1141 | char stamp[32]; |
| 1142 | char target[MAX_HOST]; |
| 1143 | int n = 0; |
| 1144 | long long t0, t1; |
| 1145 | int rc; |
| 1146 | |
| 1147 | str_copy(target, sizeof target, host_in); |
| 1148 | str_lower(target); |
| 1149 | if (!target[0]) { err_json(400, "host required"); return; } |
| 1150 | if (!valid_host(target)) { err_json(400, "invalid host"); return; } |
| 1151 | |
| 1152 | emit_json_head(); |
| 1153 | utc_stamp(time(NULL), stamp, sizeof stamp); |
| 1154 | |
| 1155 | t0 = now_ms(); |
| 1156 | rc = resolve_with_deadline(target, NULL, &res, DNS_MS); |
| 1157 | t1 = now_ms(); |
| 1158 | |
| 1159 | printf("{\"ok\":true,\"action\":\"dns\",\"host\":"); |
| 1160 | json_str(target); |
| 1161 | printf(",\"generated_at\":"); |
| 1162 | json_str(stamp); |
| 1163 | printf(",\"timeout_ms\":%d", DNS_MS); |
| 1164 | |
| 1165 | if (rc == -1) { |
| 1166 | printf(",\"resolved\":false,\"timeout\":true,\"code\":null," |
| 1167 | "\"latency_ms\":%lld,\"results\":[],\"count\":0}", |
| 1168 | (long long)(t1 - t0)); |
| 1169 | return; |
| 1170 | } |
| 1171 | if (rc != 0 || !res) { |
| 1172 | printf(",\"resolved\":false,\"timeout\":false,\"code\":%d," |
| 1173 | "\"latency_ms\":%lld,\"results\":[],\"count\":0}", |
| 1174 | rc, (long long)(t1 - t0)); |
| 1175 | return; |
| 1176 | } |
| 1177 | |
| 1178 | printf(",\"resolved\":true,\"timeout\":false,\"code\":0," |
| 1179 | "\"latency_ms\":%lld,\"results\":[", (long long)(t1 - t0)); |
| 1180 | for (rp = res; rp; rp = rp->ai_next) { |
| 1181 | char txt[64]; |
| 1182 | if (!addr_text(rp->ai_addr, txt, sizeof txt)) continue; |
| 1183 | if (n) putchar(','); |
| 1184 | n++; |
| 1185 | printf("{\"address\":"); |
| 1186 | json_str(txt); |
| 1187 | printf(",\"family\":%s", rp->ai_family == AF_INET6 ? "\"inet6\"" : "\"inet\""); |
| 1188 | printf(",\"canonical\":"); |
| 1189 | if (rp->ai_canonname && *rp->ai_canonname) json_str(rp->ai_canonname); |
| 1190 | else fputs("null", stdout); |
| 1191 | putchar('}'); |
| 1192 | if (n >= MAX_RES) break; |
| 1193 | } |
| 1194 | freeaddrinfo(res); |
| 1195 | printf("],\"count\":%d}", n); |
| 1196 | } |
| 1197 | |
| 1198 | /* ------------------------------------------------------------------ */ |
| 1199 | /* action=tcp */ |
| 1200 | /* ------------------------------------------------------------------ */ |
| 1201 | |
| 1202 | static void action_tcp(const char *host_in, const char *port_s) |
| 1203 | { |
| 1204 | long long samples[MAX_SAMPLES]; |
| 1205 | int nsamp = 0; |
| 1206 | int i; |
| 1207 | long long best = -1, worst = -1, sum = 0, cnt = 0; |
| 1208 | int status = 0; /* 0 failed, 1 open, 2 timeout */ |
| 1209 | char addr[64]; |
| 1210 | char stamp[32]; |
| 1211 | char target[MAX_HOST]; |
| 1212 | char pbuf[16]; |
| 1213 | struct addrinfo *res = NULL; |
| 1214 | struct addrinfo *rp; |
| 1215 | int rc; |
| 1216 | int port; |
| 1217 | |
| 1218 | str_copy(target, sizeof target, host_in); |
| 1219 | str_lower(target); |
| 1220 | if (!valid_host(target)) { err_json(400, "invalid host"); return; } |
| 1221 | |
| 1222 | port = atoi(port_s); |
| 1223 | if (port < 1 || port > 65535) { err_json(400, "invalid port"); return; } |
| 1224 | snprintf(pbuf, sizeof pbuf, "%d", port); |
| 1225 | |
| 1226 | emit_json_head(); |
| 1227 | utc_stamp(time(NULL), stamp, sizeof stamp); |
| 1228 | |
| 1229 | rc = resolve_with_deadline(target, pbuf, &res, DNS_MS); |
| 1230 | addr[0] = '\0'; |
| 1231 | |
| 1232 | if (rc == -1) { status = 2; samples[nsamp++] = -1; } |
| 1233 | else if (rc != 0 || !res) { status = 0; samples[nsamp++] = -2; } |
| 1234 | else { |
| 1235 | for (i = 0; i < MAX_SAMPLES; i++) { |
| 1236 | long long r = -4; /* no address family could be opened */ |
| 1237 | for (rp = res; rp; rp = rp->ai_next) { |
| 1238 | r = tcp_connect_ms(rp, TCP_MS, addr, sizeof addr); |
| 1239 | if (r >= 0 || r == -2) break; /* try the next family only on socket failure */ |
| 1240 | } |
| 1241 | if (r == -1) { samples[nsamp++] = -1; status = 2; break; } |
| 1242 | samples[nsamp++] = r; |
| 1243 | if (r >= 0) { status = 1; } |
| 1244 | else if (status != 1) { status = 0; } |
| 1245 | } |
| 1246 | freeaddrinfo(res); |
| 1247 | } |
| 1248 | |
| 1249 | for (i = 0; i < nsamp; i++) { |
| 1250 | if (samples[i] >= 0) { |
| 1251 | if (best < 0 || samples[i] < best) best = samples[i]; |
| 1252 | if (worst < 0 || samples[i] > worst) worst = samples[i]; |
| 1253 | sum += samples[i]; |
| 1254 | cnt++; |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | printf("{\"ok\":true,\"action\":\"tcp\",\"host\":"); |
| 1259 | json_str(target); |
| 1260 | printf(",\"port\":%d,\"generated_at\":", port); |
| 1261 | json_str(stamp); |
| 1262 | printf(",\"open\":%s,\"status\":", status == 1 ? "true" : "false"); |
| 1263 | json_str(status == 1 ? "open" : (status == 2 ? "timeout" : "closed")); |
| 1264 | fputs(",\"address\":", stdout); |
| 1265 | if (addr[0]) json_str(addr); else fputs("null", stdout); |
| 1266 | printf(",\"samples\":["); |
| 1267 | for (i = 0; i < nsamp; i++) { |
| 1268 | if (i) putchar(','); |
| 1269 | if (samples[i] >= 0) printf("%lld", samples[i]); else fputs("null", stdout); |
| 1270 | } |
| 1271 | printf("],\"avg_ms\":"); |
| 1272 | if (cnt) printf("%.2f", (double)sum / (double)cnt); else fputs("null", stdout); |
| 1273 | printf(",\"min_ms\":"); |
| 1274 | if (best >= 0) printf("%lld", best); else fputs("null", stdout); |
| 1275 | printf(",\"max_ms\":"); |
| 1276 | if (worst >= 0) printf("%lld", worst); else fputs("null", stdout); |
| 1277 | printf(",\"timeout_ms\":%d}", TCP_MS); |
| 1278 | } |
| 1279 | |
| 1280 | /* ------------------------------------------------------------------ */ |
| 1281 | /* action=http */ |
| 1282 | /* ------------------------------------------------------------------ */ |
| 1283 | |
| 1284 | /* Plain HTTP reachability. Sends one HEAD request, reads only the status line |
| 1285 | * and the header block, never a body, and follows no redirects. There is no |
| 1286 | * TLS library in this binary, so an https:// target is reported as a TCP |
| 1287 | * connect to 443 with tls:"not_checked". */ |
| 1288 | static void action_http(const char *url_in) |
| 1289 | { |
| 1290 | url_t u; |
| 1291 | SX_SOCK_T s = SX_SOCK_INVALID; |
| 1292 | struct addrinfo *res = NULL; |
| 1293 | struct addrinfo *rp; |
| 1294 | char req[768]; |
| 1295 | char buf[2048]; |
| 1296 | size_t have = 0; |
| 1297 | int status = 0; |
| 1298 | int header_lines = 0; |
| 1299 | int got_headers = 0; |
| 1300 | long long t0, t1, t2; |
| 1301 | char stamp[32]; |
| 1302 | char pbuf[16]; |
| 1303 | int rc; |
| 1304 | |
| 1305 | if (!parse_url(url_in, &u)) { err_json(400, "invalid url"); return; } |
| 1306 | |
| 1307 | snprintf(pbuf, sizeof pbuf, "%d", u.port); |
| 1308 | rc = resolve_with_deadline(u.host_plain, pbuf, &res, DNS_MS); |
| 1309 | |
| 1310 | emit_json_head(); |
| 1311 | utc_stamp(time(NULL), stamp, sizeof stamp); |
| 1312 | |
| 1313 | printf("{\"ok\":true,\"action\":\"http\",\"url\":"); |
| 1314 | json_str(url_in); |
| 1315 | printf(",\"host\":"); |
| 1316 | json_str(u.host); |
| 1317 | printf(",\"port\":%d,\"path\":", u.port); |
| 1318 | json_str(u.path); |
| 1319 | printf(",\"tls\":"); |
| 1320 | if (u.tls) fputs("\"not_checked\"", stdout); else fputs("false", stdout); |
| 1321 | printf(",\"generated_at\":"); |
| 1322 | json_str(stamp); |
| 1323 | |
| 1324 | if (rc == -1) { |
| 1325 | printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," |
| 1326 | "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," |
| 1327 | "\"note\":\"dns resolution timed out\"}"); |
| 1328 | return; |
| 1329 | } |
| 1330 | if (rc != 0 || !res) { |
| 1331 | printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," |
| 1332 | "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," |
| 1333 | "\"note\":\"host does not resolve\"}"); |
| 1334 | return; |
| 1335 | } |
| 1336 | |
| 1337 | t0 = now_ms(); |
| 1338 | for (rp = res; rp; rp = rp->ai_next) { |
| 1339 | s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); |
| 1340 | if (s == SX_SOCK_INVALID) continue; |
| 1341 | rc = connect(s, rp->ai_addr, rp->ai_addrlen); |
| 1342 | if (rc == 0) break; |
| 1343 | sx_close_socket(s); |
| 1344 | s = SX_SOCK_INVALID; |
| 1345 | } |
| 1346 | freeaddrinfo(res); |
| 1347 | t1 = now_ms(); |
| 1348 | |
| 1349 | if (s == SX_SOCK_INVALID) { |
| 1350 | printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," |
| 1351 | "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," |
| 1352 | "\"note\":\"tcp connect failed\""); |
| 1353 | if (u.tls) |
| 1354 | fputs(",\"tls_note\":\"no TLS library: only the TCP connect to 443 was attempted\"", |
| 1355 | stdout); |
| 1356 | puts("}"); |
| 1357 | return; |
| 1358 | } |
| 1359 | |
| 1360 | if (u.tls) { |
| 1361 | /* No TLS: report the connect and stop. */ |
| 1362 | sx_close_socket(s); |
| 1363 | printf(",\"reachable\":true,\"connect_ms\":%lld,\"status\":null," |
| 1364 | "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," |
| 1365 | "\"note\":\"tcp connect succeeded; the TLS handshake was not attempted\"", |
| 1366 | (long long)(t1 - t0)); |
| 1367 | puts("}"); |
| 1368 | return; |
| 1369 | } |
| 1370 | |
| 1371 | /* Read timeout so a server that accepts but never answers cannot hang us. */ |
| 1372 | #if defined(_WIN32) |
| 1373 | { |
| 1374 | DWORD tv = (DWORD)READ_MS; |
| 1375 | setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof tv); |
| 1376 | } |
| 1377 | #else |
| 1378 | { |
| 1379 | struct timeval tv; |
| 1380 | tv.tv_sec = READ_MS / 1000; |
| 1381 | tv.tv_usec = (READ_MS % 1000) * 1000; |
| 1382 | setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); |
| 1383 | } |
| 1384 | #endif |
| 1385 | |
| 1386 | snprintf(req, sizeof req, |
| 1387 | "HEAD %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: scorpiox-bot-netcheck/1.0\r\n" |
| 1388 | "Accept: */*\r\nConnection: close\r\n\r\n", |
| 1389 | u.path, u.host); |
| 1390 | |
| 1391 | { |
| 1392 | size_t wl = strlen(req), sent = 0; |
| 1393 | while (sent < wl) { |
| 1394 | int w; |
| 1395 | #if defined(_WIN32) |
| 1396 | w = (int)send(s, req + sent, (int)(wl - sent), 0); |
| 1397 | #else |
| 1398 | w = (int)send(s, req + sent, wl - sent, 0); |
| 1399 | #endif |
| 1400 | if (w <= 0) break; |
| 1401 | sent += (size_t)w; |
| 1402 | } |
| 1403 | } |
| 1404 | |
| 1405 | t2 = now_ms(); |
| 1406 | while (have < sizeof buf - 1) { |
| 1407 | int r = (int)recv(s, buf + have, 1, 0); |
| 1408 | if (r <= 0) break; |
| 1409 | have += (size_t)r; |
| 1410 | if (have >= 4 && memcmp(buf + have - 4, "\r\n\r\n", 4) == 0) { got_headers = 1; break; } |
| 1411 | if (have >= 2 && memcmp(buf + have - 2, "\n\n", 2) == 0) { got_headers = 1; break; } |
| 1412 | if (now_ms() - t2 > READ_MS) break; |
| 1413 | } |
| 1414 | t2 = now_ms(); |
| 1415 | sx_close_socket(s); |
| 1416 | buf[have] = '\0'; |
| 1417 | |
| 1418 | printf(",\"reachable\":true,\"connect_ms\":%lld", (long long)(t1 - t0)); |
| 1419 | |
| 1420 | if (have >= 5 && strncmp(buf, "HTTP/", 5) == 0) { |
| 1421 | const char *sp = strchr(buf, ' '); |
| 1422 | if (sp) { |
| 1423 | const char *nl = strchr(sp, '\r'); |
| 1424 | char txt[64]; |
| 1425 | size_t n; |
| 1426 | if (!nl) nl = strchr(sp, '\n'); |
| 1427 | const char *rs; |
| 1428 | status = atoi(sp + 1); |
| 1429 | /* the reason phrase starts after the code and its single space */ |
| 1430 | rs = sp + 1; |
| 1431 | while (isdigit((unsigned char)*rs)) rs++; |
| 1432 | while (*rs == ' ' || *rs == '\t') rs++; |
| 1433 | n = nl ? (size_t)(nl - rs) : 0; |
| 1434 | if (n >= sizeof txt) n = sizeof txt - 1; |
| 1435 | memcpy(txt, rs, n); |
| 1436 | txt[n] = '\0'; |
| 1437 | str_trim(txt); |
| 1438 | printf(",\"status\":%d,\"status_text\":", status); |
| 1439 | json_str(txt); |
| 1440 | } else { |
| 1441 | fputs(",\"status\":null,\"status_text\":null", stdout); |
| 1442 | } |
| 1443 | } else { |
| 1444 | fputs(",\"status\":null,\"status_text\":null", stdout); |
| 1445 | } |
| 1446 | |
| 1447 | /* count header lines: everything after the status line up to the blank line */ |
| 1448 | { |
| 1449 | const char *p = strchr(buf, '\n'); |
| 1450 | if (p) { |
| 1451 | p++; |
| 1452 | for (;;) { |
| 1453 | const char *nl; |
| 1454 | while (*p == '\r' || *p == '\n') { |
| 1455 | /* a line that is only a terminator ends the header block */ |
| 1456 | if (*p == '\n') { p++; break; } |
| 1457 | p++; |
| 1458 | } |
| 1459 | if (!*p || *p == '\n') break; /* blank line = end of headers */ |
| 1460 | nl = strchr(p, '\n'); |
| 1461 | header_lines++; |
| 1462 | if (!nl) break; |
| 1463 | p = nl + 1; |
| 1464 | } |
| 1465 | } |
| 1466 | } |
| 1467 | |
| 1468 | printf(",\"header_lines\":%d,\"body_bytes_read\":0,\"read_ms\":%lld," |
| 1469 | "\"headers_complete\":%s", |
| 1470 | header_lines, (long long)(t2 - t1), got_headers ? "true" : "false"); |
| 1471 | if (status >= 300 && status < 400) |
| 1472 | fputs(",\"redirect\":\"not_followed\"", stdout); |
| 1473 | puts("}"); |
| 1474 | } |
| 1475 | |
| 1476 | /* ------------------------------------------------------------------ */ |
| 1477 | /* action=info */ |
| 1478 | /* ------------------------------------------------------------------ */ |
| 1479 | |
| 1480 | static void action_info(void) |
| 1481 | { |
| 1482 | char stamp[32]; |
| 1483 | emit_json_head(); |
| 1484 | utc_stamp(time(NULL), stamp, sizeof stamp); |
| 1485 | printf("{\"ok\":true,\"plugin\":"); |
| 1486 | json_str(PLUGIN_ID); |
| 1487 | printf(",\"slug\":"); |
| 1488 | json_str(PLUGIN_SLUG); |
| 1489 | printf(",\"version\":"); |
| 1490 | json_str(PLUGIN_VER); |
| 1491 | printf(",\"generated_at\":"); |
| 1492 | json_str(stamp); |
| 1493 | printf(",\"actions\":[\"ifaces\",\"dns\",\"tcp\",\"http\",\"info\"]"); |
| 1494 | printf(",\"tls_library\":false,\"max_samples\":%d", MAX_SAMPLES); |
| 1495 | printf(",\"dns_timeout_ms\":%d,\"tcp_timeout_ms\":%d,\"read_timeout_ms\":%d", |
| 1496 | DNS_MS, TCP_MS, READ_MS); |
| 1497 | puts("}"); |
| 1498 | } |
| 1499 | |
| 1500 | static int is_post_request(void) |
| 1501 | { |
| 1502 | const char *m = getenv("REQUEST_METHOD"); |
| 1503 | return m && (strcmp(m, "POST") == 0 || strcmp(m, "PUT") == 0); |
| 1504 | } |
| 1505 | |
| 1506 | static int mode_meta(void) |
| 1507 | { |
| 1508 | puts("{\"name\":\"netcheck\",\"desc\":\"Net checks\"}"); |
| 1509 | return 0; |
| 1510 | } |
| 1511 | |
| 1512 | static int mode_json(const char *qs) |
| 1513 | { |
| 1514 | char action[64]; |
| 1515 | char host[MAX_HOST]; |
| 1516 | char port_s[16]; |
| 1517 | char url_s[MAX_LINE]; |
| 1518 | |
| 1519 | get_query_val(qs, "action", action, sizeof action); |
| 1520 | str_lower(action); |
| 1521 | |
| 1522 | if (action[0] == '\0') { action_info(); return 0; } |
| 1523 | |
| 1524 | if (strcmp(action, "ifaces") == 0) { action_ifaces(); return 0; } |
| 1525 | |
| 1526 | if (strcmp(action, "dns") == 0) { |
| 1527 | if (!get_query_val(qs, "host", host, sizeof host)) { |
| 1528 | err_json(400, "host required"); return 0; |
| 1529 | } |
| 1530 | action_dns(host); |
| 1531 | return 0; |
| 1532 | } |
| 1533 | |
| 1534 | if (strcmp(action, "tcp") == 0) { |
| 1535 | if (!get_query_val(qs, "host", host, sizeof host)) { |
| 1536 | err_json(400, "host required"); return 0; |
| 1537 | } |
| 1538 | if (!get_query_val(qs, "port", port_s, sizeof port_s)) { |
| 1539 | err_json(400, "port required"); return 0; |
| 1540 | } |
| 1541 | action_tcp(host, port_s); |
| 1542 | return 0; |
| 1543 | } |
| 1544 | |
| 1545 | if (strcmp(action, "http") == 0) { |
| 1546 | if (!get_query_val(qs, "url", url_s, sizeof url_s)) { |
| 1547 | err_json(400, "url required"); return 0; |
| 1548 | } |
| 1549 | action_http(url_s); |
| 1550 | return 0; |
| 1551 | } |
| 1552 | |
| 1553 | if (strcmp(action, "info") == 0) { action_info(); return 0; } |
| 1554 | |
| 1555 | err_json(400, "unknown action"); |
| 1556 | return 0; |
| 1557 | } |
| 1558 | |
| 1559 | /* ------------------------------------------------------------------ */ |
| 1560 | /* HTML mode */ |
| 1561 | /* ------------------------------------------------------------------ */ |
| 1562 | |
| 1563 | /* Split UI_HTML on the two control-byte placeholders and expand them into the |
| 1564 | * theme macros, so the page and the bot palette can never drift. */ |
| 1565 | static void emit_ui(void) |
| 1566 | { |
| 1567 | const char *p = UI_HTML; |
| 1568 | |
| 1569 | while (*p) { |
| 1570 | if (*p == '\001') { |
| 1571 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS |
| 1572 | ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}" |
| 1573 | "</style>", stdout); |
| 1574 | p++; |
| 1575 | } else if (*p == '\002') { |
| 1576 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 1577 | p++; |
| 1578 | } else { |
| 1579 | putchar(*p++); |
| 1580 | } |
| 1581 | } |
| 1582 | } |
| 1583 | |
| 1584 | static int mode_html(int embed) |
| 1585 | { |
| 1586 | (void)embed; |
| 1587 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1588 | "Cache-Control: no-store\r\n" |
| 1589 | "X-Content-Type-Options: nosniff\r\n" |
| 1590 | "X-Frame-Options: SAMEORIGIN\r\n" |
| 1591 | "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " |
| 1592 | "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " |
| 1593 | "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); |
| 1594 | emit_ui(); |
| 1595 | return 0; |
| 1596 | } |
| 1597 | |
| 1598 | int main(int argc, char **argv) |
| 1599 | { |
| 1600 | const char *qs; |
| 1601 | int embed; |
| 1602 | |
| 1603 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || |
| 1604 | (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) |
| 1605 | return mode_meta(); |
| 1606 | |
| 1607 | #if defined(_WIN32) |
| 1608 | { |
| 1609 | WSADATA wsa; |
| 1610 | if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) |
| 1611 | return mode_meta(); |
| 1612 | } |
| 1613 | #endif |
| 1614 | |
| 1615 | require_node_auth(); |
| 1616 | |
| 1617 | qs = getenv("QUERY_STRING"); |
| 1618 | if (!qs) qs = ""; |
| 1619 | |
| 1620 | if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) |
| 1621 | return mode_json(qs); |
| 1622 | |
| 1623 | embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); |
| 1624 | return mode_html(embed); |
| 1625 | } |