/* * 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* ========================================================================= * 1. Runtime CPUID + XGETBV 6-Tier ISA Detection & Function Dispatch * ========================================================================= */ typedef struct { uint32_t isa_tier; uint32_t detected_tier; uint32_t has_ssse3; uint32_t has_sse42; uint32_t has_popcnt; uint32_t has_pclmul; uint32_t has_aesni; uint32_t has_shani; uint32_t has_avx2; uint32_t has_bmi2; uint32_t has_vpclmul; uint32_t has_gfni; uint32_t has_avx512; uint32_t physical_cores; char cpu_brand[64]; char tier_name[48]; } 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_ssse3 = 0; int has_sse41 = 0; int has_sse42 = 0; int has_popcnt = 0; int has_pclmul = 0; int has_aesni = 0; int has_osxsave = 0; int has_avx = 0; int has_avx2 = 0; int has_bmi1 = 0; int has_bmi2 = 0; int has_shani = 0; int has_vpclmul = 0; int has_gfni = 0; int has_avx512f = 0; int has_avx512bw = 0; int has_avx512vl = 0; if (max_leaf >= 1 && __get_cpuid(1, &eax, &ebx, &ecx, &edx)) { has_pclmul = (ecx & (1u << 1)) != 0; has_ssse3 = (ecx & (1u << 9)) != 0; has_sse41 = (ecx & (1u << 19)) != 0; has_sse42 = (ecx & (1u << 20)) != 0; has_popcnt = (ecx & (1u << 23)) != 0; has_aesni = (ecx & (1u << 25)) != 0; has_osxsave = (ecx & (1u << 27)) != 0; has_avx = (ecx & (1u << 28)) != 0; } int ymm_os_ok = 0; int zmm_os_ok = 0; if (has_osxsave && has_avx) { uint64_t xcr0 = asm_xgetbv_eax0(); ymm_os_ok = ((xcr0 & 0x6ULL) == 0x6ULL); zmm_os_ok = ((xcr0 & 0xE6ULL) == 0xE6ULL); } 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; has_avx512f = (ebx & (1u << 16)) != 0; has_shani = (ebx & (1u << 29)) != 0; has_avx512bw = (ebx & (1u << 30)) != 0; has_avx512vl = (ebx & (1u << 31)) != 0; has_gfni = (ecx & (1u << 8)) != 0; has_vpclmul = (ecx & (1u << 10)) != 0; } int avx512_ok = zmm_os_ok && has_avx512f && has_avx512bw && has_avx512vl && ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2; int avx2_ok = ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2 && has_sse42 && has_popcnt; int goldmont_ok = has_sse41 && has_sse42 && has_popcnt && has_pclmul && has_shani; int sse42_ok = has_ssse3 && has_sse41 && has_sse42 && has_popcnt && has_pclmul; if (avx512_ok) { g_detected_tier = STL_ISA_AVX512; } else if (avx2_ok) { g_detected_tier = STL_ISA_AVX2_BMI; } else if (goldmont_ok) { g_detected_tier = STL_ISA_GOLDMONT_SHA; } else if (sse42_ok) { g_detected_tier = STL_ISA_SSE42_PCLMUL; } else if (has_ssse3) { g_detected_tier = STL_ISA_SSSE3; } 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"); } long online_cpus = sysconf(_SC_NPROCESSORS_ONLN); g_hw_caps.isa_tier = (uint32_t)g_detected_tier; g_hw_caps.detected_tier = (uint32_t)g_detected_tier; g_hw_caps.has_ssse3 = (uint32_t)has_ssse3; g_hw_caps.has_sse42 = (uint32_t)(has_sse42 && has_popcnt); g_hw_caps.has_popcnt = (uint32_t)has_popcnt; g_hw_caps.has_pclmul = (uint32_t)has_pclmul; g_hw_caps.has_aesni = (uint32_t)has_aesni; g_hw_caps.has_shani = (uint32_t)has_shani; g_hw_caps.has_avx2 = (uint32_t)avx2_ok; g_hw_caps.has_bmi2 = (uint32_t)has_bmi2; g_hw_caps.has_vpclmul = (uint32_t)(ymm_os_ok && has_vpclmul); g_hw_caps.has_gfni = (uint32_t)has_gfni; g_hw_caps.has_avx512 = (uint32_t)avx512_ok; g_hw_caps.physical_cores = (uint32_t)(online_cpus > 0 ? online_cpus : 2); 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_AVX512) { 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_AVX512: return "Tier5-AVX512(F/BW/VL)"; case STL_ISA_AVX2_BMI: return "Tier4-AVX2+BMI2(N100/Core)"; case STL_ISA_GOLDMONT_SHA: return "Tier3-Goldmont+SHA-NI(J4125)"; case STL_ISA_SSE42_PCLMUL: return "Tier2-SSE4.2+PCLMUL(J1800/N2830)"; case STL_ISA_SSSE3: return "Tier1-SSSE3-PSHUFB(Atom)"; default: return "Tier0-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 simd_base64_encode_avx2(src, len, dst); } if (tier >= STL_ISA_SSSE3) { return simd_base64_encode_ssse3(src, len, dst); } return asm_base64_encode_sse2(src, len, dst); } size_t stl_hex_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 simd_hex_encode_avx2(src, len, dst); } if (tier >= STL_ISA_SSSE3) { return simd_hex_encode_ssse3(src, len, dst); } return simd_hex_encode_sse2(src, len, dst); } uint32_t stl_crc32_ieee(uint32_t init_crc, const uint8_t *buf, size_t len) { if (!buf || len == 0) return init_crc; int tier = stl_active_isa_tier(); if (tier >= STL_ISA_AVX2_BMI && g_hw_caps.has_vpclmul && len >= 128u) { return simd_crc32_ieee_vpclmul(init_crc, buf, len); } if (tier >= STL_ISA_SSE42_PCLMUL && g_hw_caps.has_pclmul) { return simd_crc32_ieee_pclmul(init_crc, buf, len); } return simd_crc32_ieee_slicing8(init_crc, buf, len); } void stl_sha1_bytes(const uint8_t *data, size_t len, uint8_t out20[20]) { if (!out20) return; int tier = stl_active_isa_tier(); if (tier >= STL_ISA_GOLDMONT_SHA && g_hw_caps.has_shani) { simd_sha1_shani(data, len, out20); return; } simd_sha1_sw(data, len, out20); } size_t stl_ws_accept_key(const uint8_t *key_ptr, size_t key_len, uint8_t out28[28]) { static const char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; uint8_t buf[256]; if (!key_ptr || key_len > 192 || !out28) return 0; memcpy(buf, key_ptr, key_len); memcpy(buf + key_len, magic, 36); uint8_t digest[20]; stl_sha1_bytes(buf, key_len + 36, digest); return stl_base64_encode(digest, 20, out28); } 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_PCLMUL) { asm_clean_split_classify_sse42(state, src, src_len, out); } else { asm_clean_split_classify_sse2(state, src, src_len, out); } } /* ========================================================================= * 2. Monotonic 64-Bit mmap Ring Buffer (Optional Hugepage + 64B Pad + PROT_NONE Guard) * ========================================================================= */ static size_t round_up_pow2_min256k(size_t v) { size_t cap = 256u * 1024u; /* 256 KiB floor for high-density 200-500 station deployments */ 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_min256k(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 if (cap >= 2u * 1024u * 1024u) { (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. In-Process Serial / TCP-RS232 / libssh Console / libipmiconsole SOL / libfreeipmi * ========================================================================= */ static pthread_once_t g_libnet_once = PTHREAD_ONCE_INIT; static int g_ipmiconsole_ok = 0; static void init_libnet_once(void) { (void)ssh_threads_set_callbacks(ssh_threads_get_pthread()); (void)ssh_init(); if (ipmiconsole_engine_init(2, 0) == 0) { g_ipmiconsole_ok = 1; } } static void ensure_libnet_init(void) { pthread_once(&g_libnet_once, init_libnet_once); } static uint64_t monotonic_ms_now(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); } static int write_all_fd(int fd, const uint8_t *buf, size_t len, volatile int *stop_flag) { size_t off = 0; while (off < len) { if (stop_flag && __atomic_load_n(stop_flag, __ATOMIC_ACQUIRE)) return -1; ssize_t n = send(fd, buf + off, len - off, MSG_NOSIGNAL); if (n > 0) { off += (size_t)n; 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, 50); if (pr < 0 && errno == EINTR) continue; if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) return -1; continue; } return -1; } return 0; } static void stl_enable_tcp_keepalive(int fd) { if (fd < 0) return; int one = 1; int idle = 5; int intvl = 2; int cnt = 3; unsigned int user_ms = 15000; (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)); #ifdef TCP_KEEPIDLE (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)); #endif #ifdef TCP_KEEPINTVL (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)); #endif #ifdef TCP_KEEPCNT (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)); #endif #ifdef TCP_USER_TIMEOUT (void)setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_ms, sizeof(user_ms)); #endif } static ssh_session stl_libssh_connect( const char *host, int port, const char *user, const char *password, int timeout_ms, int *out_auth_fail) { ensure_libnet_init(); if (out_auth_fail) *out_auth_fail = 0; if (!host || !host[0] || !user || !password) return NULL; ssh_session sess = ssh_new(); if (!sess) return NULL; unsigned int uport = (unsigned int)(port > 0 ? port : 22); long to_sec = (timeout_ms > 0) ? ((long)(timeout_ms + 999) / 1000L) : 10L; if (to_sec < 1L) to_sec = 1L; int zero = 0; int one = 1; ssh_options_set(sess, SSH_OPTIONS_HOST, host); ssh_options_set(sess, SSH_OPTIONS_PORT, &uport); ssh_options_set(sess, SSH_OPTIONS_USER, user); ssh_options_set(sess, SSH_OPTIONS_TIMEOUT, &to_sec); ssh_options_set(sess, SSH_OPTIONS_STRICTHOSTKEYCHECK, &zero); ssh_options_set(sess, SSH_OPTIONS_KNOWNHOSTS, "/dev/null"); ssh_options_set(sess, SSH_OPTIONS_GLOBAL_KNOWNHOSTS, "/dev/null"); ssh_options_set(sess, SSH_OPTIONS_PROCESS_CONFIG, &zero); ssh_options_set(sess, SSH_OPTIONS_NODELAY, &one); if (ssh_connect(sess) != SSH_OK) { ssh_free(sess); return NULL; } socket_t sfd = ssh_get_fd(sess); if (sfd >= 0) { stl_enable_tcp_keepalive((int)sfd); } int auth = ssh_userauth_password(sess, NULL, password); if (auth != SSH_AUTH_SUCCESS) { int methods = ssh_userauth_list(sess, NULL); if (methods & SSH_AUTH_METHOD_INTERACTIVE) { int krc = ssh_userauth_kbdint(sess, NULL, NULL); int guard = 0; while (krc == SSH_AUTH_INFO && guard++ < 8) { int np = ssh_userauth_kbdint_getnprompts(sess); for (int i = 0; i < np; i++) { (void)ssh_userauth_kbdint_setanswer(sess, (unsigned int)i, password); } krc = ssh_userauth_kbdint(sess, NULL, NULL); } auth = krc; } } if (auth != SSH_AUTH_SUCCESS) { if (out_auth_fail) *out_auth_fail = 1; ssh_disconnect(sess); ssh_free(sess); return NULL; } return sess; } #define STL_SSH_PID_BASE 0x100000 #define STL_SOL_PID_BASE 0x200000 typedef struct { int in_use; volatile int alive; volatile int stop_requested; int sock_peer_fd; int thread_started; ssh_session session; ssh_channel chan; pthread_t pump_thread; } StlSshSlot; typedef struct { int in_use; ipmiconsole_ctx_t ctx; int fd; } StlSolSlot; typedef struct { int in_use; int alive; pthread_mutex_t mu; ipmi_ctx_t ctx; char host[128]; char sdr_cache_path[256]; } StlIpmiSlot; static pthread_mutex_t g_slots_lock = PTHREAD_MUTEX_INITIALIZER; static StlSshSlot **g_ssh_slots = NULL; static int g_ssh_cap = 0; static StlSolSlot **g_sol_slots = NULL; static int g_sol_cap = 0; static StlIpmiSlot **g_ipmi_slots = NULL; static int g_ipmi_cap = 0; static StlSshSlot *alloc_ssh_slot_locked(int *out_idx) { int first_null = -1; for (int i = 0; i < g_ssh_cap; i++) { if (g_ssh_slots[i] == NULL) { if (first_null < 0) first_null = i; } else if (!g_ssh_slots[i]->in_use) { *out_idx = i; return g_ssh_slots[i]; } } int idx = first_null; if (idx < 0) { int new_cap = (g_ssh_cap == 0) ? 16 : (g_ssh_cap * 2); StlSshSlot **next = (StlSshSlot **)realloc(g_ssh_slots, (size_t)new_cap * sizeof(StlSshSlot *)); if (!next) return NULL; memset(next + g_ssh_cap, 0, (size_t)(new_cap - g_ssh_cap) * sizeof(StlSshSlot *)); g_ssh_slots = next; idx = g_ssh_cap; g_ssh_cap = new_cap; } StlSshSlot *s = (StlSshSlot *)calloc(1, sizeof(StlSshSlot)); if (!s) return NULL; g_ssh_slots[idx] = s; *out_idx = idx; return s; } static StlSolSlot *alloc_sol_slot_locked(int *out_idx) { int first_null = -1; for (int i = 0; i < g_sol_cap; i++) { if (g_sol_slots[i] == NULL) { if (first_null < 0) first_null = i; } else if (!g_sol_slots[i]->in_use) { *out_idx = i; return g_sol_slots[i]; } } int idx = first_null; if (idx < 0) { int new_cap = (g_sol_cap == 0) ? 16 : (g_sol_cap * 2); StlSolSlot **next = (StlSolSlot **)realloc(g_sol_slots, (size_t)new_cap * sizeof(StlSolSlot *)); if (!next) return NULL; memset(next + g_sol_cap, 0, (size_t)(new_cap - g_sol_cap) * sizeof(StlSolSlot *)); g_sol_slots = next; idx = g_sol_cap; g_sol_cap = new_cap; } StlSolSlot *s = (StlSolSlot *)calloc(1, sizeof(StlSolSlot)); if (!s) return NULL; g_sol_slots[idx] = s; *out_idx = idx; return s; } static StlIpmiSlot *alloc_ipmi_slot_locked(int *out_idx) { int first_null = -1; for (int i = 0; i < g_ipmi_cap; i++) { if (g_ipmi_slots[i] == NULL) { if (first_null < 0) first_null = i; } else { pthread_mutex_lock(&g_ipmi_slots[i]->mu); if (!g_ipmi_slots[i]->in_use) { *out_idx = i; return g_ipmi_slots[i]; /* returns with slot->mu HELD */ } pthread_mutex_unlock(&g_ipmi_slots[i]->mu); } } int idx = first_null; if (idx < 0) { int new_cap = (g_ipmi_cap == 0) ? 16 : (g_ipmi_cap * 2); StlIpmiSlot **next = (StlIpmiSlot **)realloc(g_ipmi_slots, (size_t)new_cap * sizeof(StlIpmiSlot *)); if (!next) return NULL; memset(next + g_ipmi_cap, 0, (size_t)(new_cap - g_ipmi_cap) * sizeof(StlIpmiSlot *)); g_ipmi_slots = next; idx = g_ipmi_cap; g_ipmi_cap = new_cap; } StlIpmiSlot *s = (StlIpmiSlot *)calloc(1, sizeof(StlIpmiSlot)); if (!s) return NULL; pthread_mutex_init(&s->mu, NULL); pthread_mutex_lock(&s->mu); g_ipmi_slots[idx] = s; *out_idx = idx; return s; /* returns with slot->mu HELD */ } static void *ssh_pump_thread_fn(void *arg) { StlSshSlot *slot = (StlSshSlot *)arg; uint8_t rbuf[16384]; uint8_t tbuf[4096]; while (!__atomic_load_n(&slot->stop_requested, __ATOMIC_ACQUIRE)) { if (!ssh_is_connected(slot->session) || ssh_channel_is_eof(slot->chan) || ssh_channel_is_closed(slot->chan)) { break; } /* Drain SSH stdout & stderr non-blocking */ int progressed = 0; for (int pass = 0; pass < 32; pass++) { int n0 = ssh_channel_read_nonblocking(slot->chan, rbuf, sizeof(rbuf), 0); if (n0 > 0) { progressed = 1; if (write_all_fd(slot->sock_peer_fd, rbuf, (size_t)n0, &slot->stop_requested) != 0) { goto done; } } else if (n0 == SSH_ERROR || n0 == SSH_EOF) { goto done; } int n1 = ssh_channel_read_nonblocking(slot->chan, rbuf, sizeof(rbuf), 1); if (n1 > 0) { progressed = 1; if (write_all_fd(slot->sock_peer_fd, rbuf, (size_t)n1, &slot->stop_requested) != 0) { goto done; } } else if (n1 == SSH_ERROR || n1 == SSH_EOF) { goto done; } if (n0 <= 0 && n1 <= 0) break; } /* Drain pending TX bytes from local socketpair end -> SSH channel */ for (int tpass = 0; tpass < 32; tpass++) { ssize_t tn = read(slot->sock_peer_fd, tbuf, sizeof(tbuf)); if (tn > 0) { progressed = 1; size_t off = 0; while (off < (size_t)tn) { int wn = ssh_channel_write(slot->chan, tbuf + off, (uint32_t)((size_t)tn - off)); if (wn <= 0) goto done; off += (size_t)wn; } } else if (tn == 0) { goto done; /* Peer closed master_fd */ } else { if (errno == EINTR) continue; break; } } if (progressed) continue; struct pollfd pfds[2]; int nfds = 0; socket_t sfd = ssh_get_fd(slot->session); int ssh_idx = -1; int peer_idx = -1; if (sfd >= 0) { ssh_idx = nfds; pfds[nfds].fd = (int)sfd; pfds[nfds].events = POLLIN; pfds[nfds].revents = 0; nfds++; } if (slot->sock_peer_fd >= 0) { peer_idx = nfds; pfds[nfds].fd = slot->sock_peer_fd; pfds[nfds].events = POLLIN; pfds[nfds].revents = 0; nfds++; } if (nfds == 0) break; int pr = poll(pfds, (nfds_t)nfds, 50); if (pr < 0 && errno != EINTR) break; if (peer_idx >= 0 && (pfds[peer_idx].revents & (POLLHUP | POLLERR | POLLNVAL))) { break; } if (ssh_idx >= 0 && (pfds[ssh_idx].revents & (POLLERR | POLLHUP | POLLNVAL))) { break; } int so_err = 0; socklen_t so_len = sizeof(so_err); if (sfd >= 0 && getsockopt((int)sfd, SOL_SOCKET, SO_ERROR, &so_err, &so_len) == 0 && so_err != 0) { break; } } done: __atomic_store_n(&slot->alive, 0, __ATOMIC_RELEASE); if (slot->sock_peer_fd >= 0) { close(slot->sock_peer_fd); slot->sock_peer_fd = -1; } if (slot->chan) { (void)ssh_channel_send_eof(slot->chan); (void)ssh_channel_close(slot->chan); ssh_channel_free(slot->chan); slot->chan = NULL; } if (slot->session) { ssh_disconnect(slot->session); ssh_free(slot->session); slot->session = NULL; } return NULL; } int stl_open_tty_115200_raw(const char *path) { return c_open_tty_baud_raw(path, 115200); } 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) */ int c_open_tty_baud_raw(const char *path, int baud) { if (!path || path[0] == '\0') 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] = 1; tio.c_cc[VTIME] = 0; if (tcsetattr(fd, TCSANOW, &tio) != 0) { close(fd); return -1; } int fl = fcntl(fd, F_GETFL, 0); if (fl >= 0) { (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK); } return fd; } /* Open MCU 24-ch thermal controller UART (115200 8N1 default) */ int c_open_mcu_tty_baud_raw(const char *path, int baud) { if (!path || path[0] == '\0') 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; else if (baud == 57600) sp = B57600; else if (baud == 38400) sp = B38400; else if (baud == 9600) sp = B9600; 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] = 1; tio.c_cc[VTIME] = 0; if (tcsetattr(fd, TCSANOW, &tio) != 0) { close(fd); return -1; } int fl = fcntl(fd, F_GETFL, 0); if (fl >= 0) { (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK); } 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; } stl_enable_tcp_keepalive(sfd); 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; } int c_pty_open_tcp_listen(int port) { if (port <= 0 || port > 65535) return -1; int lfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (lfd < 0) return -1; int one = 1; (void)setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons((uint16_t)port); if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(lfd, 8) != 0) { close(lfd); return -1; } return lfd; } int c_pty_accept_tcp_nonblock(int listen_fd) { if (listen_fd < 0) return -1; int cfd = accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC); if (cfd >= 0) { stl_enable_tcp_keepalive(cfd); } return cfd; } /* * Open in-process libssh console session (port 2200) bridged over AF_UNIX non-blocking socketpair. * Explicitly sets known_hosts=/dev/null and StrictHostKeyChecking=no so swapped motherboards never block. * Returns 0 on success, -2 on auth failure, -1 on transport/slot error. */ 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; if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1; int auth_fail = 0; ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 2200, user, password, 10000, &auth_fail); if (!sess) { return auth_fail ? -2 : -1; } ssh_channel chan = ssh_channel_new(sess); if (!chan || ssh_channel_open_session(chan) != SSH_OK) { if (chan) ssh_channel_free(chan); ssh_disconnect(sess); ssh_free(sess); return -1; } if (ssh_channel_request_pty_size(chan, "vt100", 160, 48) != SSH_OK || ssh_channel_request_shell(chan) != SSH_OK) { (void)ssh_channel_close(chan); ssh_channel_free(chan); ssh_disconnect(sess); ssh_free(sess); return -1; } int sv[2] = {-1, -1}; if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0) { (void)ssh_channel_close(chan); ssh_channel_free(chan); ssh_disconnect(sess); ssh_free(sess); return -1; } (void)stl_set_nonblocking_nodelay(sv[0], 0); (void)stl_set_nonblocking_nodelay(sv[1], 0); pthread_mutex_lock(&g_slots_lock); int idx = -1; StlSshSlot *slot = alloc_ssh_slot_locked(&idx); if (slot) { memset(slot, 0, sizeof(*slot)); slot->in_use = 1; slot->alive = 1; slot->stop_requested = 0; slot->sock_peer_fd = sv[1]; slot->session = sess; slot->chan = chan; } pthread_mutex_unlock(&g_slots_lock); if (!slot || idx < 0) { close(sv[0]); close(sv[1]); (void)ssh_channel_close(chan); ssh_channel_free(chan); ssh_disconnect(sess); ssh_free(sess); return -1; } if (pthread_create(&slot->pump_thread, NULL, ssh_pump_thread_fn, slot) != 0) { pthread_mutex_lock(&g_slots_lock); slot->in_use = 0; slot->alive = 0; pthread_mutex_unlock(&g_slots_lock); close(sv[0]); close(sv[1]); (void)ssh_channel_close(chan); ssh_channel_free(chan); ssh_disconnect(sess); ssh_free(sess); return -1; } slot->thread_started = 1; *out_master_fd = sv[0]; *out_child_pid = -(STL_SSH_PID_BASE + idx); 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) { ensure_libnet_init(); if (!g_ipmiconsole_ok || !host || !user || !password || !out_master_fd || !out_child_pid) { return -1; } int ciphers[2] = { 17, 3 }; ipmiconsole_ctx_t ctx = NULL; int established = 0; int auth_err = 0; for (int ci = 0; ci < 2; ci++) { struct ipmiconsole_ipmi_config icfg; memset(&icfg, 0, sizeof(icfg)); icfg.username = (char *)user; icfg.password = (char *)password; icfg.k_g = NULL; icfg.k_g_len = 0; icfg.privilege_level = IPMICONSOLE_PRIVILEGE_ADMIN; icfg.cipher_suite_id = ciphers[ci]; icfg.workaround_flags = IPMICONSOLE_WORKAROUND_DEFAULT; struct ipmiconsole_protocol_config pcfg; pcfg.session_timeout_len = -1; pcfg.retransmission_timeout_len = -1; pcfg.retransmission_backoff_count = -1; pcfg.keepalive_timeout_len = -1; pcfg.retransmission_keepalive_timeout_len = -1; pcfg.acceptable_packet_errors_count = -1; pcfg.maximum_retransmission_count = -1; struct ipmiconsole_engine_config ecfg; ecfg.engine_flags = IPMICONSOLE_ENGINE_DEFAULT; ecfg.behavior_flags = IPMICONSOLE_BEHAVIOR_DEFAULT; ecfg.debug_flags = 0; ctx = ipmiconsole_ctx_create(host, &icfg, &pcfg, &ecfg); if (!ctx) continue; if (ipmiconsole_engine_submit_block(ctx) == 0 && ipmiconsole_ctx_status(ctx) == IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED) { established = 1; break; } int err = ipmiconsole_ctx_errnum(ctx); if (err == IPMICONSOLE_ERR_PASSWORD_INVALID || err == IPMICONSOLE_ERR_USERNAME_INVALID || err == IPMICONSOLE_ERR_PRIVILEGE_LEVEL_INSUFFICIENT) { auth_err = 1; } ipmiconsole_ctx_destroy(ctx); ctx = NULL; if (auth_err) break; } if (!established || !ctx) { return auth_err ? -2 : -1; } int fd = ipmiconsole_ctx_fd(ctx); if (fd < 0) { ipmiconsole_ctx_destroy(ctx); return -1; } (void)stl_set_nonblocking_nodelay(fd, 0); int fd_fl = fcntl(fd, F_GETFD, 0); if (fd_fl >= 0) (void)fcntl(fd, F_SETFD, fd_fl | FD_CLOEXEC); pthread_mutex_lock(&g_slots_lock); int idx = -1; StlSolSlot *sol = alloc_sol_slot_locked(&idx); if (sol) { sol->in_use = 1; sol->ctx = ctx; sol->fd = fd; } pthread_mutex_unlock(&g_slots_lock); if (!sol || idx < 0) { close(fd); ipmiconsole_ctx_destroy(ctx); return -1; } *out_master_fd = fd; *out_child_pid = -(STL_SOL_PID_BASE + idx); 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_mcu_tty_read_nonblock(int fd, uint8_t *buf, size_t cap, int is_serial) { if (fd < 0 || !buf || cap == 0) return -1; ssize_t n = read(fd, buf, cap); if (n > 0) return n; if (n == 0) { if (!is_serial) return -2; /* TCP EOF */ struct pollfd pfd = { .fd = fd, .events = POLLIN, .revents = 0 }; if (poll(&pfd, 1, 0) > 0 && (pfd.revents & (POLLHUP | POLLERR | POLLNVAL))) { return -2; /* USB serial unplugged / hangup */ } return 0; /* TTY VMIN=0 empty buffer, not EOF */ } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0; return -2; /* EIO / ENODEV / 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) { pthread_mutex_lock(&g_slots_lock); if (child_pid <= -STL_SSH_PID_BASE && child_pid > -STL_SOL_PID_BASE) { int idx = (-child_pid) - STL_SSH_PID_BASE; StlSshSlot *slot = (idx >= 0 && idx < g_ssh_cap) ? g_ssh_slots[idx] : NULL; int ok = (slot && slot->in_use && __atomic_load_n(&slot->alive, __ATOMIC_ACQUIRE)) ? 1 : 0; pthread_mutex_unlock(&g_slots_lock); return ok; } if (child_pid <= -STL_SOL_PID_BASE) { int idx = (-child_pid) - STL_SOL_PID_BASE; StlSolSlot *sol = (idx >= 0 && idx < g_sol_cap) ? g_sol_slots[idx] : NULL; ipmiconsole_ctx_t ctx = (sol && sol->in_use) ? sol->ctx : NULL; pthread_mutex_unlock(&g_slots_lock); if (!ctx) return 0; return (ipmiconsole_ctx_status(ctx) == IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED) ? 1 : 0; } pthread_mutex_unlock(&g_slots_lock); return 0; } void c_pty_close(int master_fd, int child_pid) { if (master_fd >= 0) { (void)shutdown(master_fd, SHUT_RDWR); close(master_fd); } if (child_pid <= -STL_SSH_PID_BASE && child_pid > -STL_SOL_PID_BASE) { int idx = (-child_pid) - STL_SSH_PID_BASE; pthread_mutex_lock(&g_slots_lock); StlSshSlot *slot = (idx >= 0 && idx < g_ssh_cap) ? g_ssh_slots[idx] : NULL; int started = (slot && slot->in_use) ? slot->thread_started : 0; pthread_t th; if (slot && slot->in_use) { __atomic_store_n(&slot->stop_requested, 1, __ATOMIC_RELEASE); th = slot->pump_thread; } pthread_mutex_unlock(&g_slots_lock); if (slot && started) { pthread_join(th, NULL); } if (slot) { pthread_mutex_lock(&g_slots_lock); if (slot->sock_peer_fd >= 0) { close(slot->sock_peer_fd); slot->sock_peer_fd = -1; } slot->in_use = 0; slot->alive = 0; slot->thread_started = 0; pthread_mutex_unlock(&g_slots_lock); } return; } if (child_pid <= -STL_SOL_PID_BASE) { int idx = (-child_pid) - STL_SOL_PID_BASE; ipmiconsole_ctx_t ctx = NULL; pthread_mutex_lock(&g_slots_lock); StlSolSlot *sol = (idx >= 0 && idx < g_sol_cap) ? g_sol_slots[idx] : NULL; if (sol && sol->in_use) { ctx = sol->ctx; sol->ctx = NULL; sol->fd = -1; sol->in_use = 0; } pthread_mutex_unlock(&g_slots_lock); if (ctx) { ipmiconsole_ctx_destroy(ctx); } } } /* ========================================================================= * 5. In-Process libssh Remote Exec + Atomic SFTP Upload/Download * ========================================================================= */ int c_ssh_exec_capture( const char *host, int port, const char *user, const char *password, const char *cmd, char *out_buf, size_t out_cap, size_t *out_len, int timeout_ms) { if (out_len) *out_len = 0; if (out_buf && out_cap > 0) out_buf[0] = '\0'; if (!host || !user || !password || !cmd) return -1; int auth_fail = 0; int eff_to = (timeout_ms > 0) ? timeout_ms : 5000; ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, eff_to, &auth_fail); if (!sess) return auth_fail ? -2 : -1; ssh_channel chan = ssh_channel_new(sess); if (!chan || ssh_channel_open_session(chan) != SSH_OK || ssh_channel_request_exec(chan, cmd) != SSH_OK) { if (chan) { (void)ssh_channel_close(chan); ssh_channel_free(chan); } ssh_disconnect(sess); ssh_free(sess); return -1; } size_t total = 0; uint8_t tmp[4096]; uint64_t deadline = monotonic_ms_now() + (uint64_t)eff_to; int timed_out = 0; for (;;) { int n0 = ssh_channel_read_nonblocking(chan, tmp, sizeof(tmp), 0); if (n0 > 0) { if (out_buf && out_cap > 1 && total < out_cap - 1) { size_t copy = (size_t)n0; if (copy > (out_cap - 1 - total)) copy = out_cap - 1 - total; memcpy(out_buf + total, tmp, copy); total += copy; } continue; } int n1 = ssh_channel_read_nonblocking(chan, tmp, sizeof(tmp), 1); if (n1 > 0) { if (out_buf && out_cap > 1 && total < out_cap - 1) { size_t copy = (size_t)n1; if (copy > (out_cap - 1 - total)) copy = out_cap - 1 - total; memcpy(out_buf + total, tmp, copy); total += copy; } continue; } if (n0 == SSH_ERROR || n1 == SSH_ERROR) { break; } if (ssh_channel_is_eof(chan) || ssh_channel_is_closed(chan)) { break; } uint64_t now = monotonic_ms_now(); if (now >= deadline) { timed_out = 1; break; } int rem_ms = (int)(deadline - now); if (rem_ms > 50) rem_ms = 50; socket_t sfd = ssh_get_fd(sess); if (sfd >= 0) { struct pollfd pfd = { .fd = (int)sfd, .events = POLLIN, .revents = 0 }; (void)poll(&pfd, 1, rem_ms); } else { struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000L }; nanosleep(&ts, NULL); } } if (out_buf && out_cap > 0) { out_buf[(total < out_cap) ? total : (out_cap - 1)] = '\0'; } if (out_len) *out_len = total; int exit_rc = timed_out ? -3 : 0; if (!timed_out) { uint32_t code = 0; int pcore = 0; char *psig = NULL; (void)ssh_channel_send_eof(chan); (void)ssh_channel_close(chan); if (ssh_channel_get_exit_state(chan, &code, &psig, &pcore) == SSH_OK) { exit_rc = (int)code; } if (psig) ssh_string_free_char(psig); } else { (void)ssh_channel_close(chan); } ssh_channel_free(chan); ssh_disconnect(sess); ssh_free(sess); return exit_rc; } int c_ssh_sftp_put_file( const char *host, int port, const char *user, const char *password, const char *local_path, const char *remote_path, int timeout_ms) { if (!host || !user || !password || !local_path || !remote_path) return -1; FILE *fp = fopen(local_path, "rb"); if (!fp) return -1; int auth_fail = 0; ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, timeout_ms > 0 ? timeout_ms : 5000, &auth_fail); if (!sess) { fclose(fp); return auth_fail ? -2 : -1; } sftp_session sftp = sftp_new(sess); if (!sftp || sftp_init(sftp) != SSH_OK) { if (sftp) sftp_free(sftp); ssh_disconnect(sess); ssh_free(sess); fclose(fp); return -1; } char partial[1088]; snprintf(partial, sizeof(partial), "%s.partial", remote_path); sftp_file rf = sftp_open(sftp, partial, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (!rf) { sftp_free(sftp); ssh_disconnect(sess); ssh_free(sess); fclose(fp); return -1; } int rc = 0; uint8_t buf[32768]; size_t nr; while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) { size_t off = 0; while (off < nr) { ssize_t nw = sftp_write(rf, buf + off, nr - off); if (nw <= 0) { rc = -1; break; } off += (size_t)nw; } if (rc != 0) break; } if (ferror(fp)) rc = -1; fclose(fp); if (sftp_close(rf) != SSH_OK) rc = -1; if (rc == 0) { if (sftp_rename(sftp, partial, remote_path) != 0) { (void)sftp_unlink(sftp, remote_path); if (sftp_rename(sftp, partial, remote_path) != 0) { (void)sftp_unlink(sftp, partial); rc = -1; } } } else { (void)sftp_unlink(sftp, partial); } sftp_free(sftp); ssh_disconnect(sess); ssh_free(sess); return rc; } int c_ssh_sftp_get_file( const char *host, int port, const char *user, const char *password, const char *remote_path, const char *local_path, int timeout_ms) { if (!host || !user || !password || !remote_path || !local_path) return -1; int auth_fail = 0; ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, timeout_ms > 0 ? timeout_ms : 5000, &auth_fail); if (!sess) return auth_fail ? -2 : -1; sftp_session sftp = sftp_new(sess); if (!sftp || sftp_init(sftp) != SSH_OK) { if (sftp) sftp_free(sftp); ssh_disconnect(sess); ssh_free(sess); return -1; } sftp_file rf = sftp_open(sftp, remote_path, O_RDONLY, 0); if (!rf) { sftp_free(sftp); ssh_disconnect(sess); ssh_free(sess); return -1; } char partial[1088]; snprintf(partial, sizeof(partial), "%s.partial", local_path); FILE *fp = fopen(partial, "wb"); if (!fp) { (void)sftp_close(rf); sftp_free(sftp); ssh_disconnect(sess); ssh_free(sess); return -1; } int rc = 0; uint8_t buf[32768]; for (;;) { ssize_t nr = sftp_read(rf, buf, sizeof(buf)); if (nr > 0) { if (fwrite(buf, 1, (size_t)nr, fp) != (size_t)nr) { rc = -1; break; } } else if (nr == 0) { break; } else { rc = -1; break; } } if (fclose(fp) != 0) rc = -1; (void)sftp_close(rf); sftp_free(sftp); ssh_disconnect(sess); ssh_free(sess); if (rc == 0) { if (rename(partial, local_path) != 0) { unlink(partial); rc = -1; } } else { unlink(partial); } return rc; } /* ========================================================================= * 6. In-Process libfreeipmi Persistent Out-of-Band Session & Telemetry * ========================================================================= */ static StlIpmiSlot *get_ipmi_slot(int handle) { if (handle < 1) return NULL; pthread_mutex_lock(&g_slots_lock); StlIpmiSlot *s = (handle <= g_ipmi_cap) ? g_ipmi_slots[handle - 1] : NULL; pthread_mutex_unlock(&g_slots_lock); return s; } int c_ipmi_open( const char *host, const char *user, const char *password, int cipher_suite, int timeout_ms) { if (!host || !host[0] || !user || !password) return -1; ipmi_ctx_t ctx = ipmi_ctx_create(); if (!ctx) return -1; unsigned int sess_to = (timeout_ms > 0) ? (unsigned int)timeout_ms : 3000U; uint8_t ciph = (uint8_t)(cipher_suite > 0 ? cipher_suite : 17); int rc = ipmi_ctx_open_outofband_2_0( ctx, host, user, password, NULL, 0, IPMI_PRIVILEGE_LEVEL_ADMIN, ciph, sess_to, 500U, IPMI_WORKAROUND_FLAGS_DEFAULT, IPMI_FLAGS_DEFAULT); if (rc != 0 && ciph == 17) { int err = ipmi_ctx_errnum(ctx); if (err != IPMI_ERR_PASSWORD_INVALID && err != IPMI_ERR_USERNAME_INVALID && err != IPMI_ERR_CONNECTION_TIMEOUT) { rc = ipmi_ctx_open_outofband_2_0( ctx, host, user, password, NULL, 0, IPMI_PRIVILEGE_LEVEL_ADMIN, 3, sess_to, 500U, IPMI_WORKAROUND_FLAGS_DEFAULT, IPMI_FLAGS_DEFAULT); } } if (rc != 0) { int final_err = ipmi_ctx_errnum(ctx); ipmi_ctx_destroy(ctx); return (final_err == IPMI_ERR_CONNECTION_TIMEOUT) ? -2 : -1; } pthread_mutex_lock(&g_slots_lock); int idx = -1; StlIpmiSlot *slot = alloc_ipmi_slot_locked(&idx); if (slot) { slot->in_use = 1; slot->alive = 1; slot->ctx = ctx; snprintf(slot->host, sizeof(slot->host), "%s", host); { char safe_host[96]; size_t hi = 0; for (; host[hi] && hi + 1 < sizeof(safe_host); hi++) { unsigned char ch = (unsigned char)host[hi]; safe_host[hi] = ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '.' || ch == '_' || ch == '-') ? (char)ch : '_'; } safe_host[hi] = '\0'; snprintf(slot->sdr_cache_path, sizeof(slot->sdr_cache_path), "/tmp/stl_sdr_%ld_%d_%s.cache", (long)getpid(), idx, safe_host); unlink(slot->sdr_cache_path); } pthread_mutex_unlock(&slot->mu); } pthread_mutex_unlock(&g_slots_lock); if (!slot || idx < 0) { (void)ipmi_ctx_close(ctx); ipmi_ctx_destroy(ctx); return -1; } return idx + 1; } void c_ipmi_close(int handle) { if (handle < 1) return; pthread_mutex_lock(&g_slots_lock); StlIpmiSlot *slot = (handle <= g_ipmi_cap) ? g_ipmi_slots[handle - 1] : NULL; if (!slot) { pthread_mutex_unlock(&g_slots_lock); return; } pthread_mutex_lock(&slot->mu); if (slot->in_use) { if (slot->ctx) { if (slot->alive) { (void)ipmi_ctx_close(slot->ctx); } ipmi_ctx_destroy(slot->ctx); slot->ctx = NULL; } if (slot->sdr_cache_path[0]) { unlink(slot->sdr_cache_path); slot->sdr_cache_path[0] = '\0'; } slot->alive = 0; slot->in_use = 0; slot->host[0] = '\0'; } pthread_mutex_unlock(&slot->mu); pthread_mutex_unlock(&g_slots_lock); } int c_ipmi_is_alive(int handle) { StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot) return 0; pthread_mutex_lock(&slot->mu); int alive = (slot->in_use && slot->alive && slot->ctx != NULL) ? 1 : 0; pthread_mutex_unlock(&slot->mu); return alive; } int c_ipmi_chassis_status(int handle, int *out_power_on, char *out_buf, size_t out_cap) { if (out_power_on) *out_power_on = -1; if (out_buf && out_cap > 0) out_buf[0] = '\0'; StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot) return -1; pthread_mutex_lock(&slot->mu); if (!slot->in_use || !slot->ctx) { pthread_mutex_unlock(&slot->mu); return -1; } fiid_obj_t rs = fiid_obj_create(tmpl_cmd_get_chassis_status_rs); if (!rs) { pthread_mutex_unlock(&slot->mu); return -1; } int rc = ipmi_cmd_get_chassis_status(slot->ctx, rs); if (rc != 0) { slot->alive = 0; fiid_obj_destroy(rs); pthread_mutex_unlock(&slot->mu); return -1; } uint64_t pwr = 0, ovl = 0, pflt = 0, cflt = 0, intr = 0; int got = fiid_obj_get(rs, "current_power_state.power_is_on", &pwr); (void)fiid_obj_get(rs, "current_power_state.power_overload", &ovl); (void)fiid_obj_get(rs, "current_power_state.power_fault", &pflt); (void)fiid_obj_get(rs, "current_power_state.power_control_fault", &cflt); (void)fiid_obj_get(rs, "misc_chassis_state.chassis_intrusion_active", &intr); fiid_obj_destroy(rs); pthread_mutex_unlock(&slot->mu); if (got <= 0) return -1; int is_on = (pwr != 0) ? 1 : 0; if (out_power_on) *out_power_on = is_on; if (out_buf && out_cap > 0) { snprintf( out_buf, out_cap, "System Power : %s\n" "Chassis Power is %s\n" "Power Overload : %s\n" "Main Power Fault : %s\n" "Power Control Fault : %s\n" "Chassis Intrusion : %s\n", is_on ? "on" : "off", is_on ? "on" : "off", ovl ? "true" : "false", pflt ? "true" : "false", cflt ? "true" : "false", intr ? "active" : "inactive"); } return 0; } int c_ipmi_chassis_control(int handle, int op) { StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot || !IPMI_CHASSIS_CONTROL_VALID((uint8_t)op)) return -1; pthread_mutex_lock(&slot->mu); if (!slot->in_use || !slot->ctx) { pthread_mutex_unlock(&slot->mu); return -1; } fiid_obj_t rs = fiid_obj_create(tmpl_cmd_chassis_control_rs); if (!rs) { pthread_mutex_unlock(&slot->mu); return -1; } int rc = ipmi_cmd_chassis_control(slot->ctx, (uint8_t)op, rs); if (rc != 0) slot->alive = 0; fiid_obj_destroy(rs); pthread_mutex_unlock(&slot->mu); return (rc == 0) ? 0 : -1; } int c_ipmi_warm_reset(int handle) { StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot) return -1; pthread_mutex_lock(&slot->mu); if (!slot->in_use || !slot->ctx) { pthread_mutex_unlock(&slot->mu); return -1; } fiid_obj_t rs = fiid_obj_create(tmpl_cmd_warm_reset_rs); if (!rs) { pthread_mutex_unlock(&slot->mu); return -1; } int rc = ipmi_cmd_warm_reset(slot->ctx, rs); if (rc != 0) slot->alive = 0; fiid_obj_destroy(rs); pthread_mutex_unlock(&slot->mu); return (rc == 0) ? 0 : -1; } int c_ipmi_raw( int handle, uint8_t net_fn, uint8_t cmd, const uint8_t *payload, size_t payload_len, uint8_t *out_buf, size_t out_cap, size_t *out_len) { if (out_len) *out_len = 0; StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot || payload_len > 255) return -1; uint8_t rq[260]; uint8_t rs[260]; rq[0] = cmd; if (payload && payload_len > 0) { memcpy(rq + 1, payload, payload_len); } pthread_mutex_lock(&slot->mu); if (!slot->in_use || !slot->ctx) { pthread_mutex_unlock(&slot->mu); return -1; } int rlen = ipmi_cmd_raw( slot->ctx, 0, net_fn, rq, (unsigned int)(1 + payload_len), rs, (unsigned int)sizeof(rs)); if (rlen < 0) slot->alive = 0; pthread_mutex_unlock(&slot->mu); if (rlen < 2 || rs[1] != 0x00) { return -1; } size_t data_len = (size_t)(rlen - 2); if (out_buf && out_cap > 0 && data_len > 0) { size_t cp = (data_len < out_cap) ? data_len : out_cap; memcpy(out_buf, rs + 2, cp); } if (out_len) *out_len = data_len; return 0; } typedef struct { ipmi_sensor_read_ctx_t sr; char *out_buf; size_t out_cap; size_t used; } SdrIterCtx; static int contains_ci_dimm(const char *s) { if (!s) return 0; for (size_t i = 0; s[i] && s[i+1] && s[i+2] && s[i+3]; i++) { char c0 = (s[i] >= 'a' && s[i] <= 'z') ? (char)(s[i] - 32) : s[i]; char c1 = (s[i+1] >= 'a' && s[i+1] <= 'z') ? (char)(s[i+1] - 32) : s[i+1]; char c2 = (s[i+2] >= 'a' && s[i+2] <= 'z') ? (char)(s[i+2] - 32) : s[i+2]; char c3 = (s[i+3] >= 'a' && s[i+3] <= 'z') ? (char)(s[i+3] - 32) : s[i+3]; if (c0 == 'D' && c1 == 'I' && c2 == 'M' && c3 == 'M') return 1; } return 0; } static const char *ipmi_unit_label(uint8_t base_u, uint8_t pct) { if (pct == 1) return "%"; switch (base_u) { case IPMI_SENSOR_UNIT_DEGREES_C: return "degrees C"; case IPMI_SENSOR_UNIT_DEGREES_F: return "degrees F"; case IPMI_SENSOR_UNIT_VOLTS: return "Volts"; case IPMI_SENSOR_UNIT_AMPS: return "Amps"; case IPMI_SENSOR_UNIT_WATTS: return "Watts"; case IPMI_SENSOR_UNIT_RPM: return "RPM"; case IPMI_SENSOR_UNIT_HZ: return "Hz"; default: return "units"; } } static int sdr_iterate_cb( ipmi_sdr_ctx_t sdr, uint8_t record_type, const void *sdr_record, unsigned int sdr_record_len, void *data) { SdrIterCtx *ic = (SdrIterCtx *)data; if (record_type != IPMI_SDR_FORMAT_FULL_SENSOR_RECORD && record_type != IPMI_SDR_FORMAT_COMPACT_SENSOR_RECORD) { return 0; } char name[IPMI_SDR_MAX_SENSOR_NAME_LENGTH + 1]; memset(name, 0, sizeof(name)); if (ipmi_sdr_parse_id_string(sdr, sdr_record, sdr_record_len, name, sizeof(name) - 1) < 0) { return 0; } uint8_t pct = 0, mod = 0, rate = 0, base_u = 0, mod_u = 0; int units_ok = (ipmi_sdr_parse_sensor_units( sdr, sdr_record, sdr_record_len, &pct, &mod, &rate, &base_u, &mod_u) == 0); uint8_t stype = 0, ert = 0; int has_type = (ipmi_sdr_parse_sensor_type(sdr, sdr_record, sdr_record_len, &stype) == 0 && ipmi_sdr_parse_event_reading_type_code(sdr, sdr_record, sdr_record_len, &ert) == 0); uint8_t raw = 0; double *reading = NULL; uint16_t bitmask = 0; int src = ipmi_sensor_read(ic->sr, sdr_record, sdr_record_len, 0, &raw, &reading, &bitmask); char line[256]; if (src == 1 && reading != NULL && units_ok) { const char *ulab = ipmi_unit_label(base_u, pct); snprintf(line, sizeof(line), "%s | %.2f %s | ok\n", name, *reading, ulab); } else if (units_ok && base_u == IPMI_SENSOR_UNIT_DEGREES_C) { snprintf(line, sizeof(line), "%s | no reading | ns\n", name); } else if (src == 1 && has_type) { if (contains_ci_dimm(name) && stype == IPMI_SENSOR_TYPE_MEMORY && ert == 0x6F) { snprintf(line, sizeof(line), "%s | discrete_mem=0x%04X | ok\n", name, (unsigned)bitmask); } else if (contains_ci_dimm(name) && stype == IPMI_SENSOR_TYPE_ENTITY_PRESENCE && ert == 0x6F) { snprintf(line, sizeof(line), "%s | discrete_presence=0x%04X | ok\n", name, (unsigned)bitmask); } else if (contains_ci_dimm(name) && ert == 0x08) { snprintf(line, sizeof(line), "%s | discrete_devpres=0x%04X | ok\n", name, (unsigned)bitmask); } else { snprintf(line, sizeof(line), "%s | discrete_state=0x%04X | type=0x%02X\n", name, (unsigned)bitmask, (unsigned)stype); } } else if (units_ok && (base_u == IPMI_SENSOR_UNIT_VOLTS || base_u == IPMI_SENSOR_UNIT_AMPS || base_u == IPMI_SENSOR_UNIT_WATTS || base_u == IPMI_SENSOR_UNIT_RPM)) { snprintf(line, sizeof(line), "%s | no reading (%s) | ns\n", name, ipmi_unit_label(base_u, pct)); } else { if (reading) free(reading); return 0; } if (reading) free(reading); size_t l = strlen(line); if (ic->used + l < ic->out_cap) { memcpy(ic->out_buf + ic->used, line, l); ic->used += l; ic->out_buf[ic->used] = '\0'; } return 0; } static int ensure_sdr_cache_open(ipmi_sdr_ctx_t sdr, ipmi_ctx_t ctx, const char *path) { if (ipmi_sdr_cache_open(sdr, ctx, path) == 0) { return 0; } if (ipmi_sdr_cache_create( sdr, ctx, path, IPMI_SDR_CACHE_CREATE_FLAGS_OVERWRITE | IPMI_SDR_CACHE_CREATE_FLAGS_ASSUME_MAX_SDR_RECORD_COUNT, NULL, NULL) != 0) { return -1; } return ipmi_sdr_cache_open(sdr, ctx, path); } void c_ipmi_invalidate_sdr_cache(int handle) { StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot) return; pthread_mutex_lock(&slot->mu); if (slot->in_use && slot->sdr_cache_path[0] != '\0') { unlink(slot->sdr_cache_path); } pthread_mutex_unlock(&slot->mu); } int c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len) { if (out_len) *out_len = 0; if (out_buf && out_cap > 0) out_buf[0] = '\0'; StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot || !out_buf || out_cap < 2) return -1; pthread_mutex_lock(&slot->mu); if (!slot->in_use || !slot->ctx) { pthread_mutex_unlock(&slot->mu); return -1; } ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create(); ipmi_sensor_read_ctx_t sr = ipmi_sensor_read_ctx_create(slot->ctx); if (!sdr || !sr) { if (sdr) ipmi_sdr_ctx_destroy(sdr); if (sr) ipmi_sensor_read_ctx_destroy(sr); pthread_mutex_unlock(&slot->mu); return -1; } (void)ipmi_sensor_read_ctx_set_flags(sr, IPMI_SENSOR_READ_FLAGS_DISCRETE_READING); if (ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) { slot->alive = 0; ipmi_sensor_read_ctx_destroy(sr); ipmi_sdr_ctx_destroy(sdr); pthread_mutex_unlock(&slot->mu); return -1; } SdrIterCtx ic = { .sr = sr, .out_buf = out_buf, .out_cap = out_cap, .used = 0 }; int irc = ipmi_sdr_cache_iterate(sdr, sdr_iterate_cb, &ic); if (irc < 0) slot->alive = 0; (void)ipmi_sdr_cache_close(sdr); ipmi_sensor_read_ctx_destroy(sr); ipmi_sdr_ctx_destroy(sdr); pthread_mutex_unlock(&slot->mu); if (out_len) *out_len = ic.used; return (irc >= 0) ? 0 : -1; } static void append_str(char *out_buf, size_t out_cap, size_t *used, const char *s) { if (!out_buf || out_cap == 0 || !s) return; size_t l = strlen(s); if (*used >= out_cap - 1) return; size_t rem = out_cap - 1 - *used; if (l > rem) l = rem; memcpy(out_buf + *used, s, l); *used += l; out_buf[*used] = '\0'; } typedef struct { char *out_buf; size_t out_cap; size_t used; int count; } SelIterCtx; static int sel_iterate_cb(ipmi_sel_ctx_t sel, void *data) { SelIterCtx *sc = (SelIterCtx *)data; if (sc->count >= 200 || sc->used + 128 >= sc->out_cap) return 1; char line[256]; memset(line, 0, sizeof(line)); int n = ipmi_sel_parse_read_record_string( sel, "%i | %d | %t | %s | %E", NULL, 0, line, (unsigned int)(sizeof(line) - 2), IPMI_SEL_STRING_FLAGS_IGNORE_UNAVAILABLE_FIELD | IPMI_SEL_STRING_FLAGS_OUTPUT_NOT_AVAILABLE); if (n > 0) { line[sizeof(line) - 2] = '\0'; append_str(sc->out_buf, sc->out_cap, &sc->used, line); append_str(sc->out_buf, sc->out_cap, &sc->used, "\n"); sc->count++; } return 0; } static void append_fru_field( ipmi_fru_ctx_t fru, const char *label, ipmi_fru_field_t *f, uint8_t lang, char *out_buf, size_t out_cap, size_t *used) { if (!f || f->type_length_field_length == 0) return; char sbuf[IPMI_FRU_AREA_STRING_MAX + 1]; unsigned int slen = sizeof(sbuf) - 1; memset(sbuf, 0, sizeof(sbuf)); if (ipmi_fru_type_length_field_to_string( fru, f->type_length_field, f->type_length_field_length, lang, sbuf, &slen) == 0 && sbuf[0] != '\0') { char line[600]; snprintf(line, sizeof(line), "%-24s : %s\n", label, sbuf); append_str(out_buf, out_cap, used, line); } } int c_ipmi_device_info( int handle, const char *kind, char *out_buf, size_t out_cap, size_t *out_len) { if (out_len) *out_len = 0; if (out_buf && out_cap > 0) out_buf[0] = '\0'; StlIpmiSlot *slot = get_ipmi_slot(handle); if (!slot || !kind || !out_buf || out_cap < 2) return -1; pthread_mutex_lock(&slot->mu); if (!slot->in_use || !slot->ctx) { pthread_mutex_unlock(&slot->mu); return -1; } size_t used = 0; int rc = 0; if (strcmp(kind, "mc") == 0) { fiid_obj_t rs = fiid_obj_create(tmpl_cmd_get_device_id_rs); if (!rs || ipmi_cmd_get_device_id(slot->ctx, rs) != 0) { rc = -1; } else { uint64_t did = 0, drev = 0, fw1 = 0, fw2 = 0, imaj = 0, imin = 0, mfg = 0, pid = 0; (void)fiid_obj_get(rs, "device_id", &did); (void)fiid_obj_get(rs, "device_revision.revision", &drev); (void)fiid_obj_get(rs, "firmware_revision1.major_revision", &fw1); (void)fiid_obj_get(rs, "firmware_revision2.minor_revision", &fw2); (void)fiid_obj_get(rs, "ipmi_version_major", &imaj); (void)fiid_obj_get(rs, "ipmi_version_minor", &imin); (void)fiid_obj_get(rs, "manufacturer_id.id", &mfg); (void)fiid_obj_get(rs, "product_id", &pid); char tmp[512]; snprintf( tmp, sizeof(tmp), "Device ID : %llu\n" "Device Revision : %llu\n" "Firmware Revision : %llu.%02llx\n" "IPMI Version : %llu.%llu\n" "Manufacturer ID : %llu\n" "Product ID : %llu\n", (unsigned long long)did, (unsigned long long)drev, (unsigned long long)fw1, (unsigned long long)fw2, (unsigned long long)imaj, (unsigned long long)imin, (unsigned long long)mfg, (unsigned long long)pid); append_str(out_buf, out_cap, &used, tmp); } if (rs) fiid_obj_destroy(rs); } else if (strcmp(kind, "lan") == 0) { uint8_t ip4[4] = {0}, mask4[4] = {0}, gw4[4] = {0}, mac6[6] = {0}; uint64_t src = 0; int got_lan = 0; uint8_t chs[2] = { 1, 8 }; for (int ci = 0; ci < 2 && !got_lan; ci++) { uint8_t ch = chs[ci]; fiid_obj_t rs_ip = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_ip_address_rs); if (rs_ip && ipmi_cmd_get_lan_configuration_parameters_ip_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_ip) == 0 && fiid_obj_get_data(rs_ip, "ip_address", ip4, sizeof(ip4)) == 4) { got_lan = 1; fiid_obj_t rs_m = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_subnet_mask_rs); if (rs_m && ipmi_cmd_get_lan_configuration_parameters_subnet_mask(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_m) == 0) { (void)fiid_obj_get_data(rs_m, "subnet_mask", mask4, sizeof(mask4)); } if (rs_m) fiid_obj_destroy(rs_m); fiid_obj_t rs_gw = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_default_gateway_address_rs); if (rs_gw && ipmi_cmd_get_lan_configuration_parameters_default_gateway_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_gw) == 0) { (void)fiid_obj_get_data(rs_gw, "ip_address", gw4, sizeof(gw4)); } if (rs_gw) fiid_obj_destroy(rs_gw); fiid_obj_t rs_mac = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_mac_address_rs); if (rs_mac && ipmi_cmd_get_lan_configuration_parameters_mac_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_mac) == 0) { (void)fiid_obj_get_data(rs_mac, "mac_address", mac6, sizeof(mac6)); } if (rs_mac) fiid_obj_destroy(rs_mac); fiid_obj_t rs_s = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_ip_address_source_rs); if (rs_s && ipmi_cmd_get_lan_configuration_parameters_ip_address_source(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_s) == 0) { (void)fiid_obj_get(rs_s, "ip_address_source", &src); } if (rs_s) fiid_obj_destroy(rs_s); char tmp[512]; const char *src_s = (src == 1) ? "Static Address" : (src == 2) ? "DHCP Address" : "Other"; snprintf( tmp, sizeof(tmp), "LAN Channel : %u\n" "IP Address Source : %s\n" "IP Address : %u.%u.%u.%u\n" "Subnet Mask : %u.%u.%u.%u\n" "MAC Address : %02x:%02x:%02x:%02x:%02x:%02x\n" "Default Gateway IP : %u.%u.%u.%u\n", (unsigned)ch, src_s, ip4[0], ip4[1], ip4[2], ip4[3], mask4[0], mask4[1], mask4[2], mask4[3], mac6[0], mac6[1], mac6[2], mac6[3], mac6[4], mac6[5], gw4[0], gw4[1], gw4[2], gw4[3]); append_str(out_buf, out_cap, &used, tmp); } if (rs_ip) fiid_obj_destroy(rs_ip); } if (!got_lan) rc = -1; } else if (strcmp(kind, "sel") == 0) { ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create(); if (sdr && ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) { ipmi_sdr_ctx_destroy(sdr); sdr = NULL; } ipmi_sel_ctx_t sel = ipmi_sel_ctx_create(slot->ctx, sdr); if (!sel) { rc = -1; } else { SelIterCtx sc = { .out_buf = out_buf, .out_cap = out_cap, .used = 0, .count = 0 }; if (ipmi_sel_parse(sel, IPMI_SEL_RECORD_ID_FIRST, IPMI_SEL_RECORD_ID_LAST, sel_iterate_cb, &sc) < 0) { rc = -1; } else { used = sc.used; if (sc.count == 0) { append_str(out_buf, out_cap, &used, "SEL has no entries\n"); } } ipmi_sel_ctx_destroy(sel); } if (sdr) { (void)ipmi_sdr_cache_close(sdr); ipmi_sdr_ctx_destroy(sdr); } } else if (strcmp(kind, "fru") == 0) { ipmi_fru_ctx_t fru = ipmi_fru_ctx_create(slot->ctx); if (!fru || ipmi_fru_open_device_id(fru, 0) != 0) { if (fru) ipmi_fru_ctx_destroy(fru); rc = -1; } else { uint8_t areabuf[4096]; int has_any = 0; int has = (ipmi_fru_first(fru) == 0); while (has) { unsigned int atype = 0, alen = 0; if (ipmi_fru_read_data_area(fru, &atype, &alen, areabuf, sizeof(areabuf)) == 0) { if (atype == IPMI_FRU_AREA_TYPE_BOARD_INFO_AREA) { uint8_t lang = 0; uint32_t mfg_ts = 0; ipmi_fru_field_t bm, bn, bs, bp, bf; memset(&bm, 0, sizeof(bm)); memset(&bn, 0, sizeof(bn)); memset(&bs, 0, sizeof(bs)); memset(&bp, 0, sizeof(bp)); memset(&bf, 0, sizeof(bf)); if (ipmi_fru_board_info_area(fru, areabuf, alen, &lang, &mfg_ts, &bm, &bn, &bs, &bp, &bf, NULL, 0) == 0) { has_any = 1; append_fru_field(fru, "Board Mfg", &bm, lang, out_buf, out_cap, &used); append_fru_field(fru, "Board Product", &bn, lang, out_buf, out_cap, &used); append_fru_field(fru, "Board Serial", &bs, lang, out_buf, out_cap, &used); append_fru_field(fru, "Board Part Number", &bp, lang, out_buf, out_cap, &used); } } else if (atype == IPMI_FRU_AREA_TYPE_PRODUCT_INFO_AREA) { uint8_t lang = 0; ipmi_fru_field_t pm, pn, pp, pv, ps, pa, pf; memset(&pm, 0, sizeof(pm)); memset(&pn, 0, sizeof(pn)); memset(&pp, 0, sizeof(pp)); memset(&pv, 0, sizeof(pv)); memset(&ps, 0, sizeof(ps)); memset(&pa, 0, sizeof(pa)); memset(&pf, 0, sizeof(pf)); if (ipmi_fru_product_info_area(fru, areabuf, alen, &lang, &pm, &pn, &pp, &pv, &ps, &pa, &pf, NULL, 0) == 0) { has_any = 1; append_fru_field(fru, "Product Manufacturer", &pm, lang, out_buf, out_cap, &used); append_fru_field(fru, "Product Name", &pn, lang, out_buf, out_cap, &used); append_fru_field(fru, "Product Part Number", &pp, lang, out_buf, out_cap, &used); append_fru_field(fru, "Product Version", &pv, lang, out_buf, out_cap, &used); append_fru_field(fru, "Product Serial", &ps, lang, out_buf, out_cap, &used); append_fru_field(fru, "Product Asset Tag", &pa, lang, out_buf, out_cap, &used); } } } int nxt = ipmi_fru_next(fru); if (nxt != 1) break; } (void)ipmi_fru_close_device_id(fru); ipmi_fru_ctx_destroy(fru); if (!has_any) append_str(out_buf, out_cap, &used, "FRU empty\n"); } } else if (strcmp(kind, "sol") == 0) { uint8_t chs[2] = { 1, 8 }; int got_sol = 0; for (int ci = 0; ci < 2 && !got_sol; ci++) { uint8_t ch = chs[ci]; uint8_t rq_en[4] = { 0x22, ch, 0x01, 0x00 }; /* Get SOL Config Param: Enable */ uint8_t rs_en[16]; int rl = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_en, sizeof(rq_en), rs_en, sizeof(rs_en)); if (rl >= 4 && rs_en[1] == 0x00) { got_sol = 1; int enabled = (rs_en[3] & 0x01) ? 1 : 0; uint8_t rq_auth[4] = { 0x22, ch, 0x02, 0x00 }; uint8_t rs_auth[16]; int rla = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_auth, sizeof(rq_auth), rs_auth, sizeof(rs_auth)); uint8_t rq_br[4] = { 0x22, ch, 0x05, 0x00 }; uint8_t rs_br[16]; int rlb = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_br, sizeof(rq_br), rs_br, sizeof(rs_br)); const char *baud_s = "default"; if (rlb >= 4 && rs_br[1] == 0x00) { switch (rs_br[3] & 0x0F) { case 0x06: baud_s = "9600"; break; case 0x07: baud_s = "19200"; break; case 0x08: baud_s = "38400"; break; case 0x09: baud_s = "57600"; break; case 0x0A: baud_s = "115200"; break; default: baud_s = "serial-default"; break; } } char tmp[320]; snprintf( tmp, sizeof(tmp), "SOL Channel : %u\n" "Enabled : %s\n" "Force Encryption : %s\n" "Force Authentication : %s\n" "Non-Volatile Bit Rate : %s\n", (unsigned)ch, enabled ? "true" : "false", (rla >= 4 && rs_auth[1] == 0x00 && (rs_auth[3] & 0x80)) ? "true" : "false", (rla >= 4 && rs_auth[1] == 0x00 && (rs_auth[3] & 0x40)) ? "true" : "false", baud_s); append_str(out_buf, out_cap, &used, tmp); } } if (!got_sol) { append_str(out_buf, out_cap, &used, "SOL configuration not reported by BMC (NetFn 0x0C Cmd 0x22)\n"); } } else if (strcmp(kind, "sessions") == 0) { uint8_t rq[2] = { 0x3D, 0x00 }; /* App NetFn 0x06, Get Session Info (current active session) */ uint8_t rs[64]; int rl = ipmi_cmd_raw(slot->ctx, 0, 0x06, rq, sizeof(rq), rs, sizeof(rs)); if (rl >= 6 && rs[1] == 0x00) { char tmp[320]; snprintf( tmp, sizeof(tmp), "Session Handle : 0x%02X\n" "Session Slots Total : %u\n" "Active Sessions : %u\n" "Current User ID : %u\n" "Current Privilege Level : %u\n", (unsigned)rs[2], (unsigned)(rs[3] & 0x3F), (unsigned)(rs[4] & 0x3F), (unsigned)(rs[5] & 0x3F), (unsigned)(rl >= 7 ? (rs[6] & 0x0F) : 0)); append_str(out_buf, out_cap, &used, tmp); } else { append_str(out_buf, out_cap, &used, "BMC did not return active session table (NetFn 0x06 Cmd 0x3D)\n"); } } else if (strcmp(kind, "events") == 0) { fiid_obj_t rs_info = fiid_obj_create(tmpl_cmd_get_sel_info_rs); if (rs_info && ipmi_cmd_get_sel_info(slot->ctx, rs_info) == 0) { uint64_t entries = 0, free_sp = 0, ovf = 0; (void)fiid_obj_get(rs_info, "entries", &entries); (void)fiid_obj_get(rs_info, "free_space", &free_sp); (void)fiid_obj_get(rs_info, "overflow_flag", &ovf); char hdr[256]; snprintf( hdr, sizeof(hdr), "SEL Entries : %llu\n" "SEL Free Space (bytes) : %llu\n" "SEL Overflow : %s\n", (unsigned long long)entries, (unsigned long long)free_sp, ovf ? "true" : "false"); append_str(out_buf, out_cap, &used, hdr); } if (rs_info) fiid_obj_destroy(rs_info); ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create(); if (sdr && ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) { ipmi_sdr_ctx_destroy(sdr); sdr = NULL; } ipmi_sel_ctx_t sel = ipmi_sel_ctx_create(slot->ctx, sdr); if (sel) { SelIterCtx sc = { .out_buf = out_buf, .out_cap = out_cap, .used = used, .count = 0 }; if (ipmi_sel_parse(sel, IPMI_SEL_RECORD_ID_FIRST, IPMI_SEL_RECORD_ID_LAST, sel_iterate_cb, &sc) >= 0) { used = sc.used; if (sc.count == 0) { append_str(out_buf, out_cap, &used, "No SEL event records\n"); } } ipmi_sel_ctx_destroy(sel); } if (sdr) { (void)ipmi_sdr_cache_close(sdr); ipmi_sdr_ctx_destroy(sdr); } } else if (strcmp(kind, "fan_mode") == 0) { /* Try Supermicro / Intel / AMI OEM Get Fan Mode first (0x30 0x45 0x00) */ uint8_t rq[2] = { 0x45, 0x00 }; uint8_t rs[16]; int rl = ipmi_cmd_raw(slot->ctx, 0, 0x30, rq, sizeof(rq), rs, sizeof(rs)); if (rl >= 3 && rs[1] == 0x00) { const char *mode_s = "unknown"; switch (rs[2]) { case 0x00: mode_s = "Standard (0x00)"; break; case 0x01: mode_s = "Full (0x01)"; break; case 0x02: mode_s = "Optimal (0x02)"; break; case 0x04: mode_s = "HeavyIO (0x04)"; break; default: mode_s = "Custom/Manual"; break; } char tmp[160]; snprintf(tmp, sizeof(tmp), "BMC Fan Mode : %s (raw=0x%02X)\n", mode_s, (unsigned)rs[2]); append_str(out_buf, out_cap, &used, tmp); } else { /* Standard IPMI does not expose a vendor-neutral fan-mode getter; report real status cleanly */ append_str(out_buf, out_cap, &used, "BMC Fan Mode : OEM readback unsupported (use manual fan_low_speed_on/off or inspect Fan RPM sensors)\n"); } } else { rc = -1; } if (rc < 0) slot->alive = 0; pthread_mutex_unlock(&slot->mu); if (out_len) *out_len = used; return rc; } int stl_free_disk_bytes(const char *path, uint64_t *out_avail_bytes) { if (!path || !path[0] || !out_avail_bytes) return -1; struct statvfs st; if (statvfs(path, &st) != 0) return -1; *out_avail_bytes = (uint64_t)st.f_bavail * (uint64_t)st.f_frsize; return 0; } void stl_set_thread_idle_priority(void) { #ifdef SCHED_IDLE struct sched_param sp; memset(&sp, 0, sizeof(sp)); if (pthread_setschedparam(pthread_self(), SCHED_IDLE, &sp) != 0) { (void)setpriority(PRIO_PROCESS, 0, 19); } #else (void)setpriority(PRIO_PROCESS, 0, 19); #endif } int stl_chmod_0600(const char *path) { if (!path || !path[0]) return -1; return chmod(path, 0600); } uint64_t stl_mono_us(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; return (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)(ts.tv_nsec / 1000L); } uint64_t stl_mem_diff_64b_mask(const uint8_t *a, const uint8_t *b, size_t len) { int tier = stl_active_isa_tier(); if (tier >= STL_ISA_AVX512) { return simd_mem_diff_64b_avx512(a, b, len); } if (tier >= STL_ISA_AVX2_BMI) { return simd_mem_diff_64b_avx2(a, b, len); } if (tier >= STL_ISA_SSE42_PCLMUL) { return simd_mem_diff_64b_sse42(a, b, len); } return simd_mem_diff_64b_sse2(a, b, len); } void stl_batch_mem_diff_64b_masks( const uint8_t *prev_base, const uint8_t *cur_base, size_t stride, size_t item_len, size_t count, uint64_t *out_masks) { if (!prev_base || !cur_base || !out_masks || count == 0 || item_len == 0 || stride < item_len) { return; } int tier = stl_active_isa_tier(); if (tier >= STL_ISA_AVX512) { for (size_t i = 0; i < count; i++) { out_masks[i] = simd_mem_diff_64b_avx512(prev_base + i * stride, cur_base + i * stride, item_len); } } else if (tier >= STL_ISA_AVX2_BMI) { for (size_t i = 0; i < count; i++) { out_masks[i] = simd_mem_diff_64b_avx2(prev_base + i * stride, cur_base + i * stride, item_len); } } else if (tier >= STL_ISA_SSE42_PCLMUL) { for (size_t i = 0; i < count; i++) { out_masks[i] = simd_mem_diff_64b_sse42(prev_base + i * stride, cur_base + i * stride, item_len); } } else { for (size_t i = 0; i < count; i++) { out_masks[i] = simd_mem_diff_64b_sse2(prev_base + i * stride, cur_base + i * stride, item_len); } } } /* ========================================================================= * 7. Multi-NIC IPv4 Enumeration & IP_PKTINFO Broadcast UDP Helpers (ProxyDHCP) * ========================================================================= */ int c_list_ipv4_ifaces(StlNetIface *out_list, int max_count) { if (!out_list || max_count <= 0) return -1; struct ifaddrs *ifas = NULL; if (getifaddrs(&ifas) != 0 || !ifas) return -1; int io_fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); int n = 0; for (struct ifaddrs *ifa = ifas; ifa != NULL && n < max_count; ifa = ifa->ifa_next) { if (!ifa->ifa_name || !ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) { continue; } StlNetIface *dst = &out_list[n]; memset(dst, 0, sizeof(*dst)); snprintf(dst->name, sizeof(dst->name), "%s", ifa->ifa_name); const struct sockaddr_in *sin = (const struct sockaddr_in *)ifa->ifa_addr; dst->ip_be = sin->sin_addr.s_addr; if (ifa->ifa_netmask && ifa->ifa_netmask->sa_family == AF_INET) { const struct sockaddr_in *sm = (const struct sockaddr_in *)ifa->ifa_netmask; dst->mask_be = sm->sin_addr.s_addr; } if (ifa->ifa_ifu.ifu_broadaddr && ifa->ifa_ifu.ifu_broadaddr->sa_family == AF_INET && (ifa->ifa_flags & IFF_BROADCAST)) { const struct sockaddr_in *sb = (const struct sockaddr_in *)ifa->ifa_ifu.ifu_broadaddr; dst->bcast_be = sb->sin_addr.s_addr; } else { dst->bcast_be = dst->ip_be | (~dst->mask_be); } dst->ifindex = if_nametoindex(ifa->ifa_name); dst->is_up = (ifa->ifa_flags & IFF_UP) ? 1 : 0; dst->is_loopback = (ifa->ifa_flags & IFF_LOOPBACK) ? 1 : 0; if (io_fd >= 0) { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifa->ifa_name); if (ioctl(io_fd, SIOCGIFHWADDR, &ifr) == 0) { memcpy(dst->mac, ifr.ifr_hwaddr.sa_data, 6); } } n++; } if (io_fd >= 0) close(io_fd); freeifaddrs(ifas); return n; } int c_udp_bind_dhcp_socket(const char *iface, int port, int reuse_port) { if (port < 0 || port > 65535) return -1; int fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (fd < 0) return -1; int one = 1; (void)setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); #ifdef SO_REUSEPORT if (reuse_port) { (void)setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)); } #endif (void)setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)); (void)setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &one, sizeof(one)); if (iface && iface[0] != '\0') { size_t ilen = strlen(iface); if (ilen < IFNAMSIZ) { /* Best effort: requires CAP_NET_RAW; if EPERM, keep INADDR_ANY and filter by ifindex in userspace */ (void)setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface, (socklen_t)(ilen + 1)); } } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons((uint16_t)port); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { close(fd); return -1; } return fd; } ssize_t c_udp_recv_pktinfo( int fd, uint8_t *buf, size_t cap, uint32_t *out_peer_ip_be, uint16_t *out_peer_port, uint32_t *out_local_ip_be, uint32_t *out_ifindex) { if (fd < 0 || !buf || cap == 0) return -1; if (out_peer_ip_be) *out_peer_ip_be = 0; if (out_peer_port) *out_peer_port = 0; if (out_local_ip_be) *out_local_ip_be = 0; if (out_ifindex) *out_ifindex = 0; struct sockaddr_in peer; memset(&peer, 0, sizeof(peer)); struct iovec iov = { .iov_base = buf, .iov_len = cap }; uint8_t cbuf[256]; struct msghdr msg; memset(&msg, 0, sizeof(msg)); msg.msg_name = &peer; msg.msg_namelen = sizeof(peer); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = cbuf; msg.msg_controllen = sizeof(cbuf); ssize_t n = recvmsg(fd, &msg, 0); if (n < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0; return -1; } if (out_peer_ip_be) *out_peer_ip_be = peer.sin_addr.s_addr; if (out_peer_port) *out_peer_port = ntohs(peer.sin_port); for (struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); cm != NULL; cm = CMSG_NXTHDR(&msg, cm)) { if (cm->cmsg_level == IPPROTO_IP && cm->cmsg_type == IP_PKTINFO && cm->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo))) { struct in_pktinfo pi; memcpy(&pi, CMSG_DATA(cm), sizeof(pi)); if (out_local_ip_be) *out_local_ip_be = pi.ipi_spec_dst.s_addr; if (out_ifindex) *out_ifindex = (uint32_t)pi.ipi_ifindex; break; } } return n; } ssize_t c_udp_send_pktinfo( int fd, const uint8_t *buf, size_t len, uint32_t dst_ip_be, uint16_t dst_port, uint32_t src_ip_be, uint32_t ifindex) { if (fd < 0 || !buf || len == 0) return -1; struct sockaddr_in dst; memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_addr.s_addr = dst_ip_be; dst.sin_port = htons(dst_port); struct iovec iov = { .iov_base = (void *)buf, .iov_len = len }; uint8_t cbuf[CMSG_SPACE(sizeof(struct in_pktinfo))]; memset(cbuf, 0, sizeof(cbuf)); struct msghdr msg; memset(&msg, 0, sizeof(msg)); msg.msg_name = &dst; msg.msg_namelen = sizeof(dst); msg.msg_iov = &iov; msg.msg_iovlen = 1; if (ifindex > 0 || src_ip_be != 0) { msg.msg_control = cbuf; msg.msg_controllen = sizeof(cbuf); struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); cm->cmsg_level = IPPROTO_IP; cm->cmsg_type = IP_PKTINFO; cm->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); struct in_pktinfo pi; memset(&pi, 0, sizeof(pi)); pi.ipi_ifindex = (int)ifindex; pi.ipi_spec_dst.s_addr = src_ip_be; memcpy(CMSG_DATA(cm), &pi, sizeof(pi)); } ssize_t n = sendmsg(fd, &msg, MSG_NOSIGNAL); if (n < 0 && (ifindex > 0 || src_ip_be != 0)) { /* Fallback without IP_PKTINFO if routing table rejects pinned spec_dst (e.g. loopback tests) */ msg.msg_control = NULL; msg.msg_controllen = 0; n = sendmsg(fd, &msg, MSG_NOSIGNAL); } return n; }