| 1 | /* |
| 2 | * plugin_ports - SCORPIOX BOT open-source local listening socket inspector |
| 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=listeners | ?action=probe&port=N | ?format=json -> JSON node API |
| 7 | * 3. GET (default) -> responsive HTML inspector |
| 8 | * |
| 9 | * Everything it reports is LOCAL to the node. Listening sockets come from |
| 10 | * /proc/net/tcp{,6} and /proc/net/udp{,6} parsed directly (so it keeps working |
| 11 | * inside minimal containers where ss(8) and netstat(8) are not installed), from |
| 12 | * lsof(8)/netstat(8) on macOS, and from GetExtendedTcpTable/GetExtendedUdpTable |
| 13 | * on Windows. Owners are resolved from /proc/<pid>/fd socket inodes on Linux and |
| 14 | * from the OS table on Windows. |
| 15 | * |
| 16 | * The probe action opens exactly one TCP connection, and its destination is |
| 17 | * hard-coded to the loopback address. There is no parameter anywhere in this |
| 18 | * file that can redirect it at another host, so the plugin cannot be used as an |
| 19 | * SSRF pivot. |
| 20 | * |
| 21 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 22 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 23 | * scorpiox-server on the node. |
| 24 | * |
| 25 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 26 | */ |
| 27 | |
| 28 | /* Must come before every include: iphlpapi.h and ws2tcpip.h gate |
| 29 | * GetExtendedTcpTable/QueryFullProcessImageName/inet_ntop on it, and MinGW |
| 30 | * defaults to 0x502 (Server 2003) which hides all three. */ |
| 31 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 32 | # define _WIN32_WINNT 0x0601 |
| 33 | #endif |
| 34 | |
| 35 | #if !defined(_WIN32) |
| 36 | # define _POSIX_C_SOURCE 200809L |
| 37 | # define _DEFAULT_SOURCE 1 |
| 38 | # if defined(__APPLE__) |
| 39 | # define _DARWIN_C_SOURCE 1 |
| 40 | # endif |
| 41 | #endif |
| 42 | |
| 43 | #include <stdio.h> |
| 44 | #include <stdlib.h> |
| 45 | #include <string.h> |
| 46 | #include <ctype.h> |
| 47 | #include <errno.h> |
| 48 | #include <time.h> |
| 49 | |
| 50 | #if defined(_WIN32) |
| 51 | # define WIN32_LEAN_AND_MEAN |
| 52 | # include <winsock2.h> |
| 53 | # include <ws2tcpip.h> |
| 54 | # include <windows.h> |
| 55 | # include <iphlpapi.h> |
| 56 | # define sx_popen _popen |
| 57 | # define sx_pclose _pclose |
| 58 | # define sx_close_socket closesocket |
| 59 | #else |
| 60 | # include <unistd.h> |
| 61 | # include <dirent.h> |
| 62 | # include <fcntl.h> |
| 63 | # include <sys/types.h> |
| 64 | # include <sys/socket.h> |
| 65 | # include <sys/select.h> |
| 66 | # include <sys/time.h> |
| 67 | # include <netinet/in.h> |
| 68 | # include <arpa/inet.h> |
| 69 | # define sx_popen popen |
| 70 | # define sx_pclose pclose |
| 71 | # define sx_close_socket close |
| 72 | #endif |
| 73 | |
| 74 | #include "bot_theme_plugin.h" |
| 75 | |
| 76 | #define PLUGIN_SLUG "ports" |
| 77 | #define PLUGIN_ID "plugin_ports" |
| 78 | #define PLUGIN_VER "1.0.1" |
| 79 | |
| 80 | #define MAX_LISTEN 1024 |
| 81 | #define MAX_OWNERS 8192 |
| 82 | #define MAX_LINE 1024 |
| 83 | #define PROBE_TIMEOUT_MS 2000 |
| 84 | #define HTTP_READ_MS 1500 |
| 85 | |
| 86 | /* socket scope */ |
| 87 | #define SCOPE_LOOPBACK 0 |
| 88 | #define SCOPE_WILDCARD 1 |
| 89 | #define SCOPE_SPECIFIC 2 |
| 90 | |
| 91 | typedef struct { |
| 92 | char proto[4]; /* "tcp" or "udp" */ |
| 93 | char bind_addr[64]; /* 127.0.0.1, 0.0.0.0, ::1, ::, or one bound address */ |
| 94 | int port; |
| 95 | int scope; |
| 96 | int pid; |
| 97 | char comm[96]; |
| 98 | unsigned long inode; |
| 99 | } sock_t; |
| 100 | |
| 101 | static sock_t g_socks[MAX_LISTEN]; |
| 102 | static int g_sock_count; |
| 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 || !key) return 0; |
| 136 | klen = strlen(key); |
| 137 | |
| 138 | for (p = qs; *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 | #if !defined(_WIN32) || defined(__APPLE__) |
| 186 | static void str_trim(char *s) |
| 187 | { |
| 188 | char *p; |
| 189 | size_t n; |
| 190 | if (!s) return; |
| 191 | p = s; |
| 192 | while (*p && isspace((unsigned char)*p)) p++; |
| 193 | if (p != s) memmove(s, p, strlen(p) + 1); |
| 194 | n = strlen(s); |
| 195 | while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; |
| 196 | } |
| 197 | #endif |
| 198 | |
| 199 | static int scope_of_addr(const char *addr) |
| 200 | { |
| 201 | if (!addr || !*addr) return SCOPE_SPECIFIC; |
| 202 | if (strcmp(addr, "0.0.0.0") == 0 || strcmp(addr, "::") == 0 || |
| 203 | strcmp(addr, "*") == 0) |
| 204 | return SCOPE_WILDCARD; |
| 205 | if (strncmp(addr, "127.", 4) == 0) return SCOPE_LOOPBACK; |
| 206 | if (strcmp(addr, "::1") == 0) return SCOPE_LOOPBACK; |
| 207 | return SCOPE_SPECIFIC; |
| 208 | } |
| 209 | |
| 210 | static const char *scope_name(int s) |
| 211 | { |
| 212 | if (s == SCOPE_LOOPBACK) return "loopback"; |
| 213 | if (s == SCOPE_WILDCARD) return "wildcard"; |
| 214 | return "specific"; |
| 215 | } |
| 216 | |
| 217 | static long long now_ms(void) |
| 218 | { |
| 219 | #if defined(_WIN32) |
| 220 | FILETIME ft; |
| 221 | ULARGE_INTEGER u; |
| 222 | GetSystemTimeAsFileTime(&ft); |
| 223 | u.LowPart = ft.dwLowDateTime; |
| 224 | u.HighPart = ft.dwHighDateTime; |
| 225 | return (long long)(u.QuadPart / 10000ULL); |
| 226 | #else |
| 227 | struct timeval tv; |
| 228 | gettimeofday(&tv, NULL); |
| 229 | return (long long)tv.tv_sec * 1000LL + (long long)(tv.tv_usec / 1000); |
| 230 | #endif |
| 231 | } |
| 232 | |
| 233 | static void utc_stamp(time_t t, char *buf, size_t sz) |
| 234 | { |
| 235 | struct tm tmv; |
| 236 | #if defined(_WIN32) |
| 237 | gmtime_s(&tmv, &t); |
| 238 | #else |
| 239 | gmtime_r(&t, &tmv); |
| 240 | #endif |
| 241 | strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); |
| 242 | } |
| 243 | |
| 244 | /* ------------------------------------------------------------------ */ |
| 245 | /* Node authentication */ |
| 246 | /* ------------------------------------------------------------------ */ |
| 247 | |
| 248 | static void require_node_auth(void) |
| 249 | { |
| 250 | const char *np = getenv("BOT_PASSWORD"); |
| 251 | const char *xp; |
| 252 | const char *auth; |
| 253 | const char *qs; |
| 254 | char qpwd[256]; |
| 255 | |
| 256 | if (!np || !*np) return; |
| 257 | |
| 258 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 259 | if (xp && strcmp(xp, np) == 0) return; |
| 260 | |
| 261 | auth = getenv("HTTP_AUTHORIZATION"); |
| 262 | if (auth) { |
| 263 | while (*auth == ' ') auth++; |
| 264 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 265 | auth += 7; |
| 266 | while (*auth == ' ') auth++; |
| 267 | if (strcmp(auth, np) == 0) return; |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | qs = getenv("QUERY_STRING"); |
| 272 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 273 | return; |
| 274 | |
| 275 | fputs("Status: 401 Unauthorized\r\n" |
| 276 | "Content-Type: application/json; charset=utf-8\r\n" |
| 277 | "Cache-Control: no-store\r\n" |
| 278 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 279 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 280 | exit(0); |
| 281 | } |
| 282 | |
| 283 | /* ------------------------------------------------------------------ */ |
| 284 | /* Listening-socket collection */ |
| 285 | /* ------------------------------------------------------------------ */ |
| 286 | |
| 287 | static void sock_add(const char *proto, const char *addr, int port, |
| 288 | int pid, const char *comm, unsigned long inode) |
| 289 | { |
| 290 | sock_t *s; |
| 291 | if (g_sock_count >= MAX_LISTEN) return; |
| 292 | if (port <= 0 || port > 65535) return; |
| 293 | s = &g_socks[g_sock_count++]; |
| 294 | str_copy(s->proto, sizeof(s->proto), proto); |
| 295 | str_copy(s->bind_addr, sizeof(s->bind_addr), addr && *addr ? addr : "unknown"); |
| 296 | s->port = port; |
| 297 | s->scope = scope_of_addr(s->bind_addr); |
| 298 | s->pid = pid; |
| 299 | str_copy(s->comm, sizeof(s->comm), comm ? comm : ""); |
| 300 | s->inode = inode; |
| 301 | } |
| 302 | |
| 303 | static void sort_socks(void) |
| 304 | { |
| 305 | int i, j; |
| 306 | for (i = 1; i < g_sock_count; i++) { |
| 307 | sock_t key = g_socks[i]; |
| 308 | j = i - 1; |
| 309 | while (j >= 0) { |
| 310 | int cmp; |
| 311 | if (g_socks[j].port != key.port) cmp = g_socks[j].port - key.port; |
| 312 | else cmp = strcmp(g_socks[j].proto, key.proto); |
| 313 | if (cmp <= 0) break; |
| 314 | g_socks[j + 1] = g_socks[j]; |
| 315 | j--; |
| 316 | } |
| 317 | g_socks[j + 1] = key; |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | #if !defined(_WIN32) |
| 322 | |
| 323 | /* ---- owner resolution from /proc/<pid>/fd socket inodes ---- */ |
| 324 | |
| 325 | typedef struct { |
| 326 | unsigned long inode; |
| 327 | int pid; |
| 328 | char comm[96]; |
| 329 | } owner_t; |
| 330 | |
| 331 | static owner_t g_owners[MAX_OWNERS]; |
| 332 | static int g_owner_count; |
| 333 | |
| 334 | static int is_numeric(const char *s) |
| 335 | { |
| 336 | if (!s || !*s) return 0; |
| 337 | for (; *s; s++) if (!isdigit((unsigned char)*s)) return 0; |
| 338 | return 1; |
| 339 | } |
| 340 | |
| 341 | static void owner_scan_dir(const char *fdpath, int pid, const char *comm) |
| 342 | { |
| 343 | DIR *d; |
| 344 | struct dirent *e; |
| 345 | |
| 346 | d = opendir(fdpath); |
| 347 | if (!d) return; |
| 348 | while ((e = readdir(d)) != NULL) { |
| 349 | char full[MAX_LINE * 2]; |
| 350 | char link[MAX_LINE]; |
| 351 | ssize_t n; |
| 352 | if (e->d_name[0] == '.') continue; |
| 353 | if (g_owner_count >= MAX_OWNERS) break; |
| 354 | snprintf(full, sizeof(full), "%s/%s", fdpath, e->d_name); |
| 355 | n = readlink(full, link, sizeof(link) - 1); |
| 356 | if (n <= 0) continue; |
| 357 | link[n] = '\0'; |
| 358 | if (strncmp(link, "socket:[", 8) != 0) continue; |
| 359 | g_owners[g_owner_count].inode = |
| 360 | (unsigned long)strtoul(link + 8, NULL, 10); |
| 361 | g_owners[g_owner_count].pid = pid; |
| 362 | str_copy(g_owners[g_owner_count].comm, sizeof(g_owners[0].comm), comm); |
| 363 | g_owner_count++; |
| 364 | } |
| 365 | closedir(d); |
| 366 | } |
| 367 | |
| 368 | static void resolve_owners(void) |
| 369 | { |
| 370 | DIR *d; |
| 371 | struct dirent *e; |
| 372 | |
| 373 | if (g_sock_count == 0) return; |
| 374 | #if defined(__APPLE__) |
| 375 | return; /* macOS owners come from lsof in collect_macos() */ |
| 376 | #endif |
| 377 | |
| 378 | d = opendir("/proc"); |
| 379 | if (!d) return; |
| 380 | while ((e = readdir(d)) != NULL) { |
| 381 | char comm[96] = ""; |
| 382 | char path[MAX_LINE]; |
| 383 | FILE *fp; |
| 384 | int pid; |
| 385 | |
| 386 | if (!is_numeric(e->d_name)) continue; |
| 387 | pid = atoi(e->d_name); |
| 388 | if (pid <= 0) continue; |
| 389 | |
| 390 | snprintf(path, sizeof(path), "/proc/%d/comm", pid); |
| 391 | fp = fopen(path, "r"); |
| 392 | if (fp) { |
| 393 | if (fgets(comm, sizeof(comm), fp)) str_trim(comm); |
| 394 | fclose(fp); |
| 395 | } |
| 396 | snprintf(path, sizeof(path), "/proc/%d/fd", pid); |
| 397 | owner_scan_dir(path, pid, comm); |
| 398 | } |
| 399 | closedir(d); |
| 400 | |
| 401 | { |
| 402 | int i, k, m; |
| 403 | for (i = 0; i < g_sock_count; i++) { |
| 404 | if (g_socks[i].inode == 0) continue; |
| 405 | for (k = 0; k < g_owner_count; k++) { |
| 406 | if (g_owners[k].inode != g_socks[i].inode) continue; |
| 407 | if (g_socks[i].pid <= 0) { |
| 408 | g_socks[i].pid = g_owners[k].pid; |
| 409 | str_copy(g_socks[i].comm, sizeof(g_socks[i].comm), |
| 410 | g_owners[k].comm); |
| 411 | } else if (strcmp(g_socks[i].comm, g_owners[k].comm) != 0 && |
| 412 | g_owners[k].pid < g_socks[i].pid) { |
| 413 | /* prefer the lowest pid seen for this socket */ |
| 414 | g_socks[i].pid = g_owners[k].pid; |
| 415 | str_copy(g_socks[i].comm, sizeof(g_socks[i].comm), |
| 416 | g_owners[k].comm); |
| 417 | } |
| 418 | m = 0; (void)m; |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | /* ---- /proc/net/{tcp,tcp6,udp,udp6} parsing ---- */ |
| 425 | |
| 426 | static int hex_val(int c) |
| 427 | { |
| 428 | if (c >= '0' && c <= '9') return c - '0'; |
| 429 | if (c >= 'a' && c <= 'f') return c - 'a' + 10; |
| 430 | if (c >= 'A' && c <= 'F') return c - 'A' + 10; |
| 431 | return -1; |
| 432 | } |
| 433 | |
| 434 | /* "0100007F" -> 127.0.0.1 (little-endian 32-bit word) */ |
| 435 | static int decode_v4(const char *hex, char *out, size_t sz) |
| 436 | { |
| 437 | unsigned char b[4]; |
| 438 | struct in_addr a; |
| 439 | int i; |
| 440 | for (i = 0; i < 4; i++) { |
| 441 | int hi = hex_val(hex[i * 2]); |
| 442 | int lo = hex_val(hex[i * 2 + 1]); |
| 443 | if (hi < 0 || lo < 0) return 0; |
| 444 | b[3 - i] = (unsigned char)((hi << 4) | lo); |
| 445 | } |
| 446 | memcpy(&a, b, 4); |
| 447 | return inet_ntop(AF_INET, &a, out, (socklen_t)sz) != NULL; |
| 448 | } |
| 449 | |
| 450 | /* 32 hex chars -> 16 bytes, each 8-char group is a little-endian 32-bit word */ |
| 451 | static int decode_v6(const char *hex, char *out, size_t sz) |
| 452 | { |
| 453 | unsigned char b[16]; |
| 454 | int g, i; |
| 455 | for (g = 0; g < 4; g++) { |
| 456 | unsigned int word = 0; |
| 457 | for (i = 0; i < 8; i++) { |
| 458 | int v = hex_val(hex[g * 8 + i]); |
| 459 | if (v < 0) return 0; |
| 460 | word = (word << 4) | (unsigned int)v; |
| 461 | } |
| 462 | b[g * 4 + 0] = (unsigned char)(word & 0xff); |
| 463 | b[g * 4 + 1] = (unsigned char)((word >> 8) & 0xff); |
| 464 | b[g * 4 + 2] = (unsigned char)((word >> 16) & 0xff); |
| 465 | b[g * 4 + 3] = (unsigned char)((word >> 24) & 0xff); |
| 466 | } |
| 467 | return inet_ntop(AF_INET6, b, out, (socklen_t)sz) != NULL; |
| 468 | } |
| 469 | |
| 470 | static int split_local(const char *tok, char *addr, size_t addrsz, int *port) |
| 471 | { |
| 472 | const char *colon; |
| 473 | size_t alen; |
| 474 | |
| 475 | colon = strrchr(tok, ':'); |
| 476 | if (!colon) return 0; |
| 477 | alen = (size_t)(colon - tok); |
| 478 | if (alen == 0 || alen >= addrsz) return 0; |
| 479 | |
| 480 | *port = (int)strtol(colon + 1, NULL, 16); |
| 481 | if (alen == 8) |
| 482 | return decode_v4(tok, addr, addrsz); |
| 483 | if (alen == 32) |
| 484 | return decode_v6(tok, addr, addrsz); |
| 485 | str_copy(addr, addrsz, "unknown"); |
| 486 | return 1; |
| 487 | } |
| 488 | |
| 489 | static int tokenize(char *line, char **tok, int max) |
| 490 | { |
| 491 | int n = 0; |
| 492 | char *p = line; |
| 493 | while (*p && n < max) { |
| 494 | while (*p && isspace((unsigned char)*p)) p++; |
| 495 | if (!*p) break; |
| 496 | tok[n++] = p; |
| 497 | while (*p && !isspace((unsigned char)*p)) p++; |
| 498 | if (*p) *p++ = '\0'; |
| 499 | } |
| 500 | return n; |
| 501 | } |
| 502 | |
| 503 | static void collect_proc_net(const char *path, const char *proto, int listening_only) |
| 504 | { |
| 505 | FILE *fp; |
| 506 | char line[MAX_LINE]; |
| 507 | |
| 508 | fp = fopen(path, "r"); |
| 509 | if (!fp) return; |
| 510 | if (!fgets(line, sizeof(line), fp)) { fclose(fp); return; } |
| 511 | |
| 512 | while (fgets(line, sizeof(line), fp)) { |
| 513 | char *tok[24]; |
| 514 | int n; |
| 515 | char addr[64]; |
| 516 | int port = 0; |
| 517 | unsigned long inode = 0; |
| 518 | int state = -1; |
| 519 | |
| 520 | n = tokenize(line, tok, 24); |
| 521 | if (n < 12) continue; |
| 522 | |
| 523 | state = (int)strtol(tok[3], NULL, 16); |
| 524 | inode = (unsigned long)strtoul(tok[9], NULL, 10); |
| 525 | if (listening_only && state != 0x0A) continue; |
| 526 | if (!listening_only && state != 0x07) continue; |
| 527 | |
| 528 | if (!split_local(tok[1], addr, sizeof(addr), &port)) continue; |
| 529 | sock_add(proto, addr, port, 0, "", inode); |
| 530 | } |
| 531 | fclose(fp); |
| 532 | } |
| 533 | |
| 534 | #if defined(__APPLE__) |
| 535 | |
| 536 | /* lsof -nP -iTCP -sTCP:LISTEN / lsof -nP -iUDP ; NAME column is the local endpoint */ |
| 537 | static void collect_lsof(const char *args, const char *proto) |
| 538 | { |
| 539 | char cmd[256]; |
| 540 | FILE *fp; |
| 541 | char line[MAX_LINE]; |
| 542 | |
| 543 | snprintf(cmd, sizeof(cmd), "lsof -nP %s 2>/dev/null", args); |
| 544 | fp = sx_popen(cmd, "r"); |
| 545 | if (!fp) return; |
| 546 | if (fgets(line, sizeof(line), fp)) { |
| 547 | while (fgets(line, sizeof(line), fp)) { |
| 548 | char *tok[32]; |
| 549 | char *name; |
| 550 | char *colon; |
| 551 | int n, port, pid = 0; |
| 552 | char addr[64]; |
| 553 | |
| 554 | str_trim(line); |
| 555 | if (!line[0]) continue; |
| 556 | n = tokenize(line, tok, 32); |
| 557 | if (n < 9) continue; |
| 558 | pid = atoi(tok[1]); |
| 559 | name = tok[n - 1]; |
| 560 | colon = strrchr(name, ':'); |
| 561 | if (!colon) continue; |
| 562 | port = atoi(colon + 1); |
| 563 | *colon = '\0'; |
| 564 | str_copy(addr, sizeof(addr), name); |
| 565 | if (strcmp(addr, "*") == 0) str_copy(addr, sizeof(addr), "0.0.0.0"); |
| 566 | if (strcmp(addr, "[::]") == 0) str_copy(addr, sizeof(addr), "::"); |
| 567 | if (strcmp(addr, "localhost") == 0) str_copy(addr, sizeof(addr), "127.0.0.1"); |
| 568 | sock_add(proto, addr, port, pid, tok[0], 0); |
| 569 | } |
| 570 | } |
| 571 | sx_pclose(fp); |
| 572 | } |
| 573 | |
| 574 | static void collect_netstat_fallback(const char *proto) |
| 575 | { |
| 576 | FILE *fp; |
| 577 | char line[MAX_LINE]; |
| 578 | |
| 579 | fp = sx_popen("netstat -an 2>/dev/null", "r"); |
| 580 | if (!fp) return; |
| 581 | while (fgets(line, sizeof(line), fp)) { |
| 582 | char *tok[16]; |
| 583 | int n; |
| 584 | char addr[64]; |
| 585 | int port = 0; |
| 586 | char *colon; |
| 587 | |
| 588 | str_trim(line); |
| 589 | n = tokenize(line, tok, 16); |
| 590 | if (n < 5) continue; |
| 591 | if (strcasecmp(tok[0], proto) != 0) continue; |
| 592 | if (strcmp(proto, "tcp") == 0 && strcmp(tok[5 < n ? 5 : n - 1], "LISTEN") != 0) |
| 593 | continue; |
| 594 | colon = strrchr(tok[3], '.'); |
| 595 | if (!colon) continue; |
| 596 | port = atoi(colon + 1); |
| 597 | *colon = '\0'; |
| 598 | str_copy(addr, sizeof(addr), tok[3]); |
| 599 | if (strcmp(addr, "*") == 0) str_copy(addr, sizeof(addr), "0.0.0.0"); |
| 600 | sock_add(proto, addr, port, 0, "", 0); |
| 601 | } |
| 602 | sx_pclose(fp); |
| 603 | } |
| 604 | |
| 605 | static void collect_macos(void) |
| 606 | { |
| 607 | collect_lsof("-iTCP -sTCP:LISTEN", "tcp"); |
| 608 | collect_lsof("-iUDP", "udp"); |
| 609 | if (g_sock_count == 0) { |
| 610 | collect_netstat_fallback("tcp"); |
| 611 | collect_netstat_fallback("udp"); |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | #else /* Linux */ |
| 616 | |
| 617 | static void collect_linux(void) |
| 618 | { |
| 619 | collect_proc_net("/proc/net/tcp", "tcp", 1); |
| 620 | collect_proc_net("/proc/net/tcp6", "tcp", 1); |
| 621 | /* UDP sockets have no LISTEN state; an unconnected bound socket sits in |
| 622 | state 07 (UDP_CLOSE). Anything else is already connected. */ |
| 623 | collect_proc_net("/proc/net/udp", "udp", 0); |
| 624 | collect_proc_net("/proc/net/udp6", "udp", 0); |
| 625 | } |
| 626 | |
| 627 | #endif /* __APPLE__ */ |
| 628 | |
| 629 | #else /* _WIN32 */ |
| 630 | |
| 631 | static void win_comm_for_pid(DWORD pid, char *out, size_t sz) |
| 632 | { |
| 633 | HANDLE h; |
| 634 | char path[MAX_PATH]; |
| 635 | DWORD len = (DWORD)sz; |
| 636 | |
| 637 | out[0] = '\0'; |
| 638 | if (pid == 0) return; |
| 639 | h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); |
| 640 | if (!h) return; |
| 641 | if (QueryFullProcessImageNameA(h, 0, path, &len)) { |
| 642 | char *slash = strrchr(path, '\\'); |
| 643 | str_copy(out, sz, slash ? slash + 1 : path); |
| 644 | } |
| 645 | CloseHandle(h); |
| 646 | } |
| 647 | |
| 648 | static void win_add_row(const char *proto, int is_v6, const void *addr, |
| 649 | DWORD port_be, DWORD pid) |
| 650 | { |
| 651 | char addr_s[64]; |
| 652 | int port; |
| 653 | char comm[96]; |
| 654 | |
| 655 | if (is_v6) |
| 656 | inet_ntop(AF_INET6, addr, addr_s, sizeof(addr_s)); |
| 657 | else |
| 658 | inet_ntop(AF_INET, addr, addr_s, sizeof(addr_s)); |
| 659 | |
| 660 | port = (int)ntohs((unsigned short)(port_be & 0xffff)); |
| 661 | if (pid > 0) win_comm_for_pid(pid, comm, sizeof(comm)); |
| 662 | else comm[0] = '\0'; |
| 663 | |
| 664 | sock_add(proto, addr_s, port, (int)pid, comm, 0); |
| 665 | } |
| 666 | |
| 667 | static void collect_windows(void) |
| 668 | { |
| 669 | DWORD size = 0; |
| 670 | DWORD rc; |
| 671 | int fam; |
| 672 | |
| 673 | for (fam = 0; fam < 2; fam++) { |
| 674 | int af = fam == 0 ? AF_INET : AF_INET6; |
| 675 | |
| 676 | /* TCP listeners */ |
| 677 | size = 0; |
| 678 | rc = GetExtendedTcpTable(NULL, &size, FALSE, af, |
| 679 | TCP_TABLE_OWNER_PID_LISTENER, 0); |
| 680 | if (rc == ERROR_INSUFFICIENT_BUFFER && size > 0) { |
| 681 | void *buf = malloc(size); |
| 682 | if (buf) { |
| 683 | rc = GetExtendedTcpTable(buf, &size, FALSE, af, |
| 684 | TCP_TABLE_OWNER_PID_LISTENER, 0); |
| 685 | if (rc == NO_ERROR) { |
| 686 | if (af == AF_INET) { |
| 687 | MIB_TCPTABLE_OWNER_PID *t = (MIB_TCPTABLE_OWNER_PID *)buf; |
| 688 | DWORD i; |
| 689 | for (i = 0; i < t->dwNumEntries; i++) { |
| 690 | MIB_TCPROW_OWNER_PID *r = &t->table[i]; |
| 691 | if (r->dwState != MIB_TCP_STATE_LISTEN) continue; |
| 692 | win_add_row("tcp", 0, &r->dwLocalAddr, |
| 693 | r->dwLocalPort, r->dwOwningPid); |
| 694 | } |
| 695 | } else { |
| 696 | MIB_TCP6TABLE_OWNER_PID *t = (MIB_TCP6TABLE_OWNER_PID *)buf; |
| 697 | DWORD i; |
| 698 | for (i = 0; i < t->dwNumEntries; i++) { |
| 699 | MIB_TCP6ROW_OWNER_PID *r = &t->table[i]; |
| 700 | if (r->dwState != MIB_TCP_STATE_LISTEN) continue; |
| 701 | win_add_row("tcp", 1, r->ucLocalAddr, |
| 702 | r->dwLocalPort, r->dwOwningPid); |
| 703 | } |
| 704 | } |
| 705 | } |
| 706 | free(buf); |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | /* UDP endpoints */ |
| 711 | size = 0; |
| 712 | rc = GetExtendedUdpTable(NULL, &size, FALSE, af, |
| 713 | UDP_TABLE_OWNER_PID, 0); |
| 714 | if (rc == ERROR_INSUFFICIENT_BUFFER && size > 0) { |
| 715 | void *buf = malloc(size); |
| 716 | if (buf) { |
| 717 | rc = GetExtendedUdpTable(buf, &size, FALSE, af, |
| 718 | UDP_TABLE_OWNER_PID, 0); |
| 719 | if (rc == NO_ERROR) { |
| 720 | if (af == AF_INET) { |
| 721 | MIB_UDPTABLE_OWNER_PID *t = (MIB_UDPTABLE_OWNER_PID *)buf; |
| 722 | DWORD i; |
| 723 | for (i = 0; i < t->dwNumEntries; i++) { |
| 724 | MIB_UDPROW_OWNER_PID *r = &t->table[i]; |
| 725 | win_add_row("udp", 0, &r->dwLocalAddr, |
| 726 | r->dwLocalPort, r->dwOwningPid); |
| 727 | } |
| 728 | } else { |
| 729 | MIB_UDP6TABLE_OWNER_PID *t = (MIB_UDP6TABLE_OWNER_PID *)buf; |
| 730 | DWORD i; |
| 731 | for (i = 0; i < t->dwNumEntries; i++) { |
| 732 | MIB_UDP6ROW_OWNER_PID *r = &t->table[i]; |
| 733 | win_add_row("udp", 1, r->ucLocalAddr, |
| 734 | r->dwLocalPort, r->dwOwningPid); |
| 735 | } |
| 736 | } |
| 737 | } |
| 738 | free(buf); |
| 739 | } |
| 740 | } |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | #endif /* _WIN32 */ |
| 745 | |
| 746 | static void collect_sockets(void) |
| 747 | { |
| 748 | g_sock_count = 0; |
| 749 | #if defined(_WIN32) |
| 750 | collect_windows(); |
| 751 | #elif defined(__APPLE__) |
| 752 | collect_macos(); |
| 753 | #else |
| 754 | collect_linux(); |
| 755 | resolve_owners(); |
| 756 | #endif |
| 757 | sort_socks(); |
| 758 | } |
| 759 | |
| 760 | /* ------------------------------------------------------------------ */ |
| 761 | /* Loopback probe (127.0.0.1 only - never an arbitrary destination) */ |
| 762 | /* ------------------------------------------------------------------ */ |
| 763 | |
| 764 | typedef struct { |
| 765 | int ok; /* connect() succeeded */ |
| 766 | int refused; /* reached the host, nothing listening */ |
| 767 | long connect_ms; |
| 768 | int http_tried; |
| 769 | int http_ok; |
| 770 | int http_status; |
| 771 | long http_ms; |
| 772 | } probe_t; |
| 773 | |
| 774 | #if defined(_WIN32) |
| 775 | static int probe_connect(const unsigned char v4[4], int port) |
| 776 | { |
| 777 | SOCKET s; |
| 778 | struct sockaddr_in sa; |
| 779 | u_long nb = 1; |
| 780 | int rc, err; |
| 781 | fd_set wfds; |
| 782 | struct timeval tv; |
| 783 | |
| 784 | s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); |
| 785 | if (s == INVALID_SOCKET) return -1; |
| 786 | |
| 787 | memset(&sa, 0, sizeof(sa)); |
| 788 | sa.sin_family = AF_INET; |
| 789 | sa.sin_port = htons((unsigned short)port); |
| 790 | memcpy(&sa.sin_addr, v4, 4); |
| 791 | |
| 792 | ioctlsocket(s, FIONBIO, &nb); |
| 793 | rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); |
| 794 | if (rc == SOCKET_ERROR) { |
| 795 | err = WSAGetLastError(); |
| 796 | if (err != WSAEWOULDBLOCK) { |
| 797 | closesocket(s); |
| 798 | return (err == WSAECONNREFUSED) ? 1 : -1; |
| 799 | } |
| 800 | FD_ZERO(&wfds); |
| 801 | FD_SET(s, &wfds); |
| 802 | tv.tv_sec = PROBE_TIMEOUT_MS / 1000; |
| 803 | tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; |
| 804 | rc = select(0, NULL, &wfds, NULL, &tv); |
| 805 | if (rc <= 0) { closesocket(s); return 1; } |
| 806 | { |
| 807 | int soerr = 0, slen = sizeof(soerr); |
| 808 | getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen); |
| 809 | if (soerr != 0) { |
| 810 | closesocket(s); |
| 811 | return (soerr == WSAECONNREFUSED) ? 1 : -1; |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | closesocket(s); |
| 816 | return 0; |
| 817 | } |
| 818 | #else |
| 819 | static int probe_connect(const unsigned char v4[4], int port) |
| 820 | { |
| 821 | int fd, rc, soerr = 0; |
| 822 | struct sockaddr_in sa; |
| 823 | fd_set wfds; |
| 824 | struct timeval tv; |
| 825 | socklen_t slen = sizeof(soerr); |
| 826 | |
| 827 | fd = socket(AF_INET, SOCK_STREAM, 0); |
| 828 | if (fd < 0) return -1; |
| 829 | |
| 830 | memset(&sa, 0, sizeof(sa)); |
| 831 | sa.sin_family = AF_INET; |
| 832 | sa.sin_port = htons((unsigned short)port); |
| 833 | memcpy(&sa.sin_addr, v4, 4); |
| 834 | |
| 835 | { |
| 836 | int fl = fcntl(fd, F_GETFL, 0); |
| 837 | if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK); |
| 838 | } |
| 839 | |
| 840 | rc = connect(fd, (struct sockaddr *)&sa, sizeof(sa)); |
| 841 | if (rc < 0) { |
| 842 | if (errno != EINPROGRESS) { |
| 843 | int e = errno; |
| 844 | close(fd); |
| 845 | return (e == ECONNREFUSED) ? 1 : -1; |
| 846 | } |
| 847 | FD_ZERO(&wfds); |
| 848 | FD_SET(fd, &wfds); |
| 849 | tv.tv_sec = PROBE_TIMEOUT_MS / 1000; |
| 850 | tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; |
| 851 | rc = select(fd + 1, NULL, &wfds, NULL, &tv); |
| 852 | if (rc <= 0) { close(fd); return 1; } |
| 853 | if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 || soerr != 0) { |
| 854 | close(fd); |
| 855 | return (soerr == ECONNREFUSED) ? 1 : -1; |
| 856 | } |
| 857 | } |
| 858 | close(fd); |
| 859 | return 0; |
| 860 | } |
| 861 | #endif |
| 862 | |
| 863 | #if defined(_WIN32) |
| 864 | static int probe_http(const unsigned char v4[4], int port, int *status_out) |
| 865 | { |
| 866 | SOCKET s; |
| 867 | struct sockaddr_in sa; |
| 868 | u_long nb = 1; |
| 869 | int rc, soerr = 0, slen = sizeof(soerr); |
| 870 | fd_set wfds; |
| 871 | struct timeval tv; |
| 872 | char req[128]; |
| 873 | char buf[512]; |
| 874 | long long deadline; |
| 875 | |
| 876 | s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); |
| 877 | if (s == INVALID_SOCKET) return -1; |
| 878 | |
| 879 | memset(&sa, 0, sizeof(sa)); |
| 880 | sa.sin_family = AF_INET; |
| 881 | sa.sin_port = htons((unsigned short)port); |
| 882 | memcpy(&sa.sin_addr, v4, 4); |
| 883 | |
| 884 | ioctlsocket(s, FIONBIO, &nb); |
| 885 | rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); |
| 886 | if (rc == SOCKET_ERROR) { |
| 887 | int err = WSAGetLastError(); |
| 888 | if (err != WSAEWOULDBLOCK) { closesocket(s); return -1; } |
| 889 | FD_ZERO(&wfds); |
| 890 | FD_SET(s, &wfds); |
| 891 | tv.tv_sec = PROBE_TIMEOUT_MS / 1000; |
| 892 | tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; |
| 893 | if (select(0, NULL, &wfds, NULL, &tv) <= 0) { closesocket(s); return -1; } |
| 894 | getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen); |
| 895 | if (soerr != 0) { closesocket(s); return -1; } |
| 896 | } |
| 897 | #else |
| 898 | static int probe_http(const unsigned char v4[4], int port, int *status_out) |
| 899 | { |
| 900 | int s; |
| 901 | struct sockaddr_in sa; |
| 902 | int rc, soerr = 0; |
| 903 | fd_set wfds; |
| 904 | struct timeval tv; |
| 905 | char req[128]; |
| 906 | char buf[512]; |
| 907 | long long deadline; |
| 908 | socklen_t slen = sizeof(soerr); |
| 909 | |
| 910 | s = socket(AF_INET, SOCK_STREAM, 0); |
| 911 | if (s < 0) return -1; |
| 912 | |
| 913 | memset(&sa, 0, sizeof(sa)); |
| 914 | sa.sin_family = AF_INET; |
| 915 | sa.sin_port = htons((unsigned short)port); |
| 916 | memcpy(&sa.sin_addr, v4, 4); |
| 917 | |
| 918 | { |
| 919 | int fl = fcntl(s, F_GETFL, 0); |
| 920 | if (fl >= 0) fcntl(s, F_SETFL, fl | O_NONBLOCK); |
| 921 | } |
| 922 | |
| 923 | rc = connect(s, (struct sockaddr *)&sa, sizeof(sa)); |
| 924 | if (rc < 0) { |
| 925 | if (errno != EINPROGRESS) { close(s); return -1; } |
| 926 | FD_ZERO(&wfds); |
| 927 | FD_SET(s, &wfds); |
| 928 | tv.tv_sec = PROBE_TIMEOUT_MS / 1000; |
| 929 | tv.tv_usec = (PROBE_TIMEOUT_MS % 1000) * 1000; |
| 930 | if (select(s + 1, NULL, &wfds, NULL, &tv) <= 0) { close(s); return -1; } |
| 931 | if (getsockopt(s, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 || soerr != 0) { |
| 932 | close(s); |
| 933 | return -1; |
| 934 | } |
| 935 | } |
| 936 | #endif |
| 937 | |
| 938 | snprintf(req, sizeof(req), |
| 939 | "HEAD / HTTP/1.0\r\nHost: 127.0.0.1:%d\r\n" |
| 940 | "User-Agent: %s/%s\r\nConnection: close\r\n\r\n", port, PLUGIN_ID, PLUGIN_VER); |
| 941 | if (send(s, req, (int)strlen(req), 0) <= 0) { sx_close_socket(s); return -1; } |
| 942 | |
| 943 | deadline = now_ms() + HTTP_READ_MS; |
| 944 | { |
| 945 | int total = 0; |
| 946 | for (;;) { |
| 947 | int n; |
| 948 | long long left = deadline - now_ms(); |
| 949 | if (left <= 0) break; |
| 950 | { |
| 951 | fd_set rfds; |
| 952 | struct timeval t2; |
| 953 | FD_ZERO(&rfds); |
| 954 | FD_SET(s, &rfds); |
| 955 | t2.tv_sec = (long)(left / 1000); |
| 956 | t2.tv_usec = (long)((left % 1000) * 1000); |
| 957 | #if defined(_WIN32) |
| 958 | n = (select(0, &rfds, NULL, NULL, &t2) > 0) ? 1 : 0; |
| 959 | #else |
| 960 | n = (select(s + 1, &rfds, NULL, NULL, &t2) > 0) ? 1 : 0; |
| 961 | #endif |
| 962 | if (n <= 0) break; |
| 963 | } |
| 964 | { |
| 965 | int got = recv(s, buf + total, (int)(sizeof(buf) - 1 - total), 0); |
| 966 | if (got <= 0) break; |
| 967 | total += got; |
| 968 | buf[total] = '\0'; |
| 969 | if (strstr(buf, "\r\n") || total >= (int)sizeof(buf) - 1) break; |
| 970 | } |
| 971 | } |
| 972 | buf[total] = '\0'; |
| 973 | } |
| 974 | sx_close_socket(s); |
| 975 | |
| 976 | *status_out = 0; |
| 977 | if (strncmp(buf, "HTTP/", 5) == 0) { |
| 978 | const char *sp = strchr(buf, ' '); |
| 979 | if (sp) *status_out = atoi(sp + 1); |
| 980 | return (*status_out > 0) ? 0 : -1; |
| 981 | } |
| 982 | return -1; |
| 983 | } |
| 984 | |
| 985 | static void run_probe(int port, probe_t *p) |
| 986 | { |
| 987 | /* The destination is a constant: 127.0.0.1. No query parameter, header or |
| 988 | * environment variable is ever consulted, so this cannot be aimed |
| 989 | * elsewhere. */ |
| 990 | static const unsigned char loopback[4] = { 127, 0, 0, 1 }; |
| 991 | long long t0, t1; |
| 992 | int refused; |
| 993 | |
| 994 | memset(p, 0, sizeof(*p)); |
| 995 | p->connect_ms = -1; |
| 996 | p->http_ms = -1; |
| 997 | |
| 998 | t0 = now_ms(); |
| 999 | refused = probe_connect(loopback, port); |
| 1000 | t1 = now_ms(); |
| 1001 | p->connect_ms = t1 - t0; |
| 1002 | p->ok = (refused == 0); |
| 1003 | p->refused = (refused == 1); |
| 1004 | |
| 1005 | if (p->ok) { |
| 1006 | p->http_tried = 1; |
| 1007 | t0 = now_ms(); |
| 1008 | p->http_ok = (probe_http(loopback, port, &p->http_status) == 0); |
| 1009 | t1 = now_ms(); |
| 1010 | p->http_ms = t1 - t0; |
| 1011 | } |
| 1012 | } |
| 1013 | |
| 1014 | /* ------------------------------------------------------------------ */ |
| 1015 | /* JSON output */ |
| 1016 | /* ------------------------------------------------------------------ */ |
| 1017 | |
| 1018 | static void json_header(void) |
| 1019 | { |
| 1020 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 1021 | "Cache-Control: no-store\r\n" |
| 1022 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1023 | } |
| 1024 | |
| 1025 | static int mode_meta(void) |
| 1026 | { |
| 1027 | fputs("{\"name\":\"ports\",\"desc\":\"Listening TCP\"}\n", stdout); |
| 1028 | return 0; |
| 1029 | } |
| 1030 | |
| 1031 | static void print_listeners(void) |
| 1032 | { |
| 1033 | int i; |
| 1034 | int loop = 0, wild = 0, other = 0; |
| 1035 | int tcp = 0, udp = 0; |
| 1036 | |
| 1037 | for (i = 0; i < g_sock_count; i++) { |
| 1038 | if (g_socks[i].scope == SCOPE_LOOPBACK) loop++; |
| 1039 | else if (g_socks[i].scope == SCOPE_WILDCARD) wild++; |
| 1040 | else other++; |
| 1041 | if (strcmp(g_socks[i].proto, "udp") == 0) udp++; |
| 1042 | else tcp++; |
| 1043 | } |
| 1044 | |
| 1045 | fputs("{\"ok\":true,\"action\":\"listeners\",\"source\":\"", stdout); |
| 1046 | #if defined(_WIN32) |
| 1047 | fputs("windows-tables", stdout); |
| 1048 | #elif defined(__APPLE__) |
| 1049 | fputs("lsof", stdout); |
| 1050 | #else |
| 1051 | fputs("procfs", stdout); |
| 1052 | #endif |
| 1053 | fputs("\",\"count\":", stdout); |
| 1054 | printf("%d", g_sock_count); |
| 1055 | fputs(",\"summary\":{\"tcp\":", stdout); |
| 1056 | printf("%d", tcp); |
| 1057 | fputs(",\"udp\":", stdout); |
| 1058 | printf("%d", udp); |
| 1059 | fputs(",\"loopback\":", stdout); |
| 1060 | printf("%d", loop); |
| 1061 | fputs(",\"wildcard\":", stdout); |
| 1062 | printf("%d", wild); |
| 1063 | fputs(",\"specific\":", stdout); |
| 1064 | printf("%d", other); |
| 1065 | fputs("},\"listeners\":[", stdout); |
| 1066 | |
| 1067 | for (i = 0; i < g_sock_count; i++) { |
| 1068 | sock_t *s = &g_socks[i]; |
| 1069 | if (i) putchar(','); |
| 1070 | fputs("{\"proto\":", stdout); |
| 1071 | json_str(s->proto); |
| 1072 | fputs(",\"bind_addr\":", stdout); |
| 1073 | json_str(s->bind_addr); |
| 1074 | printf(",\"port\":%d,\"scope\":", s->port); |
| 1075 | json_str(scope_name(s->scope)); |
| 1076 | printf(",\"pid\":%d,\"comm\":", s->pid); |
| 1077 | json_str(s->comm); |
| 1078 | putchar('}'); |
| 1079 | } |
| 1080 | fputs("]}\n", stdout); |
| 1081 | } |
| 1082 | |
| 1083 | static int mode_json(const char *qs) |
| 1084 | { |
| 1085 | char action[64]; |
| 1086 | char port_s[16]; |
| 1087 | |
| 1088 | action[0] = '\0'; |
| 1089 | get_query_val(qs, "action", action, sizeof(action)); |
| 1090 | |
| 1091 | json_header(); |
| 1092 | |
| 1093 | if (strcmp(action, "probe") == 0) { |
| 1094 | probe_t p; |
| 1095 | int port = 0; |
| 1096 | char now[40]; |
| 1097 | |
| 1098 | get_query_val(qs, "port", port_s, sizeof(port_s)); |
| 1099 | port = atoi(port_s); |
| 1100 | if (port < 1 || port > 65535) { |
| 1101 | fputs("{\"ok\":false,\"error\":\"port must be 1..65535\"}\n", stdout); |
| 1102 | return 0; |
| 1103 | } |
| 1104 | |
| 1105 | run_probe(port, &p); |
| 1106 | utc_stamp(time(NULL), now, sizeof(now)); |
| 1107 | |
| 1108 | fputs("{\"ok\":true,\"action\":\"probe\",\"target\":\"127.0.0.1\",\"port\":", stdout); |
| 1109 | printf("%d", port); |
| 1110 | printf(",\"open\":%s", p.ok ? "true" : "false"); |
| 1111 | printf(",\"refused\":%s", p.refused ? "true" : "false"); |
| 1112 | printf(",\"connect_ms\":%ld", p.connect_ms); |
| 1113 | printf(",\"http_tried\":%s", p.http_tried ? "true" : "false"); |
| 1114 | if (p.http_tried) { |
| 1115 | printf(",\"http_ok\":%s", p.http_ok ? "true" : "false"); |
| 1116 | printf(",\"http_status\":%d", p.http_status); |
| 1117 | printf(",\"http_ms\":%ld", p.http_ms); |
| 1118 | } |
| 1119 | fputs(",\"checked_at\":", stdout); |
| 1120 | json_str(now); |
| 1121 | fputs("}\n", stdout); |
| 1122 | return 0; |
| 1123 | } |
| 1124 | |
| 1125 | if (strcmp(action, "listeners") == 0 || !action[0] || |
| 1126 | strcmp(action, "all") == 0) { |
| 1127 | collect_sockets(); |
| 1128 | print_listeners(); |
| 1129 | return 0; |
| 1130 | } |
| 1131 | |
| 1132 | fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); |
| 1133 | return 0; |
| 1134 | } |
| 1135 | |
| 1136 | /* ------------------------------------------------------------------ */ |
| 1137 | /* HTML UI */ |
| 1138 | /* ------------------------------------------------------------------ */ |
| 1139 | |
| 1140 | static void html_head(void) |
| 1141 | { |
| 1142 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1143 | "Cache-Control: no-store\r\n" |
| 1144 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1145 | |
| 1146 | fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" |
| 1147 | "<meta name='viewport' content='width=device-width,initial-scale=1'>" |
| 1148 | "<title>ports</title>", stdout); |
| 1149 | |
| 1150 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS |
| 1151 | /* this page's short names, mapped onto the bot tokens */ |
| 1152 | ":root{--sf:var(--bg-card);--sf2:var(--surface-2);--tx:var(--text);--mu:var(--text-2);" |
| 1153 | "--ln:var(--line);--ac:var(--blue);--ok:var(--green);--wr:var(--orange);--dg:var(--red);--mo:var(--mono)}", stdout); |
| 1154 | fputs( |
| 1155 | "*{box-sizing:border-box}" |
| 1156 | "body{margin:0;padding:16px;background:var(--bg);color:var(--tx);" |
| 1157 | "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;" |
| 1158 | "line-height:1.5;-webkit-font-smoothing:antialiased}" |
| 1159 | ".wrap{max-width:1120px;margin:0 auto}" |
| 1160 | ".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" |
| 1161 | ".title{font-size:20px;font-weight:700;margin:0}" |
| 1162 | ".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;" |
| 1163 | "background:var(--sf2);color:var(--mu);border:1px solid var(--ln);white-space:nowrap}" |
| 1164 | ".sp{flex:1}" |
| 1165 | ".card{background:var(--sf);border:1px solid var(--ln);border-radius:14px;" |
| 1166 | "padding:16px;margin-bottom:14px}" |
| 1167 | ".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" |
| 1168 | "color:var(--mu);font-weight:600}" |
| 1169 | ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px}" |
| 1170 | ".kpi{background:var(--sf2);border:1px solid var(--ln);border-radius:10px;padding:10px 12px}" |
| 1171 | ".kpi .k{font-size:11px;color:var(--mu);text-transform:uppercase;letter-spacing:.05em}" |
| 1172 | ".kpi .v{font-size:20px;font-weight:700;font-family:var(--mo);margin-top:2px}" |
| 1173 | "button{background:var(--ac);color:#fff;border:0;border-radius:999px;padding:7px 14px;" |
| 1174 | "font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" |
| 1175 | "button.gh{background:transparent;color:var(--tx);border:1px solid var(--ln)}" |
| 1176 | "button.sm{padding:3px 10px;font-size:12px}" |
| 1177 | "button:active{transform:scale(.98)}" |
| 1178 | "input,select{background:var(--sf2);border:1px solid var(--ln);border-radius:10px;" |
| 1179 | "padding:9px 12px;color:var(--tx);font-size:13px;font-family:inherit}" |
| 1180 | "input:focus,select:focus{outline:2px solid var(--ac);outline-offset:-1px}" |
| 1181 | ".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" |
| 1182 | ".tb{width:100%;overflow-x:auto}" |
| 1183 | "table{width:100%;border-collapse:collapse;font-size:13px}" |
| 1184 | "th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" |
| 1185 | "color:var(--mu);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--ln);" |
| 1186 | "white-space:nowrap}" |
| 1187 | "td{padding:7px 8px;border-bottom:1px solid var(--ln);vertical-align:middle}" |
| 1188 | "tr:last-child td{border-bottom:0}" |
| 1189 | ".mo{font-family:var(--mo)}" |
| 1190 | ".tag{font-size:10px;font-weight:700;padding:2px 7px;border-radius:6px;white-space:nowrap}" |
| 1191 | ".t-lo{background:rgba(48,209,88,.16);color:var(--ok)}" |
| 1192 | ".t-wi{background:rgba(255,214,10,.16);color:var(--wr)}" |
| 1193 | ".t-sp{background:rgba(10,132,255,.16);color:var(--ac)}" |
| 1194 | ".t-p{background:var(--sf2);color:var(--mu);border:1px solid var(--ln)}" |
| 1195 | ".rt{font-size:12px;font-weight:600}" |
| 1196 | ".rt.g{color:var(--ok)}.rt.r{color:var(--dg)}.rt.n{color:var(--mu)}" |
| 1197 | ".hide{display:none!important}" |
| 1198 | "@media(max-width:560px){body{padding:10px}.card{padding:12px}}" |
| 1199 | "</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout); |
| 1200 | } |
| 1201 | |
| 1202 | static void html_box(int embed) |
| 1203 | { |
| 1204 | fputs("<div class='top'>", stdout); |
| 1205 | if (!embed) |
| 1206 | fputs("<a href='/' style='color:var(--ac);text-decoration:none;font-weight:600'>" |
| 1207 | "←</a>", stdout); |
| 1208 | fputs("<h1 class='title'>ports</h1>" |
| 1209 | "<span class='pill' id='srcPill'>local</span>" |
| 1210 | "<span class='sp'></span>" |
| 1211 | "<button class='gh sm embed-hide' id='thBtn'>Theme</button>" |
| 1212 | "<button class='sm' id='rfBtn'>Rescan</button>" |
| 1213 | "</div>", stdout); |
| 1214 | |
| 1215 | fputs("<div class='card'><h2>Listening sockets</h2><div class='grid'>" |
| 1216 | "<div class='kpi'><div class='k'>Total</div><div class='v' id='kTotal'>-</div></div>" |
| 1217 | "<div class='kpi'><div class='k'>TCP</div><div class='v' id='kTcp'>-</div></div>" |
| 1218 | "<div class='kpi'><div class='k'>UDP</div><div class='v' id='kUdp'>-</div></div>" |
| 1219 | "<div class='kpi'><div class='k'>Loopback</div><div class='v' id='kLoop'>-</div></div>" |
| 1220 | "<div class='kpi'><div class='k'>Wildcard</div><div class='v' id='kWild'>-</div></div>" |
| 1221 | "</div></div>", stdout); |
| 1222 | |
| 1223 | fputs("<div class='card'><div class='row' style='margin-bottom:10px'>" |
| 1224 | "<input id='q' placeholder='Filter by port, process or address' " |
| 1225 | "style='flex:1;min-width:180px' autocomplete='off'>" |
| 1226 | "<select id='sc'>" |
| 1227 | "<option value=''>All scopes</option>" |
| 1228 | "<option value='loopback'>Loopback only</option>" |
| 1229 | "<option value='wildcard'>Wildcard (0.0.0.0)</option>" |
| 1230 | "<option value='specific'>Specific address</option>" |
| 1231 | "</select>" |
| 1232 | "<select id='pr'>" |
| 1233 | "<option value=''>TCP+UDP</option>" |
| 1234 | "<option value='tcp'>TCP only</option>" |
| 1235 | "<option value='udp'>UDP only</option>" |
| 1236 | "</select></div>" |
| 1237 | "<div class='tb'><table><thead><tr>" |
| 1238 | "<th>Proto</th><th>Bind</th><th>Port</th><th>Scope</th>" |
| 1239 | "<th>PID</th><th>Process</th><th>Probe</th>" |
| 1240 | "</tr></thead><tbody id='rows'></tbody></table></div>" |
| 1241 | "<div id='empty' class='hide' style='color:var(--mu);padding:12px 0'>" |
| 1242 | "No listening sockets matched the filter.</div></div>", stdout); |
| 1243 | |
| 1244 | fputs("<div class='card'><h2>Loopback health probe</h2>" |
| 1245 | "<div class='row' style='margin-bottom:10px'>" |
| 1246 | "<input id='pPort' type='number' min='1' max='65535' value='8150' " |
| 1247 | "style='width:120px' placeholder='port'>" |
| 1248 | "<button id='pBtn'>Probe 127.0.0.1</button>" |
| 1249 | "<span style='color:var(--mu);font-size:12px'>" |
| 1250 | "Connects to the loopback address on this node only.</span></div>" |
| 1251 | "<div id='pOut' style='color:var(--mu);font-size:13px'>" |
| 1252 | "No probe run yet.</div></div>", stdout); |
| 1253 | } |
| 1254 | |
| 1255 | static void html_script(void) |
| 1256 | { |
| 1257 | fputs("<script>\n" |
| 1258 | "(function(){" |
| 1259 | "var q=new URLSearchParams(location.search);" |
| 1260 | "var node=q.get('node')||'';" |
| 1261 | "var sid=q.get('id')||'';" |
| 1262 | "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||" |
| 1263 | "localStorage.getItem('bot_active_pwd')||'';" |
| 1264 | "var HUB=q.get('plugin')||'';" |
| 1265 | |
| 1266 | /* Two call routes, and getting this wrong is the most common plugin bug: |
| 1267 | * page served through the hub -> call the hub proxy back |
| 1268 | * opened directly on the node -> the plugin itself is the route. |
| 1269 | * Calling /plugins?plugin= on the node returns the discovery list, not us. */ |
| 1270 | "function api(action,extra){" |
| 1271 | "var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_ports')+" |
| 1272 | "'?action='+encodeURIComponent(action)+" |
| 1273 | "(extra?('&'+extra):'')+" |
| 1274 | "(node?'&node='+encodeURIComponent(node):'')+" |
| 1275 | "(sid?'&id='+encodeURIComponent(sid):'')+" |
| 1276 | "(pwd?'&pwd='+encodeURIComponent(pwd):'');" |
| 1277 | "return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){" |
| 1278 | "if(!r.ok)throw new Error('HTTP '+r.status);return r.json();});}" |
| 1279 | |
| 1280 | "var DATA=[];var lastProbe={};" |
| 1281 | "function tagCls(s){return s==='loopback'?'t-lo':(s==='wildcard'?'t-wi':'t-sp');}" |
| 1282 | "function esc(v){return String(v==null?'':v).replace(/[&<>\"']/g,function(c){" |
| 1283 | "return({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''})[c];});}" |
| 1284 | "function txt(id,v){var e=document.getElementById(id);if(e)e.textContent=v;}" |
| 1285 | |
| 1286 | "function render(){" |
| 1287 | "var f=(document.getElementById('q').value||'').toLowerCase();" |
| 1288 | "var sc=document.getElementById('sc').value;" |
| 1289 | "var pr=document.getElementById('pr').value;" |
| 1290 | "var rows=document.getElementById('rows');" |
| 1291 | "var out=[];" |
| 1292 | "for(var i=0;i<DATA.length;i++){" |
| 1293 | "var s=DATA[i];" |
| 1294 | "if(sc&&s.scope!==sc)continue;" |
| 1295 | "if(pr&&s.proto!==pr)continue;" |
| 1296 | "var hay=(s.port+' '+s.proto+' '+s.comm+' '+s.bind_addr).toLowerCase();" |
| 1297 | "if(f&&hay.indexOf(f)<0)continue;" |
| 1298 | "out.push(s);}" |
| 1299 | "var h='';" |
| 1300 | "for(var j=0;j<out.length;j++){" |
| 1301 | "var s=out[j];" |
| 1302 | "var p=lastProbe[s.port];" |
| 1303 | "var rt=p?(p.open?'<span class=\"rt g\">open '+p.connect_ms+'ms</span>':" |
| 1304 | "(p.refused?'<span class=\"rt r\">refused</span>':'<span class=\"rt r\">closed</span>')):" |
| 1305 | "'<span class=\"rt n\">-</span>';" |
| 1306 | "h+='<tr><td class=\"mo\">'+esc(s.proto)+'</td>'" |
| 1307 | "+'<td class=\"mo\">'+esc(s.bind_addr)+'</td>'" |
| 1308 | "+'<td class=\"mo\">'+esc(s.port)+'</td>'" |
| 1309 | "+'<td><span class=\"tag '+tagCls(s.scope)+'\">'+esc(s.scope)+'</span></td>'" |
| 1310 | "+'<td class=\"mo\">'+(s.pid>0?esc(s.pid):'-')+'</td>'" |
| 1311 | "+'<td>'+esc(s.comm||'-')+'</td>'" |
| 1312 | "+'<td>'+rt+' <button class=\"gh sm\" data-p=\"'+esc(s.port)+'\">Probe</button></td></tr>';}" |
| 1313 | "rows.innerHTML=h;" |
| 1314 | "document.getElementById('empty').className=out.length?'hide':'';" |
| 1315 | "var b=rows.querySelectorAll('button[data-p]');" |
| 1316 | "for(var k=0;k<b.length;k++){b[k].onclick=function(){" |
| 1317 | "doProbe(parseInt(this.getAttribute('data-p'),10));};}}" |
| 1318 | |
| 1319 | "function load(){" |
| 1320 | "return api('listeners').then(function(d){" |
| 1321 | "DATA=(d.listeners||[]);" |
| 1322 | "var s=d.summary||{};" |
| 1323 | "txt('kTotal',d.count||0);txt('kTcp',s.tcp||0);txt('kUdp',s.udp||0);" |
| 1324 | "txt('kLoop',s.loopback||0);txt('kWild',s.wildcard||0);" |
| 1325 | "txt('srcPill','source: '+(d.source||'local'));" |
| 1326 | "render();}).catch(function(e){txt('pOut','Load failed: '+e.message);});}" |
| 1327 | |
| 1328 | "function doProbe(port){" |
| 1329 | "if(!port||port<1||port>65535){txt('pOut','Port must be between 1 and 65535.');return;}" |
| 1330 | "txt('pOut','Probing 127.0.0.1:'+port+' ...');" |
| 1331 | "return api('probe','port='+port).then(function(d){" |
| 1332 | "if(!d.ok){txt('pOut',d.error||'probe failed');return;}" |
| 1333 | "lastProbe[port]=d;" |
| 1334 | "var m='127.0.0.1:'+port+' -> '+(d.open?'open':'closed')+" |
| 1335 | "' (connect '+d.connect_ms+' ms)';" |
| 1336 | "if(d.http_tried){m+='; HTTP '+(d.http_ok?('status '+d.http_status):'no response')+" |
| 1337 | "' in '+d.http_ms+' ms';}" |
| 1338 | "txt('pOut',m);" |
| 1339 | "render();}).catch(function(e){txt('pOut','Probe failed: '+e.message);});}" |
| 1340 | |
| 1341 | "document.getElementById('rfBtn').onclick=function(){load();};" |
| 1342 | "document.getElementById('thBtn').onclick=function(){" |
| 1343 | "window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" |
| 1344 | "document.getElementById('q').oninput=render;" |
| 1345 | "document.getElementById('sc').onchange=render;" |
| 1346 | "document.getElementById('pr').onchange=render;" |
| 1347 | "document.getElementById('pBtn').onclick=function(){" |
| 1348 | "doProbe(parseInt(document.getElementById('pPort').value,10));};" |
| 1349 | "load();" |
| 1350 | "})();\n</script></body></html>\n", stdout); |
| 1351 | } |
| 1352 | |
| 1353 | static int mode_html(int embed) |
| 1354 | { |
| 1355 | html_head(); |
| 1356 | html_box(embed); |
| 1357 | html_script(); |
| 1358 | return 0; |
| 1359 | } |
| 1360 | |
| 1361 | static int is_post_request(void) |
| 1362 | { |
| 1363 | const char *m = getenv("REQUEST_METHOD"); |
| 1364 | return m && strcmp(m, "POST") == 0; |
| 1365 | } |
| 1366 | |
| 1367 | int main(int argc, char **argv) |
| 1368 | { |
| 1369 | const char *qs; |
| 1370 | int embed; |
| 1371 | |
| 1372 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || |
| 1373 | (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) |
| 1374 | return mode_meta(); |
| 1375 | |
| 1376 | #if defined(_WIN32) |
| 1377 | { |
| 1378 | WSADATA wsa; |
| 1379 | if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) |
| 1380 | return mode_meta(); |
| 1381 | } |
| 1382 | #endif |
| 1383 | |
| 1384 | require_node_auth(); |
| 1385 | |
| 1386 | qs = getenv("QUERY_STRING"); |
| 1387 | if (!qs) qs = ""; |
| 1388 | |
| 1389 | if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) |
| 1390 | return mode_json(qs); |
| 1391 | |
| 1392 | embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); |
| 1393 | return mode_html(embed); |
| 1394 | } |