c_bridge.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179
  1. /*
  2. * c_bridge.c — XJKJ-STL Native C Runtime Bridge (v0.8.1.19)
  3. *
  4. * Compiled strictly with -O3 -march=x86-64 (pure SSE2 baseline, no AVX/POPCNT
  5. * emitted by the compiler) so dual-core Celeron/Pentium (Sandy Bridge..Coffee Lake)
  6. * never trigger SIGILL. Runtime CPUID + XGETBV dispatches SSE2 / SSE4.2 / AVX2
  7. * assembly kernels dynamically.
  8. */
  9. #define _GNU_SOURCE
  10. #include "stl_accel.h"
  11. #include <arpa/inet.h>
  12. #include <cpuid.h>
  13. #include <errno.h>
  14. #include <fcntl.h>
  15. #include <freeipmi/freeipmi.h>
  16. #include <freeipmi/record-format/ipmi-sdr-record-format.h>
  17. #include <ipmiconsole.h>
  18. #include <libssh/callbacks.h>
  19. #include <libssh/libssh.h>
  20. #include <libssh/sftp.h>
  21. #include <netdb.h>
  22. #include <netinet/in.h>
  23. #include <netinet/tcp.h>
  24. #include <poll.h>
  25. #include <pthread.h>
  26. #include <sched.h>
  27. #include <signal.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <sys/epoll.h>
  32. #include <sys/eventfd.h>
  33. #include <sys/mman.h>
  34. #include <sys/socket.h>
  35. #include <sys/stat.h>
  36. #include <sys/timerfd.h>
  37. #include <sys/uio.h>
  38. #include <termios.h>
  39. #include <time.h>
  40. #include <unistd.h>
  41. /* =========================================================================
  42. * 1. Runtime CPUID + XGETBV ISA Tier Detection & Dispatch
  43. * ========================================================================= */
  44. typedef struct {
  45. uint32_t isa_tier;
  46. uint32_t has_sse42;
  47. uint32_t has_avx2;
  48. uint32_t has_bmi2;
  49. char cpu_brand[64];
  50. char tier_name[32];
  51. } StlHwCapsCompat;
  52. static pthread_once_t g_hw_once = PTHREAD_ONCE_INIT;
  53. static int g_detected_tier = STL_ISA_SSE2;
  54. static int g_forced_tier = -1;
  55. static StlHwCapsCompat g_hw_caps;
  56. static void detect_hw_once(void) {
  57. memset(&g_hw_caps, 0, sizeof(g_hw_caps));
  58. unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0;
  59. unsigned int max_leaf = __get_cpuid_max(0, NULL);
  60. int has_sse42 = 0;
  61. int has_popcnt = 0;
  62. int has_osxsave = 0;
  63. int has_avx = 0;
  64. int has_avx2 = 0;
  65. int has_bmi1 = 0;
  66. int has_bmi2 = 0;
  67. if (max_leaf >= 1 && __get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
  68. has_sse42 = (ecx & (1u << 20)) != 0;
  69. has_popcnt = (ecx & (1u << 23)) != 0;
  70. has_osxsave = (ecx & (1u << 27)) != 0;
  71. has_avx = (ecx & (1u << 28)) != 0;
  72. }
  73. int ymm_os_ok = 0;
  74. if (has_osxsave && has_avx) {
  75. uint64_t xcr0 = asm_xgetbv_eax0();
  76. ymm_os_ok = ((xcr0 & 0x6ULL) == 0x6ULL);
  77. }
  78. if (max_leaf >= 7 && __get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx)) {
  79. has_bmi1 = (ebx & (1u << 3)) != 0;
  80. has_avx2 = (ebx & (1u << 5)) != 0;
  81. has_bmi2 = (ebx & (1u << 8)) != 0;
  82. }
  83. if (ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2 && has_sse42 && has_popcnt) {
  84. g_detected_tier = STL_ISA_AVX2_BMI;
  85. } else if (has_sse42 && has_popcnt) {
  86. g_detected_tier = STL_ISA_SSE42_POPCNT;
  87. } else {
  88. g_detected_tier = STL_ISA_SSE2;
  89. }
  90. /* Read CPU brand string (leaves 0x80000002..0x80000004) */
  91. unsigned int max_ext = __get_cpuid_max(0x80000000u, NULL);
  92. if (max_ext >= 0x80000004u) {
  93. uint32_t brand_words[12];
  94. __get_cpuid(0x80000002u, &brand_words[0], &brand_words[1], &brand_words[2], &brand_words[3]);
  95. __get_cpuid(0x80000003u, &brand_words[4], &brand_words[5], &brand_words[6], &brand_words[7]);
  96. __get_cpuid(0x80000004u, &brand_words[8], &brand_words[9], &brand_words[10], &brand_words[11]);
  97. memcpy(g_hw_caps.cpu_brand, brand_words, 48);
  98. g_hw_caps.cpu_brand[48] = '\0';
  99. } else {
  100. snprintf(g_hw_caps.cpu_brand, sizeof(g_hw_caps.cpu_brand), "x86_64-generic");
  101. }
  102. g_hw_caps.isa_tier = (uint32_t)g_detected_tier;
  103. g_hw_caps.has_sse42 = (uint32_t)(has_sse42 && has_popcnt);
  104. g_hw_caps.has_avx2 = (uint32_t)(ymm_os_ok && has_avx2);
  105. g_hw_caps.has_bmi2 = (uint32_t)has_bmi2;
  106. snprintf(g_hw_caps.tier_name, sizeof(g_hw_caps.tier_name), "%s", stl_isa_tier_name(g_detected_tier));
  107. }
  108. void c_init_once_hw_dispatch(void) {
  109. pthread_once(&g_hw_once, detect_hw_once);
  110. }
  111. int stl_cpu_tier_detect(void) {
  112. pthread_once(&g_hw_once, detect_hw_once);
  113. return g_detected_tier;
  114. }
  115. int stl_active_isa_tier(void) {
  116. pthread_once(&g_hw_once, detect_hw_once);
  117. int forced = __atomic_load_n(&g_forced_tier, __ATOMIC_RELAXED);
  118. if (forced >= STL_ISA_SSE2 && forced <= STL_ISA_AVX2_BMI) {
  119. if (forced <= g_detected_tier) return forced;
  120. }
  121. return g_detected_tier;
  122. }
  123. void stl_force_isa_tier(int tier) {
  124. pthread_once(&g_hw_once, detect_hw_once);
  125. __atomic_store_n(&g_forced_tier, tier, __ATOMIC_RELAXED);
  126. }
  127. const char *stl_isa_tier_name(int tier) {
  128. switch (tier) {
  129. case STL_ISA_AVX2_BMI: return "AVX2+BMI1/2";
  130. case STL_ISA_SSE42_POPCNT: return "SSE4.2+POPCNT";
  131. default: return "SSE2-baseline";
  132. }
  133. }
  134. void c_get_hw_caps(StlHwCapsCompat *out_caps) {
  135. pthread_once(&g_hw_once, detect_hw_once);
  136. if (!out_caps) return;
  137. *out_caps = g_hw_caps;
  138. int active = stl_active_isa_tier();
  139. out_caps->isa_tier = (uint32_t)active;
  140. snprintf(out_caps->tier_name, sizeof(out_caps->tier_name), "%s", stl_isa_tier_name(active));
  141. }
  142. size_t stl_base64_encode(const uint8_t *src, size_t len, uint8_t *dst) {
  143. if (!src || !dst || len == 0) return 0;
  144. int tier = stl_active_isa_tier();
  145. if (tier >= STL_ISA_AVX2_BMI) {
  146. return asm_base64_encode_avx2(src, len, dst);
  147. }
  148. return asm_base64_encode_sse2(src, len, dst);
  149. }
  150. void stl_clean_stream_init(StlCleanStreamState *state) {
  151. if (!state) return;
  152. memset(state, 0, sizeof(*state));
  153. }
  154. void stl_clean_stream_clear_halfline(StlCleanStreamState *state) {
  155. if (!state) return;
  156. state->half_len = 0;
  157. state->tag_mask = 0;
  158. state->first_nonws = 0;
  159. state->cur_col = 0;
  160. state->prev_was_cr = 0;
  161. state->esc_state = 0;
  162. }
  163. void stl_clean_split_classify(
  164. StlCleanStreamState *state,
  165. const uint8_t *src,
  166. size_t src_len,
  167. StlCleanOutput *out) {
  168. if (!state || !out) return;
  169. if (!src || src_len == 0) {
  170. out->src_consumed = 0;
  171. return;
  172. }
  173. int tier = stl_active_isa_tier();
  174. if (tier >= STL_ISA_AVX2_BMI) {
  175. asm_clean_split_classify_avx2(state, src, src_len, out);
  176. } else if (tier >= STL_ISA_SSE42_POPCNT) {
  177. asm_clean_split_classify_sse42(state, src, src_len, out);
  178. } else {
  179. asm_clean_split_classify_sse2(state, src, src_len, out);
  180. }
  181. }
  182. /* Pure SSE2 helper for legacy single-buffer scan (zero rdtsc/lfence!) */
  183. size_t c_dispatch_scan_special(
  184. const uint8_t *buf,
  185. size_t len,
  186. uint64_t *out_newlines,
  187. uint64_t *out_specials) {
  188. uint64_t nl = 0;
  189. uint64_t sp = 0;
  190. size_t first_ctrl = len;
  191. for (size_t i = 0; i < len; i++) {
  192. uint8_t b = buf[i];
  193. if (b == '\n' || b == '\r') {
  194. nl++;
  195. } else if (b < 0x20 || b == 0x7f) {
  196. sp++;
  197. if (first_ctrl == len) first_ctrl = i;
  198. }
  199. }
  200. if (out_newlines) *out_newlines = nl;
  201. if (out_specials) *out_specials = sp;
  202. return first_ctrl;
  203. }
  204. /* =========================================================================
  205. * 2. Monotonic 64-Bit mmap Ring Buffer (Hugepage + 64B Pad + PROT_NONE Guard)
  206. * ========================================================================= */
  207. static size_t round_up_pow2_min2m(size_t v) {
  208. size_t cap = 2u * 1024u * 1024u; /* 2 MiB hugepage granularity */
  209. while (cap < v && cap < (1ULL << 30)) {
  210. cap <<= 1;
  211. }
  212. return cap;
  213. }
  214. int stl_ring_init(StlRingBuf *rb, size_t requested_cap) {
  215. if (!rb) return -1;
  216. memset(rb, 0, sizeof(*rb));
  217. size_t cap = round_up_pow2_min2m(requested_cap == 0 ? (8u * 1024u * 1024u) : requested_cap);
  218. size_t page_sz = 4096u;
  219. /* [0..cap): circular ring; [cap..cap+4096): 64B+ zeroed tail pad page; [cap+4096..cap+8192): PROT_NONE guard */
  220. size_t pad_bytes = page_sz;
  221. size_t guard_bytes = page_sz;
  222. size_t total = cap + pad_bytes + guard_bytes;
  223. void *mem = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  224. if (mem == MAP_FAILED) {
  225. return -1;
  226. }
  227. #ifdef MADV_HUGEPAGE
  228. (void)madvise(mem, cap, MADV_HUGEPAGE);
  229. #endif
  230. /* Arm hardware guard page immediately after the 4KB tail-padding page */
  231. uint8_t *base = (uint8_t *)mem;
  232. memset(base + cap, 0, pad_bytes);
  233. if (mprotect(base + cap + pad_bytes, guard_bytes, PROT_NONE) != 0) {
  234. munmap(mem, total);
  235. return -1;
  236. }
  237. rb->buf = base;
  238. rb->cap = cap;
  239. rb->mask = cap - 1;
  240. rb->mmap_total = total;
  241. rb->base_offset = 0;
  242. rb->write_offset = 0;
  243. return 0;
  244. }
  245. void stl_ring_destroy(StlRingBuf *rb) {
  246. if (!rb) return;
  247. if (rb->buf && rb->mmap_total > 0) {
  248. munmap(rb->buf, rb->mmap_total);
  249. }
  250. memset(rb, 0, sizeof(*rb));
  251. }
  252. uint64_t stl_ring_append(StlRingBuf *rb, const uint8_t *data, size_t len) {
  253. if (!rb || !rb->buf) return 0;
  254. if (!data || len == 0) return rb->write_offset;
  255. if (len >= rb->cap) {
  256. /* Input chunk exceeds entire ring capacity: retain trailing cap bytes */
  257. const uint8_t *tail = data + (len - rb->cap);
  258. uint64_t new_wo = rb->write_offset + (uint64_t)len;
  259. uint64_t new_bo = new_wo - (uint64_t)rb->cap;
  260. size_t pos = (size_t)(new_bo & rb->mask);
  261. size_t first = rb->cap - pos;
  262. memcpy(rb->buf + pos, tail, first);
  263. if (first < rb->cap) {
  264. memcpy(rb->buf, tail + first, rb->cap - first);
  265. }
  266. memset(rb->buf + rb->cap, 0, 64);
  267. rb->write_offset = new_wo;
  268. rb->base_offset = new_bo;
  269. return rb->write_offset;
  270. }
  271. size_t pos = (size_t)(rb->write_offset & rb->mask);
  272. size_t first = rb->cap - pos;
  273. if (first >= len) {
  274. memcpy(rb->buf + pos, data, len);
  275. } else {
  276. memcpy(rb->buf + pos, data, first);
  277. memcpy(rb->buf, data + first, len - first);
  278. }
  279. /* Ensure 64-byte SIMD tail padding stays zeroed */
  280. memset(rb->buf + rb->cap, 0, 64);
  281. rb->write_offset += (uint64_t)len;
  282. if (rb->write_offset - rb->base_offset > (uint64_t)rb->cap) {
  283. /* Slide oldest bound forward; write_offset NEVER regresses */
  284. rb->base_offset = rb->write_offset - (uint64_t)rb->cap;
  285. }
  286. return rb->write_offset;
  287. }
  288. size_t stl_ring_read(
  289. const StlRingBuf *rb,
  290. uint64_t req_offset,
  291. uint8_t *dst,
  292. size_t max_len,
  293. uint64_t *out_actual_start,
  294. uint64_t *out_next_offset) {
  295. if (!rb || !rb->buf) {
  296. if (out_actual_start) *out_actual_start = 0;
  297. if (out_next_offset) *out_next_offset = 0;
  298. return 0;
  299. }
  300. uint64_t start = req_offset;
  301. if (start < rb->base_offset) {
  302. /* Reader fell behind trimmed window: advance monotonically to base_offset */
  303. start = rb->base_offset;
  304. }
  305. if (start >= rb->write_offset || !dst || max_len == 0) {
  306. uint64_t cur = rb->write_offset;
  307. if (out_actual_start) *out_actual_start = cur;
  308. if (out_next_offset) *out_next_offset = cur;
  309. return 0;
  310. }
  311. uint64_t avail = rb->write_offset - start;
  312. size_t n = (avail < (uint64_t)max_len) ? (size_t)avail : max_len;
  313. size_t pos = (size_t)(start & rb->mask);
  314. size_t first = rb->cap - pos;
  315. if (first >= n) {
  316. memcpy(dst, rb->buf + pos, n);
  317. } else {
  318. memcpy(dst, rb->buf + pos, first);
  319. memcpy(dst + first, rb->buf, n - first);
  320. }
  321. if (out_actual_start) *out_actual_start = start;
  322. if (out_next_offset) *out_next_offset = start + (uint64_t)n;
  323. return n;
  324. }
  325. void stl_ring_clear_monotonic(StlRingBuf *rb) {
  326. if (!rb) return;
  327. /* Advance base_offset to write_offset so old data is logically trimmed WITHOUT resetting offset! */
  328. rb->base_offset = rb->write_offset;
  329. }
  330. /* =========================================================================
  331. * 3. epoll / timerfd / eventfd / TCP_NODELAY + writev / Core Affinity
  332. * ========================================================================= */
  333. int stl_epoll_create(void) {
  334. return epoll_create1(EPOLL_CLOEXEC);
  335. }
  336. int stl_epoll_ctl_fd(int epfd, int op, int fd, uint32_t events, uint64_t token) {
  337. struct epoll_event ev;
  338. memset(&ev, 0, sizeof(ev));
  339. ev.events = events;
  340. ev.data.u64 = token;
  341. return epoll_ctl(epfd, op, fd, &ev);
  342. }
  343. int stl_epoll_wait_tokens(
  344. int epfd,
  345. uint64_t *out_tokens,
  346. uint32_t *out_events,
  347. int max_ev,
  348. int timeout_ms) {
  349. if (epfd < 0 || max_ev <= 0) return 0;
  350. if (max_ev > 128) max_ev = 128;
  351. struct epoll_event evs[128];
  352. int n = epoll_wait(epfd, evs, max_ev, timeout_ms);
  353. if (n <= 0) return 0;
  354. for (int i = 0; i < n; i++) {
  355. if (out_tokens) out_tokens[i] = evs[i].data.u64;
  356. if (out_events) out_events[i] = evs[i].events;
  357. }
  358. return n;
  359. }
  360. int stl_timerfd_create_ms(uint64_t initial_ms, uint64_t interval_ms) {
  361. int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
  362. if (tfd < 0) return -1;
  363. if (stl_timerfd_arm_ms(tfd, initial_ms, interval_ms) != 0) {
  364. close(tfd);
  365. return -1;
  366. }
  367. return tfd;
  368. }
  369. int stl_timerfd_arm_ms(int tfd, uint64_t initial_ms, uint64_t interval_ms) {
  370. if (tfd < 0) return -1;
  371. struct itimerspec its;
  372. memset(&its, 0, sizeof(its));
  373. its.it_value.tv_sec = (time_t)(initial_ms / 1000ULL);
  374. its.it_value.tv_nsec = (long)((initial_ms % 1000ULL) * 1000000ULL);
  375. its.it_interval.tv_sec = (time_t)(interval_ms / 1000ULL);
  376. its.it_interval.tv_nsec = (long)((interval_ms % 1000ULL) * 1000000ULL);
  377. return timerfd_settime(tfd, 0, &its, NULL);
  378. }
  379. void stl_timerfd_drain(int tfd) {
  380. if (tfd < 0) return;
  381. uint64_t exp = 0;
  382. while (read(tfd, &exp, sizeof(exp)) > 0) {}
  383. }
  384. int stl_eventfd_create(void) {
  385. return eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
  386. }
  387. void stl_eventfd_notify(int efd) {
  388. if (efd < 0) return;
  389. uint64_t v = 1;
  390. ssize_t _r = write(efd, &v, sizeof(v));
  391. (void)_r;
  392. }
  393. void stl_eventfd_drain(int efd) {
  394. if (efd < 0) return;
  395. uint64_t v = 0;
  396. while (read(efd, &v, sizeof(v)) > 0) {}
  397. }
  398. int stl_set_nonblocking_nodelay(int fd, int is_tcp) {
  399. if (fd < 0) return -1;
  400. int flags = fcntl(fd, F_GETFL, 0);
  401. if (flags >= 0) {
  402. (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  403. }
  404. if (is_tcp) {
  405. int one = 1;
  406. (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
  407. (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
  408. }
  409. return 0;
  410. }
  411. /* Merged WebSocket header + payload writev (eliminates 44ms delayed-ACK stall) */
  412. int64_t stl_ws_writev2(
  413. int fd,
  414. const uint8_t *hdr,
  415. size_t hdr_len,
  416. const uint8_t *body,
  417. size_t body_len) {
  418. if (fd < 0) return -1;
  419. size_t off0 = 0;
  420. size_t off1 = 0;
  421. size_t total = hdr_len + body_len;
  422. size_t sent = 0;
  423. while (sent < total) {
  424. struct iovec iov[2];
  425. int iovcnt = 0;
  426. if (off0 < hdr_len) {
  427. iov[iovcnt].iov_base = (void *)(hdr + off0);
  428. iov[iovcnt].iov_len = hdr_len - off0;
  429. iovcnt++;
  430. }
  431. if (off1 < body_len) {
  432. iov[iovcnt].iov_base = (void *)(body + off1);
  433. iov[iovcnt].iov_len = body_len - off1;
  434. iovcnt++;
  435. }
  436. ssize_t n = writev(fd, iov, iovcnt);
  437. if (n > 0) {
  438. size_t adv = (size_t)n;
  439. sent += adv;
  440. if (off0 < hdr_len) {
  441. size_t rem0 = hdr_len - off0;
  442. if (adv <= rem0) {
  443. off0 += adv;
  444. adv = 0;
  445. } else {
  446. off0 = hdr_len;
  447. adv -= rem0;
  448. }
  449. }
  450. off1 += adv;
  451. continue;
  452. }
  453. if (n < 0 && errno == EINTR) continue;
  454. if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
  455. struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
  456. int pr = poll(&pfd, 1, 2000);
  457. if (pr > 0) continue;
  458. return -1;
  459. }
  460. return -1;
  461. }
  462. return (int64_t)sent;
  463. }
  464. void stl_pin_thread_to_core(int core_index) {
  465. if (core_index < 0) return;
  466. long ncores = sysconf(_SC_NPROCESSORS_ONLN);
  467. if (ncores <= 0) return;
  468. int target = core_index % (int)ncores;
  469. cpu_set_t set;
  470. CPU_ZERO(&set);
  471. CPU_SET(target, &set);
  472. (void)pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
  473. }
  474. /* =========================================================================
  475. * 4. In-Process Serial / TCP-RS232 / libssh Console / libipmiconsole SOL / libfreeipmi
  476. * ========================================================================= */
  477. static pthread_once_t g_libnet_once = PTHREAD_ONCE_INIT;
  478. static int g_ipmiconsole_ok = 0;
  479. static void init_libnet_once(void) {
  480. (void)ssh_threads_set_callbacks(ssh_threads_get_pthread());
  481. (void)ssh_init();
  482. if (ipmiconsole_engine_init(2, 0) == 0) {
  483. g_ipmiconsole_ok = 1;
  484. }
  485. }
  486. static void ensure_libnet_init(void) {
  487. pthread_once(&g_libnet_once, init_libnet_once);
  488. }
  489. static uint64_t monotonic_ms_now(void) {
  490. struct timespec ts;
  491. clock_gettime(CLOCK_MONOTONIC, &ts);
  492. return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L);
  493. }
  494. static int write_all_fd(int fd, const uint8_t *buf, size_t len, volatile int *stop_flag) {
  495. size_t off = 0;
  496. while (off < len) {
  497. if (stop_flag && __atomic_load_n(stop_flag, __ATOMIC_ACQUIRE)) return -1;
  498. ssize_t n = send(fd, buf + off, len - off, MSG_NOSIGNAL);
  499. if (n > 0) {
  500. off += (size_t)n;
  501. continue;
  502. }
  503. if (n < 0 && errno == EINTR) continue;
  504. if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
  505. struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
  506. int pr = poll(&pfd, 1, 50);
  507. if (pr < 0 && errno == EINTR) continue;
  508. if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) return -1;
  509. continue;
  510. }
  511. return -1;
  512. }
  513. return 0;
  514. }
  515. static void stl_enable_tcp_keepalive(int fd) {
  516. if (fd < 0) return;
  517. int one = 1;
  518. int idle = 5;
  519. int intvl = 2;
  520. int cnt = 3;
  521. unsigned int user_ms = 15000;
  522. (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
  523. (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
  524. #ifdef TCP_KEEPIDLE
  525. (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
  526. #endif
  527. #ifdef TCP_KEEPINTVL
  528. (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl));
  529. #endif
  530. #ifdef TCP_KEEPCNT
  531. (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt));
  532. #endif
  533. #ifdef TCP_USER_TIMEOUT
  534. (void)setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_ms, sizeof(user_ms));
  535. #endif
  536. }
  537. static ssh_session stl_libssh_connect(
  538. const char *host,
  539. int port,
  540. const char *user,
  541. const char *password,
  542. int timeout_ms,
  543. int *out_auth_fail) {
  544. ensure_libnet_init();
  545. if (out_auth_fail) *out_auth_fail = 0;
  546. if (!host || !host[0] || !user || !password) return NULL;
  547. ssh_session sess = ssh_new();
  548. if (!sess) return NULL;
  549. unsigned int uport = (unsigned int)(port > 0 ? port : 22);
  550. long to_sec = (timeout_ms > 0) ? ((long)(timeout_ms + 999) / 1000L) : 10L;
  551. if (to_sec < 1L) to_sec = 1L;
  552. int zero = 0;
  553. int one = 1;
  554. ssh_options_set(sess, SSH_OPTIONS_HOST, host);
  555. ssh_options_set(sess, SSH_OPTIONS_PORT, &uport);
  556. ssh_options_set(sess, SSH_OPTIONS_USER, user);
  557. ssh_options_set(sess, SSH_OPTIONS_TIMEOUT, &to_sec);
  558. ssh_options_set(sess, SSH_OPTIONS_STRICTHOSTKEYCHECK, &zero);
  559. ssh_options_set(sess, SSH_OPTIONS_KNOWNHOSTS, "/dev/null");
  560. ssh_options_set(sess, SSH_OPTIONS_GLOBAL_KNOWNHOSTS, "/dev/null");
  561. ssh_options_set(sess, SSH_OPTIONS_PROCESS_CONFIG, &zero);
  562. ssh_options_set(sess, SSH_OPTIONS_NODELAY, &one);
  563. if (ssh_connect(sess) != SSH_OK) {
  564. ssh_free(sess);
  565. return NULL;
  566. }
  567. socket_t sfd = ssh_get_fd(sess);
  568. if (sfd >= 0) {
  569. stl_enable_tcp_keepalive((int)sfd);
  570. }
  571. int auth = ssh_userauth_password(sess, NULL, password);
  572. if (auth != SSH_AUTH_SUCCESS) {
  573. int methods = ssh_userauth_list(sess, NULL);
  574. if (methods & SSH_AUTH_METHOD_INTERACTIVE) {
  575. int krc = ssh_userauth_kbdint(sess, NULL, NULL);
  576. int guard = 0;
  577. while (krc == SSH_AUTH_INFO && guard++ < 8) {
  578. int np = ssh_userauth_kbdint_getnprompts(sess);
  579. for (int i = 0; i < np; i++) {
  580. (void)ssh_userauth_kbdint_setanswer(sess, (unsigned int)i, password);
  581. }
  582. krc = ssh_userauth_kbdint(sess, NULL, NULL);
  583. }
  584. auth = krc;
  585. }
  586. }
  587. if (auth != SSH_AUTH_SUCCESS) {
  588. if (out_auth_fail) *out_auth_fail = 1;
  589. ssh_disconnect(sess);
  590. ssh_free(sess);
  591. return NULL;
  592. }
  593. return sess;
  594. }
  595. #define MAX_SSH_SLOTS 16
  596. #define MAX_SOL_SLOTS 16
  597. #define MAX_IPMI_SLOTS 16
  598. typedef struct {
  599. int in_use;
  600. volatile int alive;
  601. volatile int stop_requested;
  602. int sock_peer_fd;
  603. int thread_started;
  604. ssh_session session;
  605. ssh_channel chan;
  606. pthread_t pump_thread;
  607. } StlSshSlot;
  608. typedef struct {
  609. int in_use;
  610. ipmiconsole_ctx_t ctx;
  611. int fd;
  612. } StlSolSlot;
  613. typedef struct {
  614. int in_use;
  615. int alive;
  616. pthread_mutex_t mu;
  617. ipmi_ctx_t ctx;
  618. char host[128];
  619. char sdr_cache_path[256];
  620. } StlIpmiSlot;
  621. static pthread_mutex_t g_slots_lock = PTHREAD_MUTEX_INITIALIZER;
  622. static StlSshSlot g_ssh_slots[MAX_SSH_SLOTS];
  623. static StlSolSlot g_sol_slots[MAX_SOL_SLOTS];
  624. static StlIpmiSlot g_ipmi_slots[MAX_IPMI_SLOTS];
  625. static pthread_once_t g_ipmi_slots_once = PTHREAD_ONCE_INIT;
  626. static void init_ipmi_slots_once(void) {
  627. for (int i = 0; i < MAX_IPMI_SLOTS; i++) {
  628. pthread_mutex_init(&g_ipmi_slots[i].mu, NULL);
  629. }
  630. }
  631. static void *ssh_pump_thread_fn(void *arg) {
  632. StlSshSlot *slot = (StlSshSlot *)arg;
  633. uint8_t rbuf[16384];
  634. uint8_t tbuf[4096];
  635. while (!__atomic_load_n(&slot->stop_requested, __ATOMIC_ACQUIRE)) {
  636. if (!ssh_is_connected(slot->session) ||
  637. ssh_channel_is_eof(slot->chan) ||
  638. ssh_channel_is_closed(slot->chan)) {
  639. break;
  640. }
  641. /* Drain SSH stdout & stderr non-blocking */
  642. int progressed = 0;
  643. for (int pass = 0; pass < 32; pass++) {
  644. int n0 = ssh_channel_read_nonblocking(slot->chan, rbuf, sizeof(rbuf), 0);
  645. if (n0 > 0) {
  646. progressed = 1;
  647. if (write_all_fd(slot->sock_peer_fd, rbuf, (size_t)n0, &slot->stop_requested) != 0) {
  648. goto done;
  649. }
  650. } else if (n0 == SSH_ERROR || n0 == SSH_EOF) {
  651. goto done;
  652. }
  653. int n1 = ssh_channel_read_nonblocking(slot->chan, rbuf, sizeof(rbuf), 1);
  654. if (n1 > 0) {
  655. progressed = 1;
  656. if (write_all_fd(slot->sock_peer_fd, rbuf, (size_t)n1, &slot->stop_requested) != 0) {
  657. goto done;
  658. }
  659. } else if (n1 == SSH_ERROR || n1 == SSH_EOF) {
  660. goto done;
  661. }
  662. if (n0 <= 0 && n1 <= 0) break;
  663. }
  664. /* Drain pending TX bytes from local socketpair end -> SSH channel */
  665. for (int tpass = 0; tpass < 32; tpass++) {
  666. ssize_t tn = read(slot->sock_peer_fd, tbuf, sizeof(tbuf));
  667. if (tn > 0) {
  668. progressed = 1;
  669. size_t off = 0;
  670. while (off < (size_t)tn) {
  671. int wn = ssh_channel_write(slot->chan, tbuf + off, (uint32_t)((size_t)tn - off));
  672. if (wn <= 0) goto done;
  673. off += (size_t)wn;
  674. }
  675. } else if (tn == 0) {
  676. goto done; /* Peer closed master_fd */
  677. } else {
  678. if (errno == EINTR) continue;
  679. break;
  680. }
  681. }
  682. if (progressed) continue;
  683. struct pollfd pfds[2];
  684. int nfds = 0;
  685. socket_t sfd = ssh_get_fd(slot->session);
  686. int ssh_idx = -1;
  687. int peer_idx = -1;
  688. if (sfd >= 0) {
  689. ssh_idx = nfds;
  690. pfds[nfds].fd = (int)sfd;
  691. pfds[nfds].events = POLLIN;
  692. pfds[nfds].revents = 0;
  693. nfds++;
  694. }
  695. if (slot->sock_peer_fd >= 0) {
  696. peer_idx = nfds;
  697. pfds[nfds].fd = slot->sock_peer_fd;
  698. pfds[nfds].events = POLLIN;
  699. pfds[nfds].revents = 0;
  700. nfds++;
  701. }
  702. if (nfds == 0) break;
  703. int pr = poll(pfds, (nfds_t)nfds, 50);
  704. if (pr < 0 && errno != EINTR) break;
  705. if (peer_idx >= 0 && (pfds[peer_idx].revents & (POLLHUP | POLLERR | POLLNVAL))) {
  706. break;
  707. }
  708. if (ssh_idx >= 0 && (pfds[ssh_idx].revents & (POLLERR | POLLHUP | POLLNVAL))) {
  709. break;
  710. }
  711. int so_err = 0;
  712. socklen_t so_len = sizeof(so_err);
  713. if (sfd >= 0 && getsockopt((int)sfd, SOL_SOCKET, SO_ERROR, &so_err, &so_len) == 0 && so_err != 0) {
  714. break;
  715. }
  716. }
  717. done:
  718. __atomic_store_n(&slot->alive, 0, __ATOMIC_RELEASE);
  719. if (slot->sock_peer_fd >= 0) {
  720. close(slot->sock_peer_fd);
  721. slot->sock_peer_fd = -1;
  722. }
  723. if (slot->chan) {
  724. (void)ssh_channel_send_eof(slot->chan);
  725. (void)ssh_channel_close(slot->chan);
  726. ssh_channel_free(slot->chan);
  727. slot->chan = NULL;
  728. }
  729. if (slot->session) {
  730. ssh_disconnect(slot->session);
  731. ssh_free(slot->session);
  732. slot->session = NULL;
  733. }
  734. return NULL;
  735. }
  736. int stl_open_tty_115200_raw(const char *path) {
  737. return c_open_tty_baud_raw(path, 115200);
  738. }
  739. int c_pty_open_serial_115200(const char *path) {
  740. return stl_open_tty_115200_raw(path);
  741. }
  742. /* Open serial with configurable baud rate (115200 / 230400 / 460800 / 921600) for thermal hood */
  743. int c_open_tty_baud_raw(const char *path, int baud) {
  744. if (!path || path[0] == '\0') return -1;
  745. if (strstr(path, "ttyUSB1") != NULL) return -1;
  746. int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
  747. if (fd < 0) return -1;
  748. struct termios tio;
  749. if (tcgetattr(fd, &tio) != 0) {
  750. close(fd);
  751. return -1;
  752. }
  753. cfmakeraw(&tio);
  754. speed_t sp = B115200;
  755. if (baud == 921600) sp = B921600;
  756. else if (baud == 460800) sp = B460800;
  757. else if (baud == 230400) sp = B230400;
  758. cfsetispeed(&tio, sp);
  759. cfsetospeed(&tio, sp);
  760. tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
  761. tio.c_cflag |= (CS8 | CLOCAL | CREAD);
  762. tio.c_iflag &= ~(IXON | IXOFF | IXANY);
  763. tio.c_cc[VMIN] = 1;
  764. tio.c_cc[VTIME] = 0;
  765. if (tcsetattr(fd, TCSANOW, &tio) != 0) {
  766. close(fd);
  767. return -1;
  768. }
  769. int fl = fcntl(fd, F_GETFL, 0);
  770. if (fl >= 0) {
  771. (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
  772. }
  773. return fd;
  774. }
  775. /* Open MCU 24-ch thermal controller UART (115200 8N1 default) */
  776. int c_open_mcu_tty_baud_raw(const char *path, int baud) {
  777. if (!path || path[0] == '\0') return -1;
  778. int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
  779. if (fd < 0) return -1;
  780. struct termios tio;
  781. if (tcgetattr(fd, &tio) != 0) {
  782. close(fd);
  783. return -1;
  784. }
  785. cfmakeraw(&tio);
  786. speed_t sp = B115200;
  787. if (baud == 921600) sp = B921600;
  788. else if (baud == 460800) sp = B460800;
  789. else if (baud == 230400) sp = B230400;
  790. else if (baud == 57600) sp = B57600;
  791. else if (baud == 38400) sp = B38400;
  792. else if (baud == 9600) sp = B9600;
  793. cfsetispeed(&tio, sp);
  794. cfsetospeed(&tio, sp);
  795. tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
  796. tio.c_cflag |= (CS8 | CLOCAL | CREAD);
  797. tio.c_iflag &= ~(IXON | IXOFF | IXANY);
  798. tio.c_cc[VMIN] = 1;
  799. tio.c_cc[VTIME] = 0;
  800. if (tcsetattr(fd, TCSANOW, &tio) != 0) {
  801. close(fd);
  802. return -1;
  803. }
  804. int fl = fcntl(fd, F_GETFL, 0);
  805. if (fl >= 0) {
  806. (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
  807. }
  808. return fd;
  809. }
  810. int c_pty_open_tcp_serial(const char *host, int port, int timeout_ms) {
  811. if (!host || host[0] == '\0' || port <= 0) return -1;
  812. struct addrinfo hints, *res = NULL;
  813. memset(&hints, 0, sizeof(hints));
  814. hints.ai_family = AF_INET;
  815. hints.ai_socktype = SOCK_STREAM;
  816. char port_s[16];
  817. snprintf(port_s, sizeof(port_s), "%d", port);
  818. if (getaddrinfo(host, port_s, &hints, &res) != 0 || !res) return -1;
  819. int sfd = socket(res->ai_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  820. if (sfd < 0) {
  821. freeaddrinfo(res);
  822. return -1;
  823. }
  824. stl_enable_tcp_keepalive(sfd);
  825. int rc = connect(sfd, res->ai_addr, res->ai_addrlen);
  826. freeaddrinfo(res);
  827. if (rc != 0) {
  828. if (errno != EINPROGRESS) {
  829. close(sfd);
  830. return -1;
  831. }
  832. struct pollfd pfd = { .fd = sfd, .events = POLLOUT, .revents = 0 };
  833. int wait_ms = (timeout_ms > 0) ? timeout_ms : 1500;
  834. if (poll(&pfd, 1, wait_ms) <= 0) {
  835. close(sfd);
  836. return -1;
  837. }
  838. int so_err = 0;
  839. socklen_t slen = sizeof(so_err);
  840. if (getsockopt(sfd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 || so_err != 0) {
  841. close(sfd);
  842. return -1;
  843. }
  844. }
  845. return sfd;
  846. }
  847. int c_pty_open_tcp_listen(int port) {
  848. if (port <= 0 || port > 65535) return -1;
  849. int lfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  850. if (lfd < 0) return -1;
  851. int one = 1;
  852. (void)setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  853. struct sockaddr_in addr;
  854. memset(&addr, 0, sizeof(addr));
  855. addr.sin_family = AF_INET;
  856. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  857. addr.sin_port = htons((uint16_t)port);
  858. if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(lfd, 8) != 0) {
  859. close(lfd);
  860. return -1;
  861. }
  862. return lfd;
  863. }
  864. int c_pty_accept_tcp_nonblock(int listen_fd) {
  865. if (listen_fd < 0) return -1;
  866. int cfd = accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
  867. if (cfd >= 0) {
  868. stl_enable_tcp_keepalive(cfd);
  869. }
  870. return cfd;
  871. }
  872. /*
  873. * Open in-process libssh console session (port 2200) bridged over AF_UNIX non-blocking socketpair.
  874. * Explicitly sets known_hosts=/dev/null and StrictHostKeyChecking=no so swapped motherboards never block.
  875. * Returns 0 on success, -2 on auth failure, -1 on transport/slot error.
  876. */
  877. int c_pty_spawn_ssh_console(
  878. const char *host,
  879. int port,
  880. const char *user,
  881. const char *password,
  882. const char *known_hosts_path,
  883. int *out_master_fd,
  884. int *out_child_pid) {
  885. (void)known_hosts_path;
  886. if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
  887. int auth_fail = 0;
  888. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 2200, user, password, 10000, &auth_fail);
  889. if (!sess) {
  890. return auth_fail ? -2 : -1;
  891. }
  892. ssh_channel chan = ssh_channel_new(sess);
  893. if (!chan || ssh_channel_open_session(chan) != SSH_OK) {
  894. if (chan) ssh_channel_free(chan);
  895. ssh_disconnect(sess);
  896. ssh_free(sess);
  897. return -1;
  898. }
  899. if (ssh_channel_request_pty_size(chan, "vt100", 160, 48) != SSH_OK ||
  900. ssh_channel_request_shell(chan) != SSH_OK) {
  901. (void)ssh_channel_close(chan);
  902. ssh_channel_free(chan);
  903. ssh_disconnect(sess);
  904. ssh_free(sess);
  905. return -1;
  906. }
  907. int sv[2] = {-1, -1};
  908. if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0) {
  909. (void)ssh_channel_close(chan);
  910. ssh_channel_free(chan);
  911. ssh_disconnect(sess);
  912. ssh_free(sess);
  913. return -1;
  914. }
  915. (void)stl_set_nonblocking_nodelay(sv[0], 0);
  916. (void)stl_set_nonblocking_nodelay(sv[1], 0);
  917. pthread_mutex_lock(&g_slots_lock);
  918. int idx = -1;
  919. for (int i = 0; i < MAX_SSH_SLOTS; i++) {
  920. if (!g_ssh_slots[i].in_use) {
  921. idx = i;
  922. memset(&g_ssh_slots[i], 0, sizeof(g_ssh_slots[i]));
  923. g_ssh_slots[i].in_use = 1;
  924. g_ssh_slots[i].alive = 1;
  925. g_ssh_slots[i].stop_requested = 0;
  926. g_ssh_slots[i].sock_peer_fd = sv[1];
  927. g_ssh_slots[i].session = sess;
  928. g_ssh_slots[i].chan = chan;
  929. break;
  930. }
  931. }
  932. pthread_mutex_unlock(&g_slots_lock);
  933. if (idx < 0) {
  934. close(sv[0]);
  935. close(sv[1]);
  936. (void)ssh_channel_close(chan);
  937. ssh_channel_free(chan);
  938. ssh_disconnect(sess);
  939. ssh_free(sess);
  940. return -1;
  941. }
  942. if (pthread_create(&g_ssh_slots[idx].pump_thread, NULL, ssh_pump_thread_fn, &g_ssh_slots[idx]) != 0) {
  943. pthread_mutex_lock(&g_slots_lock);
  944. g_ssh_slots[idx].in_use = 0;
  945. g_ssh_slots[idx].alive = 0;
  946. pthread_mutex_unlock(&g_slots_lock);
  947. close(sv[0]);
  948. close(sv[1]);
  949. (void)ssh_channel_close(chan);
  950. ssh_channel_free(chan);
  951. ssh_disconnect(sess);
  952. ssh_free(sess);
  953. return -1;
  954. }
  955. g_ssh_slots[idx].thread_started = 1;
  956. *out_master_fd = sv[0];
  957. *out_child_pid = -(100 + idx);
  958. return 0;
  959. }
  960. int c_pty_spawn_ipmi_sol(
  961. const char *host,
  962. const char *user,
  963. const char *password,
  964. int *out_master_fd,
  965. int *out_child_pid) {
  966. ensure_libnet_init();
  967. if (!g_ipmiconsole_ok || !host || !user || !password || !out_master_fd || !out_child_pid) {
  968. return -1;
  969. }
  970. int ciphers[2] = { 17, 3 };
  971. ipmiconsole_ctx_t ctx = NULL;
  972. int established = 0;
  973. int auth_err = 0;
  974. for (int ci = 0; ci < 2; ci++) {
  975. struct ipmiconsole_ipmi_config icfg;
  976. memset(&icfg, 0, sizeof(icfg));
  977. icfg.username = (char *)user;
  978. icfg.password = (char *)password;
  979. icfg.k_g = NULL;
  980. icfg.k_g_len = 0;
  981. icfg.privilege_level = IPMICONSOLE_PRIVILEGE_ADMIN;
  982. icfg.cipher_suite_id = ciphers[ci];
  983. icfg.workaround_flags = IPMICONSOLE_WORKAROUND_DEFAULT;
  984. struct ipmiconsole_protocol_config pcfg;
  985. pcfg.session_timeout_len = -1;
  986. pcfg.retransmission_timeout_len = -1;
  987. pcfg.retransmission_backoff_count = -1;
  988. pcfg.keepalive_timeout_len = -1;
  989. pcfg.retransmission_keepalive_timeout_len = -1;
  990. pcfg.acceptable_packet_errors_count = -1;
  991. pcfg.maximum_retransmission_count = -1;
  992. struct ipmiconsole_engine_config ecfg;
  993. ecfg.engine_flags = IPMICONSOLE_ENGINE_DEFAULT;
  994. ecfg.behavior_flags = IPMICONSOLE_BEHAVIOR_DEFAULT;
  995. ecfg.debug_flags = 0;
  996. ctx = ipmiconsole_ctx_create(host, &icfg, &pcfg, &ecfg);
  997. if (!ctx) continue;
  998. if (ipmiconsole_engine_submit_block(ctx) == 0 &&
  999. ipmiconsole_ctx_status(ctx) == IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED) {
  1000. established = 1;
  1001. break;
  1002. }
  1003. int err = ipmiconsole_ctx_errnum(ctx);
  1004. if (err == IPMICONSOLE_ERR_PASSWORD_INVALID ||
  1005. err == IPMICONSOLE_ERR_USERNAME_INVALID ||
  1006. err == IPMICONSOLE_ERR_PRIVILEGE_LEVEL_INSUFFICIENT) {
  1007. auth_err = 1;
  1008. }
  1009. ipmiconsole_ctx_destroy(ctx);
  1010. ctx = NULL;
  1011. if (auth_err) break;
  1012. }
  1013. if (!established || !ctx) {
  1014. return auth_err ? -2 : -1;
  1015. }
  1016. int fd = ipmiconsole_ctx_fd(ctx);
  1017. if (fd < 0) {
  1018. ipmiconsole_ctx_destroy(ctx);
  1019. return -1;
  1020. }
  1021. (void)stl_set_nonblocking_nodelay(fd, 0);
  1022. int fd_fl = fcntl(fd, F_GETFD, 0);
  1023. if (fd_fl >= 0) (void)fcntl(fd, F_SETFD, fd_fl | FD_CLOEXEC);
  1024. pthread_mutex_lock(&g_slots_lock);
  1025. int idx = -1;
  1026. for (int i = 0; i < MAX_SOL_SLOTS; i++) {
  1027. if (!g_sol_slots[i].in_use) {
  1028. idx = i;
  1029. g_sol_slots[i].in_use = 1;
  1030. g_sol_slots[i].ctx = ctx;
  1031. g_sol_slots[i].fd = fd;
  1032. break;
  1033. }
  1034. }
  1035. pthread_mutex_unlock(&g_slots_lock);
  1036. if (idx < 0) {
  1037. close(fd);
  1038. ipmiconsole_ctx_destroy(ctx);
  1039. return -1;
  1040. }
  1041. *out_master_fd = fd;
  1042. *out_child_pid = -(200 + idx);
  1043. return 0;
  1044. }
  1045. ssize_t c_pty_read_nonblock(int master_fd, uint8_t *buf, size_t cap) {
  1046. if (master_fd < 0 || !buf || cap == 0) return -1;
  1047. ssize_t n = read(master_fd, buf, cap);
  1048. if (n > 0) return n;
  1049. if (n == 0) return -2; /* EOF */
  1050. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  1051. return -2; /* EIO / closed */
  1052. }
  1053. ssize_t c_mcu_tty_read_nonblock(int fd, uint8_t *buf, size_t cap, int is_serial) {
  1054. if (fd < 0 || !buf || cap == 0) return -1;
  1055. ssize_t n = read(fd, buf, cap);
  1056. if (n > 0) return n;
  1057. if (n == 0) {
  1058. if (!is_serial) return -2; /* TCP EOF */
  1059. struct pollfd pfd = { .fd = fd, .events = POLLIN, .revents = 0 };
  1060. if (poll(&pfd, 1, 0) > 0 && (pfd.revents & (POLLHUP | POLLERR | POLLNVAL))) {
  1061. return -2; /* USB serial unplugged / hangup */
  1062. }
  1063. return 0; /* TTY VMIN=0 empty buffer, not EOF */
  1064. }
  1065. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  1066. return -2; /* EIO / ENODEV / closed */
  1067. }
  1068. ssize_t c_pty_write_bytes(int master_fd, const uint8_t *buf, size_t len) {
  1069. if (master_fd < 0 || !buf || len == 0) return 0;
  1070. ssize_t n = write(master_fd, buf, len);
  1071. if (n >= 0) return n;
  1072. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  1073. return -1;
  1074. }
  1075. int c_pty_is_alive(int child_pid) {
  1076. if (child_pid <= -100 && child_pid >= -(100 + MAX_SSH_SLOTS - 1)) {
  1077. int idx = (-child_pid) - 100;
  1078. return (g_ssh_slots[idx].in_use &&
  1079. __atomic_load_n(&g_ssh_slots[idx].alive, __ATOMIC_ACQUIRE))
  1080. ? 1
  1081. : 0;
  1082. }
  1083. if (child_pid <= -200 && child_pid >= -(200 + MAX_SOL_SLOTS - 1)) {
  1084. int idx = (-child_pid) - 200;
  1085. if (!g_sol_slots[idx].in_use || !g_sol_slots[idx].ctx) return 0;
  1086. return (ipmiconsole_ctx_status(g_sol_slots[idx].ctx) ==
  1087. IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED)
  1088. ? 1
  1089. : 0;
  1090. }
  1091. return 0;
  1092. }
  1093. void c_pty_close(int master_fd, int child_pid) {
  1094. if (master_fd >= 0) {
  1095. (void)shutdown(master_fd, SHUT_RDWR);
  1096. close(master_fd);
  1097. }
  1098. if (child_pid <= -100 && child_pid >= -(100 + MAX_SSH_SLOTS - 1)) {
  1099. int idx = (-child_pid) - 100;
  1100. StlSshSlot *slot = &g_ssh_slots[idx];
  1101. __atomic_store_n(&slot->stop_requested, 1, __ATOMIC_RELEASE);
  1102. if (slot->thread_started) {
  1103. pthread_join(slot->pump_thread, NULL);
  1104. }
  1105. pthread_mutex_lock(&g_slots_lock);
  1106. if (slot->sock_peer_fd >= 0) {
  1107. close(slot->sock_peer_fd);
  1108. slot->sock_peer_fd = -1;
  1109. }
  1110. slot->in_use = 0;
  1111. slot->alive = 0;
  1112. slot->thread_started = 0;
  1113. pthread_mutex_unlock(&g_slots_lock);
  1114. return;
  1115. }
  1116. if (child_pid <= -200 && child_pid >= -(200 + MAX_SOL_SLOTS - 1)) {
  1117. int idx = (-child_pid) - 200;
  1118. ipmiconsole_ctx_t ctx = NULL;
  1119. pthread_mutex_lock(&g_slots_lock);
  1120. if (g_sol_slots[idx].in_use) {
  1121. ctx = g_sol_slots[idx].ctx;
  1122. g_sol_slots[idx].ctx = NULL;
  1123. g_sol_slots[idx].fd = -1;
  1124. g_sol_slots[idx].in_use = 0;
  1125. }
  1126. pthread_mutex_unlock(&g_slots_lock);
  1127. if (ctx) {
  1128. ipmiconsole_ctx_destroy(ctx);
  1129. }
  1130. }
  1131. }
  1132. /* =========================================================================
  1133. * 5. In-Process libssh Remote Exec + Atomic SFTP Upload/Download
  1134. * ========================================================================= */
  1135. int c_ssh_exec_capture(
  1136. const char *host,
  1137. int port,
  1138. const char *user,
  1139. const char *password,
  1140. const char *cmd,
  1141. char *out_buf,
  1142. size_t out_cap,
  1143. size_t *out_len,
  1144. int timeout_ms) {
  1145. if (out_len) *out_len = 0;
  1146. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  1147. if (!host || !user || !password || !cmd) return -1;
  1148. int auth_fail = 0;
  1149. int eff_to = (timeout_ms > 0) ? timeout_ms : 5000;
  1150. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, eff_to, &auth_fail);
  1151. if (!sess) return auth_fail ? -2 : -1;
  1152. ssh_channel chan = ssh_channel_new(sess);
  1153. if (!chan || ssh_channel_open_session(chan) != SSH_OK ||
  1154. ssh_channel_request_exec(chan, cmd) != SSH_OK) {
  1155. if (chan) {
  1156. (void)ssh_channel_close(chan);
  1157. ssh_channel_free(chan);
  1158. }
  1159. ssh_disconnect(sess);
  1160. ssh_free(sess);
  1161. return -1;
  1162. }
  1163. size_t total = 0;
  1164. uint8_t tmp[4096];
  1165. uint64_t deadline = monotonic_ms_now() + (uint64_t)eff_to;
  1166. int timed_out = 0;
  1167. for (;;) {
  1168. int n0 = ssh_channel_read_nonblocking(chan, tmp, sizeof(tmp), 0);
  1169. if (n0 > 0) {
  1170. if (out_buf && out_cap > 1 && total < out_cap - 1) {
  1171. size_t copy = (size_t)n0;
  1172. if (copy > (out_cap - 1 - total)) copy = out_cap - 1 - total;
  1173. memcpy(out_buf + total, tmp, copy);
  1174. total += copy;
  1175. }
  1176. continue;
  1177. }
  1178. int n1 = ssh_channel_read_nonblocking(chan, tmp, sizeof(tmp), 1);
  1179. if (n1 > 0) {
  1180. if (out_buf && out_cap > 1 && total < out_cap - 1) {
  1181. size_t copy = (size_t)n1;
  1182. if (copy > (out_cap - 1 - total)) copy = out_cap - 1 - total;
  1183. memcpy(out_buf + total, tmp, copy);
  1184. total += copy;
  1185. }
  1186. continue;
  1187. }
  1188. if (n0 == SSH_ERROR || n1 == SSH_ERROR) {
  1189. break;
  1190. }
  1191. if (ssh_channel_is_eof(chan) || ssh_channel_is_closed(chan)) {
  1192. break;
  1193. }
  1194. uint64_t now = monotonic_ms_now();
  1195. if (now >= deadline) {
  1196. timed_out = 1;
  1197. break;
  1198. }
  1199. int rem_ms = (int)(deadline - now);
  1200. if (rem_ms > 50) rem_ms = 50;
  1201. socket_t sfd = ssh_get_fd(sess);
  1202. if (sfd >= 0) {
  1203. struct pollfd pfd = { .fd = (int)sfd, .events = POLLIN, .revents = 0 };
  1204. (void)poll(&pfd, 1, rem_ms);
  1205. } else {
  1206. struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000L };
  1207. nanosleep(&ts, NULL);
  1208. }
  1209. }
  1210. if (out_buf && out_cap > 0) {
  1211. out_buf[(total < out_cap) ? total : (out_cap - 1)] = '\0';
  1212. }
  1213. if (out_len) *out_len = total;
  1214. int exit_rc = timed_out ? -3 : 0;
  1215. if (!timed_out) {
  1216. uint32_t code = 0;
  1217. int pcore = 0;
  1218. char *psig = NULL;
  1219. (void)ssh_channel_send_eof(chan);
  1220. (void)ssh_channel_close(chan);
  1221. if (ssh_channel_get_exit_state(chan, &code, &psig, &pcore) == SSH_OK) {
  1222. exit_rc = (int)code;
  1223. }
  1224. if (psig) ssh_string_free_char(psig);
  1225. } else {
  1226. (void)ssh_channel_close(chan);
  1227. }
  1228. ssh_channel_free(chan);
  1229. ssh_disconnect(sess);
  1230. ssh_free(sess);
  1231. return exit_rc;
  1232. }
  1233. int c_ssh_sftp_put_file(
  1234. const char *host,
  1235. int port,
  1236. const char *user,
  1237. const char *password,
  1238. const char *local_path,
  1239. const char *remote_path,
  1240. int timeout_ms) {
  1241. if (!host || !user || !password || !local_path || !remote_path) return -1;
  1242. FILE *fp = fopen(local_path, "rb");
  1243. if (!fp) return -1;
  1244. int auth_fail = 0;
  1245. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, timeout_ms > 0 ? timeout_ms : 5000, &auth_fail);
  1246. if (!sess) {
  1247. fclose(fp);
  1248. return auth_fail ? -2 : -1;
  1249. }
  1250. sftp_session sftp = sftp_new(sess);
  1251. if (!sftp || sftp_init(sftp) != SSH_OK) {
  1252. if (sftp) sftp_free(sftp);
  1253. ssh_disconnect(sess);
  1254. ssh_free(sess);
  1255. fclose(fp);
  1256. return -1;
  1257. }
  1258. char partial[1088];
  1259. snprintf(partial, sizeof(partial), "%s.partial", remote_path);
  1260. sftp_file rf = sftp_open(sftp, partial, O_WRONLY | O_CREAT | O_TRUNC, 0644);
  1261. if (!rf) {
  1262. sftp_free(sftp);
  1263. ssh_disconnect(sess);
  1264. ssh_free(sess);
  1265. fclose(fp);
  1266. return -1;
  1267. }
  1268. int rc = 0;
  1269. uint8_t buf[32768];
  1270. size_t nr;
  1271. while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) {
  1272. size_t off = 0;
  1273. while (off < nr) {
  1274. ssize_t nw = sftp_write(rf, buf + off, nr - off);
  1275. if (nw <= 0) {
  1276. rc = -1;
  1277. break;
  1278. }
  1279. off += (size_t)nw;
  1280. }
  1281. if (rc != 0) break;
  1282. }
  1283. if (ferror(fp)) rc = -1;
  1284. fclose(fp);
  1285. if (sftp_close(rf) != SSH_OK) rc = -1;
  1286. if (rc == 0) {
  1287. if (sftp_rename(sftp, partial, remote_path) != 0) {
  1288. (void)sftp_unlink(sftp, remote_path);
  1289. if (sftp_rename(sftp, partial, remote_path) != 0) {
  1290. (void)sftp_unlink(sftp, partial);
  1291. rc = -1;
  1292. }
  1293. }
  1294. } else {
  1295. (void)sftp_unlink(sftp, partial);
  1296. }
  1297. sftp_free(sftp);
  1298. ssh_disconnect(sess);
  1299. ssh_free(sess);
  1300. return rc;
  1301. }
  1302. int c_ssh_sftp_get_file(
  1303. const char *host,
  1304. int port,
  1305. const char *user,
  1306. const char *password,
  1307. const char *remote_path,
  1308. const char *local_path,
  1309. int timeout_ms) {
  1310. if (!host || !user || !password || !remote_path || !local_path) return -1;
  1311. int auth_fail = 0;
  1312. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, timeout_ms > 0 ? timeout_ms : 5000, &auth_fail);
  1313. if (!sess) return auth_fail ? -2 : -1;
  1314. sftp_session sftp = sftp_new(sess);
  1315. if (!sftp || sftp_init(sftp) != SSH_OK) {
  1316. if (sftp) sftp_free(sftp);
  1317. ssh_disconnect(sess);
  1318. ssh_free(sess);
  1319. return -1;
  1320. }
  1321. sftp_file rf = sftp_open(sftp, remote_path, O_RDONLY, 0);
  1322. if (!rf) {
  1323. sftp_free(sftp);
  1324. ssh_disconnect(sess);
  1325. ssh_free(sess);
  1326. return -1;
  1327. }
  1328. char partial[1088];
  1329. snprintf(partial, sizeof(partial), "%s.partial", local_path);
  1330. FILE *fp = fopen(partial, "wb");
  1331. if (!fp) {
  1332. (void)sftp_close(rf);
  1333. sftp_free(sftp);
  1334. ssh_disconnect(sess);
  1335. ssh_free(sess);
  1336. return -1;
  1337. }
  1338. int rc = 0;
  1339. uint8_t buf[32768];
  1340. for (;;) {
  1341. ssize_t nr = sftp_read(rf, buf, sizeof(buf));
  1342. if (nr > 0) {
  1343. if (fwrite(buf, 1, (size_t)nr, fp) != (size_t)nr) {
  1344. rc = -1;
  1345. break;
  1346. }
  1347. } else if (nr == 0) {
  1348. break;
  1349. } else {
  1350. rc = -1;
  1351. break;
  1352. }
  1353. }
  1354. if (fclose(fp) != 0) rc = -1;
  1355. (void)sftp_close(rf);
  1356. sftp_free(sftp);
  1357. ssh_disconnect(sess);
  1358. ssh_free(sess);
  1359. if (rc == 0) {
  1360. if (rename(partial, local_path) != 0) {
  1361. unlink(partial);
  1362. rc = -1;
  1363. }
  1364. } else {
  1365. unlink(partial);
  1366. }
  1367. return rc;
  1368. }
  1369. /* =========================================================================
  1370. * 6. In-Process libfreeipmi Persistent Out-of-Band Session & Telemetry
  1371. * ========================================================================= */
  1372. static StlIpmiSlot *get_ipmi_slot(int handle) {
  1373. pthread_once(&g_ipmi_slots_once, init_ipmi_slots_once);
  1374. if (handle < 1 || handle > MAX_IPMI_SLOTS) return NULL;
  1375. return &g_ipmi_slots[handle - 1];
  1376. }
  1377. int c_ipmi_open(
  1378. const char *host,
  1379. const char *user,
  1380. const char *password,
  1381. int cipher_suite,
  1382. int timeout_ms) {
  1383. pthread_once(&g_ipmi_slots_once, init_ipmi_slots_once);
  1384. if (!host || !host[0] || !user || !password) return -1;
  1385. ipmi_ctx_t ctx = ipmi_ctx_create();
  1386. if (!ctx) return -1;
  1387. unsigned int sess_to = (timeout_ms > 0) ? (unsigned int)timeout_ms : 3000U;
  1388. uint8_t ciph = (uint8_t)(cipher_suite > 0 ? cipher_suite : 17);
  1389. int rc = ipmi_ctx_open_outofband_2_0(
  1390. ctx, host, user, password, NULL, 0,
  1391. IPMI_PRIVILEGE_LEVEL_ADMIN, ciph,
  1392. sess_to, 500U,
  1393. IPMI_WORKAROUND_FLAGS_DEFAULT,
  1394. IPMI_FLAGS_DEFAULT);
  1395. if (rc != 0 && ciph == 17) {
  1396. int err = ipmi_ctx_errnum(ctx);
  1397. if (err != IPMI_ERR_PASSWORD_INVALID &&
  1398. err != IPMI_ERR_USERNAME_INVALID &&
  1399. err != IPMI_ERR_CONNECTION_TIMEOUT) {
  1400. rc = ipmi_ctx_open_outofband_2_0(
  1401. ctx, host, user, password, NULL, 0,
  1402. IPMI_PRIVILEGE_LEVEL_ADMIN, 3,
  1403. sess_to, 500U,
  1404. IPMI_WORKAROUND_FLAGS_DEFAULT,
  1405. IPMI_FLAGS_DEFAULT);
  1406. }
  1407. }
  1408. if (rc != 0) {
  1409. int final_err = ipmi_ctx_errnum(ctx);
  1410. ipmi_ctx_destroy(ctx);
  1411. return (final_err == IPMI_ERR_CONNECTION_TIMEOUT) ? -2 : -1;
  1412. }
  1413. pthread_mutex_lock(&g_slots_lock);
  1414. int idx = -1;
  1415. for (int i = 0; i < MAX_IPMI_SLOTS; i++) {
  1416. pthread_mutex_lock(&g_ipmi_slots[i].mu);
  1417. if (!g_ipmi_slots[i].in_use) {
  1418. idx = i;
  1419. g_ipmi_slots[i].in_use = 1;
  1420. g_ipmi_slots[i].alive = 1;
  1421. g_ipmi_slots[i].ctx = ctx;
  1422. snprintf(g_ipmi_slots[i].host, sizeof(g_ipmi_slots[i].host), "%s", host);
  1423. {
  1424. char safe_host[96];
  1425. size_t hi = 0;
  1426. for (; host[hi] && hi + 1 < sizeof(safe_host); hi++) {
  1427. unsigned char ch = (unsigned char)host[hi];
  1428. safe_host[hi] = ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') ||
  1429. (ch >= 'A' && ch <= 'Z') || ch == '.' || ch == '_' || ch == '-')
  1430. ? (char)ch
  1431. : '_';
  1432. }
  1433. safe_host[hi] = '\0';
  1434. snprintf(g_ipmi_slots[i].sdr_cache_path, sizeof(g_ipmi_slots[i].sdr_cache_path),
  1435. "/tmp/stl_sdr_%ld_%d_%s.cache", (long)getpid(), i, safe_host);
  1436. unlink(g_ipmi_slots[i].sdr_cache_path);
  1437. }
  1438. pthread_mutex_unlock(&g_ipmi_slots[i].mu);
  1439. break;
  1440. }
  1441. pthread_mutex_unlock(&g_ipmi_slots[i].mu);
  1442. }
  1443. pthread_mutex_unlock(&g_slots_lock);
  1444. if (idx < 0) {
  1445. (void)ipmi_ctx_close(ctx);
  1446. ipmi_ctx_destroy(ctx);
  1447. return -1;
  1448. }
  1449. return idx + 1;
  1450. }
  1451. void c_ipmi_close(int handle) {
  1452. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1453. if (!slot) return;
  1454. pthread_mutex_lock(&g_slots_lock);
  1455. pthread_mutex_lock(&slot->mu);
  1456. if (slot->in_use) {
  1457. if (slot->ctx) {
  1458. if (slot->alive) {
  1459. (void)ipmi_ctx_close(slot->ctx);
  1460. }
  1461. ipmi_ctx_destroy(slot->ctx);
  1462. slot->ctx = NULL;
  1463. }
  1464. if (slot->sdr_cache_path[0]) {
  1465. unlink(slot->sdr_cache_path);
  1466. slot->sdr_cache_path[0] = '\0';
  1467. }
  1468. slot->alive = 0;
  1469. slot->in_use = 0;
  1470. slot->host[0] = '\0';
  1471. }
  1472. pthread_mutex_unlock(&slot->mu);
  1473. pthread_mutex_unlock(&g_slots_lock);
  1474. }
  1475. int c_ipmi_is_alive(int handle) {
  1476. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1477. if (!slot) return 0;
  1478. pthread_mutex_lock(&slot->mu);
  1479. int alive = (slot->in_use && slot->alive && slot->ctx != NULL) ? 1 : 0;
  1480. pthread_mutex_unlock(&slot->mu);
  1481. return alive;
  1482. }
  1483. int c_ipmi_chassis_status(int handle, int *out_power_on, char *out_buf, size_t out_cap) {
  1484. if (out_power_on) *out_power_on = -1;
  1485. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  1486. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1487. if (!slot) return -1;
  1488. pthread_mutex_lock(&slot->mu);
  1489. if (!slot->in_use || !slot->ctx) {
  1490. pthread_mutex_unlock(&slot->mu);
  1491. return -1;
  1492. }
  1493. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_get_chassis_status_rs);
  1494. if (!rs) {
  1495. pthread_mutex_unlock(&slot->mu);
  1496. return -1;
  1497. }
  1498. int rc = ipmi_cmd_get_chassis_status(slot->ctx, rs);
  1499. if (rc != 0) {
  1500. slot->alive = 0;
  1501. fiid_obj_destroy(rs);
  1502. pthread_mutex_unlock(&slot->mu);
  1503. return -1;
  1504. }
  1505. uint64_t pwr = 0, ovl = 0, pflt = 0, cflt = 0, intr = 0;
  1506. int got = fiid_obj_get(rs, "current_power_state.power_is_on", &pwr);
  1507. (void)fiid_obj_get(rs, "current_power_state.power_overload", &ovl);
  1508. (void)fiid_obj_get(rs, "current_power_state.power_fault", &pflt);
  1509. (void)fiid_obj_get(rs, "current_power_state.power_control_fault", &cflt);
  1510. (void)fiid_obj_get(rs, "misc_chassis_state.chassis_intrusion_active", &intr);
  1511. fiid_obj_destroy(rs);
  1512. pthread_mutex_unlock(&slot->mu);
  1513. if (got <= 0) return -1;
  1514. int is_on = (pwr != 0) ? 1 : 0;
  1515. if (out_power_on) *out_power_on = is_on;
  1516. if (out_buf && out_cap > 0) {
  1517. snprintf(
  1518. out_buf,
  1519. out_cap,
  1520. "System Power : %s\n"
  1521. "Chassis Power is %s\n"
  1522. "Power Overload : %s\n"
  1523. "Main Power Fault : %s\n"
  1524. "Power Control Fault : %s\n"
  1525. "Chassis Intrusion : %s\n",
  1526. is_on ? "on" : "off",
  1527. is_on ? "on" : "off",
  1528. ovl ? "true" : "false",
  1529. pflt ? "true" : "false",
  1530. cflt ? "true" : "false",
  1531. intr ? "active" : "inactive");
  1532. }
  1533. return 0;
  1534. }
  1535. int c_ipmi_chassis_control(int handle, int op) {
  1536. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1537. if (!slot || !IPMI_CHASSIS_CONTROL_VALID((uint8_t)op)) return -1;
  1538. pthread_mutex_lock(&slot->mu);
  1539. if (!slot->in_use || !slot->ctx) {
  1540. pthread_mutex_unlock(&slot->mu);
  1541. return -1;
  1542. }
  1543. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_chassis_control_rs);
  1544. if (!rs) {
  1545. pthread_mutex_unlock(&slot->mu);
  1546. return -1;
  1547. }
  1548. int rc = ipmi_cmd_chassis_control(slot->ctx, (uint8_t)op, rs);
  1549. if (rc != 0) slot->alive = 0;
  1550. fiid_obj_destroy(rs);
  1551. pthread_mutex_unlock(&slot->mu);
  1552. return (rc == 0) ? 0 : -1;
  1553. }
  1554. int c_ipmi_warm_reset(int handle) {
  1555. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1556. if (!slot) return -1;
  1557. pthread_mutex_lock(&slot->mu);
  1558. if (!slot->in_use || !slot->ctx) {
  1559. pthread_mutex_unlock(&slot->mu);
  1560. return -1;
  1561. }
  1562. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_warm_reset_rs);
  1563. if (!rs) {
  1564. pthread_mutex_unlock(&slot->mu);
  1565. return -1;
  1566. }
  1567. int rc = ipmi_cmd_warm_reset(slot->ctx, rs);
  1568. if (rc != 0) slot->alive = 0;
  1569. fiid_obj_destroy(rs);
  1570. pthread_mutex_unlock(&slot->mu);
  1571. return (rc == 0) ? 0 : -1;
  1572. }
  1573. int c_ipmi_raw(
  1574. int handle,
  1575. uint8_t net_fn,
  1576. uint8_t cmd,
  1577. const uint8_t *payload,
  1578. size_t payload_len,
  1579. uint8_t *out_buf,
  1580. size_t out_cap,
  1581. size_t *out_len) {
  1582. if (out_len) *out_len = 0;
  1583. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1584. if (!slot || payload_len > 255) return -1;
  1585. uint8_t rq[260];
  1586. uint8_t rs[260];
  1587. rq[0] = cmd;
  1588. if (payload && payload_len > 0) {
  1589. memcpy(rq + 1, payload, payload_len);
  1590. }
  1591. pthread_mutex_lock(&slot->mu);
  1592. if (!slot->in_use || !slot->ctx) {
  1593. pthread_mutex_unlock(&slot->mu);
  1594. return -1;
  1595. }
  1596. int rlen = ipmi_cmd_raw(
  1597. slot->ctx, 0, net_fn,
  1598. rq, (unsigned int)(1 + payload_len),
  1599. rs, (unsigned int)sizeof(rs));
  1600. if (rlen < 0) slot->alive = 0;
  1601. pthread_mutex_unlock(&slot->mu);
  1602. if (rlen < 2 || rs[1] != 0x00) {
  1603. return -1;
  1604. }
  1605. size_t data_len = (size_t)(rlen - 2);
  1606. if (out_buf && out_cap > 0 && data_len > 0) {
  1607. size_t cp = (data_len < out_cap) ? data_len : out_cap;
  1608. memcpy(out_buf, rs + 2, cp);
  1609. }
  1610. if (out_len) *out_len = data_len;
  1611. return 0;
  1612. }
  1613. typedef struct {
  1614. ipmi_sensor_read_ctx_t sr;
  1615. char *out_buf;
  1616. size_t out_cap;
  1617. size_t used;
  1618. } SdrIterCtx;
  1619. static int contains_ci_dimm(const char *s) {
  1620. if (!s) return 0;
  1621. for (size_t i = 0; s[i] && s[i+1] && s[i+2] && s[i+3]; i++) {
  1622. char c0 = (s[i] >= 'a' && s[i] <= 'z') ? (char)(s[i] - 32) : s[i];
  1623. char c1 = (s[i+1] >= 'a' && s[i+1] <= 'z') ? (char)(s[i+1] - 32) : s[i+1];
  1624. char c2 = (s[i+2] >= 'a' && s[i+2] <= 'z') ? (char)(s[i+2] - 32) : s[i+2];
  1625. char c3 = (s[i+3] >= 'a' && s[i+3] <= 'z') ? (char)(s[i+3] - 32) : s[i+3];
  1626. if (c0 == 'D' && c1 == 'I' && c2 == 'M' && c3 == 'M') return 1;
  1627. }
  1628. return 0;
  1629. }
  1630. static int sdr_iterate_cb(
  1631. ipmi_sdr_ctx_t sdr,
  1632. uint8_t record_type,
  1633. const void *sdr_record,
  1634. unsigned int sdr_record_len,
  1635. void *data) {
  1636. SdrIterCtx *ic = (SdrIterCtx *)data;
  1637. if (record_type != IPMI_SDR_FORMAT_FULL_SENSOR_RECORD &&
  1638. record_type != IPMI_SDR_FORMAT_COMPACT_SENSOR_RECORD) {
  1639. return 0;
  1640. }
  1641. char name[IPMI_SDR_MAX_SENSOR_NAME_LENGTH + 1];
  1642. memset(name, 0, sizeof(name));
  1643. if (ipmi_sdr_parse_id_string(sdr, sdr_record, sdr_record_len, name, sizeof(name) - 1) < 0) {
  1644. return 0;
  1645. }
  1646. uint8_t pct = 0, mod = 0, rate = 0, base_u = 0, mod_u = 0;
  1647. int units_ok = (ipmi_sdr_parse_sensor_units(
  1648. sdr, sdr_record, sdr_record_len,
  1649. &pct, &mod, &rate, &base_u, &mod_u) == 0);
  1650. uint8_t raw = 0;
  1651. double *reading = NULL;
  1652. uint16_t bitmask = 0;
  1653. int src = ipmi_sensor_read(ic->sr, sdr_record, sdr_record_len, 0, &raw, &reading, &bitmask);
  1654. char line[256];
  1655. if (src == 1 && reading != NULL && units_ok) {
  1656. if (base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
  1657. snprintf(line, sizeof(line), "%s | %.2f degrees C | ok\n", name, *reading);
  1658. } else {
  1659. snprintf(line, sizeof(line), "%s | %.2f | ok\n", name, *reading);
  1660. }
  1661. } else if (units_ok && base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
  1662. snprintf(line, sizeof(line), "%s | no reading | ns\n", name);
  1663. } else if (src == 1 && contains_ci_dimm(name)) {
  1664. uint8_t stype = 0, ert = 0;
  1665. if (ipmi_sdr_parse_sensor_type(sdr, sdr_record, sdr_record_len, &stype) == 0 &&
  1666. ipmi_sdr_parse_event_reading_type_code(sdr, sdr_record, sdr_record_len, &ert) == 0) {
  1667. if (stype == IPMI_SENSOR_TYPE_MEMORY && ert == 0x6F) {
  1668. snprintf(line, sizeof(line), "%s | discrete_mem=0x%04X | ok\n", name, (unsigned)bitmask);
  1669. } else if (stype == IPMI_SENSOR_TYPE_ENTITY_PRESENCE && ert == 0x6F) {
  1670. snprintf(line, sizeof(line), "%s | discrete_presence=0x%04X | ok\n", name, (unsigned)bitmask);
  1671. } else if (ert == 0x08) {
  1672. snprintf(line, sizeof(line), "%s | discrete_devpres=0x%04X | ok\n", name, (unsigned)bitmask);
  1673. } else {
  1674. if (reading) free(reading);
  1675. return 0;
  1676. }
  1677. } else {
  1678. if (reading) free(reading);
  1679. return 0;
  1680. }
  1681. } else {
  1682. if (reading) free(reading);
  1683. return 0;
  1684. }
  1685. if (reading) free(reading);
  1686. size_t l = strlen(line);
  1687. if (ic->used + l < ic->out_cap) {
  1688. memcpy(ic->out_buf + ic->used, line, l);
  1689. ic->used += l;
  1690. ic->out_buf[ic->used] = '\0';
  1691. }
  1692. return 0;
  1693. }
  1694. static int ensure_sdr_cache_open(ipmi_sdr_ctx_t sdr, ipmi_ctx_t ctx, const char *path) {
  1695. if (ipmi_sdr_cache_open(sdr, ctx, path) == 0) {
  1696. return 0;
  1697. }
  1698. if (ipmi_sdr_cache_create(
  1699. sdr, ctx, path,
  1700. IPMI_SDR_CACHE_CREATE_FLAGS_OVERWRITE | IPMI_SDR_CACHE_CREATE_FLAGS_ASSUME_MAX_SDR_RECORD_COUNT,
  1701. NULL, NULL) != 0) {
  1702. return -1;
  1703. }
  1704. return ipmi_sdr_cache_open(sdr, ctx, path);
  1705. }
  1706. void c_ipmi_invalidate_sdr_cache(int handle) {
  1707. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1708. if (!slot) return;
  1709. pthread_mutex_lock(&slot->mu);
  1710. if (slot->in_use && slot->sdr_cache_path[0] != '\0') {
  1711. unlink(slot->sdr_cache_path);
  1712. }
  1713. pthread_mutex_unlock(&slot->mu);
  1714. }
  1715. int c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len) {
  1716. if (out_len) *out_len = 0;
  1717. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  1718. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1719. if (!slot || !out_buf || out_cap < 2) return -1;
  1720. pthread_mutex_lock(&slot->mu);
  1721. if (!slot->in_use || !slot->ctx) {
  1722. pthread_mutex_unlock(&slot->mu);
  1723. return -1;
  1724. }
  1725. ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create();
  1726. ipmi_sensor_read_ctx_t sr = ipmi_sensor_read_ctx_create(slot->ctx);
  1727. if (!sdr || !sr) {
  1728. if (sdr) ipmi_sdr_ctx_destroy(sdr);
  1729. if (sr) ipmi_sensor_read_ctx_destroy(sr);
  1730. pthread_mutex_unlock(&slot->mu);
  1731. return -1;
  1732. }
  1733. (void)ipmi_sensor_read_ctx_set_flags(sr, IPMI_SENSOR_READ_FLAGS_DISCRETE_READING);
  1734. if (ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
  1735. slot->alive = 0;
  1736. ipmi_sensor_read_ctx_destroy(sr);
  1737. ipmi_sdr_ctx_destroy(sdr);
  1738. pthread_mutex_unlock(&slot->mu);
  1739. return -1;
  1740. }
  1741. SdrIterCtx ic = { .sr = sr, .out_buf = out_buf, .out_cap = out_cap, .used = 0 };
  1742. int irc = ipmi_sdr_cache_iterate(sdr, sdr_iterate_cb, &ic);
  1743. if (irc < 0) slot->alive = 0;
  1744. (void)ipmi_sdr_cache_close(sdr);
  1745. ipmi_sensor_read_ctx_destroy(sr);
  1746. ipmi_sdr_ctx_destroy(sdr);
  1747. pthread_mutex_unlock(&slot->mu);
  1748. if (out_len) *out_len = ic.used;
  1749. return (irc >= 0) ? 0 : -1;
  1750. }
  1751. static void append_str(char *out_buf, size_t out_cap, size_t *used, const char *s) {
  1752. if (!out_buf || out_cap == 0 || !s) return;
  1753. size_t l = strlen(s);
  1754. if (*used >= out_cap - 1) return;
  1755. size_t rem = out_cap - 1 - *used;
  1756. if (l > rem) l = rem;
  1757. memcpy(out_buf + *used, s, l);
  1758. *used += l;
  1759. out_buf[*used] = '\0';
  1760. }
  1761. typedef struct {
  1762. char *out_buf;
  1763. size_t out_cap;
  1764. size_t used;
  1765. int count;
  1766. } SelIterCtx;
  1767. static int sel_iterate_cb(ipmi_sel_ctx_t sel, void *data) {
  1768. SelIterCtx *sc = (SelIterCtx *)data;
  1769. if (sc->count >= 200 || sc->used + 128 >= sc->out_cap) return 1;
  1770. char line[256];
  1771. memset(line, 0, sizeof(line));
  1772. int n = ipmi_sel_parse_read_record_string(
  1773. sel,
  1774. "%i | %d | %t | %s | %E",
  1775. NULL, 0,
  1776. line, (unsigned int)(sizeof(line) - 2),
  1777. IPMI_SEL_STRING_FLAGS_IGNORE_UNAVAILABLE_FIELD | IPMI_SEL_STRING_FLAGS_OUTPUT_NOT_AVAILABLE);
  1778. if (n > 0) {
  1779. line[sizeof(line) - 2] = '\0';
  1780. append_str(sc->out_buf, sc->out_cap, &sc->used, line);
  1781. append_str(sc->out_buf, sc->out_cap, &sc->used, "\n");
  1782. sc->count++;
  1783. }
  1784. return 0;
  1785. }
  1786. static void append_fru_field(
  1787. ipmi_fru_ctx_t fru,
  1788. const char *label,
  1789. ipmi_fru_field_t *f,
  1790. uint8_t lang,
  1791. char *out_buf,
  1792. size_t out_cap,
  1793. size_t *used) {
  1794. if (!f || f->type_length_field_length == 0) return;
  1795. char sbuf[IPMI_FRU_AREA_STRING_MAX + 1];
  1796. unsigned int slen = sizeof(sbuf) - 1;
  1797. memset(sbuf, 0, sizeof(sbuf));
  1798. if (ipmi_fru_type_length_field_to_string(
  1799. fru, f->type_length_field, f->type_length_field_length, lang, sbuf, &slen) == 0 &&
  1800. sbuf[0] != '\0') {
  1801. char line[600];
  1802. snprintf(line, sizeof(line), "%-24s : %s\n", label, sbuf);
  1803. append_str(out_buf, out_cap, used, line);
  1804. }
  1805. }
  1806. int c_ipmi_device_info(
  1807. int handle,
  1808. const char *kind,
  1809. char *out_buf,
  1810. size_t out_cap,
  1811. size_t *out_len) {
  1812. if (out_len) *out_len = 0;
  1813. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  1814. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1815. if (!slot || !kind || !out_buf || out_cap < 2) return -1;
  1816. pthread_mutex_lock(&slot->mu);
  1817. if (!slot->in_use || !slot->ctx) {
  1818. pthread_mutex_unlock(&slot->mu);
  1819. return -1;
  1820. }
  1821. size_t used = 0;
  1822. int rc = 0;
  1823. if (strcmp(kind, "mc") == 0) {
  1824. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_get_device_id_rs);
  1825. if (!rs || ipmi_cmd_get_device_id(slot->ctx, rs) != 0) {
  1826. rc = -1;
  1827. } else {
  1828. uint64_t did = 0, drev = 0, fw1 = 0, fw2 = 0, imaj = 0, imin = 0, mfg = 0, pid = 0;
  1829. (void)fiid_obj_get(rs, "device_id", &did);
  1830. (void)fiid_obj_get(rs, "device_revision.revision", &drev);
  1831. (void)fiid_obj_get(rs, "firmware_revision1.major_revision", &fw1);
  1832. (void)fiid_obj_get(rs, "firmware_revision2.minor_revision", &fw2);
  1833. (void)fiid_obj_get(rs, "ipmi_version_major", &imaj);
  1834. (void)fiid_obj_get(rs, "ipmi_version_minor", &imin);
  1835. (void)fiid_obj_get(rs, "manufacturer_id.id", &mfg);
  1836. (void)fiid_obj_get(rs, "product_id", &pid);
  1837. char tmp[512];
  1838. snprintf(
  1839. tmp, sizeof(tmp),
  1840. "Device ID : %llu\n"
  1841. "Device Revision : %llu\n"
  1842. "Firmware Revision : %llu.%02llx\n"
  1843. "IPMI Version : %llu.%llu\n"
  1844. "Manufacturer ID : %llu\n"
  1845. "Product ID : %llu\n",
  1846. (unsigned long long)did,
  1847. (unsigned long long)drev,
  1848. (unsigned long long)fw1, (unsigned long long)fw2,
  1849. (unsigned long long)imaj, (unsigned long long)imin,
  1850. (unsigned long long)mfg,
  1851. (unsigned long long)pid);
  1852. append_str(out_buf, out_cap, &used, tmp);
  1853. }
  1854. if (rs) fiid_obj_destroy(rs);
  1855. } else if (strcmp(kind, "lan") == 0) {
  1856. uint8_t ip4[4] = {0}, mask4[4] = {0}, gw4[4] = {0}, mac6[6] = {0};
  1857. uint64_t src = 0;
  1858. int got_lan = 0;
  1859. uint8_t chs[2] = { 1, 8 };
  1860. for (int ci = 0; ci < 2 && !got_lan; ci++) {
  1861. uint8_t ch = chs[ci];
  1862. fiid_obj_t rs_ip = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_ip_address_rs);
  1863. if (rs_ip &&
  1864. ipmi_cmd_get_lan_configuration_parameters_ip_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_ip) == 0 &&
  1865. fiid_obj_get_data(rs_ip, "ip_address", ip4, sizeof(ip4)) == 4) {
  1866. got_lan = 1;
  1867. fiid_obj_t rs_m = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_subnet_mask_rs);
  1868. if (rs_m &&
  1869. ipmi_cmd_get_lan_configuration_parameters_subnet_mask(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_m) == 0) {
  1870. (void)fiid_obj_get_data(rs_m, "subnet_mask", mask4, sizeof(mask4));
  1871. }
  1872. if (rs_m) fiid_obj_destroy(rs_m);
  1873. fiid_obj_t rs_gw = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_default_gateway_address_rs);
  1874. if (rs_gw &&
  1875. ipmi_cmd_get_lan_configuration_parameters_default_gateway_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_gw) == 0) {
  1876. (void)fiid_obj_get_data(rs_gw, "ip_address", gw4, sizeof(gw4));
  1877. }
  1878. if (rs_gw) fiid_obj_destroy(rs_gw);
  1879. fiid_obj_t rs_mac = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_mac_address_rs);
  1880. if (rs_mac &&
  1881. ipmi_cmd_get_lan_configuration_parameters_mac_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_mac) == 0) {
  1882. (void)fiid_obj_get_data(rs_mac, "mac_address", mac6, sizeof(mac6));
  1883. }
  1884. if (rs_mac) fiid_obj_destroy(rs_mac);
  1885. fiid_obj_t rs_s = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_ip_address_source_rs);
  1886. if (rs_s &&
  1887. ipmi_cmd_get_lan_configuration_parameters_ip_address_source(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_s) == 0) {
  1888. (void)fiid_obj_get(rs_s, "ip_address_source", &src);
  1889. }
  1890. if (rs_s) fiid_obj_destroy(rs_s);
  1891. char tmp[512];
  1892. const char *src_s = (src == 1) ? "Static Address" : (src == 2) ? "DHCP Address" : "Other";
  1893. snprintf(
  1894. tmp, sizeof(tmp),
  1895. "LAN Channel : %u\n"
  1896. "IP Address Source : %s\n"
  1897. "IP Address : %u.%u.%u.%u\n"
  1898. "Subnet Mask : %u.%u.%u.%u\n"
  1899. "MAC Address : %02x:%02x:%02x:%02x:%02x:%02x\n"
  1900. "Default Gateway IP : %u.%u.%u.%u\n",
  1901. (unsigned)ch, src_s,
  1902. ip4[0], ip4[1], ip4[2], ip4[3],
  1903. mask4[0], mask4[1], mask4[2], mask4[3],
  1904. mac6[0], mac6[1], mac6[2], mac6[3], mac6[4], mac6[5],
  1905. gw4[0], gw4[1], gw4[2], gw4[3]);
  1906. append_str(out_buf, out_cap, &used, tmp);
  1907. }
  1908. if (rs_ip) fiid_obj_destroy(rs_ip);
  1909. }
  1910. if (!got_lan) rc = -1;
  1911. } else if (strcmp(kind, "sel") == 0) {
  1912. ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create();
  1913. if (sdr && ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
  1914. ipmi_sdr_ctx_destroy(sdr);
  1915. sdr = NULL;
  1916. }
  1917. ipmi_sel_ctx_t sel = ipmi_sel_ctx_create(slot->ctx, sdr);
  1918. if (!sel) {
  1919. rc = -1;
  1920. } else {
  1921. SelIterCtx sc = { .out_buf = out_buf, .out_cap = out_cap, .used = 0, .count = 0 };
  1922. if (ipmi_sel_parse(sel, IPMI_SEL_RECORD_ID_FIRST, IPMI_SEL_RECORD_ID_LAST, sel_iterate_cb, &sc) < 0) {
  1923. rc = -1;
  1924. } else {
  1925. used = sc.used;
  1926. if (sc.count == 0) {
  1927. append_str(out_buf, out_cap, &used, "SEL has no entries\n");
  1928. }
  1929. }
  1930. ipmi_sel_ctx_destroy(sel);
  1931. }
  1932. if (sdr) {
  1933. (void)ipmi_sdr_cache_close(sdr);
  1934. ipmi_sdr_ctx_destroy(sdr);
  1935. }
  1936. } else if (strcmp(kind, "fru") == 0) {
  1937. ipmi_fru_ctx_t fru = ipmi_fru_ctx_create(slot->ctx);
  1938. if (!fru || ipmi_fru_open_device_id(fru, 0) != 0) {
  1939. if (fru) ipmi_fru_ctx_destroy(fru);
  1940. rc = -1;
  1941. } else {
  1942. uint8_t areabuf[4096];
  1943. int has_any = 0;
  1944. int has = (ipmi_fru_first(fru) == 0);
  1945. while (has) {
  1946. unsigned int atype = 0, alen = 0;
  1947. if (ipmi_fru_read_data_area(fru, &atype, &alen, areabuf, sizeof(areabuf)) == 0) {
  1948. if (atype == IPMI_FRU_AREA_TYPE_BOARD_INFO_AREA) {
  1949. uint8_t lang = 0;
  1950. uint32_t mfg_ts = 0;
  1951. ipmi_fru_field_t bm, bn, bs, bp, bf;
  1952. memset(&bm, 0, sizeof(bm)); memset(&bn, 0, sizeof(bn));
  1953. memset(&bs, 0, sizeof(bs)); memset(&bp, 0, sizeof(bp));
  1954. memset(&bf, 0, sizeof(bf));
  1955. if (ipmi_fru_board_info_area(fru, areabuf, alen, &lang, &mfg_ts, &bm, &bn, &bs, &bp, &bf, NULL, 0) == 0) {
  1956. has_any = 1;
  1957. append_fru_field(fru, "Board Mfg", &bm, lang, out_buf, out_cap, &used);
  1958. append_fru_field(fru, "Board Product", &bn, lang, out_buf, out_cap, &used);
  1959. append_fru_field(fru, "Board Serial", &bs, lang, out_buf, out_cap, &used);
  1960. append_fru_field(fru, "Board Part Number", &bp, lang, out_buf, out_cap, &used);
  1961. }
  1962. } else if (atype == IPMI_FRU_AREA_TYPE_PRODUCT_INFO_AREA) {
  1963. uint8_t lang = 0;
  1964. ipmi_fru_field_t pm, pn, pp, pv, ps, pa, pf;
  1965. memset(&pm, 0, sizeof(pm)); memset(&pn, 0, sizeof(pn));
  1966. memset(&pp, 0, sizeof(pp)); memset(&pv, 0, sizeof(pv));
  1967. memset(&ps, 0, sizeof(ps)); memset(&pa, 0, sizeof(pa));
  1968. memset(&pf, 0, sizeof(pf));
  1969. if (ipmi_fru_product_info_area(fru, areabuf, alen, &lang, &pm, &pn, &pp, &pv, &ps, &pa, &pf, NULL, 0) == 0) {
  1970. has_any = 1;
  1971. append_fru_field(fru, "Product Manufacturer", &pm, lang, out_buf, out_cap, &used);
  1972. append_fru_field(fru, "Product Name", &pn, lang, out_buf, out_cap, &used);
  1973. append_fru_field(fru, "Product Part Number", &pp, lang, out_buf, out_cap, &used);
  1974. append_fru_field(fru, "Product Version", &pv, lang, out_buf, out_cap, &used);
  1975. append_fru_field(fru, "Product Serial", &ps, lang, out_buf, out_cap, &used);
  1976. append_fru_field(fru, "Product Asset Tag", &pa, lang, out_buf, out_cap, &used);
  1977. }
  1978. }
  1979. }
  1980. int nxt = ipmi_fru_next(fru);
  1981. if (nxt != 1) break;
  1982. }
  1983. (void)ipmi_fru_close_device_id(fru);
  1984. ipmi_fru_ctx_destroy(fru);
  1985. if (!has_any) append_str(out_buf, out_cap, &used, "FRU empty\n");
  1986. }
  1987. } else {
  1988. rc = -1;
  1989. }
  1990. if (rc < 0) slot->alive = 0;
  1991. pthread_mutex_unlock(&slot->mu);
  1992. if (out_len) *out_len = used;
  1993. return rc;
  1994. }