| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817 |
- /*
- * c_bridge.c — XJKJ-STL Native C Runtime Bridge (v0.8.1.19)
- *
- * Compiled strictly with -O3 -march=x86-64 (pure SSE2 baseline, no AVX/POPCNT
- * emitted by the compiler) so dual-core Celeron/Pentium (Sandy Bridge..Coffee Lake)
- * never trigger SIGILL. Runtime CPUID + XGETBV dispatches SSE2 / SSE4.2 / AVX2
- * assembly kernels dynamically.
- */
- #define _GNU_SOURCE
- #include "stl_accel.h"
- #include <arpa/inet.h>
- #include <cpuid.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <netdb.h>
- #include <netinet/in.h>
- #include <netinet/tcp.h>
- #include <poll.h>
- #include <pty.h>
- #include <pthread.h>
- #include <sched.h>
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/epoll.h>
- #include <sys/eventfd.h>
- #include <sys/mman.h>
- #include <sys/socket.h>
- #include <sys/timerfd.h>
- #include <sys/uio.h>
- #include <sys/wait.h>
- #include <termios.h>
- #include <time.h>
- #include <unistd.h>
- /* =========================================================================
- * 1. Runtime CPUID + XGETBV ISA Tier Detection & Dispatch
- * ========================================================================= */
- typedef struct {
- uint32_t isa_tier;
- uint32_t has_sse42;
- uint32_t has_avx2;
- uint32_t has_bmi2;
- char cpu_brand[64];
- char tier_name[32];
- } StlHwCapsCompat;
- static pthread_once_t g_hw_once = PTHREAD_ONCE_INIT;
- static int g_detected_tier = STL_ISA_SSE2;
- static int g_forced_tier = -1;
- static StlHwCapsCompat g_hw_caps;
- static void detect_hw_once(void) {
- memset(&g_hw_caps, 0, sizeof(g_hw_caps));
- unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0;
- unsigned int max_leaf = __get_cpuid_max(0, NULL);
- int has_sse42 = 0;
- int has_popcnt = 0;
- int has_osxsave = 0;
- int has_avx = 0;
- int has_avx2 = 0;
- int has_bmi1 = 0;
- int has_bmi2 = 0;
- if (max_leaf >= 1 && __get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
- has_sse42 = (ecx & (1u << 20)) != 0;
- has_popcnt = (ecx & (1u << 23)) != 0;
- has_osxsave = (ecx & (1u << 27)) != 0;
- has_avx = (ecx & (1u << 28)) != 0;
- }
- int ymm_os_ok = 0;
- if (has_osxsave && has_avx) {
- uint64_t xcr0 = asm_xgetbv_eax0();
- ymm_os_ok = ((xcr0 & 0x6ULL) == 0x6ULL);
- }
- if (max_leaf >= 7 && __get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx)) {
- has_bmi1 = (ebx & (1u << 3)) != 0;
- has_avx2 = (ebx & (1u << 5)) != 0;
- has_bmi2 = (ebx & (1u << 8)) != 0;
- }
- if (ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2 && has_sse42 && has_popcnt) {
- g_detected_tier = STL_ISA_AVX2_BMI;
- } else if (has_sse42 && has_popcnt) {
- g_detected_tier = STL_ISA_SSE42_POPCNT;
- } else {
- g_detected_tier = STL_ISA_SSE2;
- }
- /* Read CPU brand string (leaves 0x80000002..0x80000004) */
- unsigned int max_ext = __get_cpuid_max(0x80000000u, NULL);
- if (max_ext >= 0x80000004u) {
- uint32_t brand_words[12];
- __get_cpuid(0x80000002u, &brand_words[0], &brand_words[1], &brand_words[2], &brand_words[3]);
- __get_cpuid(0x80000003u, &brand_words[4], &brand_words[5], &brand_words[6], &brand_words[7]);
- __get_cpuid(0x80000004u, &brand_words[8], &brand_words[9], &brand_words[10], &brand_words[11]);
- memcpy(g_hw_caps.cpu_brand, brand_words, 48);
- g_hw_caps.cpu_brand[48] = '\0';
- } else {
- snprintf(g_hw_caps.cpu_brand, sizeof(g_hw_caps.cpu_brand), "x86_64-generic");
- }
- g_hw_caps.isa_tier = (uint32_t)g_detected_tier;
- g_hw_caps.has_sse42 = (uint32_t)(has_sse42 && has_popcnt);
- g_hw_caps.has_avx2 = (uint32_t)(ymm_os_ok && has_avx2);
- g_hw_caps.has_bmi2 = (uint32_t)has_bmi2;
- snprintf(g_hw_caps.tier_name, sizeof(g_hw_caps.tier_name), "%s", stl_isa_tier_name(g_detected_tier));
- }
- void c_init_once_hw_dispatch(void) {
- pthread_once(&g_hw_once, detect_hw_once);
- }
- int stl_cpu_tier_detect(void) {
- pthread_once(&g_hw_once, detect_hw_once);
- return g_detected_tier;
- }
- int stl_active_isa_tier(void) {
- pthread_once(&g_hw_once, detect_hw_once);
- int forced = __atomic_load_n(&g_forced_tier, __ATOMIC_RELAXED);
- if (forced >= STL_ISA_SSE2 && forced <= STL_ISA_AVX2_BMI) {
- if (forced <= g_detected_tier) return forced;
- }
- return g_detected_tier;
- }
- void stl_force_isa_tier(int tier) {
- pthread_once(&g_hw_once, detect_hw_once);
- __atomic_store_n(&g_forced_tier, tier, __ATOMIC_RELAXED);
- }
- const char *stl_isa_tier_name(int tier) {
- switch (tier) {
- case STL_ISA_AVX2_BMI: return "AVX2+BMI1/2";
- case STL_ISA_SSE42_POPCNT: return "SSE4.2+POPCNT";
- default: return "SSE2-baseline";
- }
- }
- void c_get_hw_caps(StlHwCapsCompat *out_caps) {
- pthread_once(&g_hw_once, detect_hw_once);
- if (!out_caps) return;
- *out_caps = g_hw_caps;
- int active = stl_active_isa_tier();
- out_caps->isa_tier = (uint32_t)active;
- snprintf(out_caps->tier_name, sizeof(out_caps->tier_name), "%s", stl_isa_tier_name(active));
- }
- size_t stl_base64_encode(const uint8_t *src, size_t len, uint8_t *dst) {
- if (!src || !dst || len == 0) return 0;
- int tier = stl_active_isa_tier();
- if (tier >= STL_ISA_AVX2_BMI) {
- return asm_base64_encode_avx2(src, len, dst);
- }
- return asm_base64_encode_sse2(src, len, dst);
- }
- void stl_clean_stream_init(StlCleanStreamState *state) {
- if (!state) return;
- memset(state, 0, sizeof(*state));
- }
- void stl_clean_stream_clear_halfline(StlCleanStreamState *state) {
- if (!state) return;
- state->half_len = 0;
- state->tag_mask = 0;
- state->first_nonws = 0;
- state->cur_col = 0;
- state->prev_was_cr = 0;
- state->esc_state = 0;
- }
- void stl_clean_split_classify(
- StlCleanStreamState *state,
- const uint8_t *src,
- size_t src_len,
- StlCleanOutput *out) {
- if (!state || !out) return;
- if (!src || src_len == 0) {
- out->src_consumed = 0;
- return;
- }
- int tier = stl_active_isa_tier();
- if (tier >= STL_ISA_AVX2_BMI) {
- asm_clean_split_classify_avx2(state, src, src_len, out);
- } else if (tier >= STL_ISA_SSE42_POPCNT) {
- asm_clean_split_classify_sse42(state, src, src_len, out);
- } else {
- asm_clean_split_classify_sse2(state, src, src_len, out);
- }
- }
- /* Pure SSE2 helper for legacy single-buffer scan (zero rdtsc/lfence!) */
- size_t c_dispatch_scan_special(
- const uint8_t *buf,
- size_t len,
- uint64_t *out_newlines,
- uint64_t *out_specials) {
- uint64_t nl = 0;
- uint64_t sp = 0;
- size_t first_ctrl = len;
- for (size_t i = 0; i < len; i++) {
- uint8_t b = buf[i];
- if (b == '\n' || b == '\r') {
- nl++;
- } else if (b < 0x20 || b == 0x7f) {
- sp++;
- if (first_ctrl == len) first_ctrl = i;
- }
- }
- if (out_newlines) *out_newlines = nl;
- if (out_specials) *out_specials = sp;
- return first_ctrl;
- }
- /* =========================================================================
- * 2. Monotonic 64-Bit mmap Ring Buffer (Hugepage + 64B Pad + PROT_NONE Guard)
- * ========================================================================= */
- static size_t round_up_pow2_min2m(size_t v) {
- size_t cap = 2u * 1024u * 1024u; /* 2 MiB hugepage granularity */
- while (cap < v && cap < (1ULL << 30)) {
- cap <<= 1;
- }
- return cap;
- }
- int stl_ring_init(StlRingBuf *rb, size_t requested_cap) {
- if (!rb) return -1;
- memset(rb, 0, sizeof(*rb));
- size_t cap = round_up_pow2_min2m(requested_cap == 0 ? (8u * 1024u * 1024u) : requested_cap);
- size_t page_sz = 4096u;
- /* [0..cap): circular ring; [cap..cap+4096): 64B+ zeroed tail pad page; [cap+4096..cap+8192): PROT_NONE guard */
- size_t pad_bytes = page_sz;
- size_t guard_bytes = page_sz;
- size_t total = cap + pad_bytes + guard_bytes;
- void *mem = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
- if (mem == MAP_FAILED) {
- return -1;
- }
- #ifdef MADV_HUGEPAGE
- (void)madvise(mem, cap, MADV_HUGEPAGE);
- #endif
- /* Arm hardware guard page immediately after the 4KB tail-padding page */
- uint8_t *base = (uint8_t *)mem;
- memset(base + cap, 0, pad_bytes);
- if (mprotect(base + cap + pad_bytes, guard_bytes, PROT_NONE) != 0) {
- munmap(mem, total);
- return -1;
- }
- rb->buf = base;
- rb->cap = cap;
- rb->mask = cap - 1;
- rb->mmap_total = total;
- rb->base_offset = 0;
- rb->write_offset = 0;
- return 0;
- }
- void stl_ring_destroy(StlRingBuf *rb) {
- if (!rb) return;
- if (rb->buf && rb->mmap_total > 0) {
- munmap(rb->buf, rb->mmap_total);
- }
- memset(rb, 0, sizeof(*rb));
- }
- uint64_t stl_ring_append(StlRingBuf *rb, const uint8_t *data, size_t len) {
- if (!rb || !rb->buf) return 0;
- if (!data || len == 0) return rb->write_offset;
- if (len >= rb->cap) {
- /* Input chunk exceeds entire ring capacity: retain trailing cap bytes */
- const uint8_t *tail = data + (len - rb->cap);
- uint64_t new_wo = rb->write_offset + (uint64_t)len;
- uint64_t new_bo = new_wo - (uint64_t)rb->cap;
- size_t pos = (size_t)(new_bo & rb->mask);
- size_t first = rb->cap - pos;
- memcpy(rb->buf + pos, tail, first);
- if (first < rb->cap) {
- memcpy(rb->buf, tail + first, rb->cap - first);
- }
- memset(rb->buf + rb->cap, 0, 64);
- rb->write_offset = new_wo;
- rb->base_offset = new_bo;
- return rb->write_offset;
- }
- size_t pos = (size_t)(rb->write_offset & rb->mask);
- size_t first = rb->cap - pos;
- if (first >= len) {
- memcpy(rb->buf + pos, data, len);
- } else {
- memcpy(rb->buf + pos, data, first);
- memcpy(rb->buf, data + first, len - first);
- }
- /* Ensure 64-byte SIMD tail padding stays zeroed */
- memset(rb->buf + rb->cap, 0, 64);
- rb->write_offset += (uint64_t)len;
- if (rb->write_offset - rb->base_offset > (uint64_t)rb->cap) {
- /* Slide oldest bound forward; write_offset NEVER regresses */
- rb->base_offset = rb->write_offset - (uint64_t)rb->cap;
- }
- return rb->write_offset;
- }
- size_t stl_ring_read(
- const StlRingBuf *rb,
- uint64_t req_offset,
- uint8_t *dst,
- size_t max_len,
- uint64_t *out_actual_start,
- uint64_t *out_next_offset) {
- if (!rb || !rb->buf) {
- if (out_actual_start) *out_actual_start = 0;
- if (out_next_offset) *out_next_offset = 0;
- return 0;
- }
- uint64_t start = req_offset;
- if (start < rb->base_offset) {
- /* Reader fell behind trimmed window: advance monotonically to base_offset */
- start = rb->base_offset;
- }
- if (start >= rb->write_offset || !dst || max_len == 0) {
- uint64_t cur = rb->write_offset;
- if (out_actual_start) *out_actual_start = cur;
- if (out_next_offset) *out_next_offset = cur;
- return 0;
- }
- uint64_t avail = rb->write_offset - start;
- size_t n = (avail < (uint64_t)max_len) ? (size_t)avail : max_len;
- size_t pos = (size_t)(start & rb->mask);
- size_t first = rb->cap - pos;
- if (first >= n) {
- memcpy(dst, rb->buf + pos, n);
- } else {
- memcpy(dst, rb->buf + pos, first);
- memcpy(dst + first, rb->buf, n - first);
- }
- if (out_actual_start) *out_actual_start = start;
- if (out_next_offset) *out_next_offset = start + (uint64_t)n;
- return n;
- }
- void stl_ring_clear_monotonic(StlRingBuf *rb) {
- if (!rb) return;
- /* Advance base_offset to write_offset so old data is logically trimmed WITHOUT resetting offset! */
- rb->base_offset = rb->write_offset;
- }
- /* =========================================================================
- * 3. epoll / timerfd / eventfd / TCP_NODELAY + writev / Core Affinity
- * ========================================================================= */
- int stl_epoll_create(void) {
- return epoll_create1(EPOLL_CLOEXEC);
- }
- int stl_epoll_ctl_fd(int epfd, int op, int fd, uint32_t events, uint64_t token) {
- struct epoll_event ev;
- memset(&ev, 0, sizeof(ev));
- ev.events = events;
- ev.data.u64 = token;
- return epoll_ctl(epfd, op, fd, &ev);
- }
- int stl_epoll_wait_tokens(
- int epfd,
- uint64_t *out_tokens,
- uint32_t *out_events,
- int max_ev,
- int timeout_ms) {
- if (epfd < 0 || max_ev <= 0) return 0;
- if (max_ev > 128) max_ev = 128;
- struct epoll_event evs[128];
- int n = epoll_wait(epfd, evs, max_ev, timeout_ms);
- if (n <= 0) return 0;
- for (int i = 0; i < n; i++) {
- if (out_tokens) out_tokens[i] = evs[i].data.u64;
- if (out_events) out_events[i] = evs[i].events;
- }
- return n;
- }
- int stl_timerfd_create_ms(uint64_t initial_ms, uint64_t interval_ms) {
- int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
- if (tfd < 0) return -1;
- if (stl_timerfd_arm_ms(tfd, initial_ms, interval_ms) != 0) {
- close(tfd);
- return -1;
- }
- return tfd;
- }
- int stl_timerfd_arm_ms(int tfd, uint64_t initial_ms, uint64_t interval_ms) {
- if (tfd < 0) return -1;
- struct itimerspec its;
- memset(&its, 0, sizeof(its));
- its.it_value.tv_sec = (time_t)(initial_ms / 1000ULL);
- its.it_value.tv_nsec = (long)((initial_ms % 1000ULL) * 1000000ULL);
- its.it_interval.tv_sec = (time_t)(interval_ms / 1000ULL);
- its.it_interval.tv_nsec = (long)((interval_ms % 1000ULL) * 1000000ULL);
- return timerfd_settime(tfd, 0, &its, NULL);
- }
- void stl_timerfd_drain(int tfd) {
- if (tfd < 0) return;
- uint64_t exp = 0;
- while (read(tfd, &exp, sizeof(exp)) > 0) {}
- }
- int stl_eventfd_create(void) {
- return eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
- }
- void stl_eventfd_notify(int efd) {
- if (efd < 0) return;
- uint64_t v = 1;
- ssize_t _r = write(efd, &v, sizeof(v));
- (void)_r;
- }
- void stl_eventfd_drain(int efd) {
- if (efd < 0) return;
- uint64_t v = 0;
- while (read(efd, &v, sizeof(v)) > 0) {}
- }
- int stl_set_nonblocking_nodelay(int fd, int is_tcp) {
- if (fd < 0) return -1;
- int flags = fcntl(fd, F_GETFL, 0);
- if (flags >= 0) {
- (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
- }
- if (is_tcp) {
- int one = 1;
- (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
- (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
- }
- return 0;
- }
- /* Merged WebSocket header + payload writev (eliminates 44ms delayed-ACK stall) */
- int64_t stl_ws_writev2(
- int fd,
- const uint8_t *hdr,
- size_t hdr_len,
- const uint8_t *body,
- size_t body_len) {
- if (fd < 0) return -1;
- size_t off0 = 0;
- size_t off1 = 0;
- size_t total = hdr_len + body_len;
- size_t sent = 0;
- while (sent < total) {
- struct iovec iov[2];
- int iovcnt = 0;
- if (off0 < hdr_len) {
- iov[iovcnt].iov_base = (void *)(hdr + off0);
- iov[iovcnt].iov_len = hdr_len - off0;
- iovcnt++;
- }
- if (off1 < body_len) {
- iov[iovcnt].iov_base = (void *)(body + off1);
- iov[iovcnt].iov_len = body_len - off1;
- iovcnt++;
- }
- ssize_t n = writev(fd, iov, iovcnt);
- if (n > 0) {
- size_t adv = (size_t)n;
- sent += adv;
- if (off0 < hdr_len) {
- size_t rem0 = hdr_len - off0;
- if (adv <= rem0) {
- off0 += adv;
- adv = 0;
- } else {
- off0 = hdr_len;
- adv -= rem0;
- }
- }
- off1 += adv;
- continue;
- }
- if (n < 0 && errno == EINTR) continue;
- if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
- struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
- int pr = poll(&pfd, 1, 2000);
- if (pr > 0) continue;
- return -1;
- }
- return -1;
- }
- return (int64_t)sent;
- }
- void stl_pin_thread_to_core(int core_index) {
- if (core_index < 0) return;
- long ncores = sysconf(_SC_NPROCESSORS_ONLN);
- if (ncores <= 0) return;
- int target = core_index % (int)ncores;
- cpu_set_t set;
- CPU_ZERO(&set);
- CPU_SET(target, &set);
- (void)pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
- }
- /* =========================================================================
- * 4. Serial / TCP-RS232 / SSH Console (ignore known_hosts!) / IPMI SOL PTYs
- * ========================================================================= */
- int stl_open_tty_115200_raw(const char *path) {
- if (!path || path[0] == '\0') return -1;
- /* Safety guard: NEVER touch /dev/ttyUSB1 (reserved for unrelated board) */
- if (strstr(path, "ttyUSB1") != NULL) {
- return -1;
- }
- int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
- if (fd < 0) return -1;
- struct termios tio;
- if (tcgetattr(fd, &tio) != 0) {
- close(fd);
- return -1;
- }
- cfmakeraw(&tio);
- cfsetispeed(&tio, B115200);
- cfsetospeed(&tio, B115200);
- tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
- tio.c_cflag |= (CS8 | CLOCAL | CREAD);
- tio.c_iflag &= ~(IXON | IXOFF | IXANY);
- tio.c_cc[VMIN] = 0;
- tio.c_cc[VTIME] = 0;
- if (tcsetattr(fd, TCSANOW, &tio) != 0) {
- close(fd);
- return -1;
- }
- return fd;
- }
- int c_pty_open_serial_115200(const char *path) {
- return stl_open_tty_115200_raw(path);
- }
- /* Open serial with configurable baud rate (115200 / 230400 / 460800 / 921600) for thermal hood */
- int c_open_tty_baud_raw(const char *path, int baud) {
- if (!path || path[0] == '\0') return -1;
- if (strstr(path, "ttyUSB1") != NULL) return -1;
- int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
- if (fd < 0) return -1;
- struct termios tio;
- if (tcgetattr(fd, &tio) != 0) {
- close(fd);
- return -1;
- }
- cfmakeraw(&tio);
- speed_t sp = B115200;
- if (baud == 921600) sp = B921600;
- else if (baud == 460800) sp = B460800;
- else if (baud == 230400) sp = B230400;
- cfsetispeed(&tio, sp);
- cfsetospeed(&tio, sp);
- tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
- tio.c_cflag |= (CS8 | CLOCAL | CREAD);
- tio.c_iflag &= ~(IXON | IXOFF | IXANY);
- tio.c_cc[VMIN] = 0;
- tio.c_cc[VTIME] = 0;
- if (tcsetattr(fd, TCSANOW, &tio) != 0) {
- close(fd);
- return -1;
- }
- return fd;
- }
- int c_pty_open_tcp_serial(const char *host, int port, int timeout_ms) {
- if (!host || host[0] == '\0' || port <= 0) return -1;
- struct addrinfo hints, *res = NULL;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
- char port_s[16];
- snprintf(port_s, sizeof(port_s), "%d", port);
- if (getaddrinfo(host, port_s, &hints, &res) != 0 || !res) return -1;
- int sfd = socket(res->ai_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
- if (sfd < 0) {
- freeaddrinfo(res);
- return -1;
- }
- int one = 1;
- (void)setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
- (void)setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
- int rc = connect(sfd, res->ai_addr, res->ai_addrlen);
- freeaddrinfo(res);
- if (rc != 0) {
- if (errno != EINPROGRESS) {
- close(sfd);
- return -1;
- }
- struct pollfd pfd = { .fd = sfd, .events = POLLOUT, .revents = 0 };
- int wait_ms = (timeout_ms > 0) ? timeout_ms : 1500;
- if (poll(&pfd, 1, wait_ms) <= 0) {
- close(sfd);
- return -1;
- }
- int so_err = 0;
- socklen_t slen = sizeof(so_err);
- if (getsockopt(sfd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 || so_err != 0) {
- close(sfd);
- return -1;
- }
- }
- return sfd;
- }
- /*
- * Spawn SSH console (port 2200) inside non-blocking PTY.
- * Explicitly ignores known_hosts host-key changes so swapping server motherboards
- * never blocks or fails with REMOTE HOST IDENTIFICATION HAS CHANGED.
- */
- int c_pty_spawn_ssh_console(
- const char *host,
- int port,
- const char *user,
- const char *password,
- const char *known_hosts_path,
- int *out_master_fd,
- int *out_child_pid) {
- (void)known_hosts_path; /* Ignored intentionally per motherboard-swap requirement */
- if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
- int master_fd = -1;
- pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);
- if (pid < 0) return -1;
- if (pid == 0) {
- char port_str[16];
- snprintf(port_str, sizeof(port_str), "%d", port > 0 ? port : 2200);
- setenv("SSHPASS", password, 1);
- setenv("TERM", "vt100", 1);
- execlp(
- "sshpass", "sshpass", "-e",
- "ssh",
- "-tt",
- "-p", port_str,
- "-o", "StrictHostKeyChecking=no",
- "-o", "UserKnownHostsFile=/dev/null",
- "-o", "GlobalKnownHostsFile=/dev/null",
- "-o", "LogLevel=ERROR",
- "-o", "ConnectTimeout=15",
- "-o", "ServerAliveInterval=10",
- "-o", "ServerAliveCountMax=3",
- "-l", user,
- host,
- (char *)NULL);
- _exit(127);
- }
- int flags = fcntl(master_fd, F_GETFL, 0);
- if (flags >= 0) (void)fcntl(master_fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
- *out_master_fd = master_fd;
- *out_child_pid = (int)pid;
- return 0;
- }
- int c_pty_spawn_ipmi_sol(
- const char *host,
- const char *user,
- const char *password,
- int *out_master_fd,
- int *out_child_pid) {
- if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
- int master_fd = -1;
- pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);
- if (pid < 0) return -1;
- if (pid == 0) {
- setenv("IPMI_PASSWORD", password, 1);
- setenv("TERM", "vt100", 1);
- execlp(
- "ipmitool", "ipmitool",
- "-I", "lanplus",
- "-C", "17",
- "-H", host,
- "-U", user,
- "-E",
- "sol", "activate",
- (char *)NULL);
- _exit(127);
- }
- int flags = fcntl(master_fd, F_GETFL, 0);
- if (flags >= 0) (void)fcntl(master_fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
- *out_master_fd = master_fd;
- *out_child_pid = (int)pid;
- return 0;
- }
- /*
- * Persistent non-blocking IPMI shell session per station:
- * Keeps a single RMCP+ session open via `ipmitool -I lanplus -C <cipher> -H <host> -U <user> -E shell`
- * connected to non-blocking stdin/stdout pipes so power & SDR queries execute with zero blocking!
- */
- int c_spawn_persistent_ipmi_shell(
- const char *host,
- const char *user,
- const char *password,
- int cipher_suite,
- int *out_stdin_fd,
- int *out_stdout_fd,
- int *out_child_pid) {
- if (!host || !user || !password || !out_stdin_fd || !out_stdout_fd || !out_child_pid) return -1;
- int in_pipe[2] = {-1, -1};
- int out_pipe[2] = {-1, -1};
- if (pipe2(in_pipe, O_CLOEXEC) != 0) return -1;
- if (pipe2(out_pipe, O_CLOEXEC) != 0) {
- close(in_pipe[0]);
- close(in_pipe[1]);
- return -1;
- }
- pid_t pid = fork();
- if (pid < 0) {
- close(in_pipe[0]); close(in_pipe[1]);
- close(out_pipe[0]); close(out_pipe[1]);
- return -1;
- }
- if (pid == 0) {
- dup2(in_pipe[0], STDIN_FILENO);
- dup2(out_pipe[1], STDOUT_FILENO);
- dup2(out_pipe[1], STDERR_FILENO);
- close(in_pipe[0]); close(in_pipe[1]);
- close(out_pipe[0]); close(out_pipe[1]);
- setenv("IPMI_PASSWORD", password, 1);
- char ciph[16];
- snprintf(ciph, sizeof(ciph), "%d", cipher_suite > 0 ? cipher_suite : 17);
- execlp(
- "ipmitool", "ipmitool",
- "-I", "lanplus",
- "-C", ciph,
- "-N", "2",
- "-R", "1",
- "-H", host,
- "-U", user,
- "-E",
- "shell",
- (char *)NULL);
- _exit(127);
- }
- close(in_pipe[0]);
- close(out_pipe[1]);
- (void)stl_set_nonblocking_nodelay(in_pipe[1], 0);
- (void)stl_set_nonblocking_nodelay(out_pipe[0], 0);
- *out_stdin_fd = in_pipe[1];
- *out_stdout_fd = out_pipe[0];
- *out_child_pid = (int)pid;
- return 0;
- }
- ssize_t c_pty_read_nonblock(int master_fd, uint8_t *buf, size_t cap) {
- if (master_fd < 0 || !buf || cap == 0) return -1;
- ssize_t n = read(master_fd, buf, cap);
- if (n > 0) return n;
- if (n == 0) return -2; /* EOF */
- if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
- return -2; /* EIO / closed */
- }
- ssize_t c_pty_write_bytes(int master_fd, const uint8_t *buf, size_t len) {
- if (master_fd < 0 || !buf || len == 0) return 0;
- ssize_t n = write(master_fd, buf, len);
- if (n >= 0) return n;
- if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
- return -1;
- }
- int c_pty_is_alive(int child_pid) {
- if (child_pid <= 0) return 0;
- int status = 0;
- pid_t r = waitpid((pid_t)child_pid, &status, WNOHANG);
- if (r == 0) return 1;
- return 0;
- }
- void c_pty_close(int master_fd, int child_pid) {
- if (master_fd >= 0) close(master_fd);
- if (child_pid > 0 && kill((pid_t)child_pid, 0) == 0) {
- kill((pid_t)child_pid, SIGTERM);
- int status = 0;
- for (int i = 0; i < 10; i++) {
- if (waitpid((pid_t)child_pid, &status, WNOHANG) != 0) return;
- struct timespec ts = { .tv_sec = 0, .tv_nsec = 5000000L };
- nanosleep(&ts, NULL);
- }
- kill((pid_t)child_pid, SIGKILL);
- (void)waitpid((pid_t)child_pid, &status, 0);
- }
- }
|