/* * plugin_netcheck - SCORPIOX BOT open-source network diagnostics from this node * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata * 2. ?action=ifaces | dns&host= | tcp&host=&port= | http&url= | info -> JSON node API * 3. GET (default) -> responsive HTML diagnostics UI * * Everything it reports is about the node it runs on: the interfaces and their * addresses, the configured DNS servers, a name resolution, a TCP connect * latency, and a plain-HTTP reachability check (status line and headers only, * body never read). The only outbound connections are the ones the node owner * asks for by typing a host into the box, and every one of them sits behind * node authentication, so the plugin is not a blind SSRF pivot. * * Interfaces come from getifaddrs(3) on Linux/macOS and from * GetAdaptersAddresses on Windows. DNS uses getaddrinfo guarded by a deadline * (a worker thread, because the resolver itself is blocking). TCP latency is * the mean of three non-blocking connect() round trips. HTTP is a raw HEAD * request over TCP - there is no TLS library anywhere in this binary, so an * https:// target is reported as a TCP connect to port 443 with * "tls":"not_checked". * * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang * and x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must come before every include: iphlpapi.h and ws2tcpip.h gate * GetAdaptersAddresses and the IPv6 helpers on it, and MinGW defaults to 0x502 * (Server 2003) which hides all of them. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include # include # define sx_popen _popen # define sx_pclose _pclose # define sx_close_socket closesocket # define SX_SOCK_T SOCKET # define SX_SOCK_INVALID INVALID_SOCKET #else # include # include # include # include # include # include # include # include # include # include # include # include # define sx_popen popen # define sx_pclose pclose # define sx_close_socket close # define SX_SOCK_T int # define SX_SOCK_INVALID (-1) #endif #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "netcheck" #define PLUGIN_ID "plugin_netcheck" #define PLUGIN_VER "1.0.0" #define MAX_IFACES 128 #define MAX_LINE 1024 #define MAX_HOST 256 #define MAX_PATHZ 256 #define MAX_SAMPLES 3 #define MAX_RES 16 /* Hard ceilings so a typed host cannot make the plugin hang forever. Each * phase (resolve, connect, read) gets its own budget. */ #define DNS_MS 3000 #define TCP_MS 3000 #define READ_MS 2000 /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs) return 0; klen = strlen(key); p = qs; while (*p) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static void json_str(const char *s) { putchar('"'); for (; s && *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': fputs("\\\"", stdout); break; case '\\': fputs("\\\\", stdout); break; case '\n': fputs("\\n", stdout); break; case '\r': fputs("\\r", stdout); break; case '\t': fputs("\\t", stdout); break; default: if (c < 0x20) printf("\\u%04x", c); else putchar(c); } } putchar('"'); } static void str_copy(char *dst, size_t sz, const char *src) { size_t n; if (!dst || sz == 0) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= sz) n = sz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static void str_trim(char *s) { char *p; size_t n; if (!s) return; p = s; while (*p && isspace((unsigned char)*p)) p++; if (p != s) memmove(s, p, strlen(p) + 1); n = strlen(s); while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; } static void str_lower(char *s) { for (; s && *s; s++) *s = (char)tolower((unsigned char)*s); } static long long now_ms(void) { #if defined(_WIN32) FILETIME ft; ULARGE_INTEGER u; GetSystemTimeAsFileTime(&ft); u.LowPart = ft.dwLowDateTime; u.HighPart = ft.dwHighDateTime; return (long long)(u.QuadPart / 10000ULL); #else struct timeval tv; gettimeofday(&tv, NULL); return (long long)tv.tv_sec * 1000LL + (long long)(tv.tv_usec / 1000); #endif } static void utc_stamp(time_t t, char *buf, size_t sz) { struct tm tmv; #if defined(_WIN32) gmtime_s(&tmv, &t); #else gmtime_r(&t, &tmv); #endif strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); } /* ------------------------------------------------------------------ */ /* Node authentication */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; const char *qs; char qpwd[256]; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Address formatting */ /* ------------------------------------------------------------------ */ /* Render a sockaddr into a printable address string. Returns the family * (AF_INET / AF_INET6) or 0 when the address cannot be rendered. */ static int addr_text(const struct sockaddr *sa, char *out, size_t outsz) { if (!sa || !out || outsz == 0) return 0; out[0] = '\0'; switch (sa->sa_family) { case AF_INET: { const struct sockaddr_in *in = (const struct sockaddr_in *)sa; if (inet_ntop(AF_INET, &in->sin_addr, out, (unsigned int)outsz)) return AF_INET; return 0; } case AF_INET6: { const struct sockaddr_in6 *in6 = (const struct sockaddr_in6 *)sa; if (inet_ntop(AF_INET6, &in6->sin6_addr, out, (unsigned int)outsz)) return AF_INET6; return 0; } default: return 0; } } static int netmask_text(const struct sockaddr *sa, char *out, size_t outsz) { if (!sa || sa->sa_family != AF_INET || !out || outsz == 0) return 0; return inet_ntop(AF_INET, &((const struct sockaddr_in *)sa)->sin_addr, out, (unsigned int)outsz) ? 1 : 0; } /* ------------------------------------------------------------------ */ /* Interface collection */ /* ------------------------------------------------------------------ */ typedef struct { char name[64]; char addr[64]; char mask[64]; char broad[64]; int family; /* 4 or 6 */ int loopback; int up; int running; } iface_t; static iface_t g_ifaces[MAX_IFACES]; static int g_iface_count; static int is_loopback_text(const char *a) { if (!a) return 0; if (strncmp(a, "127.", 4) == 0) return 1; if (strcmp(a, "::1") == 0) return 1; return 0; } static void iface_add(const char *name, const struct sockaddr *sa, const struct sockaddr *mask, const struct sockaddr *broad, int up, int running) { iface_t *f; char a[64]; int fam; if (g_iface_count >= MAX_IFACES) return; fam = addr_text(sa, a, sizeof a); if (!fam) return; f = &g_ifaces[g_iface_count++]; memset(f, 0, sizeof *f); str_copy(f->name, sizeof f->name, name ? name : "?"); str_copy(f->addr, sizeof f->addr, a); f->family = (fam == AF_INET6) ? 6 : 4; f->loopback = is_loopback_text(f->addr); f->up = up; f->running = running; if (mask) netmask_text(mask, f->mask, sizeof f->mask); if (broad) addr_text(broad, f->broad, sizeof f->broad); } #if defined(_WIN32) /* ASCII-fold a wide adapter name; Windows adapter names are alphanumeric with * spaces, dashes and dots, so a byte-per-wchar fold is lossless in practice. */ static void wide_to_ascii(const wchar_t *w, char *out, size_t outsz) { size_t i = 0; if (outsz) out[0] = '\0'; if (!w || !out || outsz == 0) return; for (i = 0; i + 1 < outsz && w[i]; i++) out[i] = (char)((unsigned char)w[i]); out[i] = '\0'; } static PIP_ADAPTER_ADDRESSES fetch_adapters(ULONG flags) { ULONG want = 0; ULONG rc; PIP_ADAPTER_ADDRESSES adapters; rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, NULL, &want); if (rc != ERROR_SUCCESS && rc != ERROR_BUFFER_OVERFLOW) return NULL; if (want < 2048) want = 2048; adapters = (PIP_ADAPTER_ADDRESSES)malloc(want + 1024); if (!adapters) return NULL; rc = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapters, &want); if (rc != ERROR_SUCCESS) { free(adapters); return NULL; } return adapters; } static void collect_ifaces_windows(void) { PIP_ADAPTER_ADDRESSES adapters; PIP_ADAPTER_ADDRESSES a; PIP_ADAPTER_UNICAST_ADDRESS u; adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER); if (!adapters) return; for (a = adapters; a; a = a->Next) { char ascii[64]; const wchar_t *friendly = a->FriendlyName ? a->FriendlyName : NULL; int up = (a->OperStatus == IfOperStatusUp); if (friendly) wide_to_ascii(friendly, ascii, sizeof ascii); else if (a->AdapterName) str_copy(ascii, sizeof ascii, a->AdapterName); else str_copy(ascii, sizeof ascii, "adapter"); for (u = a->FirstUnicastAddress; u; u = u->Next) { const struct sockaddr *sa = u->Address.lpSockaddr; struct sockaddr_storage nm; struct sockaddr *nmp = NULL; /* SOCKET_ADDRESS is {lpSockaddr, iSockaddrLength}, not an inline * sockaddr, so the family has to be read through the pointer and * guarded by the length the OS reported. */ if (!sa || u->Address.iSockaddrLength < (int)sizeof(struct sockaddr)) continue; /* OnLinkPrefixLength is a CIDR length, not a dotted mask. Expand it * into a dotted netmask so the table has something familiar to show. */ memset(&nm, 0, sizeof nm); if (sa->sa_family == AF_INET && u->OnLinkPrefixLength < 32) { struct sockaddr_in *in4 = (struct sockaddr_in *)&nm; in4->sin_family = AF_INET; in4->sin_addr.s_addr = htonl(0xFFFFFFFFUL << (32 - u->OnLinkPrefixLength)); nmp = (struct sockaddr *)in4; } iface_add(ascii, sa, nmp, NULL, up, up); } } free(adapters); } #else static void collect_ifaces_posix(void) { struct ifaddrs *list = NULL; struct ifaddrs *i; if (getifaddrs(&list) != 0 || !list) return; for (i = list; i; i = i->ifa_next) { int up, running; if (!i->ifa_addr) continue; up = (i->ifa_flags & IFF_UP) != 0; running = (i->ifa_flags & IFF_RUNNING) != 0; iface_add(i->ifa_name, i->ifa_addr, i->ifa_netmask, i->ifa_broadaddr, up, running); } freeifaddrs(list); } #endif /* ------------------------------------------------------------------ */ /* Host validation */ /* ------------------------------------------------------------------ */ /* A host is accepted only as a DNS hostname label sequence or a literal IPv4 / * IPv6 address. That keeps typed input from smuggling a URL, a path, or a * shell metacharacter into anything we do with it. */ static int valid_hostname(const char *s) { size_t i, n = strlen(s); if (n == 0 || n > 253) return 0; if (s[0] == '.' || s[n - 1] == '.') return 0; for (i = 0; i < n; i++) { unsigned char c = (unsigned char)s[i]; if (c == '.') { if (i == 0 || s[i - 1] == '.') return 0; continue; } if (!isalnum(c) && c != '-' && c != '_') return 0; } return 1; } static int looks_ipv4(const char *s) { struct sockaddr_in in; return inet_pton(AF_INET, s, &in.sin_addr) == 1; } static int looks_ipv6(const char *s) { struct sockaddr_in6 in6; return inet_pton(AF_INET6, s, &in6.sin6_addr) == 1; } static int valid_host(const char *s) { if (!s || !*s) return 0; if (looks_ipv4(s) || looks_ipv6(s)) return 1; return valid_hostname(s); } /* ------------------------------------------------------------------ */ /* Test hooks */ /* ------------------------------------------------------------------ */ /* The offline suite needs deterministic, network-free answers, so three * environment hooks exist. They are only consulted when the variable is set, * which is never the case on a real node, and they let the suite exercise the * timeout and the multi-address paths without a live resolver. * * NETCHECK_MOCK_IFACES "lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,eth0|..." * name|address|netmask|broadcast|family|up * NETCHECK_MOCK_DNS "host=addr,addr;host2=addr" (family inferred) * NETCHECK_MOCK_TIMEOUT 1 -> every resolution reports a deadline miss */ static int mock_timeout_enabled(void) { const char *v = getenv("NETCHECK_MOCK_TIMEOUT"); return v && v[0] == '1'; } /* Fill *res with a synthetic addrinfo chain for host. Returns 0 on success. */ static int mock_resolve(const char *host, const char *port, struct addrinfo **res) { const char *map = getenv("NETCHECK_MOCK_DNS"); char entry[512]; char addrs[512]; size_t hl, el, i; struct addrinfo *head = NULL, *tail = NULL; int count = 0; int mock_port = 0; if (!map || !host) return -1; if (port) { long v = strtol(port, NULL, 10); if (v >= 1 && v <= 65535) mock_port = (int)v; } hl = strlen(host); i = 0; for (;;) { size_t j = i; char *eq; size_t k, al; struct addrinfo *ai; while (map[j] && map[j] != ';') j++; el = j - i; if (el > 0 && el < sizeof entry) { memcpy(entry, map + i, el); entry[el] = 0; eq = strchr(entry, '='); if (eq && (size_t)(eq - entry) == hl && strncmp(entry, host, hl) == 0) { str_copy(addrs, sizeof addrs, eq + 1); al = strlen(addrs); k = 0; while (k < al) { char tok[128]; size_t tl = 0; struct sockaddr_in *in4; struct sockaddr_in6 *in6; while (k < al && addrs[k] != ',') { if (tl < sizeof tok - 1) tok[tl++] = addrs[k]; k++; } tok[tl] = 0; if (k < al) k++; /* skip the comma */ while (tl > 0 && isspace((unsigned char)tok[tl - 1])) tok[--tl] = 0; if (tl == 0) continue; ai = (struct addrinfo *)calloc(1, sizeof *ai); if (!ai) return -2; if (looks_ipv4(tok)) { in4 = (struct sockaddr_in *)calloc(1, sizeof *in4); if (!in4) { free(ai); return -2; } in4->sin_family = AF_INET; in4->sin_port = htons((unsigned short)mock_port); inet_pton(AF_INET, tok, &in4->sin_addr); ai->ai_family = AF_INET; ai->ai_socktype = SOCK_STREAM; ai->ai_addr = (struct sockaddr *)in4; ai->ai_addrlen = sizeof *in4; } else if (looks_ipv6(tok)) { in6 = (struct sockaddr_in6 *)calloc(1, sizeof *in6); if (!in6) { free(ai); return -2; } in6->sin6_family = AF_INET6; in6->sin6_port = htons((unsigned short)mock_port); inet_pton(AF_INET6, tok, &in6->sin6_addr); ai->ai_family = AF_INET6; ai->ai_socktype = SOCK_STREAM; ai->ai_addr = (struct sockaddr *)in6; ai->ai_addrlen = sizeof *in6; } else { free(ai); continue; } if (tail) tail->ai_next = ai; else head = ai; tail = ai; if (++count >= MAX_RES) break; } *res = head; return 0; } } if (map[j] == ';') { i = j + 1; continue; } break; } return -1; } /* Synthetic interface table for the offline suite. * Format: name|address|netmask|broadcast|family|up (entries separated by ','). * A pipe is used between fields because an IPv6 address is full of colons. */ static int mock_ifaces(void) { const char *spec = getenv("NETCHECK_MOCK_IFACES"); char tok[256]; char *parts[6]; size_t i = 0, n; if (!spec) return 0; n = strlen(spec); i = 0; while (i < n) { size_t tl = 0, pi; iface_t *f; struct sockaddr_storage sa; struct sockaddr_storage nm; struct sockaddr *nmp = NULL; char *pp; int fam = 0; while (i < n && spec[i] != ',') { if (tl < sizeof tok - 1) tok[tl++] = spec[i]; i++; } tok[tl] = 0; if (i < n) i++; /* skip the comma */ if (tl == 0) continue; for (pi = 0; pi < 6; pi++) parts[pi] = (char *)""; parts[0] = tok; pi = 1; pp = tok; while (pp && pi < 6) { char *nx = strchr(pp, '|'); if (!nx) break; *nx = 0; parts[pi++] = nx + 1; pp = nx + 1; } for (; pi < 6; pi++) parts[pi] = (char *)""; memset(&sa, 0, sizeof sa); memset(&nm, 0, sizeof nm); if (looks_ipv4(parts[1])) { struct sockaddr_in *in4 = (struct sockaddr_in *)&sa; in4->sin_family = AF_INET; inet_pton(AF_INET, parts[1], &in4->sin_addr); fam = 4; if (parts[2][0] && looks_ipv4(parts[2])) { struct sockaddr_in *m4 = (struct sockaddr_in *)&nm; m4->sin_family = AF_INET; inet_pton(AF_INET, parts[2], &m4->sin_addr); nmp = (struct sockaddr *)m4; } } else if (looks_ipv6(parts[1])) { struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&sa; in6->sin6_family = AF_INET6; inet_pton(AF_INET6, parts[1], &in6->sin6_addr); fam = 6; } else { continue; } if (g_iface_count >= MAX_IFACES) break; f = &g_ifaces[g_iface_count++]; memset(f, 0, sizeof *f); str_copy(f->name, sizeof f->name, parts[0]); str_copy(f->addr, sizeof f->addr, parts[1]); f->family = fam; f->loopback = is_loopback_text(f->addr); f->up = parts[5][0] == '1'; f->running = f->up; if (nmp) netmask_text(nmp, f->mask, sizeof f->mask); if (parts[3][0]) str_copy(f->broad, sizeof f->broad, parts[3]); } return 1; } static void collect_ifaces(void) { g_iface_count = 0; if (mock_ifaces()) return; #if defined(_WIN32) collect_ifaces_windows(); #else collect_ifaces_posix(); #endif } /* ------------------------------------------------------------------ */ /* DNS server discovery */ /* ------------------------------------------------------------------ */ #define MAX_NS 16 static char g_ns[MAX_NS][64]; static int g_ns_count; static void ns_add(const char *s) { char buf[64]; int i; if (!s) return; str_copy(buf, sizeof buf, s); str_trim(buf); if (!buf[0]) return; for (i = 0; i < g_ns_count; i++) if (strcmp(g_ns[i], buf) == 0) return; if (g_ns_count >= MAX_NS) return; str_copy(g_ns[g_ns_count++], sizeof g_ns[0], buf); } static void discover_nameservers(void) { g_ns_count = 0; #if defined(_WIN32) { /* The interface query above deliberately skipped the DNS server list, * so re-query with the flag left on rather than parsing a text tool. */ PIP_ADAPTER_ADDRESSES adapters = fetch_adapters(GAA_FLAG_INCLUDE_PREFIX); PIP_ADAPTER_ADDRESSES a; PIP_ADAPTER_DNS_SERVER_ADDRESS_XP d; if (adapters) { for (a = adapters; a; a = a->Next) for (d = a->FirstDnsServerAddress; d; d = d->Next) { char txt[64]; const struct sockaddr *sa = d->Address.lpSockaddr; if (!sa || d->Address.iSockaddrLength < (int)sizeof(struct sockaddr)) continue; if (addr_text(sa, txt, sizeof txt)) ns_add(txt); } free(adapters); } } #else { FILE *f = fopen("/etc/resolv.conf", "r"); char line[MAX_LINE]; if (f) { while (fgets(line, sizeof line, f)) { char *p = line; if (*p == '#') continue; if (strncmp(p, "nameserver", 10) == 0) { p += 10; while (*p == ' ' || *p == '\t') p++; ns_add(p); } } fclose(f); } } #endif #if defined(__APPLE__) /* macOS keeps /etc/resolv.conf as a symlink to a rotating stub; scutil is * the authoritative source. Fixed argv - no user input reaches the shell. * scutil lives in /usr/sbin on macOS (measured on the MacBook builder), so * both absolute spellings are tried rather than trusting one. */ { static const char *SCUTIL_PATHS[] = {"/usr/sbin/scutil", "/usr/bin/scutil"}; FILE *f = NULL; char line[MAX_LINE]; int si; for (si = 0; si < 2 && !f; si++) { char cmd[64]; snprintf(cmd, sizeof cmd, "%s --dns", SCUTIL_PATHS[si]); f = sx_popen(cmd, "r"); } if (f) { while (fgets(line, sizeof line, f)) { const char *p = strstr(line, "nameserver["); char srv[64]; size_t i = 0; if (!p) continue; p += 11; while (*p && *p != ']' && i < sizeof srv - 1) srv[i++] = *p++; srv[i] = '\0'; str_trim(srv); if (srv[0]) ns_add(srv); } sx_pclose(f); } } #endif } /* ------------------------------------------------------------------ */ /* Deadline-guarded DNS */ /* ------------------------------------------------------------------ */ /* getaddrinfo is blocking and has no timeout argument, so the deadline lives * in a worker thread. On timeout the thread is left running: this process is a * CGI child that exits as soon as the request is answered, so the leak is * bounded by the request itself. */ typedef struct { const char *host; const char *port; struct addrinfo *res; int rc; int done; } resolve_job; #if defined(_WIN32) static DWORD WINAPI resolve_thread(LPVOID arg) { resolve_job *j = (resolve_job *)arg; struct addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); j->done = 1; return 0; } static int resolve_with_deadline(const char *host, const char *port, struct addrinfo **res, int timeout_ms) { resolve_job job; HANDLE th; DWORD wait; if (mock_timeout_enabled()) return -1; if (mock_resolve(host, port, res) == 0) return 0; job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; th = CreateThread(NULL, 0, resolve_thread, &job, 0, NULL); if (!th) return -4; wait = WaitForSingleObject(th, (DWORD)timeout_ms); if (wait == WAIT_TIMEOUT) { CloseHandle(th); return -1; } CloseHandle(th); *res = job.res; return job.rc; } #else static void *resolve_thread(void *arg) { resolve_job *j = (resolve_job *)arg; struct addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; j->rc = getaddrinfo(j->host, j->port, &hints, &j->res); j->done = 1; return NULL; } static int resolve_with_deadline(const char *host, const char *port, struct addrinfo **res, int timeout_ms) { resolve_job job; pthread_t th; long long deadline = now_ms() + timeout_ms; if (mock_timeout_enabled()) return -1; if (mock_resolve(host, port, res) == 0) return 0; job.host = host; job.port = port; job.res = NULL; job.rc = 0; job.done = 0; if (pthread_create(&th, NULL, resolve_thread, &job) != 0) return -4; while (!job.done) { if (now_ms() >= deadline) return -1; /* thread keeps running; process exits soon */ usleep(20000); } pthread_join(th, NULL); *res = job.res; return job.rc; } #endif /* ------------------------------------------------------------------ */ /* TCP connect with a deadline */ /* ------------------------------------------------------------------ */ /* Returns >=0 connect latency in ms, -1 timeout, -2 connect failed/refused, * -3 resolution failed, -4 socket/thread failure. Writes the resolved address * into addr_out when available. */ static int tcp_connect_ms(const struct addrinfo *rp, int timeout_ms, char *addr_out, size_t addr_sz) { SX_SOCK_T s; long long start; int rc; if (addr_out && addr_sz) addr_out[0] = '\0'; s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (s == SX_SOCK_INVALID) return -4; /* Non-blocking so connect() returns immediately and select() enforces the * deadline. A blocking connect on some stacks ignores the deadline. */ #if defined(_WIN32) { u_long nb = 1; ioctlsocket(s, FIONBIO, &nb); } #else { int fl = fcntl(s, F_GETFL, 0); if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK); } #endif start = now_ms(); rc = connect(s, rp->ai_addr, rp->ai_addrlen); if (rc != 0) { #if defined(_WIN32) int inprogress = (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEALREADY); #else int inprogress = (errno == EINPROGRESS || errno == EALREADY || errno == EWOULDBLOCK); #endif if (!inprogress) { sx_close_socket(s); return -2; } { fd_set wfds; struct timeval tv; int sr; FD_ZERO(&wfds); FD_SET(s, &wfds); tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; sr = select((int)s + 1, NULL, &wfds, NULL, &tv); if (sr <= 0) { sx_close_socket(s); return -1; } { int soerr = 0; #if defined(_WIN32) int sl = sizeof soerr; #else socklen_t sl = sizeof soerr; #endif if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &sl) != 0 || soerr != 0) { sx_close_socket(s); return -2; } } } } rc = (int)(now_ms() - start); if (rc < 0) rc = 0; addr_text(rp->ai_addr, addr_out, addr_sz); sx_close_socket(s); return rc; } /* ------------------------------------------------------------------ */ /* URL parsing for the http action */ /* ------------------------------------------------------------------ */ typedef struct { char scheme[8]; char host[MAX_HOST]; /* bracketed when it is an IPv6 literal */ char host_plain[MAX_HOST];/* bare address, for getaddrinfo */ int port; char path[MAX_PATHZ]; int tls; } url_t; static int parse_url(const char *in, url_t *u) { const char *p = in; const char *hs, *he, *ps; size_t n; memset(u, 0, sizeof *u); if (!in || !*in) return 0; if (strncmp(p, "http://", 7) == 0) { str_copy(u->scheme, sizeof u->scheme, "http"); u->tls = 0; p += 7; } else if (strncmp(p, "https://", 8) == 0) { str_copy(u->scheme, sizeof u->scheme, "https"); u->tls = 1; p += 8; } else { return 0; } hs = p; he = p; while (*he && *he != '/' && *he != '?' && *he != '#') he++; ps = he; /* the path starts at the first '/', not at the port */ /* strip userinfo */ { const char *at = NULL, *q; for (q = hs; q < he; q++) if (*q == '@') at = q; if (at) hs = at + 1; } /* split an optional :port. Scan right-to-left for the last colon outside * IPv6 brackets: an unbracketed IPv6 literal (127.0.0.1:80 style aside) * contains several colons, and the port is always the final one. */ { const char *col = NULL; intptr_t qi = (intptr_t)(he - hs) - 1; while (qi >= 0) { char c = hs[qi]; if (c == ']') { qi--; continue; } if (c == '[') break; /* bracketed IPv6, no plain port colon */ if (c == ':') { col = hs + qi; break; } if (c == '/' || c == '?' || c == '#') break; qi--; } if (col) { long v; char pbuf[16]; size_t pn = (size_t)(he - col - 1); size_t k; if (pn == 0 || pn >= sizeof pbuf) return 0; memcpy(pbuf, col + 1, pn); pbuf[pn] = '\0'; for (k = 0; k < pn; k++) if (!isdigit((unsigned char)pbuf[k])) return 0; v = strtol(pbuf, NULL, 10); if (v < 1 || v > 65535) return 0; u->port = (int)v; he = col; } else { u->port = u->tls ? 443 : 80; } } n = (size_t)(he - hs); if (n == 0 || n >= sizeof u->host) return 0; memcpy(u->host, hs, n); u->host[n] = '\0'; /* bare address for the resolver */ if (u->host[0] == '[' && u->host[n - 1] == ']') { if (n < 3 || n - 2 >= sizeof u->host_plain) return 0; memcpy(u->host_plain, u->host + 1, n - 2); u->host_plain[n - 2] = '\0'; if (!looks_ipv6(u->host_plain)) return 0; } else { str_copy(u->host_plain, sizeof u->host_plain, u->host); if (!valid_host(u->host_plain)) return 0; } /* path */ { const char *e = ps; while (*e && *e != '?' && *e != '#') e++; n = (size_t)(e - ps); if (n == 0) { str_copy(u->path, sizeof u->path, "/"); } else { if (n >= sizeof u->path) n = sizeof u->path - 1; memcpy(u->path, ps, n); u->path[n] = '\0'; if (u->path[0] != '/') return 0; } } return 1; } /* ------------------------------------------------------------------ */ /* JSON helpers */ /* ------------------------------------------------------------------ */ static void emit_json_head(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void err_json(int status, const char *msg) { printf("Status: %d %s\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":", status, status == 400 ? "Bad Request" : "Internal Error"); json_str(msg); puts("}"); } /* ------------------------------------------------------------------ */ /* action=ifaces */ /* ------------------------------------------------------------------ */ static void action_ifaces(void) { int i; char stamp[32]; collect_ifaces(); discover_nameservers(); emit_json_head(); utc_stamp(time(NULL), stamp, sizeof stamp); printf("{\"ok\":true,\"action\":\"ifaces\",\"generated_at\":"); json_str(stamp); printf(",\"count\":%d,\"interfaces\":[", g_iface_count); for (i = 0; i < g_iface_count; i++) { const iface_t *f = &g_ifaces[i]; if (i) putchar(','); printf("{\"name\":"); json_str(f->name); printf(",\"address\":"); json_str(f->addr); printf(",\"family\":%d,\"netmask\":", f->family); if (f->mask[0]) json_str(f->mask); else fputs("null", stdout); printf(",\"broadcast\":"); if (f->broad[0]) json_str(f->broad); else fputs("null", stdout); printf(",\"loopback\":%s,\"up\":%s,\"running\":%s}", f->loopback ? "true" : "false", f->up ? "true" : "false", f->running ? "true" : "false"); } printf("],\"nameservers\":["); for (i = 0; i < g_ns_count; i++) { if (i) putchar(','); json_str(g_ns[i]); } printf("],\"nameserver_count\":%d}", g_ns_count); } /* ------------------------------------------------------------------ */ /* action=dns */ /* ------------------------------------------------------------------ */ static void action_dns(const char *host_in) { struct addrinfo *res = NULL; struct addrinfo *rp; char stamp[32]; char target[MAX_HOST]; int n = 0; long long t0, t1; int rc; str_copy(target, sizeof target, host_in); str_lower(target); if (!target[0]) { err_json(400, "host required"); return; } if (!valid_host(target)) { err_json(400, "invalid host"); return; } emit_json_head(); utc_stamp(time(NULL), stamp, sizeof stamp); t0 = now_ms(); rc = resolve_with_deadline(target, NULL, &res, DNS_MS); t1 = now_ms(); printf("{\"ok\":true,\"action\":\"dns\",\"host\":"); json_str(target); printf(",\"generated_at\":"); json_str(stamp); printf(",\"timeout_ms\":%d", DNS_MS); if (rc == -1) { printf(",\"resolved\":false,\"timeout\":true,\"code\":null," "\"latency_ms\":%lld,\"results\":[],\"count\":0}", (long long)(t1 - t0)); return; } if (rc != 0 || !res) { printf(",\"resolved\":false,\"timeout\":false,\"code\":%d," "\"latency_ms\":%lld,\"results\":[],\"count\":0}", rc, (long long)(t1 - t0)); return; } printf(",\"resolved\":true,\"timeout\":false,\"code\":0," "\"latency_ms\":%lld,\"results\":[", (long long)(t1 - t0)); for (rp = res; rp; rp = rp->ai_next) { char txt[64]; if (!addr_text(rp->ai_addr, txt, sizeof txt)) continue; if (n) putchar(','); n++; printf("{\"address\":"); json_str(txt); printf(",\"family\":%s", rp->ai_family == AF_INET6 ? "\"inet6\"" : "\"inet\""); printf(",\"canonical\":"); if (rp->ai_canonname && *rp->ai_canonname) json_str(rp->ai_canonname); else fputs("null", stdout); putchar('}'); if (n >= MAX_RES) break; } freeaddrinfo(res); printf("],\"count\":%d}", n); } /* ------------------------------------------------------------------ */ /* action=tcp */ /* ------------------------------------------------------------------ */ static void action_tcp(const char *host_in, const char *port_s) { long long samples[MAX_SAMPLES]; int nsamp = 0; int i; long long best = -1, worst = -1, sum = 0, cnt = 0; int status = 0; /* 0 failed, 1 open, 2 timeout */ char addr[64]; char stamp[32]; char target[MAX_HOST]; char pbuf[16]; struct addrinfo *res = NULL; struct addrinfo *rp; int rc; int port; str_copy(target, sizeof target, host_in); str_lower(target); if (!valid_host(target)) { err_json(400, "invalid host"); return; } port = atoi(port_s); if (port < 1 || port > 65535) { err_json(400, "invalid port"); return; } snprintf(pbuf, sizeof pbuf, "%d", port); emit_json_head(); utc_stamp(time(NULL), stamp, sizeof stamp); rc = resolve_with_deadline(target, pbuf, &res, DNS_MS); addr[0] = '\0'; if (rc == -1) { status = 2; samples[nsamp++] = -1; } else if (rc != 0 || !res) { status = 0; samples[nsamp++] = -2; } else { for (i = 0; i < MAX_SAMPLES; i++) { long long r = -4; /* no address family could be opened */ for (rp = res; rp; rp = rp->ai_next) { r = tcp_connect_ms(rp, TCP_MS, addr, sizeof addr); if (r >= 0 || r == -2) break; /* try the next family only on socket failure */ } if (r == -1) { samples[nsamp++] = -1; status = 2; break; } samples[nsamp++] = r; if (r >= 0) { status = 1; } else if (status != 1) { status = 0; } } freeaddrinfo(res); } for (i = 0; i < nsamp; i++) { if (samples[i] >= 0) { if (best < 0 || samples[i] < best) best = samples[i]; if (worst < 0 || samples[i] > worst) worst = samples[i]; sum += samples[i]; cnt++; } } printf("{\"ok\":true,\"action\":\"tcp\",\"host\":"); json_str(target); printf(",\"port\":%d,\"generated_at\":", port); json_str(stamp); printf(",\"open\":%s,\"status\":", status == 1 ? "true" : "false"); json_str(status == 1 ? "open" : (status == 2 ? "timeout" : "closed")); fputs(",\"address\":", stdout); if (addr[0]) json_str(addr); else fputs("null", stdout); printf(",\"samples\":["); for (i = 0; i < nsamp; i++) { if (i) putchar(','); if (samples[i] >= 0) printf("%lld", samples[i]); else fputs("null", stdout); } printf("],\"avg_ms\":"); if (cnt) printf("%.2f", (double)sum / (double)cnt); else fputs("null", stdout); printf(",\"min_ms\":"); if (best >= 0) printf("%lld", best); else fputs("null", stdout); printf(",\"max_ms\":"); if (worst >= 0) printf("%lld", worst); else fputs("null", stdout); printf(",\"timeout_ms\":%d}", TCP_MS); } /* ------------------------------------------------------------------ */ /* action=http */ /* ------------------------------------------------------------------ */ /* Plain HTTP reachability. Sends one HEAD request, reads only the status line * and the header block, never a body, and follows no redirects. There is no * TLS library in this binary, so an https:// target is reported as a TCP * connect to 443 with tls:"not_checked". */ static void action_http(const char *url_in) { url_t u; SX_SOCK_T s = SX_SOCK_INVALID; struct addrinfo *res = NULL; struct addrinfo *rp; char req[768]; char buf[2048]; size_t have = 0; int status = 0; int header_lines = 0; int got_headers = 0; long long t0, t1, t2; char stamp[32]; char pbuf[16]; int rc; if (!parse_url(url_in, &u)) { err_json(400, "invalid url"); return; } snprintf(pbuf, sizeof pbuf, "%d", u.port); rc = resolve_with_deadline(u.host_plain, pbuf, &res, DNS_MS); emit_json_head(); utc_stamp(time(NULL), stamp, sizeof stamp); printf("{\"ok\":true,\"action\":\"http\",\"url\":"); json_str(url_in); printf(",\"host\":"); json_str(u.host); printf(",\"port\":%d,\"path\":", u.port); json_str(u.path); printf(",\"tls\":"); if (u.tls) fputs("\"not_checked\"", stdout); else fputs("false", stdout); printf(",\"generated_at\":"); json_str(stamp); if (rc == -1) { printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," "\"note\":\"dns resolution timed out\"}"); return; } if (rc != 0 || !res) { printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," "\"note\":\"host does not resolve\"}"); return; } t0 = now_ms(); for (rp = res; rp; rp = rp->ai_next) { s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (s == SX_SOCK_INVALID) continue; rc = connect(s, rp->ai_addr, rp->ai_addrlen); if (rc == 0) break; sx_close_socket(s); s = SX_SOCK_INVALID; } freeaddrinfo(res); t1 = now_ms(); if (s == SX_SOCK_INVALID) { printf(",\"reachable\":false,\"connect_ms\":null,\"status\":null," "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," "\"note\":\"tcp connect failed\""); if (u.tls) fputs(",\"tls_note\":\"no TLS library: only the TCP connect to 443 was attempted\"", stdout); puts("}"); return; } if (u.tls) { /* No TLS: report the connect and stop. */ sx_close_socket(s); printf(",\"reachable\":true,\"connect_ms\":%lld,\"status\":null," "\"status_text\":null,\"header_lines\":0,\"body_bytes_read\":0," "\"note\":\"tcp connect succeeded; the TLS handshake was not attempted\"", (long long)(t1 - t0)); puts("}"); return; } /* Read timeout so a server that accepts but never answers cannot hang us. */ #if defined(_WIN32) { DWORD tv = (DWORD)READ_MS; setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof tv); } #else { struct timeval tv; tv.tv_sec = READ_MS / 1000; tv.tv_usec = (READ_MS % 1000) * 1000; setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); } #endif snprintf(req, sizeof req, "HEAD %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: scorpiox-bot-netcheck/1.0\r\n" "Accept: */*\r\nConnection: close\r\n\r\n", u.path, u.host); { size_t wl = strlen(req), sent = 0; while (sent < wl) { int w; #if defined(_WIN32) w = (int)send(s, req + sent, (int)(wl - sent), 0); #else w = (int)send(s, req + sent, wl - sent, 0); #endif if (w <= 0) break; sent += (size_t)w; } } t2 = now_ms(); while (have < sizeof buf - 1) { int r = (int)recv(s, buf + have, 1, 0); if (r <= 0) break; have += (size_t)r; if (have >= 4 && memcmp(buf + have - 4, "\r\n\r\n", 4) == 0) { got_headers = 1; break; } if (have >= 2 && memcmp(buf + have - 2, "\n\n", 2) == 0) { got_headers = 1; break; } if (now_ms() - t2 > READ_MS) break; } t2 = now_ms(); sx_close_socket(s); buf[have] = '\0'; printf(",\"reachable\":true,\"connect_ms\":%lld", (long long)(t1 - t0)); if (have >= 5 && strncmp(buf, "HTTP/", 5) == 0) { const char *sp = strchr(buf, ' '); if (sp) { const char *nl = strchr(sp, '\r'); char txt[64]; size_t n; if (!nl) nl = strchr(sp, '\n'); const char *rs; status = atoi(sp + 1); /* the reason phrase starts after the code and its single space */ rs = sp + 1; while (isdigit((unsigned char)*rs)) rs++; while (*rs == ' ' || *rs == '\t') rs++; n = nl ? (size_t)(nl - rs) : 0; if (n >= sizeof txt) n = sizeof txt - 1; memcpy(txt, rs, n); txt[n] = '\0'; str_trim(txt); printf(",\"status\":%d,\"status_text\":", status); json_str(txt); } else { fputs(",\"status\":null,\"status_text\":null", stdout); } } else { fputs(",\"status\":null,\"status_text\":null", stdout); } /* count header lines: everything after the status line up to the blank line */ { const char *p = strchr(buf, '\n'); if (p) { p++; for (;;) { const char *nl; while (*p == '\r' || *p == '\n') { /* a line that is only a terminator ends the header block */ if (*p == '\n') { p++; break; } p++; } if (!*p || *p == '\n') break; /* blank line = end of headers */ nl = strchr(p, '\n'); header_lines++; if (!nl) break; p = nl + 1; } } } printf(",\"header_lines\":%d,\"body_bytes_read\":0,\"read_ms\":%lld," "\"headers_complete\":%s", header_lines, (long long)(t2 - t1), got_headers ? "true" : "false"); if (status >= 300 && status < 400) fputs(",\"redirect\":\"not_followed\"", stdout); puts("}"); } /* ------------------------------------------------------------------ */ /* action=info */ /* ------------------------------------------------------------------ */ static void action_info(void) { char stamp[32]; emit_json_head(); utc_stamp(time(NULL), stamp, sizeof stamp); printf("{\"ok\":true,\"plugin\":"); json_str(PLUGIN_ID); printf(",\"slug\":"); json_str(PLUGIN_SLUG); printf(",\"version\":"); json_str(PLUGIN_VER); printf(",\"generated_at\":"); json_str(stamp); printf(",\"actions\":[\"ifaces\",\"dns\",\"tcp\",\"http\",\"info\"]"); printf(",\"tls_library\":false,\"max_samples\":%d", MAX_SAMPLES); printf(",\"dns_timeout_ms\":%d,\"tcp_timeout_ms\":%d,\"read_timeout_ms\":%d", DNS_MS, TCP_MS, READ_MS); puts("}"); } static int is_post_request(void) { const char *m = getenv("REQUEST_METHOD"); return m && (strcmp(m, "POST") == 0 || strcmp(m, "PUT") == 0); } static int mode_meta(void) { puts("{\"name\":\"netcheck\",\"desc\":\"Net checks\"}"); return 0; } static int mode_json(const char *qs) { char action[64]; char host[MAX_HOST]; char port_s[16]; char url_s[MAX_LINE]; get_query_val(qs, "action", action, sizeof action); str_lower(action); if (action[0] == '\0') { action_info(); return 0; } if (strcmp(action, "ifaces") == 0) { action_ifaces(); return 0; } if (strcmp(action, "dns") == 0) { if (!get_query_val(qs, "host", host, sizeof host)) { err_json(400, "host required"); return 0; } action_dns(host); return 0; } if (strcmp(action, "tcp") == 0) { if (!get_query_val(qs, "host", host, sizeof host)) { err_json(400, "host required"); return 0; } if (!get_query_val(qs, "port", port_s, sizeof port_s)) { err_json(400, "port required"); return 0; } action_tcp(host, port_s); return 0; } if (strcmp(action, "http") == 0) { if (!get_query_val(qs, "url", url_s, sizeof url_s)) { err_json(400, "url required"); return 0; } action_http(url_s); return 0; } if (strcmp(action, "info") == 0) { action_info(); return 0; } err_json(400, "unknown action"); return 0; } /* ------------------------------------------------------------------ */ /* HTML mode */ /* ------------------------------------------------------------------ */ /* Split UI_HTML on the two control-byte placeholders and expand them into the * theme macros, so the page and the bot palette can never drift. */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } static int mode_html(int embed) { (void)embed; fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "X-Frame-Options: SAMEORIGIN\r\n" "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); emit_ui(); return 0; } int main(int argc, char **argv) { const char *qs; int embed; if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) return mode_meta(); #if defined(_WIN32) { WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return mode_meta(); } #endif require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) return mode_json(qs); embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); return mode_html(embed); }