c_bridge.c 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758
  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 <emmintrin.h>
  14. #include <errno.h>
  15. #include <fcntl.h>
  16. #include <freeipmi/freeipmi.h>
  17. #include <freeipmi/record-format/ipmi-sdr-record-format.h>
  18. #include <ifaddrs.h>
  19. #include <ipmiconsole.h>
  20. #include <libssh/callbacks.h>
  21. #include <libssh/libssh.h>
  22. #include <libssh/sftp.h>
  23. #include <net/if.h>
  24. #include <netdb.h>
  25. #include <netinet/in.h>
  26. #include <netinet/tcp.h>
  27. #include <poll.h>
  28. #include <pthread.h>
  29. #include <sched.h>
  30. #include <signal.h>
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <sys/epoll.h>
  35. #include <sys/eventfd.h>
  36. #include <sys/ioctl.h>
  37. #include <sys/mman.h>
  38. #include <sys/resource.h>
  39. #include <sys/socket.h>
  40. #include <sys/stat.h>
  41. #include <sys/statvfs.h>
  42. #include <sys/timerfd.h>
  43. #include <sys/uio.h>
  44. #include <termios.h>
  45. #include <time.h>
  46. #include <unistd.h>
  47. /* =========================================================================
  48. * 1. Runtime CPUID + XGETBV 6-Tier ISA Detection & Function Dispatch
  49. * ========================================================================= */
  50. typedef struct {
  51. uint32_t isa_tier;
  52. uint32_t detected_tier;
  53. uint32_t has_ssse3;
  54. uint32_t has_sse42;
  55. uint32_t has_popcnt;
  56. uint32_t has_pclmul;
  57. uint32_t has_aesni;
  58. uint32_t has_shani;
  59. uint32_t has_avx2;
  60. uint32_t has_bmi2;
  61. uint32_t has_vpclmul;
  62. uint32_t has_gfni;
  63. uint32_t has_avx512;
  64. uint32_t physical_cores;
  65. char cpu_brand[64];
  66. char tier_name[48];
  67. } StlHwCapsCompat;
  68. static pthread_once_t g_hw_once = PTHREAD_ONCE_INIT;
  69. static int g_detected_tier = STL_ISA_SSE2;
  70. static int g_forced_tier = -1;
  71. static StlHwCapsCompat g_hw_caps;
  72. static void detect_hw_once(void) {
  73. memset(&g_hw_caps, 0, sizeof(g_hw_caps));
  74. unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0;
  75. unsigned int max_leaf = __get_cpuid_max(0, NULL);
  76. int has_ssse3 = 0;
  77. int has_sse41 = 0;
  78. int has_sse42 = 0;
  79. int has_popcnt = 0;
  80. int has_pclmul = 0;
  81. int has_aesni = 0;
  82. int has_osxsave = 0;
  83. int has_avx = 0;
  84. int has_avx2 = 0;
  85. int has_bmi1 = 0;
  86. int has_bmi2 = 0;
  87. int has_shani = 0;
  88. int has_vpclmul = 0;
  89. int has_gfni = 0;
  90. int has_avx512f = 0;
  91. int has_avx512bw = 0;
  92. int has_avx512vl = 0;
  93. if (max_leaf >= 1 && __get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
  94. has_pclmul = (ecx & (1u << 1)) != 0;
  95. has_ssse3 = (ecx & (1u << 9)) != 0;
  96. has_sse41 = (ecx & (1u << 19)) != 0;
  97. has_sse42 = (ecx & (1u << 20)) != 0;
  98. has_popcnt = (ecx & (1u << 23)) != 0;
  99. has_aesni = (ecx & (1u << 25)) != 0;
  100. has_osxsave = (ecx & (1u << 27)) != 0;
  101. has_avx = (ecx & (1u << 28)) != 0;
  102. }
  103. int ymm_os_ok = 0;
  104. int zmm_os_ok = 0;
  105. if (has_osxsave && has_avx) {
  106. uint64_t xcr0 = asm_xgetbv_eax0();
  107. ymm_os_ok = ((xcr0 & 0x6ULL) == 0x6ULL);
  108. zmm_os_ok = ((xcr0 & 0xE6ULL) == 0xE6ULL);
  109. }
  110. if (max_leaf >= 7 && __get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx)) {
  111. has_bmi1 = (ebx & (1u << 3)) != 0;
  112. has_avx2 = (ebx & (1u << 5)) != 0;
  113. has_bmi2 = (ebx & (1u << 8)) != 0;
  114. has_avx512f = (ebx & (1u << 16)) != 0;
  115. has_shani = (ebx & (1u << 29)) != 0;
  116. has_avx512bw = (ebx & (1u << 30)) != 0;
  117. has_avx512vl = (ebx & (1u << 31)) != 0;
  118. has_gfni = (ecx & (1u << 8)) != 0;
  119. has_vpclmul = (ecx & (1u << 10)) != 0;
  120. }
  121. int avx512_ok = zmm_os_ok && has_avx512f && has_avx512bw && has_avx512vl &&
  122. ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2;
  123. int avx2_ok = ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2 && has_sse42 && has_popcnt;
  124. int goldmont_ok = has_sse41 && has_sse42 && has_popcnt && has_pclmul && has_shani;
  125. int sse42_ok = has_ssse3 && has_sse41 && has_sse42 && has_popcnt && has_pclmul;
  126. if (avx512_ok) {
  127. g_detected_tier = STL_ISA_AVX512;
  128. } else if (avx2_ok) {
  129. g_detected_tier = STL_ISA_AVX2_BMI;
  130. } else if (goldmont_ok) {
  131. g_detected_tier = STL_ISA_GOLDMONT_SHA;
  132. } else if (sse42_ok) {
  133. g_detected_tier = STL_ISA_SSE42_PCLMUL;
  134. } else if (has_ssse3) {
  135. g_detected_tier = STL_ISA_SSSE3;
  136. } else {
  137. g_detected_tier = STL_ISA_SSE2;
  138. }
  139. /* Read CPU brand string (leaves 0x80000002..0x80000004) */
  140. unsigned int max_ext = __get_cpuid_max(0x80000000u, NULL);
  141. if (max_ext >= 0x80000004u) {
  142. uint32_t brand_words[12];
  143. __get_cpuid(0x80000002u, &brand_words[0], &brand_words[1], &brand_words[2], &brand_words[3]);
  144. __get_cpuid(0x80000003u, &brand_words[4], &brand_words[5], &brand_words[6], &brand_words[7]);
  145. __get_cpuid(0x80000004u, &brand_words[8], &brand_words[9], &brand_words[10], &brand_words[11]);
  146. memcpy(g_hw_caps.cpu_brand, brand_words, 48);
  147. g_hw_caps.cpu_brand[48] = '\0';
  148. } else {
  149. snprintf(g_hw_caps.cpu_brand, sizeof(g_hw_caps.cpu_brand), "x86_64-generic");
  150. }
  151. long online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  152. g_hw_caps.isa_tier = (uint32_t)g_detected_tier;
  153. g_hw_caps.detected_tier = (uint32_t)g_detected_tier;
  154. g_hw_caps.has_ssse3 = (uint32_t)has_ssse3;
  155. g_hw_caps.has_sse42 = (uint32_t)(has_sse42 && has_popcnt);
  156. g_hw_caps.has_popcnt = (uint32_t)has_popcnt;
  157. g_hw_caps.has_pclmul = (uint32_t)has_pclmul;
  158. g_hw_caps.has_aesni = (uint32_t)has_aesni;
  159. g_hw_caps.has_shani = (uint32_t)has_shani;
  160. g_hw_caps.has_avx2 = (uint32_t)avx2_ok;
  161. g_hw_caps.has_bmi2 = (uint32_t)has_bmi2;
  162. g_hw_caps.has_vpclmul = (uint32_t)(ymm_os_ok && has_vpclmul);
  163. g_hw_caps.has_gfni = (uint32_t)has_gfni;
  164. g_hw_caps.has_avx512 = (uint32_t)avx512_ok;
  165. g_hw_caps.physical_cores = (uint32_t)(online_cpus > 0 ? online_cpus : 2);
  166. snprintf(g_hw_caps.tier_name, sizeof(g_hw_caps.tier_name), "%s", stl_isa_tier_name(g_detected_tier));
  167. }
  168. void c_init_once_hw_dispatch(void) {
  169. pthread_once(&g_hw_once, detect_hw_once);
  170. }
  171. int stl_cpu_tier_detect(void) {
  172. pthread_once(&g_hw_once, detect_hw_once);
  173. return g_detected_tier;
  174. }
  175. int stl_active_isa_tier(void) {
  176. pthread_once(&g_hw_once, detect_hw_once);
  177. int forced = __atomic_load_n(&g_forced_tier, __ATOMIC_RELAXED);
  178. if (forced >= STL_ISA_SSE2 && forced <= STL_ISA_AVX512) {
  179. if (forced <= g_detected_tier) return forced;
  180. }
  181. return g_detected_tier;
  182. }
  183. void stl_force_isa_tier(int tier) {
  184. pthread_once(&g_hw_once, detect_hw_once);
  185. __atomic_store_n(&g_forced_tier, tier, __ATOMIC_RELAXED);
  186. }
  187. const char *stl_isa_tier_name(int tier) {
  188. switch (tier) {
  189. case STL_ISA_AVX512: return "Tier5-AVX512(F/BW/VL)";
  190. case STL_ISA_AVX2_BMI: return "Tier4-AVX2+BMI2(N100/Core)";
  191. case STL_ISA_GOLDMONT_SHA: return "Tier3-Goldmont+SHA-NI(J4125)";
  192. case STL_ISA_SSE42_PCLMUL: return "Tier2-SSE4.2+PCLMUL(J1800/N2830)";
  193. case STL_ISA_SSSE3: return "Tier1-SSSE3-PSHUFB(Atom)";
  194. default: return "Tier0-SSE2-Baseline";
  195. }
  196. }
  197. void c_get_hw_caps(StlHwCapsCompat *out_caps) {
  198. pthread_once(&g_hw_once, detect_hw_once);
  199. if (!out_caps) return;
  200. *out_caps = g_hw_caps;
  201. int active = stl_active_isa_tier();
  202. out_caps->isa_tier = (uint32_t)active;
  203. snprintf(out_caps->tier_name, sizeof(out_caps->tier_name), "%s", stl_isa_tier_name(active));
  204. }
  205. size_t stl_base64_encode(const uint8_t *src, size_t len, uint8_t *dst) {
  206. if (!src || !dst || len == 0) return 0;
  207. int tier = stl_active_isa_tier();
  208. if (tier >= STL_ISA_AVX2_BMI) {
  209. return simd_base64_encode_avx2(src, len, dst);
  210. }
  211. if (tier >= STL_ISA_SSSE3) {
  212. return simd_base64_encode_ssse3(src, len, dst);
  213. }
  214. return asm_base64_encode_sse2(src, len, dst);
  215. }
  216. size_t stl_hex_encode(const uint8_t *src, size_t len, uint8_t *dst) {
  217. if (!src || !dst || len == 0) return 0;
  218. int tier = stl_active_isa_tier();
  219. if (tier >= STL_ISA_AVX2_BMI) {
  220. return simd_hex_encode_avx2(src, len, dst);
  221. }
  222. if (tier >= STL_ISA_SSSE3) {
  223. return simd_hex_encode_ssse3(src, len, dst);
  224. }
  225. return simd_hex_encode_sse2(src, len, dst);
  226. }
  227. uint32_t stl_crc32_ieee(uint32_t init_crc, const uint8_t *buf, size_t len) {
  228. if (!buf || len == 0) return init_crc;
  229. int tier = stl_active_isa_tier();
  230. if (tier >= STL_ISA_AVX2_BMI && g_hw_caps.has_vpclmul && len >= 128u) {
  231. return simd_crc32_ieee_vpclmul(init_crc, buf, len);
  232. }
  233. if (tier >= STL_ISA_SSE42_PCLMUL && g_hw_caps.has_pclmul) {
  234. return simd_crc32_ieee_pclmul(init_crc, buf, len);
  235. }
  236. return simd_crc32_ieee_slicing8(init_crc, buf, len);
  237. }
  238. void stl_sha1_bytes(const uint8_t *data, size_t len, uint8_t out20[20]) {
  239. if (!out20) return;
  240. int tier = stl_active_isa_tier();
  241. if (tier >= STL_ISA_GOLDMONT_SHA && g_hw_caps.has_shani) {
  242. simd_sha1_shani(data, len, out20);
  243. return;
  244. }
  245. simd_sha1_sw(data, len, out20);
  246. }
  247. size_t stl_ws_accept_key(const uint8_t *key_ptr, size_t key_len, uint8_t out28[28]) {
  248. static const char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  249. uint8_t buf[256];
  250. if (!key_ptr || key_len > 192 || !out28) return 0;
  251. memcpy(buf, key_ptr, key_len);
  252. memcpy(buf + key_len, magic, 36);
  253. uint8_t digest[20];
  254. stl_sha1_bytes(buf, key_len + 36, digest);
  255. return stl_base64_encode(digest, 20, out28);
  256. }
  257. void stl_clean_stream_init(StlCleanStreamState *state) {
  258. if (!state) return;
  259. memset(state, 0, sizeof(*state));
  260. }
  261. void stl_clean_stream_clear_halfline(StlCleanStreamState *state) {
  262. if (!state) return;
  263. state->half_len = 0;
  264. state->tag_mask = 0;
  265. state->first_nonws = 0;
  266. state->cur_col = 0;
  267. state->prev_was_cr = 0;
  268. state->esc_state = 0;
  269. }
  270. void stl_clean_split_classify(
  271. StlCleanStreamState *state,
  272. const uint8_t *src,
  273. size_t src_len,
  274. StlCleanOutput *out) {
  275. if (!state || !out) return;
  276. if (!src || src_len == 0) {
  277. out->src_consumed = 0;
  278. return;
  279. }
  280. int tier = stl_active_isa_tier();
  281. if (tier >= STL_ISA_AVX2_BMI) {
  282. asm_clean_split_classify_avx2(state, src, src_len, out);
  283. } else if (tier >= STL_ISA_SSE42_PCLMUL) {
  284. asm_clean_split_classify_sse42(state, src, src_len, out);
  285. } else {
  286. asm_clean_split_classify_sse2(state, src, src_len, out);
  287. }
  288. }
  289. /* =========================================================================
  290. * 2. Monotonic 64-Bit mmap Ring Buffer (Optional Hugepage + 64B Pad + PROT_NONE Guard)
  291. * ========================================================================= */
  292. static size_t round_up_pow2_min256k(size_t v) {
  293. size_t cap = 256u * 1024u; /* 256 KiB floor for high-density 200-500 station deployments */
  294. while (cap < v && cap < (1ULL << 30)) {
  295. cap <<= 1;
  296. }
  297. return cap;
  298. }
  299. int stl_ring_init(StlRingBuf *rb, size_t requested_cap) {
  300. if (!rb) return -1;
  301. memset(rb, 0, sizeof(*rb));
  302. size_t cap = round_up_pow2_min256k(requested_cap == 0 ? (8u * 1024u * 1024u) : requested_cap);
  303. size_t page_sz = 4096u;
  304. /* [0..cap): circular ring; [cap..cap+4096): 64B+ zeroed tail pad page; [cap+4096..cap+8192): PROT_NONE guard */
  305. size_t pad_bytes = page_sz;
  306. size_t guard_bytes = page_sz;
  307. size_t total = cap + pad_bytes + guard_bytes;
  308. void *mem = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  309. if (mem == MAP_FAILED) {
  310. return -1;
  311. }
  312. #ifdef MADV_HUGEPAGE
  313. if (cap >= 2u * 1024u * 1024u) {
  314. (void)madvise(mem, cap, MADV_HUGEPAGE);
  315. }
  316. #endif
  317. /* Arm hardware guard page immediately after the 4KB tail-padding page */
  318. uint8_t *base = (uint8_t *)mem;
  319. memset(base + cap, 0, pad_bytes);
  320. if (mprotect(base + cap + pad_bytes, guard_bytes, PROT_NONE) != 0) {
  321. munmap(mem, total);
  322. return -1;
  323. }
  324. rb->buf = base;
  325. rb->cap = cap;
  326. rb->mask = cap - 1;
  327. rb->mmap_total = total;
  328. rb->base_offset = 0;
  329. rb->write_offset = 0;
  330. return 0;
  331. }
  332. void stl_ring_destroy(StlRingBuf *rb) {
  333. if (!rb) return;
  334. if (rb->buf && rb->mmap_total > 0) {
  335. munmap(rb->buf, rb->mmap_total);
  336. }
  337. memset(rb, 0, sizeof(*rb));
  338. }
  339. uint64_t stl_ring_append(StlRingBuf *rb, const uint8_t *data, size_t len) {
  340. if (!rb || !rb->buf) return 0;
  341. if (!data || len == 0) return rb->write_offset;
  342. if (len >= rb->cap) {
  343. /* Input chunk exceeds entire ring capacity: retain trailing cap bytes */
  344. const uint8_t *tail = data + (len - rb->cap);
  345. uint64_t new_wo = rb->write_offset + (uint64_t)len;
  346. uint64_t new_bo = new_wo - (uint64_t)rb->cap;
  347. size_t pos = (size_t)(new_bo & rb->mask);
  348. size_t first = rb->cap - pos;
  349. memcpy(rb->buf + pos, tail, first);
  350. if (first < rb->cap) {
  351. memcpy(rb->buf, tail + first, rb->cap - first);
  352. }
  353. memset(rb->buf + rb->cap, 0, 64);
  354. rb->write_offset = new_wo;
  355. rb->base_offset = new_bo;
  356. return rb->write_offset;
  357. }
  358. size_t pos = (size_t)(rb->write_offset & rb->mask);
  359. size_t first = rb->cap - pos;
  360. if (first >= len) {
  361. memcpy(rb->buf + pos, data, len);
  362. } else {
  363. memcpy(rb->buf + pos, data, first);
  364. memcpy(rb->buf, data + first, len - first);
  365. }
  366. /* Ensure 64-byte SIMD tail padding stays zeroed */
  367. memset(rb->buf + rb->cap, 0, 64);
  368. rb->write_offset += (uint64_t)len;
  369. if (rb->write_offset - rb->base_offset > (uint64_t)rb->cap) {
  370. /* Slide oldest bound forward; write_offset NEVER regresses */
  371. rb->base_offset = rb->write_offset - (uint64_t)rb->cap;
  372. }
  373. return rb->write_offset;
  374. }
  375. size_t stl_ring_read(
  376. const StlRingBuf *rb,
  377. uint64_t req_offset,
  378. uint8_t *dst,
  379. size_t max_len,
  380. uint64_t *out_actual_start,
  381. uint64_t *out_next_offset) {
  382. if (!rb || !rb->buf) {
  383. if (out_actual_start) *out_actual_start = 0;
  384. if (out_next_offset) *out_next_offset = 0;
  385. return 0;
  386. }
  387. uint64_t start = req_offset;
  388. if (start < rb->base_offset) {
  389. /* Reader fell behind trimmed window: advance monotonically to base_offset */
  390. start = rb->base_offset;
  391. }
  392. if (start >= rb->write_offset || !dst || max_len == 0) {
  393. uint64_t cur = rb->write_offset;
  394. if (out_actual_start) *out_actual_start = cur;
  395. if (out_next_offset) *out_next_offset = cur;
  396. return 0;
  397. }
  398. uint64_t avail = rb->write_offset - start;
  399. size_t n = (avail < (uint64_t)max_len) ? (size_t)avail : max_len;
  400. size_t pos = (size_t)(start & rb->mask);
  401. size_t first = rb->cap - pos;
  402. if (first >= n) {
  403. memcpy(dst, rb->buf + pos, n);
  404. } else {
  405. memcpy(dst, rb->buf + pos, first);
  406. memcpy(dst + first, rb->buf, n - first);
  407. }
  408. if (out_actual_start) *out_actual_start = start;
  409. if (out_next_offset) *out_next_offset = start + (uint64_t)n;
  410. return n;
  411. }
  412. void stl_ring_clear_monotonic(StlRingBuf *rb) {
  413. if (!rb) return;
  414. /* Advance base_offset to write_offset so old data is logically trimmed WITHOUT resetting offset! */
  415. rb->base_offset = rb->write_offset;
  416. }
  417. /* =========================================================================
  418. * 3. epoll / timerfd / eventfd / TCP_NODELAY + writev / Core Affinity
  419. * ========================================================================= */
  420. int stl_epoll_create(void) {
  421. return epoll_create1(EPOLL_CLOEXEC);
  422. }
  423. int stl_epoll_ctl_fd(int epfd, int op, int fd, uint32_t events, uint64_t token) {
  424. struct epoll_event ev;
  425. memset(&ev, 0, sizeof(ev));
  426. ev.events = events;
  427. ev.data.u64 = token;
  428. return epoll_ctl(epfd, op, fd, &ev);
  429. }
  430. int stl_epoll_wait_tokens(
  431. int epfd,
  432. uint64_t *out_tokens,
  433. uint32_t *out_events,
  434. int max_ev,
  435. int timeout_ms) {
  436. if (epfd < 0 || max_ev <= 0) return 0;
  437. if (max_ev > 128) max_ev = 128;
  438. struct epoll_event evs[128];
  439. int n = epoll_wait(epfd, evs, max_ev, timeout_ms);
  440. if (n <= 0) return 0;
  441. for (int i = 0; i < n; i++) {
  442. if (out_tokens) out_tokens[i] = evs[i].data.u64;
  443. if (out_events) out_events[i] = evs[i].events;
  444. }
  445. return n;
  446. }
  447. int stl_timerfd_create_ms(uint64_t initial_ms, uint64_t interval_ms) {
  448. int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
  449. if (tfd < 0) return -1;
  450. if (stl_timerfd_arm_ms(tfd, initial_ms, interval_ms) != 0) {
  451. close(tfd);
  452. return -1;
  453. }
  454. return tfd;
  455. }
  456. int stl_timerfd_arm_ms(int tfd, uint64_t initial_ms, uint64_t interval_ms) {
  457. if (tfd < 0) return -1;
  458. struct itimerspec its;
  459. memset(&its, 0, sizeof(its));
  460. its.it_value.tv_sec = (time_t)(initial_ms / 1000ULL);
  461. its.it_value.tv_nsec = (long)((initial_ms % 1000ULL) * 1000000ULL);
  462. its.it_interval.tv_sec = (time_t)(interval_ms / 1000ULL);
  463. its.it_interval.tv_nsec = (long)((interval_ms % 1000ULL) * 1000000ULL);
  464. return timerfd_settime(tfd, 0, &its, NULL);
  465. }
  466. void stl_timerfd_drain(int tfd) {
  467. if (tfd < 0) return;
  468. uint64_t exp = 0;
  469. while (read(tfd, &exp, sizeof(exp)) > 0) {}
  470. }
  471. int stl_eventfd_create(void) {
  472. return eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
  473. }
  474. void stl_eventfd_notify(int efd) {
  475. if (efd < 0) return;
  476. uint64_t v = 1;
  477. ssize_t _r = write(efd, &v, sizeof(v));
  478. (void)_r;
  479. }
  480. void stl_eventfd_drain(int efd) {
  481. if (efd < 0) return;
  482. uint64_t v = 0;
  483. while (read(efd, &v, sizeof(v)) > 0) {}
  484. }
  485. int stl_set_nonblocking_nodelay(int fd, int is_tcp) {
  486. if (fd < 0) return -1;
  487. int flags = fcntl(fd, F_GETFL, 0);
  488. if (flags >= 0) {
  489. (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  490. }
  491. if (is_tcp) {
  492. int one = 1;
  493. (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
  494. (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
  495. }
  496. return 0;
  497. }
  498. /* Merged WebSocket header + payload writev (eliminates 44ms delayed-ACK stall) */
  499. int64_t stl_ws_writev2(
  500. int fd,
  501. const uint8_t *hdr,
  502. size_t hdr_len,
  503. const uint8_t *body,
  504. size_t body_len) {
  505. if (fd < 0) return -1;
  506. size_t off0 = 0;
  507. size_t off1 = 0;
  508. size_t total = hdr_len + body_len;
  509. size_t sent = 0;
  510. while (sent < total) {
  511. struct iovec iov[2];
  512. int iovcnt = 0;
  513. if (off0 < hdr_len) {
  514. iov[iovcnt].iov_base = (void *)(hdr + off0);
  515. iov[iovcnt].iov_len = hdr_len - off0;
  516. iovcnt++;
  517. }
  518. if (off1 < body_len) {
  519. iov[iovcnt].iov_base = (void *)(body + off1);
  520. iov[iovcnt].iov_len = body_len - off1;
  521. iovcnt++;
  522. }
  523. ssize_t n = writev(fd, iov, iovcnt);
  524. if (n > 0) {
  525. size_t adv = (size_t)n;
  526. sent += adv;
  527. if (off0 < hdr_len) {
  528. size_t rem0 = hdr_len - off0;
  529. if (adv <= rem0) {
  530. off0 += adv;
  531. adv = 0;
  532. } else {
  533. off0 = hdr_len;
  534. adv -= rem0;
  535. }
  536. }
  537. off1 += adv;
  538. continue;
  539. }
  540. if (n < 0 && errno == EINTR) continue;
  541. if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
  542. struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
  543. int pr = poll(&pfd, 1, 2000);
  544. if (pr > 0) continue;
  545. return -1;
  546. }
  547. return -1;
  548. }
  549. return (int64_t)sent;
  550. }
  551. void stl_pin_thread_to_core(int core_index) {
  552. if (core_index < 0) return;
  553. long ncores = sysconf(_SC_NPROCESSORS_ONLN);
  554. if (ncores <= 0) return;
  555. int target = core_index % (int)ncores;
  556. cpu_set_t set;
  557. CPU_ZERO(&set);
  558. CPU_SET(target, &set);
  559. (void)pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
  560. }
  561. /* =========================================================================
  562. * 4. In-Process Serial / TCP-RS232 / libssh Console / libipmiconsole SOL / libfreeipmi
  563. * ========================================================================= */
  564. static pthread_once_t g_libnet_once = PTHREAD_ONCE_INIT;
  565. static int g_ipmiconsole_ok = 0;
  566. static void init_libnet_once(void) {
  567. (void)ssh_threads_set_callbacks(ssh_threads_get_pthread());
  568. (void)ssh_init();
  569. if (ipmiconsole_engine_init(2, 0) == 0) {
  570. g_ipmiconsole_ok = 1;
  571. }
  572. }
  573. static void ensure_libnet_init(void) {
  574. pthread_once(&g_libnet_once, init_libnet_once);
  575. }
  576. static uint64_t monotonic_ms_now(void) {
  577. struct timespec ts;
  578. clock_gettime(CLOCK_MONOTONIC, &ts);
  579. return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L);
  580. }
  581. static int write_all_fd(int fd, const uint8_t *buf, size_t len, volatile int *stop_flag) {
  582. size_t off = 0;
  583. while (off < len) {
  584. if (stop_flag && __atomic_load_n(stop_flag, __ATOMIC_ACQUIRE)) return -1;
  585. ssize_t n = send(fd, buf + off, len - off, MSG_NOSIGNAL);
  586. if (n > 0) {
  587. off += (size_t)n;
  588. continue;
  589. }
  590. if (n < 0 && errno == EINTR) continue;
  591. if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
  592. struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
  593. int pr = poll(&pfd, 1, 50);
  594. if (pr < 0 && errno == EINTR) continue;
  595. if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) return -1;
  596. continue;
  597. }
  598. return -1;
  599. }
  600. return 0;
  601. }
  602. static void stl_enable_tcp_keepalive(int fd) {
  603. if (fd < 0) return;
  604. int one = 1;
  605. int idle = 5;
  606. int intvl = 2;
  607. int cnt = 3;
  608. unsigned int user_ms = 15000;
  609. (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
  610. (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
  611. #ifdef TCP_KEEPIDLE
  612. (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
  613. #endif
  614. #ifdef TCP_KEEPINTVL
  615. (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl));
  616. #endif
  617. #ifdef TCP_KEEPCNT
  618. (void)setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt));
  619. #endif
  620. #ifdef TCP_USER_TIMEOUT
  621. (void)setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_ms, sizeof(user_ms));
  622. #endif
  623. }
  624. static ssh_session stl_libssh_connect(
  625. const char *host,
  626. int port,
  627. const char *user,
  628. const char *password,
  629. int timeout_ms,
  630. int *out_auth_fail) {
  631. ensure_libnet_init();
  632. if (out_auth_fail) *out_auth_fail = 0;
  633. if (!host || !host[0] || !user || !password) return NULL;
  634. ssh_session sess = ssh_new();
  635. if (!sess) return NULL;
  636. unsigned int uport = (unsigned int)(port > 0 ? port : 22);
  637. long to_sec = (timeout_ms > 0) ? ((long)(timeout_ms + 999) / 1000L) : 10L;
  638. if (to_sec < 1L) to_sec = 1L;
  639. int zero = 0;
  640. int one = 1;
  641. ssh_options_set(sess, SSH_OPTIONS_HOST, host);
  642. ssh_options_set(sess, SSH_OPTIONS_PORT, &uport);
  643. ssh_options_set(sess, SSH_OPTIONS_USER, user);
  644. ssh_options_set(sess, SSH_OPTIONS_TIMEOUT, &to_sec);
  645. ssh_options_set(sess, SSH_OPTIONS_STRICTHOSTKEYCHECK, &zero);
  646. ssh_options_set(sess, SSH_OPTIONS_KNOWNHOSTS, "/dev/null");
  647. ssh_options_set(sess, SSH_OPTIONS_GLOBAL_KNOWNHOSTS, "/dev/null");
  648. ssh_options_set(sess, SSH_OPTIONS_PROCESS_CONFIG, &zero);
  649. ssh_options_set(sess, SSH_OPTIONS_NODELAY, &one);
  650. if (ssh_connect(sess) != SSH_OK) {
  651. ssh_free(sess);
  652. return NULL;
  653. }
  654. socket_t sfd = ssh_get_fd(sess);
  655. if (sfd >= 0) {
  656. stl_enable_tcp_keepalive((int)sfd);
  657. }
  658. int auth = ssh_userauth_password(sess, NULL, password);
  659. if (auth != SSH_AUTH_SUCCESS) {
  660. int methods = ssh_userauth_list(sess, NULL);
  661. if (methods & SSH_AUTH_METHOD_INTERACTIVE) {
  662. int krc = ssh_userauth_kbdint(sess, NULL, NULL);
  663. int guard = 0;
  664. while (krc == SSH_AUTH_INFO && guard++ < 8) {
  665. int np = ssh_userauth_kbdint_getnprompts(sess);
  666. for (int i = 0; i < np; i++) {
  667. (void)ssh_userauth_kbdint_setanswer(sess, (unsigned int)i, password);
  668. }
  669. krc = ssh_userauth_kbdint(sess, NULL, NULL);
  670. }
  671. auth = krc;
  672. }
  673. }
  674. if (auth != SSH_AUTH_SUCCESS) {
  675. if (out_auth_fail) *out_auth_fail = 1;
  676. ssh_disconnect(sess);
  677. ssh_free(sess);
  678. return NULL;
  679. }
  680. return sess;
  681. }
  682. #define STL_SSH_PID_BASE 0x100000
  683. #define STL_SOL_PID_BASE 0x200000
  684. typedef struct {
  685. int in_use;
  686. volatile int alive;
  687. volatile int stop_requested;
  688. int sock_peer_fd;
  689. int thread_started;
  690. ssh_session session;
  691. ssh_channel chan;
  692. pthread_t pump_thread;
  693. } StlSshSlot;
  694. typedef struct {
  695. int in_use;
  696. ipmiconsole_ctx_t ctx;
  697. int fd;
  698. } StlSolSlot;
  699. typedef struct {
  700. int in_use;
  701. int alive;
  702. pthread_mutex_t mu;
  703. ipmi_ctx_t ctx;
  704. char host[128];
  705. char sdr_cache_path[256];
  706. } StlIpmiSlot;
  707. static pthread_mutex_t g_slots_lock = PTHREAD_MUTEX_INITIALIZER;
  708. static StlSshSlot **g_ssh_slots = NULL;
  709. static int g_ssh_cap = 0;
  710. static StlSolSlot **g_sol_slots = NULL;
  711. static int g_sol_cap = 0;
  712. static StlIpmiSlot **g_ipmi_slots = NULL;
  713. static int g_ipmi_cap = 0;
  714. static StlSshSlot *alloc_ssh_slot_locked(int *out_idx) {
  715. int first_null = -1;
  716. for (int i = 0; i < g_ssh_cap; i++) {
  717. if (g_ssh_slots[i] == NULL) {
  718. if (first_null < 0) first_null = i;
  719. } else if (!g_ssh_slots[i]->in_use) {
  720. *out_idx = i;
  721. return g_ssh_slots[i];
  722. }
  723. }
  724. int idx = first_null;
  725. if (idx < 0) {
  726. int new_cap = (g_ssh_cap == 0) ? 16 : (g_ssh_cap * 2);
  727. StlSshSlot **next = (StlSshSlot **)realloc(g_ssh_slots, (size_t)new_cap * sizeof(StlSshSlot *));
  728. if (!next) return NULL;
  729. memset(next + g_ssh_cap, 0, (size_t)(new_cap - g_ssh_cap) * sizeof(StlSshSlot *));
  730. g_ssh_slots = next;
  731. idx = g_ssh_cap;
  732. g_ssh_cap = new_cap;
  733. }
  734. StlSshSlot *s = (StlSshSlot *)calloc(1, sizeof(StlSshSlot));
  735. if (!s) return NULL;
  736. g_ssh_slots[idx] = s;
  737. *out_idx = idx;
  738. return s;
  739. }
  740. static StlSolSlot *alloc_sol_slot_locked(int *out_idx) {
  741. int first_null = -1;
  742. for (int i = 0; i < g_sol_cap; i++) {
  743. if (g_sol_slots[i] == NULL) {
  744. if (first_null < 0) first_null = i;
  745. } else if (!g_sol_slots[i]->in_use) {
  746. *out_idx = i;
  747. return g_sol_slots[i];
  748. }
  749. }
  750. int idx = first_null;
  751. if (idx < 0) {
  752. int new_cap = (g_sol_cap == 0) ? 16 : (g_sol_cap * 2);
  753. StlSolSlot **next = (StlSolSlot **)realloc(g_sol_slots, (size_t)new_cap * sizeof(StlSolSlot *));
  754. if (!next) return NULL;
  755. memset(next + g_sol_cap, 0, (size_t)(new_cap - g_sol_cap) * sizeof(StlSolSlot *));
  756. g_sol_slots = next;
  757. idx = g_sol_cap;
  758. g_sol_cap = new_cap;
  759. }
  760. StlSolSlot *s = (StlSolSlot *)calloc(1, sizeof(StlSolSlot));
  761. if (!s) return NULL;
  762. g_sol_slots[idx] = s;
  763. *out_idx = idx;
  764. return s;
  765. }
  766. static StlIpmiSlot *alloc_ipmi_slot_locked(int *out_idx) {
  767. int first_null = -1;
  768. for (int i = 0; i < g_ipmi_cap; i++) {
  769. if (g_ipmi_slots[i] == NULL) {
  770. if (first_null < 0) first_null = i;
  771. } else {
  772. pthread_mutex_lock(&g_ipmi_slots[i]->mu);
  773. if (!g_ipmi_slots[i]->in_use) {
  774. *out_idx = i;
  775. return g_ipmi_slots[i]; /* returns with slot->mu HELD */
  776. }
  777. pthread_mutex_unlock(&g_ipmi_slots[i]->mu);
  778. }
  779. }
  780. int idx = first_null;
  781. if (idx < 0) {
  782. int new_cap = (g_ipmi_cap == 0) ? 16 : (g_ipmi_cap * 2);
  783. StlIpmiSlot **next = (StlIpmiSlot **)realloc(g_ipmi_slots, (size_t)new_cap * sizeof(StlIpmiSlot *));
  784. if (!next) return NULL;
  785. memset(next + g_ipmi_cap, 0, (size_t)(new_cap - g_ipmi_cap) * sizeof(StlIpmiSlot *));
  786. g_ipmi_slots = next;
  787. idx = g_ipmi_cap;
  788. g_ipmi_cap = new_cap;
  789. }
  790. StlIpmiSlot *s = (StlIpmiSlot *)calloc(1, sizeof(StlIpmiSlot));
  791. if (!s) return NULL;
  792. pthread_mutex_init(&s->mu, NULL);
  793. pthread_mutex_lock(&s->mu);
  794. g_ipmi_slots[idx] = s;
  795. *out_idx = idx;
  796. return s; /* returns with slot->mu HELD */
  797. }
  798. static void *ssh_pump_thread_fn(void *arg) {
  799. StlSshSlot *slot = (StlSshSlot *)arg;
  800. uint8_t rbuf[16384];
  801. uint8_t tbuf[4096];
  802. while (!__atomic_load_n(&slot->stop_requested, __ATOMIC_ACQUIRE)) {
  803. if (!ssh_is_connected(slot->session) ||
  804. ssh_channel_is_eof(slot->chan) ||
  805. ssh_channel_is_closed(slot->chan)) {
  806. break;
  807. }
  808. /* Drain SSH stdout & stderr non-blocking */
  809. int progressed = 0;
  810. for (int pass = 0; pass < 32; pass++) {
  811. int n0 = ssh_channel_read_nonblocking(slot->chan, rbuf, sizeof(rbuf), 0);
  812. if (n0 > 0) {
  813. progressed = 1;
  814. if (write_all_fd(slot->sock_peer_fd, rbuf, (size_t)n0, &slot->stop_requested) != 0) {
  815. goto done;
  816. }
  817. } else if (n0 == SSH_ERROR || n0 == SSH_EOF) {
  818. goto done;
  819. }
  820. int n1 = ssh_channel_read_nonblocking(slot->chan, rbuf, sizeof(rbuf), 1);
  821. if (n1 > 0) {
  822. progressed = 1;
  823. if (write_all_fd(slot->sock_peer_fd, rbuf, (size_t)n1, &slot->stop_requested) != 0) {
  824. goto done;
  825. }
  826. } else if (n1 == SSH_ERROR || n1 == SSH_EOF) {
  827. goto done;
  828. }
  829. if (n0 <= 0 && n1 <= 0) break;
  830. }
  831. /* Drain pending TX bytes from local socketpair end -> SSH channel */
  832. for (int tpass = 0; tpass < 32; tpass++) {
  833. ssize_t tn = read(slot->sock_peer_fd, tbuf, sizeof(tbuf));
  834. if (tn > 0) {
  835. progressed = 1;
  836. size_t off = 0;
  837. while (off < (size_t)tn) {
  838. int wn = ssh_channel_write(slot->chan, tbuf + off, (uint32_t)((size_t)tn - off));
  839. if (wn <= 0) goto done;
  840. off += (size_t)wn;
  841. }
  842. } else if (tn == 0) {
  843. goto done; /* Peer closed master_fd */
  844. } else {
  845. if (errno == EINTR) continue;
  846. break;
  847. }
  848. }
  849. if (progressed) continue;
  850. struct pollfd pfds[2];
  851. int nfds = 0;
  852. socket_t sfd = ssh_get_fd(slot->session);
  853. int ssh_idx = -1;
  854. int peer_idx = -1;
  855. if (sfd >= 0) {
  856. ssh_idx = nfds;
  857. pfds[nfds].fd = (int)sfd;
  858. pfds[nfds].events = POLLIN;
  859. pfds[nfds].revents = 0;
  860. nfds++;
  861. }
  862. if (slot->sock_peer_fd >= 0) {
  863. peer_idx = nfds;
  864. pfds[nfds].fd = slot->sock_peer_fd;
  865. pfds[nfds].events = POLLIN;
  866. pfds[nfds].revents = 0;
  867. nfds++;
  868. }
  869. if (nfds == 0) break;
  870. int pr = poll(pfds, (nfds_t)nfds, 50);
  871. if (pr < 0 && errno != EINTR) break;
  872. if (peer_idx >= 0 && (pfds[peer_idx].revents & (POLLHUP | POLLERR | POLLNVAL))) {
  873. break;
  874. }
  875. if (ssh_idx >= 0 && (pfds[ssh_idx].revents & (POLLERR | POLLHUP | POLLNVAL))) {
  876. break;
  877. }
  878. int so_err = 0;
  879. socklen_t so_len = sizeof(so_err);
  880. if (sfd >= 0 && getsockopt((int)sfd, SOL_SOCKET, SO_ERROR, &so_err, &so_len) == 0 && so_err != 0) {
  881. break;
  882. }
  883. }
  884. done:
  885. __atomic_store_n(&slot->alive, 0, __ATOMIC_RELEASE);
  886. if (slot->sock_peer_fd >= 0) {
  887. close(slot->sock_peer_fd);
  888. slot->sock_peer_fd = -1;
  889. }
  890. if (slot->chan) {
  891. (void)ssh_channel_send_eof(slot->chan);
  892. (void)ssh_channel_close(slot->chan);
  893. ssh_channel_free(slot->chan);
  894. slot->chan = NULL;
  895. }
  896. if (slot->session) {
  897. ssh_disconnect(slot->session);
  898. ssh_free(slot->session);
  899. slot->session = NULL;
  900. }
  901. return NULL;
  902. }
  903. int stl_open_tty_115200_raw(const char *path) {
  904. return c_open_tty_baud_raw(path, 115200);
  905. }
  906. int c_pty_open_serial_115200(const char *path) {
  907. return stl_open_tty_115200_raw(path);
  908. }
  909. /* Open serial with configurable baud rate (115200 / 230400 / 460800 / 921600) */
  910. int c_open_tty_baud_raw(const char *path, int baud) {
  911. if (!path || path[0] == '\0') return -1;
  912. int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
  913. if (fd < 0) return -1;
  914. struct termios tio;
  915. if (tcgetattr(fd, &tio) != 0) {
  916. close(fd);
  917. return -1;
  918. }
  919. cfmakeraw(&tio);
  920. speed_t sp = B115200;
  921. if (baud == 921600) sp = B921600;
  922. else if (baud == 460800) sp = B460800;
  923. else if (baud == 230400) sp = B230400;
  924. cfsetispeed(&tio, sp);
  925. cfsetospeed(&tio, sp);
  926. tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
  927. tio.c_cflag |= (CS8 | CLOCAL | CREAD);
  928. tio.c_iflag &= ~(IXON | IXOFF | IXANY);
  929. tio.c_cc[VMIN] = 1;
  930. tio.c_cc[VTIME] = 0;
  931. if (tcsetattr(fd, TCSANOW, &tio) != 0) {
  932. close(fd);
  933. return -1;
  934. }
  935. int fl = fcntl(fd, F_GETFL, 0);
  936. if (fl >= 0) {
  937. (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
  938. }
  939. return fd;
  940. }
  941. /* Open MCU 24-ch thermal controller UART (115200 8N1 default) */
  942. int c_open_mcu_tty_baud_raw(const char *path, int baud) {
  943. if (!path || path[0] == '\0') return -1;
  944. int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
  945. if (fd < 0) return -1;
  946. struct termios tio;
  947. if (tcgetattr(fd, &tio) != 0) {
  948. close(fd);
  949. return -1;
  950. }
  951. cfmakeraw(&tio);
  952. speed_t sp = B115200;
  953. if (baud == 921600) sp = B921600;
  954. else if (baud == 460800) sp = B460800;
  955. else if (baud == 230400) sp = B230400;
  956. else if (baud == 57600) sp = B57600;
  957. else if (baud == 38400) sp = B38400;
  958. else if (baud == 9600) sp = B9600;
  959. cfsetispeed(&tio, sp);
  960. cfsetospeed(&tio, sp);
  961. tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
  962. tio.c_cflag |= (CS8 | CLOCAL | CREAD);
  963. tio.c_iflag &= ~(IXON | IXOFF | IXANY);
  964. tio.c_cc[VMIN] = 1;
  965. tio.c_cc[VTIME] = 0;
  966. if (tcsetattr(fd, TCSANOW, &tio) != 0) {
  967. close(fd);
  968. return -1;
  969. }
  970. int fl = fcntl(fd, F_GETFL, 0);
  971. if (fl >= 0) {
  972. (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
  973. }
  974. return fd;
  975. }
  976. int c_pty_open_tcp_serial(const char *host, int port, int timeout_ms) {
  977. if (!host || host[0] == '\0' || port <= 0) return -1;
  978. struct addrinfo hints, *res = NULL;
  979. memset(&hints, 0, sizeof(hints));
  980. hints.ai_family = AF_INET;
  981. hints.ai_socktype = SOCK_STREAM;
  982. char port_s[16];
  983. snprintf(port_s, sizeof(port_s), "%d", port);
  984. if (getaddrinfo(host, port_s, &hints, &res) != 0 || !res) return -1;
  985. int sfd = socket(res->ai_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  986. if (sfd < 0) {
  987. freeaddrinfo(res);
  988. return -1;
  989. }
  990. stl_enable_tcp_keepalive(sfd);
  991. int rc = connect(sfd, res->ai_addr, res->ai_addrlen);
  992. freeaddrinfo(res);
  993. if (rc != 0) {
  994. if (errno != EINPROGRESS) {
  995. close(sfd);
  996. return -1;
  997. }
  998. struct pollfd pfd = { .fd = sfd, .events = POLLOUT, .revents = 0 };
  999. int wait_ms = (timeout_ms > 0) ? timeout_ms : 1500;
  1000. if (poll(&pfd, 1, wait_ms) <= 0) {
  1001. close(sfd);
  1002. return -1;
  1003. }
  1004. int so_err = 0;
  1005. socklen_t slen = sizeof(so_err);
  1006. if (getsockopt(sfd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 || so_err != 0) {
  1007. close(sfd);
  1008. return -1;
  1009. }
  1010. }
  1011. return sfd;
  1012. }
  1013. int c_pty_open_tcp_listen(int port) {
  1014. if (port <= 0 || port > 65535) return -1;
  1015. int lfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  1016. if (lfd < 0) return -1;
  1017. int one = 1;
  1018. (void)setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  1019. struct sockaddr_in addr;
  1020. memset(&addr, 0, sizeof(addr));
  1021. addr.sin_family = AF_INET;
  1022. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  1023. addr.sin_port = htons((uint16_t)port);
  1024. if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(lfd, 8) != 0) {
  1025. close(lfd);
  1026. return -1;
  1027. }
  1028. return lfd;
  1029. }
  1030. int c_pty_accept_tcp_nonblock(int listen_fd) {
  1031. if (listen_fd < 0) return -1;
  1032. int cfd = accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
  1033. if (cfd >= 0) {
  1034. stl_enable_tcp_keepalive(cfd);
  1035. }
  1036. return cfd;
  1037. }
  1038. /*
  1039. * Open in-process libssh console session (port 2200) bridged over AF_UNIX non-blocking socketpair.
  1040. * Explicitly sets known_hosts=/dev/null and StrictHostKeyChecking=no so swapped motherboards never block.
  1041. * Returns 0 on success, -2 on auth failure, -1 on transport/slot error.
  1042. */
  1043. int c_pty_spawn_ssh_console(
  1044. const char *host,
  1045. int port,
  1046. const char *user,
  1047. const char *password,
  1048. const char *known_hosts_path,
  1049. int *out_master_fd,
  1050. int *out_child_pid) {
  1051. (void)known_hosts_path;
  1052. if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
  1053. int auth_fail = 0;
  1054. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 2200, user, password, 10000, &auth_fail);
  1055. if (!sess) {
  1056. return auth_fail ? -2 : -1;
  1057. }
  1058. ssh_channel chan = ssh_channel_new(sess);
  1059. if (!chan || ssh_channel_open_session(chan) != SSH_OK) {
  1060. if (chan) ssh_channel_free(chan);
  1061. ssh_disconnect(sess);
  1062. ssh_free(sess);
  1063. return -1;
  1064. }
  1065. if (ssh_channel_request_pty_size(chan, "vt100", 160, 48) != SSH_OK ||
  1066. ssh_channel_request_shell(chan) != SSH_OK) {
  1067. (void)ssh_channel_close(chan);
  1068. ssh_channel_free(chan);
  1069. ssh_disconnect(sess);
  1070. ssh_free(sess);
  1071. return -1;
  1072. }
  1073. int sv[2] = {-1, -1};
  1074. if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0) {
  1075. (void)ssh_channel_close(chan);
  1076. ssh_channel_free(chan);
  1077. ssh_disconnect(sess);
  1078. ssh_free(sess);
  1079. return -1;
  1080. }
  1081. (void)stl_set_nonblocking_nodelay(sv[0], 0);
  1082. (void)stl_set_nonblocking_nodelay(sv[1], 0);
  1083. pthread_mutex_lock(&g_slots_lock);
  1084. int idx = -1;
  1085. StlSshSlot *slot = alloc_ssh_slot_locked(&idx);
  1086. if (slot) {
  1087. memset(slot, 0, sizeof(*slot));
  1088. slot->in_use = 1;
  1089. slot->alive = 1;
  1090. slot->stop_requested = 0;
  1091. slot->sock_peer_fd = sv[1];
  1092. slot->session = sess;
  1093. slot->chan = chan;
  1094. }
  1095. pthread_mutex_unlock(&g_slots_lock);
  1096. if (!slot || idx < 0) {
  1097. close(sv[0]);
  1098. close(sv[1]);
  1099. (void)ssh_channel_close(chan);
  1100. ssh_channel_free(chan);
  1101. ssh_disconnect(sess);
  1102. ssh_free(sess);
  1103. return -1;
  1104. }
  1105. if (pthread_create(&slot->pump_thread, NULL, ssh_pump_thread_fn, slot) != 0) {
  1106. pthread_mutex_lock(&g_slots_lock);
  1107. slot->in_use = 0;
  1108. slot->alive = 0;
  1109. pthread_mutex_unlock(&g_slots_lock);
  1110. close(sv[0]);
  1111. close(sv[1]);
  1112. (void)ssh_channel_close(chan);
  1113. ssh_channel_free(chan);
  1114. ssh_disconnect(sess);
  1115. ssh_free(sess);
  1116. return -1;
  1117. }
  1118. slot->thread_started = 1;
  1119. *out_master_fd = sv[0];
  1120. *out_child_pid = -(STL_SSH_PID_BASE + idx);
  1121. return 0;
  1122. }
  1123. int c_pty_spawn_ipmi_sol(
  1124. const char *host,
  1125. const char *user,
  1126. const char *password,
  1127. int *out_master_fd,
  1128. int *out_child_pid) {
  1129. ensure_libnet_init();
  1130. if (!g_ipmiconsole_ok || !host || !user || !password || !out_master_fd || !out_child_pid) {
  1131. return -1;
  1132. }
  1133. int ciphers[2] = { 17, 3 };
  1134. ipmiconsole_ctx_t ctx = NULL;
  1135. int established = 0;
  1136. int auth_err = 0;
  1137. for (int ci = 0; ci < 2; ci++) {
  1138. struct ipmiconsole_ipmi_config icfg;
  1139. memset(&icfg, 0, sizeof(icfg));
  1140. icfg.username = (char *)user;
  1141. icfg.password = (char *)password;
  1142. icfg.k_g = NULL;
  1143. icfg.k_g_len = 0;
  1144. icfg.privilege_level = IPMICONSOLE_PRIVILEGE_ADMIN;
  1145. icfg.cipher_suite_id = ciphers[ci];
  1146. icfg.workaround_flags = IPMICONSOLE_WORKAROUND_DEFAULT;
  1147. struct ipmiconsole_protocol_config pcfg;
  1148. pcfg.session_timeout_len = -1;
  1149. pcfg.retransmission_timeout_len = -1;
  1150. pcfg.retransmission_backoff_count = -1;
  1151. pcfg.keepalive_timeout_len = -1;
  1152. pcfg.retransmission_keepalive_timeout_len = -1;
  1153. pcfg.acceptable_packet_errors_count = -1;
  1154. pcfg.maximum_retransmission_count = -1;
  1155. struct ipmiconsole_engine_config ecfg;
  1156. ecfg.engine_flags = IPMICONSOLE_ENGINE_DEFAULT;
  1157. ecfg.behavior_flags = IPMICONSOLE_BEHAVIOR_DEFAULT;
  1158. ecfg.debug_flags = 0;
  1159. ctx = ipmiconsole_ctx_create(host, &icfg, &pcfg, &ecfg);
  1160. if (!ctx) continue;
  1161. if (ipmiconsole_engine_submit_block(ctx) == 0 &&
  1162. ipmiconsole_ctx_status(ctx) == IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED) {
  1163. established = 1;
  1164. break;
  1165. }
  1166. int err = ipmiconsole_ctx_errnum(ctx);
  1167. if (err == IPMICONSOLE_ERR_PASSWORD_INVALID ||
  1168. err == IPMICONSOLE_ERR_USERNAME_INVALID ||
  1169. err == IPMICONSOLE_ERR_PRIVILEGE_LEVEL_INSUFFICIENT) {
  1170. auth_err = 1;
  1171. }
  1172. ipmiconsole_ctx_destroy(ctx);
  1173. ctx = NULL;
  1174. if (auth_err) break;
  1175. }
  1176. if (!established || !ctx) {
  1177. return auth_err ? -2 : -1;
  1178. }
  1179. int fd = ipmiconsole_ctx_fd(ctx);
  1180. if (fd < 0) {
  1181. ipmiconsole_ctx_destroy(ctx);
  1182. return -1;
  1183. }
  1184. (void)stl_set_nonblocking_nodelay(fd, 0);
  1185. int fd_fl = fcntl(fd, F_GETFD, 0);
  1186. if (fd_fl >= 0) (void)fcntl(fd, F_SETFD, fd_fl | FD_CLOEXEC);
  1187. pthread_mutex_lock(&g_slots_lock);
  1188. int idx = -1;
  1189. StlSolSlot *sol = alloc_sol_slot_locked(&idx);
  1190. if (sol) {
  1191. sol->in_use = 1;
  1192. sol->ctx = ctx;
  1193. sol->fd = fd;
  1194. }
  1195. pthread_mutex_unlock(&g_slots_lock);
  1196. if (!sol || idx < 0) {
  1197. close(fd);
  1198. ipmiconsole_ctx_destroy(ctx);
  1199. return -1;
  1200. }
  1201. *out_master_fd = fd;
  1202. *out_child_pid = -(STL_SOL_PID_BASE + idx);
  1203. return 0;
  1204. }
  1205. ssize_t c_pty_read_nonblock(int master_fd, uint8_t *buf, size_t cap) {
  1206. if (master_fd < 0 || !buf || cap == 0) return -1;
  1207. ssize_t n = read(master_fd, buf, cap);
  1208. if (n > 0) return n;
  1209. if (n == 0) return -2; /* EOF */
  1210. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  1211. return -2; /* EIO / closed */
  1212. }
  1213. ssize_t c_mcu_tty_read_nonblock(int fd, uint8_t *buf, size_t cap, int is_serial) {
  1214. if (fd < 0 || !buf || cap == 0) return -1;
  1215. ssize_t n = read(fd, buf, cap);
  1216. if (n > 0) return n;
  1217. if (n == 0) {
  1218. if (!is_serial) return -2; /* TCP EOF */
  1219. struct pollfd pfd = { .fd = fd, .events = POLLIN, .revents = 0 };
  1220. if (poll(&pfd, 1, 0) > 0 && (pfd.revents & (POLLHUP | POLLERR | POLLNVAL))) {
  1221. return -2; /* USB serial unplugged / hangup */
  1222. }
  1223. return 0; /* TTY VMIN=0 empty buffer, not EOF */
  1224. }
  1225. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  1226. return -2; /* EIO / ENODEV / closed */
  1227. }
  1228. ssize_t c_pty_write_bytes(int master_fd, const uint8_t *buf, size_t len) {
  1229. if (master_fd < 0 || !buf || len == 0) return 0;
  1230. ssize_t n = write(master_fd, buf, len);
  1231. if (n >= 0) return n;
  1232. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  1233. return -1;
  1234. }
  1235. int c_pty_is_alive(int child_pid) {
  1236. pthread_mutex_lock(&g_slots_lock);
  1237. if (child_pid <= -STL_SSH_PID_BASE && child_pid > -STL_SOL_PID_BASE) {
  1238. int idx = (-child_pid) - STL_SSH_PID_BASE;
  1239. StlSshSlot *slot = (idx >= 0 && idx < g_ssh_cap) ? g_ssh_slots[idx] : NULL;
  1240. int ok = (slot && slot->in_use &&
  1241. __atomic_load_n(&slot->alive, __ATOMIC_ACQUIRE))
  1242. ? 1
  1243. : 0;
  1244. pthread_mutex_unlock(&g_slots_lock);
  1245. return ok;
  1246. }
  1247. if (child_pid <= -STL_SOL_PID_BASE) {
  1248. int idx = (-child_pid) - STL_SOL_PID_BASE;
  1249. StlSolSlot *sol = (idx >= 0 && idx < g_sol_cap) ? g_sol_slots[idx] : NULL;
  1250. ipmiconsole_ctx_t ctx = (sol && sol->in_use) ? sol->ctx : NULL;
  1251. pthread_mutex_unlock(&g_slots_lock);
  1252. if (!ctx) return 0;
  1253. return (ipmiconsole_ctx_status(ctx) ==
  1254. IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED)
  1255. ? 1
  1256. : 0;
  1257. }
  1258. pthread_mutex_unlock(&g_slots_lock);
  1259. return 0;
  1260. }
  1261. void c_pty_close(int master_fd, int child_pid) {
  1262. if (master_fd >= 0) {
  1263. (void)shutdown(master_fd, SHUT_RDWR);
  1264. close(master_fd);
  1265. }
  1266. if (child_pid <= -STL_SSH_PID_BASE && child_pid > -STL_SOL_PID_BASE) {
  1267. int idx = (-child_pid) - STL_SSH_PID_BASE;
  1268. pthread_mutex_lock(&g_slots_lock);
  1269. StlSshSlot *slot = (idx >= 0 && idx < g_ssh_cap) ? g_ssh_slots[idx] : NULL;
  1270. int started = (slot && slot->in_use) ? slot->thread_started : 0;
  1271. pthread_t th;
  1272. if (slot && slot->in_use) {
  1273. __atomic_store_n(&slot->stop_requested, 1, __ATOMIC_RELEASE);
  1274. th = slot->pump_thread;
  1275. }
  1276. pthread_mutex_unlock(&g_slots_lock);
  1277. if (slot && started) {
  1278. pthread_join(th, NULL);
  1279. }
  1280. if (slot) {
  1281. pthread_mutex_lock(&g_slots_lock);
  1282. if (slot->sock_peer_fd >= 0) {
  1283. close(slot->sock_peer_fd);
  1284. slot->sock_peer_fd = -1;
  1285. }
  1286. slot->in_use = 0;
  1287. slot->alive = 0;
  1288. slot->thread_started = 0;
  1289. pthread_mutex_unlock(&g_slots_lock);
  1290. }
  1291. return;
  1292. }
  1293. if (child_pid <= -STL_SOL_PID_BASE) {
  1294. int idx = (-child_pid) - STL_SOL_PID_BASE;
  1295. ipmiconsole_ctx_t ctx = NULL;
  1296. pthread_mutex_lock(&g_slots_lock);
  1297. StlSolSlot *sol = (idx >= 0 && idx < g_sol_cap) ? g_sol_slots[idx] : NULL;
  1298. if (sol && sol->in_use) {
  1299. ctx = sol->ctx;
  1300. sol->ctx = NULL;
  1301. sol->fd = -1;
  1302. sol->in_use = 0;
  1303. }
  1304. pthread_mutex_unlock(&g_slots_lock);
  1305. if (ctx) {
  1306. ipmiconsole_ctx_destroy(ctx);
  1307. }
  1308. }
  1309. }
  1310. /* =========================================================================
  1311. * 5. In-Process libssh Remote Exec + Atomic SFTP Upload/Download
  1312. * ========================================================================= */
  1313. int c_ssh_exec_capture(
  1314. const char *host,
  1315. int port,
  1316. const char *user,
  1317. const char *password,
  1318. const char *cmd,
  1319. char *out_buf,
  1320. size_t out_cap,
  1321. size_t *out_len,
  1322. int timeout_ms) {
  1323. if (out_len) *out_len = 0;
  1324. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  1325. if (!host || !user || !password || !cmd) return -1;
  1326. int auth_fail = 0;
  1327. int eff_to = (timeout_ms > 0) ? timeout_ms : 5000;
  1328. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, eff_to, &auth_fail);
  1329. if (!sess) return auth_fail ? -2 : -1;
  1330. ssh_channel chan = ssh_channel_new(sess);
  1331. if (!chan || ssh_channel_open_session(chan) != SSH_OK ||
  1332. ssh_channel_request_exec(chan, cmd) != SSH_OK) {
  1333. if (chan) {
  1334. (void)ssh_channel_close(chan);
  1335. ssh_channel_free(chan);
  1336. }
  1337. ssh_disconnect(sess);
  1338. ssh_free(sess);
  1339. return -1;
  1340. }
  1341. size_t total = 0;
  1342. uint8_t tmp[4096];
  1343. uint64_t deadline = monotonic_ms_now() + (uint64_t)eff_to;
  1344. int timed_out = 0;
  1345. for (;;) {
  1346. int n0 = ssh_channel_read_nonblocking(chan, tmp, sizeof(tmp), 0);
  1347. if (n0 > 0) {
  1348. if (out_buf && out_cap > 1 && total < out_cap - 1) {
  1349. size_t copy = (size_t)n0;
  1350. if (copy > (out_cap - 1 - total)) copy = out_cap - 1 - total;
  1351. memcpy(out_buf + total, tmp, copy);
  1352. total += copy;
  1353. }
  1354. continue;
  1355. }
  1356. int n1 = ssh_channel_read_nonblocking(chan, tmp, sizeof(tmp), 1);
  1357. if (n1 > 0) {
  1358. if (out_buf && out_cap > 1 && total < out_cap - 1) {
  1359. size_t copy = (size_t)n1;
  1360. if (copy > (out_cap - 1 - total)) copy = out_cap - 1 - total;
  1361. memcpy(out_buf + total, tmp, copy);
  1362. total += copy;
  1363. }
  1364. continue;
  1365. }
  1366. if (n0 == SSH_ERROR || n1 == SSH_ERROR) {
  1367. break;
  1368. }
  1369. if (ssh_channel_is_eof(chan) || ssh_channel_is_closed(chan)) {
  1370. break;
  1371. }
  1372. uint64_t now = monotonic_ms_now();
  1373. if (now >= deadline) {
  1374. timed_out = 1;
  1375. break;
  1376. }
  1377. int rem_ms = (int)(deadline - now);
  1378. if (rem_ms > 50) rem_ms = 50;
  1379. socket_t sfd = ssh_get_fd(sess);
  1380. if (sfd >= 0) {
  1381. struct pollfd pfd = { .fd = (int)sfd, .events = POLLIN, .revents = 0 };
  1382. (void)poll(&pfd, 1, rem_ms);
  1383. } else {
  1384. struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000L };
  1385. nanosleep(&ts, NULL);
  1386. }
  1387. }
  1388. if (out_buf && out_cap > 0) {
  1389. out_buf[(total < out_cap) ? total : (out_cap - 1)] = '\0';
  1390. }
  1391. if (out_len) *out_len = total;
  1392. int exit_rc = timed_out ? -3 : 0;
  1393. if (!timed_out) {
  1394. uint32_t code = 0;
  1395. int pcore = 0;
  1396. char *psig = NULL;
  1397. (void)ssh_channel_send_eof(chan);
  1398. (void)ssh_channel_close(chan);
  1399. if (ssh_channel_get_exit_state(chan, &code, &psig, &pcore) == SSH_OK) {
  1400. exit_rc = (int)code;
  1401. }
  1402. if (psig) ssh_string_free_char(psig);
  1403. } else {
  1404. (void)ssh_channel_close(chan);
  1405. }
  1406. ssh_channel_free(chan);
  1407. ssh_disconnect(sess);
  1408. ssh_free(sess);
  1409. return exit_rc;
  1410. }
  1411. int c_ssh_sftp_put_file(
  1412. const char *host,
  1413. int port,
  1414. const char *user,
  1415. const char *password,
  1416. const char *local_path,
  1417. const char *remote_path,
  1418. int timeout_ms) {
  1419. if (!host || !user || !password || !local_path || !remote_path) return -1;
  1420. FILE *fp = fopen(local_path, "rb");
  1421. if (!fp) return -1;
  1422. int auth_fail = 0;
  1423. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, timeout_ms > 0 ? timeout_ms : 5000, &auth_fail);
  1424. if (!sess) {
  1425. fclose(fp);
  1426. return auth_fail ? -2 : -1;
  1427. }
  1428. sftp_session sftp = sftp_new(sess);
  1429. if (!sftp || sftp_init(sftp) != SSH_OK) {
  1430. if (sftp) sftp_free(sftp);
  1431. ssh_disconnect(sess);
  1432. ssh_free(sess);
  1433. fclose(fp);
  1434. return -1;
  1435. }
  1436. char partial[1088];
  1437. snprintf(partial, sizeof(partial), "%s.partial", remote_path);
  1438. sftp_file rf = sftp_open(sftp, partial, O_WRONLY | O_CREAT | O_TRUNC, 0644);
  1439. if (!rf) {
  1440. sftp_free(sftp);
  1441. ssh_disconnect(sess);
  1442. ssh_free(sess);
  1443. fclose(fp);
  1444. return -1;
  1445. }
  1446. int rc = 0;
  1447. uint8_t buf[32768];
  1448. size_t nr;
  1449. while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) {
  1450. size_t off = 0;
  1451. while (off < nr) {
  1452. ssize_t nw = sftp_write(rf, buf + off, nr - off);
  1453. if (nw <= 0) {
  1454. rc = -1;
  1455. break;
  1456. }
  1457. off += (size_t)nw;
  1458. }
  1459. if (rc != 0) break;
  1460. }
  1461. if (ferror(fp)) rc = -1;
  1462. fclose(fp);
  1463. if (sftp_close(rf) != SSH_OK) rc = -1;
  1464. if (rc == 0) {
  1465. if (sftp_rename(sftp, partial, remote_path) != 0) {
  1466. (void)sftp_unlink(sftp, remote_path);
  1467. if (sftp_rename(sftp, partial, remote_path) != 0) {
  1468. (void)sftp_unlink(sftp, partial);
  1469. rc = -1;
  1470. }
  1471. }
  1472. } else {
  1473. (void)sftp_unlink(sftp, partial);
  1474. }
  1475. sftp_free(sftp);
  1476. ssh_disconnect(sess);
  1477. ssh_free(sess);
  1478. return rc;
  1479. }
  1480. int c_ssh_sftp_get_file(
  1481. const char *host,
  1482. int port,
  1483. const char *user,
  1484. const char *password,
  1485. const char *remote_path,
  1486. const char *local_path,
  1487. int timeout_ms) {
  1488. if (!host || !user || !password || !remote_path || !local_path) return -1;
  1489. int auth_fail = 0;
  1490. ssh_session sess = stl_libssh_connect(host, port > 0 ? port : 22, user, password, timeout_ms > 0 ? timeout_ms : 5000, &auth_fail);
  1491. if (!sess) return auth_fail ? -2 : -1;
  1492. sftp_session sftp = sftp_new(sess);
  1493. if (!sftp || sftp_init(sftp) != SSH_OK) {
  1494. if (sftp) sftp_free(sftp);
  1495. ssh_disconnect(sess);
  1496. ssh_free(sess);
  1497. return -1;
  1498. }
  1499. sftp_file rf = sftp_open(sftp, remote_path, O_RDONLY, 0);
  1500. if (!rf) {
  1501. sftp_free(sftp);
  1502. ssh_disconnect(sess);
  1503. ssh_free(sess);
  1504. return -1;
  1505. }
  1506. char partial[1088];
  1507. snprintf(partial, sizeof(partial), "%s.partial", local_path);
  1508. FILE *fp = fopen(partial, "wb");
  1509. if (!fp) {
  1510. (void)sftp_close(rf);
  1511. sftp_free(sftp);
  1512. ssh_disconnect(sess);
  1513. ssh_free(sess);
  1514. return -1;
  1515. }
  1516. int rc = 0;
  1517. uint8_t buf[32768];
  1518. for (;;) {
  1519. ssize_t nr = sftp_read(rf, buf, sizeof(buf));
  1520. if (nr > 0) {
  1521. if (fwrite(buf, 1, (size_t)nr, fp) != (size_t)nr) {
  1522. rc = -1;
  1523. break;
  1524. }
  1525. } else if (nr == 0) {
  1526. break;
  1527. } else {
  1528. rc = -1;
  1529. break;
  1530. }
  1531. }
  1532. if (fclose(fp) != 0) rc = -1;
  1533. (void)sftp_close(rf);
  1534. sftp_free(sftp);
  1535. ssh_disconnect(sess);
  1536. ssh_free(sess);
  1537. if (rc == 0) {
  1538. if (rename(partial, local_path) != 0) {
  1539. unlink(partial);
  1540. rc = -1;
  1541. }
  1542. } else {
  1543. unlink(partial);
  1544. }
  1545. return rc;
  1546. }
  1547. /* =========================================================================
  1548. * 6. In-Process libfreeipmi Persistent Out-of-Band Session & Telemetry
  1549. * ========================================================================= */
  1550. static StlIpmiSlot *get_ipmi_slot(int handle) {
  1551. if (handle < 1) return NULL;
  1552. pthread_mutex_lock(&g_slots_lock);
  1553. StlIpmiSlot *s = (handle <= g_ipmi_cap) ? g_ipmi_slots[handle - 1] : NULL;
  1554. pthread_mutex_unlock(&g_slots_lock);
  1555. return s;
  1556. }
  1557. int c_ipmi_open(
  1558. const char *host,
  1559. const char *user,
  1560. const char *password,
  1561. int cipher_suite,
  1562. int timeout_ms) {
  1563. if (!host || !host[0] || !user || !password) return -1;
  1564. ipmi_ctx_t ctx = ipmi_ctx_create();
  1565. if (!ctx) return -1;
  1566. unsigned int sess_to = (timeout_ms > 0) ? (unsigned int)timeout_ms : 3000U;
  1567. uint8_t ciph = (uint8_t)(cipher_suite > 0 ? cipher_suite : 17);
  1568. int rc = ipmi_ctx_open_outofband_2_0(
  1569. ctx, host, user, password, NULL, 0,
  1570. IPMI_PRIVILEGE_LEVEL_ADMIN, ciph,
  1571. sess_to, 500U,
  1572. IPMI_WORKAROUND_FLAGS_DEFAULT,
  1573. IPMI_FLAGS_DEFAULT);
  1574. if (rc != 0 && ciph == 17) {
  1575. int err = ipmi_ctx_errnum(ctx);
  1576. if (err != IPMI_ERR_PASSWORD_INVALID &&
  1577. err != IPMI_ERR_USERNAME_INVALID &&
  1578. err != IPMI_ERR_CONNECTION_TIMEOUT) {
  1579. rc = ipmi_ctx_open_outofband_2_0(
  1580. ctx, host, user, password, NULL, 0,
  1581. IPMI_PRIVILEGE_LEVEL_ADMIN, 3,
  1582. sess_to, 500U,
  1583. IPMI_WORKAROUND_FLAGS_DEFAULT,
  1584. IPMI_FLAGS_DEFAULT);
  1585. }
  1586. }
  1587. if (rc != 0) {
  1588. int final_err = ipmi_ctx_errnum(ctx);
  1589. ipmi_ctx_destroy(ctx);
  1590. return (final_err == IPMI_ERR_CONNECTION_TIMEOUT) ? -2 : -1;
  1591. }
  1592. pthread_mutex_lock(&g_slots_lock);
  1593. int idx = -1;
  1594. StlIpmiSlot *slot = alloc_ipmi_slot_locked(&idx);
  1595. if (slot) {
  1596. slot->in_use = 1;
  1597. slot->alive = 1;
  1598. slot->ctx = ctx;
  1599. snprintf(slot->host, sizeof(slot->host), "%s", host);
  1600. {
  1601. char safe_host[96];
  1602. size_t hi = 0;
  1603. for (; host[hi] && hi + 1 < sizeof(safe_host); hi++) {
  1604. unsigned char ch = (unsigned char)host[hi];
  1605. safe_host[hi] = ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') ||
  1606. (ch >= 'A' && ch <= 'Z') || ch == '.' || ch == '_' || ch == '-')
  1607. ? (char)ch
  1608. : '_';
  1609. }
  1610. safe_host[hi] = '\0';
  1611. snprintf(slot->sdr_cache_path, sizeof(slot->sdr_cache_path),
  1612. "/tmp/stl_sdr_%ld_%d_%s.cache", (long)getpid(), idx, safe_host);
  1613. unlink(slot->sdr_cache_path);
  1614. }
  1615. pthread_mutex_unlock(&slot->mu);
  1616. }
  1617. pthread_mutex_unlock(&g_slots_lock);
  1618. if (!slot || idx < 0) {
  1619. (void)ipmi_ctx_close(ctx);
  1620. ipmi_ctx_destroy(ctx);
  1621. return -1;
  1622. }
  1623. return idx + 1;
  1624. }
  1625. void c_ipmi_close(int handle) {
  1626. if (handle < 1) return;
  1627. pthread_mutex_lock(&g_slots_lock);
  1628. StlIpmiSlot *slot = (handle <= g_ipmi_cap) ? g_ipmi_slots[handle - 1] : NULL;
  1629. if (!slot) {
  1630. pthread_mutex_unlock(&g_slots_lock);
  1631. return;
  1632. }
  1633. pthread_mutex_lock(&slot->mu);
  1634. if (slot->in_use) {
  1635. if (slot->ctx) {
  1636. if (slot->alive) {
  1637. (void)ipmi_ctx_close(slot->ctx);
  1638. }
  1639. ipmi_ctx_destroy(slot->ctx);
  1640. slot->ctx = NULL;
  1641. }
  1642. if (slot->sdr_cache_path[0]) {
  1643. unlink(slot->sdr_cache_path);
  1644. slot->sdr_cache_path[0] = '\0';
  1645. }
  1646. slot->alive = 0;
  1647. slot->in_use = 0;
  1648. slot->host[0] = '\0';
  1649. }
  1650. pthread_mutex_unlock(&slot->mu);
  1651. pthread_mutex_unlock(&g_slots_lock);
  1652. }
  1653. int c_ipmi_is_alive(int handle) {
  1654. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1655. if (!slot) return 0;
  1656. pthread_mutex_lock(&slot->mu);
  1657. int alive = (slot->in_use && slot->alive && slot->ctx != NULL) ? 1 : 0;
  1658. pthread_mutex_unlock(&slot->mu);
  1659. return alive;
  1660. }
  1661. int c_ipmi_chassis_status(int handle, int *out_power_on, char *out_buf, size_t out_cap) {
  1662. if (out_power_on) *out_power_on = -1;
  1663. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  1664. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1665. if (!slot) return -1;
  1666. pthread_mutex_lock(&slot->mu);
  1667. if (!slot->in_use || !slot->ctx) {
  1668. pthread_mutex_unlock(&slot->mu);
  1669. return -1;
  1670. }
  1671. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_get_chassis_status_rs);
  1672. if (!rs) {
  1673. pthread_mutex_unlock(&slot->mu);
  1674. return -1;
  1675. }
  1676. int rc = ipmi_cmd_get_chassis_status(slot->ctx, rs);
  1677. if (rc != 0) {
  1678. slot->alive = 0;
  1679. fiid_obj_destroy(rs);
  1680. pthread_mutex_unlock(&slot->mu);
  1681. return -1;
  1682. }
  1683. uint64_t pwr = 0, ovl = 0, pflt = 0, cflt = 0, intr = 0;
  1684. int got = fiid_obj_get(rs, "current_power_state.power_is_on", &pwr);
  1685. (void)fiid_obj_get(rs, "current_power_state.power_overload", &ovl);
  1686. (void)fiid_obj_get(rs, "current_power_state.power_fault", &pflt);
  1687. (void)fiid_obj_get(rs, "current_power_state.power_control_fault", &cflt);
  1688. (void)fiid_obj_get(rs, "misc_chassis_state.chassis_intrusion_active", &intr);
  1689. fiid_obj_destroy(rs);
  1690. pthread_mutex_unlock(&slot->mu);
  1691. if (got <= 0) return -1;
  1692. int is_on = (pwr != 0) ? 1 : 0;
  1693. if (out_power_on) *out_power_on = is_on;
  1694. if (out_buf && out_cap > 0) {
  1695. snprintf(
  1696. out_buf,
  1697. out_cap,
  1698. "System Power : %s\n"
  1699. "Chassis Power is %s\n"
  1700. "Power Overload : %s\n"
  1701. "Main Power Fault : %s\n"
  1702. "Power Control Fault : %s\n"
  1703. "Chassis Intrusion : %s\n",
  1704. is_on ? "on" : "off",
  1705. is_on ? "on" : "off",
  1706. ovl ? "true" : "false",
  1707. pflt ? "true" : "false",
  1708. cflt ? "true" : "false",
  1709. intr ? "active" : "inactive");
  1710. }
  1711. return 0;
  1712. }
  1713. int c_ipmi_chassis_control(int handle, int op) {
  1714. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1715. if (!slot || !IPMI_CHASSIS_CONTROL_VALID((uint8_t)op)) return -1;
  1716. pthread_mutex_lock(&slot->mu);
  1717. if (!slot->in_use || !slot->ctx) {
  1718. pthread_mutex_unlock(&slot->mu);
  1719. return -1;
  1720. }
  1721. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_chassis_control_rs);
  1722. if (!rs) {
  1723. pthread_mutex_unlock(&slot->mu);
  1724. return -1;
  1725. }
  1726. int rc = ipmi_cmd_chassis_control(slot->ctx, (uint8_t)op, rs);
  1727. if (rc != 0) slot->alive = 0;
  1728. fiid_obj_destroy(rs);
  1729. pthread_mutex_unlock(&slot->mu);
  1730. return (rc == 0) ? 0 : -1;
  1731. }
  1732. int c_ipmi_warm_reset(int handle) {
  1733. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1734. if (!slot) return -1;
  1735. pthread_mutex_lock(&slot->mu);
  1736. if (!slot->in_use || !slot->ctx) {
  1737. pthread_mutex_unlock(&slot->mu);
  1738. return -1;
  1739. }
  1740. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_warm_reset_rs);
  1741. if (!rs) {
  1742. pthread_mutex_unlock(&slot->mu);
  1743. return -1;
  1744. }
  1745. int rc = ipmi_cmd_warm_reset(slot->ctx, rs);
  1746. if (rc != 0) slot->alive = 0;
  1747. fiid_obj_destroy(rs);
  1748. pthread_mutex_unlock(&slot->mu);
  1749. return (rc == 0) ? 0 : -1;
  1750. }
  1751. int c_ipmi_raw(
  1752. int handle,
  1753. uint8_t net_fn,
  1754. uint8_t cmd,
  1755. const uint8_t *payload,
  1756. size_t payload_len,
  1757. uint8_t *out_buf,
  1758. size_t out_cap,
  1759. size_t *out_len) {
  1760. if (out_len) *out_len = 0;
  1761. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1762. if (!slot || payload_len > 255) return -1;
  1763. uint8_t rq[260];
  1764. uint8_t rs[260];
  1765. rq[0] = cmd;
  1766. if (payload && payload_len > 0) {
  1767. memcpy(rq + 1, payload, payload_len);
  1768. }
  1769. pthread_mutex_lock(&slot->mu);
  1770. if (!slot->in_use || !slot->ctx) {
  1771. pthread_mutex_unlock(&slot->mu);
  1772. return -1;
  1773. }
  1774. int rlen = ipmi_cmd_raw(
  1775. slot->ctx, 0, net_fn,
  1776. rq, (unsigned int)(1 + payload_len),
  1777. rs, (unsigned int)sizeof(rs));
  1778. if (rlen < 0) slot->alive = 0;
  1779. pthread_mutex_unlock(&slot->mu);
  1780. if (rlen < 2 || rs[1] != 0x00) {
  1781. return -1;
  1782. }
  1783. size_t data_len = (size_t)(rlen - 2);
  1784. if (out_buf && out_cap > 0 && data_len > 0) {
  1785. size_t cp = (data_len < out_cap) ? data_len : out_cap;
  1786. memcpy(out_buf, rs + 2, cp);
  1787. }
  1788. if (out_len) *out_len = data_len;
  1789. return 0;
  1790. }
  1791. typedef struct {
  1792. ipmi_sensor_read_ctx_t sr;
  1793. char *out_buf;
  1794. size_t out_cap;
  1795. size_t used;
  1796. } SdrIterCtx;
  1797. static int contains_ci_dimm(const char *s) {
  1798. if (!s) return 0;
  1799. for (size_t i = 0; s[i] && s[i+1] && s[i+2] && s[i+3]; i++) {
  1800. char c0 = (s[i] >= 'a' && s[i] <= 'z') ? (char)(s[i] - 32) : s[i];
  1801. char c1 = (s[i+1] >= 'a' && s[i+1] <= 'z') ? (char)(s[i+1] - 32) : s[i+1];
  1802. char c2 = (s[i+2] >= 'a' && s[i+2] <= 'z') ? (char)(s[i+2] - 32) : s[i+2];
  1803. char c3 = (s[i+3] >= 'a' && s[i+3] <= 'z') ? (char)(s[i+3] - 32) : s[i+3];
  1804. if (c0 == 'D' && c1 == 'I' && c2 == 'M' && c3 == 'M') return 1;
  1805. }
  1806. return 0;
  1807. }
  1808. static const char *ipmi_unit_label(uint8_t base_u, uint8_t pct) {
  1809. if (pct == 1) return "%";
  1810. switch (base_u) {
  1811. case IPMI_SENSOR_UNIT_DEGREES_C: return "degrees C";
  1812. case IPMI_SENSOR_UNIT_DEGREES_F: return "degrees F";
  1813. case IPMI_SENSOR_UNIT_VOLTS: return "Volts";
  1814. case IPMI_SENSOR_UNIT_AMPS: return "Amps";
  1815. case IPMI_SENSOR_UNIT_WATTS: return "Watts";
  1816. case IPMI_SENSOR_UNIT_RPM: return "RPM";
  1817. case IPMI_SENSOR_UNIT_HZ: return "Hz";
  1818. default: return "units";
  1819. }
  1820. }
  1821. static int sdr_iterate_cb(
  1822. ipmi_sdr_ctx_t sdr,
  1823. uint8_t record_type,
  1824. const void *sdr_record,
  1825. unsigned int sdr_record_len,
  1826. void *data) {
  1827. SdrIterCtx *ic = (SdrIterCtx *)data;
  1828. if (record_type != IPMI_SDR_FORMAT_FULL_SENSOR_RECORD &&
  1829. record_type != IPMI_SDR_FORMAT_COMPACT_SENSOR_RECORD) {
  1830. return 0;
  1831. }
  1832. char name[IPMI_SDR_MAX_SENSOR_NAME_LENGTH + 1];
  1833. memset(name, 0, sizeof(name));
  1834. if (ipmi_sdr_parse_id_string(sdr, sdr_record, sdr_record_len, name, sizeof(name) - 1) < 0) {
  1835. return 0;
  1836. }
  1837. uint8_t pct = 0, mod = 0, rate = 0, base_u = 0, mod_u = 0;
  1838. int units_ok = (ipmi_sdr_parse_sensor_units(
  1839. sdr, sdr_record, sdr_record_len,
  1840. &pct, &mod, &rate, &base_u, &mod_u) == 0);
  1841. uint8_t stype = 0, ert = 0;
  1842. int has_type = (ipmi_sdr_parse_sensor_type(sdr, sdr_record, sdr_record_len, &stype) == 0 &&
  1843. ipmi_sdr_parse_event_reading_type_code(sdr, sdr_record, sdr_record_len, &ert) == 0);
  1844. uint8_t raw = 0;
  1845. double *reading = NULL;
  1846. uint16_t bitmask = 0;
  1847. int src = ipmi_sensor_read(ic->sr, sdr_record, sdr_record_len, 0, &raw, &reading, &bitmask);
  1848. char line[256];
  1849. if (src == 1 && reading != NULL && units_ok) {
  1850. const char *ulab = ipmi_unit_label(base_u, pct);
  1851. snprintf(line, sizeof(line), "%s | %.2f %s | ok\n", name, *reading, ulab);
  1852. } else if (units_ok && base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
  1853. snprintf(line, sizeof(line), "%s | no reading | ns\n", name);
  1854. } else if (src == 1 && has_type) {
  1855. if (contains_ci_dimm(name) && stype == IPMI_SENSOR_TYPE_MEMORY && ert == 0x6F) {
  1856. snprintf(line, sizeof(line), "%s | discrete_mem=0x%04X | ok\n", name, (unsigned)bitmask);
  1857. } else if (contains_ci_dimm(name) && stype == IPMI_SENSOR_TYPE_ENTITY_PRESENCE && ert == 0x6F) {
  1858. snprintf(line, sizeof(line), "%s | discrete_presence=0x%04X | ok\n", name, (unsigned)bitmask);
  1859. } else if (contains_ci_dimm(name) && ert == 0x08) {
  1860. snprintf(line, sizeof(line), "%s | discrete_devpres=0x%04X | ok\n", name, (unsigned)bitmask);
  1861. } else {
  1862. snprintf(line, sizeof(line), "%s | discrete_state=0x%04X | type=0x%02X\n",
  1863. name, (unsigned)bitmask, (unsigned)stype);
  1864. }
  1865. } else if (units_ok && (base_u == IPMI_SENSOR_UNIT_VOLTS || base_u == IPMI_SENSOR_UNIT_AMPS ||
  1866. base_u == IPMI_SENSOR_UNIT_WATTS || base_u == IPMI_SENSOR_UNIT_RPM)) {
  1867. snprintf(line, sizeof(line), "%s | no reading (%s) | ns\n", name, ipmi_unit_label(base_u, pct));
  1868. } else {
  1869. if (reading) free(reading);
  1870. return 0;
  1871. }
  1872. if (reading) free(reading);
  1873. size_t l = strlen(line);
  1874. if (ic->used + l < ic->out_cap) {
  1875. memcpy(ic->out_buf + ic->used, line, l);
  1876. ic->used += l;
  1877. ic->out_buf[ic->used] = '\0';
  1878. }
  1879. return 0;
  1880. }
  1881. static int ensure_sdr_cache_open(ipmi_sdr_ctx_t sdr, ipmi_ctx_t ctx, const char *path) {
  1882. if (ipmi_sdr_cache_open(sdr, ctx, path) == 0) {
  1883. return 0;
  1884. }
  1885. if (ipmi_sdr_cache_create(
  1886. sdr, ctx, path,
  1887. IPMI_SDR_CACHE_CREATE_FLAGS_OVERWRITE | IPMI_SDR_CACHE_CREATE_FLAGS_ASSUME_MAX_SDR_RECORD_COUNT,
  1888. NULL, NULL) != 0) {
  1889. return -1;
  1890. }
  1891. return ipmi_sdr_cache_open(sdr, ctx, path);
  1892. }
  1893. void c_ipmi_invalidate_sdr_cache(int handle) {
  1894. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1895. if (!slot) return;
  1896. pthread_mutex_lock(&slot->mu);
  1897. if (slot->in_use && slot->sdr_cache_path[0] != '\0') {
  1898. unlink(slot->sdr_cache_path);
  1899. }
  1900. pthread_mutex_unlock(&slot->mu);
  1901. }
  1902. int c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len) {
  1903. if (out_len) *out_len = 0;
  1904. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  1905. StlIpmiSlot *slot = get_ipmi_slot(handle);
  1906. if (!slot || !out_buf || out_cap < 2) return -1;
  1907. pthread_mutex_lock(&slot->mu);
  1908. if (!slot->in_use || !slot->ctx) {
  1909. pthread_mutex_unlock(&slot->mu);
  1910. return -1;
  1911. }
  1912. ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create();
  1913. ipmi_sensor_read_ctx_t sr = ipmi_sensor_read_ctx_create(slot->ctx);
  1914. if (!sdr || !sr) {
  1915. if (sdr) ipmi_sdr_ctx_destroy(sdr);
  1916. if (sr) ipmi_sensor_read_ctx_destroy(sr);
  1917. pthread_mutex_unlock(&slot->mu);
  1918. return -1;
  1919. }
  1920. (void)ipmi_sensor_read_ctx_set_flags(sr, IPMI_SENSOR_READ_FLAGS_DISCRETE_READING);
  1921. if (ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
  1922. slot->alive = 0;
  1923. ipmi_sensor_read_ctx_destroy(sr);
  1924. ipmi_sdr_ctx_destroy(sdr);
  1925. pthread_mutex_unlock(&slot->mu);
  1926. return -1;
  1927. }
  1928. SdrIterCtx ic = { .sr = sr, .out_buf = out_buf, .out_cap = out_cap, .used = 0 };
  1929. int irc = ipmi_sdr_cache_iterate(sdr, sdr_iterate_cb, &ic);
  1930. if (irc < 0) slot->alive = 0;
  1931. (void)ipmi_sdr_cache_close(sdr);
  1932. ipmi_sensor_read_ctx_destroy(sr);
  1933. ipmi_sdr_ctx_destroy(sdr);
  1934. pthread_mutex_unlock(&slot->mu);
  1935. if (out_len) *out_len = ic.used;
  1936. return (irc >= 0) ? 0 : -1;
  1937. }
  1938. static void append_str(char *out_buf, size_t out_cap, size_t *used, const char *s) {
  1939. if (!out_buf || out_cap == 0 || !s) return;
  1940. size_t l = strlen(s);
  1941. if (*used >= out_cap - 1) return;
  1942. size_t rem = out_cap - 1 - *used;
  1943. if (l > rem) l = rem;
  1944. memcpy(out_buf + *used, s, l);
  1945. *used += l;
  1946. out_buf[*used] = '\0';
  1947. }
  1948. typedef struct {
  1949. char *out_buf;
  1950. size_t out_cap;
  1951. size_t used;
  1952. int count;
  1953. } SelIterCtx;
  1954. static int sel_iterate_cb(ipmi_sel_ctx_t sel, void *data) {
  1955. SelIterCtx *sc = (SelIterCtx *)data;
  1956. if (sc->count >= 200 || sc->used + 128 >= sc->out_cap) return 1;
  1957. char line[256];
  1958. memset(line, 0, sizeof(line));
  1959. int n = ipmi_sel_parse_read_record_string(
  1960. sel,
  1961. "%i | %d | %t | %s | %E",
  1962. NULL, 0,
  1963. line, (unsigned int)(sizeof(line) - 2),
  1964. IPMI_SEL_STRING_FLAGS_IGNORE_UNAVAILABLE_FIELD | IPMI_SEL_STRING_FLAGS_OUTPUT_NOT_AVAILABLE);
  1965. if (n > 0) {
  1966. line[sizeof(line) - 2] = '\0';
  1967. append_str(sc->out_buf, sc->out_cap, &sc->used, line);
  1968. append_str(sc->out_buf, sc->out_cap, &sc->used, "\n");
  1969. sc->count++;
  1970. }
  1971. return 0;
  1972. }
  1973. static void append_fru_field(
  1974. ipmi_fru_ctx_t fru,
  1975. const char *label,
  1976. ipmi_fru_field_t *f,
  1977. uint8_t lang,
  1978. char *out_buf,
  1979. size_t out_cap,
  1980. size_t *used) {
  1981. if (!f || f->type_length_field_length == 0) return;
  1982. char sbuf[IPMI_FRU_AREA_STRING_MAX + 1];
  1983. unsigned int slen = sizeof(sbuf) - 1;
  1984. memset(sbuf, 0, sizeof(sbuf));
  1985. if (ipmi_fru_type_length_field_to_string(
  1986. fru, f->type_length_field, f->type_length_field_length, lang, sbuf, &slen) == 0 &&
  1987. sbuf[0] != '\0') {
  1988. char line[600];
  1989. snprintf(line, sizeof(line), "%-24s : %s\n", label, sbuf);
  1990. append_str(out_buf, out_cap, used, line);
  1991. }
  1992. }
  1993. int c_ipmi_device_info(
  1994. int handle,
  1995. const char *kind,
  1996. char *out_buf,
  1997. size_t out_cap,
  1998. size_t *out_len) {
  1999. if (out_len) *out_len = 0;
  2000. if (out_buf && out_cap > 0) out_buf[0] = '\0';
  2001. StlIpmiSlot *slot = get_ipmi_slot(handle);
  2002. if (!slot || !kind || !out_buf || out_cap < 2) return -1;
  2003. pthread_mutex_lock(&slot->mu);
  2004. if (!slot->in_use || !slot->ctx) {
  2005. pthread_mutex_unlock(&slot->mu);
  2006. return -1;
  2007. }
  2008. size_t used = 0;
  2009. int rc = 0;
  2010. if (strcmp(kind, "mc") == 0) {
  2011. fiid_obj_t rs = fiid_obj_create(tmpl_cmd_get_device_id_rs);
  2012. if (!rs || ipmi_cmd_get_device_id(slot->ctx, rs) != 0) {
  2013. rc = -1;
  2014. } else {
  2015. uint64_t did = 0, drev = 0, fw1 = 0, fw2 = 0, imaj = 0, imin = 0, mfg = 0, pid = 0;
  2016. (void)fiid_obj_get(rs, "device_id", &did);
  2017. (void)fiid_obj_get(rs, "device_revision.revision", &drev);
  2018. (void)fiid_obj_get(rs, "firmware_revision1.major_revision", &fw1);
  2019. (void)fiid_obj_get(rs, "firmware_revision2.minor_revision", &fw2);
  2020. (void)fiid_obj_get(rs, "ipmi_version_major", &imaj);
  2021. (void)fiid_obj_get(rs, "ipmi_version_minor", &imin);
  2022. (void)fiid_obj_get(rs, "manufacturer_id.id", &mfg);
  2023. (void)fiid_obj_get(rs, "product_id", &pid);
  2024. char tmp[512];
  2025. snprintf(
  2026. tmp, sizeof(tmp),
  2027. "Device ID : %llu\n"
  2028. "Device Revision : %llu\n"
  2029. "Firmware Revision : %llu.%02llx\n"
  2030. "IPMI Version : %llu.%llu\n"
  2031. "Manufacturer ID : %llu\n"
  2032. "Product ID : %llu\n",
  2033. (unsigned long long)did,
  2034. (unsigned long long)drev,
  2035. (unsigned long long)fw1, (unsigned long long)fw2,
  2036. (unsigned long long)imaj, (unsigned long long)imin,
  2037. (unsigned long long)mfg,
  2038. (unsigned long long)pid);
  2039. append_str(out_buf, out_cap, &used, tmp);
  2040. }
  2041. if (rs) fiid_obj_destroy(rs);
  2042. } else if (strcmp(kind, "lan") == 0) {
  2043. uint8_t ip4[4] = {0}, mask4[4] = {0}, gw4[4] = {0}, mac6[6] = {0};
  2044. uint64_t src = 0;
  2045. int got_lan = 0;
  2046. uint8_t chs[2] = { 1, 8 };
  2047. for (int ci = 0; ci < 2 && !got_lan; ci++) {
  2048. uint8_t ch = chs[ci];
  2049. fiid_obj_t rs_ip = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_ip_address_rs);
  2050. if (rs_ip &&
  2051. ipmi_cmd_get_lan_configuration_parameters_ip_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_ip) == 0 &&
  2052. fiid_obj_get_data(rs_ip, "ip_address", ip4, sizeof(ip4)) == 4) {
  2053. got_lan = 1;
  2054. fiid_obj_t rs_m = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_subnet_mask_rs);
  2055. if (rs_m &&
  2056. ipmi_cmd_get_lan_configuration_parameters_subnet_mask(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_m) == 0) {
  2057. (void)fiid_obj_get_data(rs_m, "subnet_mask", mask4, sizeof(mask4));
  2058. }
  2059. if (rs_m) fiid_obj_destroy(rs_m);
  2060. fiid_obj_t rs_gw = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_default_gateway_address_rs);
  2061. if (rs_gw &&
  2062. ipmi_cmd_get_lan_configuration_parameters_default_gateway_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_gw) == 0) {
  2063. (void)fiid_obj_get_data(rs_gw, "ip_address", gw4, sizeof(gw4));
  2064. }
  2065. if (rs_gw) fiid_obj_destroy(rs_gw);
  2066. fiid_obj_t rs_mac = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_mac_address_rs);
  2067. if (rs_mac &&
  2068. ipmi_cmd_get_lan_configuration_parameters_mac_address(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_mac) == 0) {
  2069. (void)fiid_obj_get_data(rs_mac, "mac_address", mac6, sizeof(mac6));
  2070. }
  2071. if (rs_mac) fiid_obj_destroy(rs_mac);
  2072. fiid_obj_t rs_s = fiid_obj_create(tmpl_cmd_get_lan_configuration_parameters_ip_address_source_rs);
  2073. if (rs_s &&
  2074. ipmi_cmd_get_lan_configuration_parameters_ip_address_source(slot->ctx, ch, IPMI_GET_LAN_PARAMETER, 0, 0, rs_s) == 0) {
  2075. (void)fiid_obj_get(rs_s, "ip_address_source", &src);
  2076. }
  2077. if (rs_s) fiid_obj_destroy(rs_s);
  2078. char tmp[512];
  2079. const char *src_s = (src == 1) ? "Static Address" : (src == 2) ? "DHCP Address" : "Other";
  2080. snprintf(
  2081. tmp, sizeof(tmp),
  2082. "LAN Channel : %u\n"
  2083. "IP Address Source : %s\n"
  2084. "IP Address : %u.%u.%u.%u\n"
  2085. "Subnet Mask : %u.%u.%u.%u\n"
  2086. "MAC Address : %02x:%02x:%02x:%02x:%02x:%02x\n"
  2087. "Default Gateway IP : %u.%u.%u.%u\n",
  2088. (unsigned)ch, src_s,
  2089. ip4[0], ip4[1], ip4[2], ip4[3],
  2090. mask4[0], mask4[1], mask4[2], mask4[3],
  2091. mac6[0], mac6[1], mac6[2], mac6[3], mac6[4], mac6[5],
  2092. gw4[0], gw4[1], gw4[2], gw4[3]);
  2093. append_str(out_buf, out_cap, &used, tmp);
  2094. }
  2095. if (rs_ip) fiid_obj_destroy(rs_ip);
  2096. }
  2097. if (!got_lan) rc = -1;
  2098. } else if (strcmp(kind, "sel") == 0) {
  2099. ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create();
  2100. if (sdr && ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
  2101. ipmi_sdr_ctx_destroy(sdr);
  2102. sdr = NULL;
  2103. }
  2104. ipmi_sel_ctx_t sel = ipmi_sel_ctx_create(slot->ctx, sdr);
  2105. if (!sel) {
  2106. rc = -1;
  2107. } else {
  2108. SelIterCtx sc = { .out_buf = out_buf, .out_cap = out_cap, .used = 0, .count = 0 };
  2109. if (ipmi_sel_parse(sel, IPMI_SEL_RECORD_ID_FIRST, IPMI_SEL_RECORD_ID_LAST, sel_iterate_cb, &sc) < 0) {
  2110. rc = -1;
  2111. } else {
  2112. used = sc.used;
  2113. if (sc.count == 0) {
  2114. append_str(out_buf, out_cap, &used, "SEL has no entries\n");
  2115. }
  2116. }
  2117. ipmi_sel_ctx_destroy(sel);
  2118. }
  2119. if (sdr) {
  2120. (void)ipmi_sdr_cache_close(sdr);
  2121. ipmi_sdr_ctx_destroy(sdr);
  2122. }
  2123. } else if (strcmp(kind, "fru") == 0) {
  2124. ipmi_fru_ctx_t fru = ipmi_fru_ctx_create(slot->ctx);
  2125. if (!fru || ipmi_fru_open_device_id(fru, 0) != 0) {
  2126. if (fru) ipmi_fru_ctx_destroy(fru);
  2127. rc = -1;
  2128. } else {
  2129. uint8_t areabuf[4096];
  2130. int has_any = 0;
  2131. int has = (ipmi_fru_first(fru) == 0);
  2132. while (has) {
  2133. unsigned int atype = 0, alen = 0;
  2134. if (ipmi_fru_read_data_area(fru, &atype, &alen, areabuf, sizeof(areabuf)) == 0) {
  2135. if (atype == IPMI_FRU_AREA_TYPE_BOARD_INFO_AREA) {
  2136. uint8_t lang = 0;
  2137. uint32_t mfg_ts = 0;
  2138. ipmi_fru_field_t bm, bn, bs, bp, bf;
  2139. memset(&bm, 0, sizeof(bm)); memset(&bn, 0, sizeof(bn));
  2140. memset(&bs, 0, sizeof(bs)); memset(&bp, 0, sizeof(bp));
  2141. memset(&bf, 0, sizeof(bf));
  2142. if (ipmi_fru_board_info_area(fru, areabuf, alen, &lang, &mfg_ts, &bm, &bn, &bs, &bp, &bf, NULL, 0) == 0) {
  2143. has_any = 1;
  2144. append_fru_field(fru, "Board Mfg", &bm, lang, out_buf, out_cap, &used);
  2145. append_fru_field(fru, "Board Product", &bn, lang, out_buf, out_cap, &used);
  2146. append_fru_field(fru, "Board Serial", &bs, lang, out_buf, out_cap, &used);
  2147. append_fru_field(fru, "Board Part Number", &bp, lang, out_buf, out_cap, &used);
  2148. }
  2149. } else if (atype == IPMI_FRU_AREA_TYPE_PRODUCT_INFO_AREA) {
  2150. uint8_t lang = 0;
  2151. ipmi_fru_field_t pm, pn, pp, pv, ps, pa, pf;
  2152. memset(&pm, 0, sizeof(pm)); memset(&pn, 0, sizeof(pn));
  2153. memset(&pp, 0, sizeof(pp)); memset(&pv, 0, sizeof(pv));
  2154. memset(&ps, 0, sizeof(ps)); memset(&pa, 0, sizeof(pa));
  2155. memset(&pf, 0, sizeof(pf));
  2156. if (ipmi_fru_product_info_area(fru, areabuf, alen, &lang, &pm, &pn, &pp, &pv, &ps, &pa, &pf, NULL, 0) == 0) {
  2157. has_any = 1;
  2158. append_fru_field(fru, "Product Manufacturer", &pm, lang, out_buf, out_cap, &used);
  2159. append_fru_field(fru, "Product Name", &pn, lang, out_buf, out_cap, &used);
  2160. append_fru_field(fru, "Product Part Number", &pp, lang, out_buf, out_cap, &used);
  2161. append_fru_field(fru, "Product Version", &pv, lang, out_buf, out_cap, &used);
  2162. append_fru_field(fru, "Product Serial", &ps, lang, out_buf, out_cap, &used);
  2163. append_fru_field(fru, "Product Asset Tag", &pa, lang, out_buf, out_cap, &used);
  2164. }
  2165. }
  2166. }
  2167. int nxt = ipmi_fru_next(fru);
  2168. if (nxt != 1) break;
  2169. }
  2170. (void)ipmi_fru_close_device_id(fru);
  2171. ipmi_fru_ctx_destroy(fru);
  2172. if (!has_any) append_str(out_buf, out_cap, &used, "FRU empty\n");
  2173. }
  2174. } else if (strcmp(kind, "sol") == 0) {
  2175. uint8_t chs[2] = { 1, 8 };
  2176. int got_sol = 0;
  2177. for (int ci = 0; ci < 2 && !got_sol; ci++) {
  2178. uint8_t ch = chs[ci];
  2179. uint8_t rq_en[4] = { 0x22, ch, 0x01, 0x00 }; /* Get SOL Config Param: Enable */
  2180. uint8_t rs_en[16];
  2181. int rl = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_en, sizeof(rq_en), rs_en, sizeof(rs_en));
  2182. if (rl >= 4 && rs_en[1] == 0x00) {
  2183. got_sol = 1;
  2184. int enabled = (rs_en[3] & 0x01) ? 1 : 0;
  2185. uint8_t rq_auth[4] = { 0x22, ch, 0x02, 0x00 };
  2186. uint8_t rs_auth[16];
  2187. int rla = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_auth, sizeof(rq_auth), rs_auth, sizeof(rs_auth));
  2188. uint8_t rq_br[4] = { 0x22, ch, 0x05, 0x00 };
  2189. uint8_t rs_br[16];
  2190. int rlb = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_br, sizeof(rq_br), rs_br, sizeof(rs_br));
  2191. const char *baud_s = "default";
  2192. if (rlb >= 4 && rs_br[1] == 0x00) {
  2193. switch (rs_br[3] & 0x0F) {
  2194. case 0x06: baud_s = "9600"; break;
  2195. case 0x07: baud_s = "19200"; break;
  2196. case 0x08: baud_s = "38400"; break;
  2197. case 0x09: baud_s = "57600"; break;
  2198. case 0x0A: baud_s = "115200"; break;
  2199. default: baud_s = "serial-default"; break;
  2200. }
  2201. }
  2202. char tmp[320];
  2203. snprintf(
  2204. tmp, sizeof(tmp),
  2205. "SOL Channel : %u\n"
  2206. "Enabled : %s\n"
  2207. "Force Encryption : %s\n"
  2208. "Force Authentication : %s\n"
  2209. "Non-Volatile Bit Rate : %s\n",
  2210. (unsigned)ch,
  2211. enabled ? "true" : "false",
  2212. (rla >= 4 && rs_auth[1] == 0x00 && (rs_auth[3] & 0x80)) ? "true" : "false",
  2213. (rla >= 4 && rs_auth[1] == 0x00 && (rs_auth[3] & 0x40)) ? "true" : "false",
  2214. baud_s);
  2215. append_str(out_buf, out_cap, &used, tmp);
  2216. }
  2217. }
  2218. if (!got_sol) {
  2219. append_str(out_buf, out_cap, &used, "SOL configuration not reported by BMC (NetFn 0x0C Cmd 0x22)\n");
  2220. }
  2221. } else if (strcmp(kind, "sessions") == 0) {
  2222. uint8_t rq[2] = { 0x3D, 0x00 }; /* App NetFn 0x06, Get Session Info (current active session) */
  2223. uint8_t rs[64];
  2224. int rl = ipmi_cmd_raw(slot->ctx, 0, 0x06, rq, sizeof(rq), rs, sizeof(rs));
  2225. if (rl >= 6 && rs[1] == 0x00) {
  2226. char tmp[320];
  2227. snprintf(
  2228. tmp, sizeof(tmp),
  2229. "Session Handle : 0x%02X\n"
  2230. "Session Slots Total : %u\n"
  2231. "Active Sessions : %u\n"
  2232. "Current User ID : %u\n"
  2233. "Current Privilege Level : %u\n",
  2234. (unsigned)rs[2],
  2235. (unsigned)(rs[3] & 0x3F),
  2236. (unsigned)(rs[4] & 0x3F),
  2237. (unsigned)(rs[5] & 0x3F),
  2238. (unsigned)(rl >= 7 ? (rs[6] & 0x0F) : 0));
  2239. append_str(out_buf, out_cap, &used, tmp);
  2240. } else {
  2241. append_str(out_buf, out_cap, &used, "BMC did not return active session table (NetFn 0x06 Cmd 0x3D)\n");
  2242. }
  2243. } else if (strcmp(kind, "events") == 0) {
  2244. fiid_obj_t rs_info = fiid_obj_create(tmpl_cmd_get_sel_info_rs);
  2245. if (rs_info && ipmi_cmd_get_sel_info(slot->ctx, rs_info) == 0) {
  2246. uint64_t entries = 0, free_sp = 0, ovf = 0;
  2247. (void)fiid_obj_get(rs_info, "entries", &entries);
  2248. (void)fiid_obj_get(rs_info, "free_space", &free_sp);
  2249. (void)fiid_obj_get(rs_info, "overflow_flag", &ovf);
  2250. char hdr[256];
  2251. snprintf(
  2252. hdr, sizeof(hdr),
  2253. "SEL Entries : %llu\n"
  2254. "SEL Free Space (bytes) : %llu\n"
  2255. "SEL Overflow : %s\n",
  2256. (unsigned long long)entries,
  2257. (unsigned long long)free_sp,
  2258. ovf ? "true" : "false");
  2259. append_str(out_buf, out_cap, &used, hdr);
  2260. }
  2261. if (rs_info) fiid_obj_destroy(rs_info);
  2262. ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create();
  2263. if (sdr && ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
  2264. ipmi_sdr_ctx_destroy(sdr);
  2265. sdr = NULL;
  2266. }
  2267. ipmi_sel_ctx_t sel = ipmi_sel_ctx_create(slot->ctx, sdr);
  2268. if (sel) {
  2269. SelIterCtx sc = { .out_buf = out_buf, .out_cap = out_cap, .used = used, .count = 0 };
  2270. if (ipmi_sel_parse(sel, IPMI_SEL_RECORD_ID_FIRST, IPMI_SEL_RECORD_ID_LAST, sel_iterate_cb, &sc) >= 0) {
  2271. used = sc.used;
  2272. if (sc.count == 0) {
  2273. append_str(out_buf, out_cap, &used, "No SEL event records\n");
  2274. }
  2275. }
  2276. ipmi_sel_ctx_destroy(sel);
  2277. }
  2278. if (sdr) {
  2279. (void)ipmi_sdr_cache_close(sdr);
  2280. ipmi_sdr_ctx_destroy(sdr);
  2281. }
  2282. } else if (strcmp(kind, "fan_mode") == 0) {
  2283. /* Try Supermicro / Intel / AMI OEM Get Fan Mode first (0x30 0x45 0x00) */
  2284. uint8_t rq[2] = { 0x45, 0x00 };
  2285. uint8_t rs[16];
  2286. int rl = ipmi_cmd_raw(slot->ctx, 0, 0x30, rq, sizeof(rq), rs, sizeof(rs));
  2287. if (rl >= 3 && rs[1] == 0x00) {
  2288. const char *mode_s = "unknown";
  2289. switch (rs[2]) {
  2290. case 0x00: mode_s = "Standard (0x00)"; break;
  2291. case 0x01: mode_s = "Full (0x01)"; break;
  2292. case 0x02: mode_s = "Optimal (0x02)"; break;
  2293. case 0x04: mode_s = "HeavyIO (0x04)"; break;
  2294. default: mode_s = "Custom/Manual"; break;
  2295. }
  2296. char tmp[160];
  2297. snprintf(tmp, sizeof(tmp), "BMC Fan Mode : %s (raw=0x%02X)\n", mode_s, (unsigned)rs[2]);
  2298. append_str(out_buf, out_cap, &used, tmp);
  2299. } else {
  2300. /* Standard IPMI does not expose a vendor-neutral fan-mode getter; report real status cleanly */
  2301. append_str(out_buf, out_cap, &used,
  2302. "BMC Fan Mode : OEM readback unsupported (use manual fan_low_speed_on/off or inspect Fan RPM sensors)\n");
  2303. }
  2304. } else {
  2305. rc = -1;
  2306. }
  2307. if (rc < 0) slot->alive = 0;
  2308. pthread_mutex_unlock(&slot->mu);
  2309. if (out_len) *out_len = used;
  2310. return rc;
  2311. }
  2312. int stl_free_disk_bytes(const char *path, uint64_t *out_avail_bytes) {
  2313. if (!path || !path[0] || !out_avail_bytes) return -1;
  2314. struct statvfs st;
  2315. if (statvfs(path, &st) != 0) return -1;
  2316. *out_avail_bytes = (uint64_t)st.f_bavail * (uint64_t)st.f_frsize;
  2317. return 0;
  2318. }
  2319. void stl_set_thread_idle_priority(void) {
  2320. #ifdef SCHED_IDLE
  2321. struct sched_param sp;
  2322. memset(&sp, 0, sizeof(sp));
  2323. if (pthread_setschedparam(pthread_self(), SCHED_IDLE, &sp) != 0) {
  2324. (void)setpriority(PRIO_PROCESS, 0, 19);
  2325. }
  2326. #else
  2327. (void)setpriority(PRIO_PROCESS, 0, 19);
  2328. #endif
  2329. }
  2330. int stl_chmod_0600(const char *path) {
  2331. if (!path || !path[0]) return -1;
  2332. return chmod(path, 0600);
  2333. }
  2334. uint64_t stl_mono_us(void) {
  2335. struct timespec ts;
  2336. if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0;
  2337. return (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)(ts.tv_nsec / 1000L);
  2338. }
  2339. uint64_t stl_mem_diff_64b_mask(const uint8_t *a, const uint8_t *b, size_t len) {
  2340. int tier = stl_active_isa_tier();
  2341. if (tier >= STL_ISA_AVX512) {
  2342. return simd_mem_diff_64b_avx512(a, b, len);
  2343. }
  2344. if (tier >= STL_ISA_AVX2_BMI) {
  2345. return simd_mem_diff_64b_avx2(a, b, len);
  2346. }
  2347. if (tier >= STL_ISA_SSE42_PCLMUL) {
  2348. return simd_mem_diff_64b_sse42(a, b, len);
  2349. }
  2350. return simd_mem_diff_64b_sse2(a, b, len);
  2351. }
  2352. void stl_batch_mem_diff_64b_masks(
  2353. const uint8_t *prev_base,
  2354. const uint8_t *cur_base,
  2355. size_t stride,
  2356. size_t item_len,
  2357. size_t count,
  2358. uint64_t *out_masks) {
  2359. if (!prev_base || !cur_base || !out_masks || count == 0 || item_len == 0 || stride < item_len) {
  2360. return;
  2361. }
  2362. int tier = stl_active_isa_tier();
  2363. if (tier >= STL_ISA_AVX512) {
  2364. for (size_t i = 0; i < count; i++) {
  2365. out_masks[i] = simd_mem_diff_64b_avx512(prev_base + i * stride, cur_base + i * stride, item_len);
  2366. }
  2367. } else if (tier >= STL_ISA_AVX2_BMI) {
  2368. for (size_t i = 0; i < count; i++) {
  2369. out_masks[i] = simd_mem_diff_64b_avx2(prev_base + i * stride, cur_base + i * stride, item_len);
  2370. }
  2371. } else if (tier >= STL_ISA_SSE42_PCLMUL) {
  2372. for (size_t i = 0; i < count; i++) {
  2373. out_masks[i] = simd_mem_diff_64b_sse42(prev_base + i * stride, cur_base + i * stride, item_len);
  2374. }
  2375. } else {
  2376. for (size_t i = 0; i < count; i++) {
  2377. out_masks[i] = simd_mem_diff_64b_sse2(prev_base + i * stride, cur_base + i * stride, item_len);
  2378. }
  2379. }
  2380. }
  2381. /* =========================================================================
  2382. * 7. Multi-NIC IPv4 Enumeration & IP_PKTINFO Broadcast UDP Helpers (ProxyDHCP)
  2383. * ========================================================================= */
  2384. int c_list_ipv4_ifaces(StlNetIface *out_list, int max_count) {
  2385. if (!out_list || max_count <= 0) return -1;
  2386. struct ifaddrs *ifas = NULL;
  2387. if (getifaddrs(&ifas) != 0 || !ifas) return -1;
  2388. int io_fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  2389. int n = 0;
  2390. for (struct ifaddrs *ifa = ifas; ifa != NULL && n < max_count; ifa = ifa->ifa_next) {
  2391. if (!ifa->ifa_name || !ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) {
  2392. continue;
  2393. }
  2394. StlNetIface *dst = &out_list[n];
  2395. memset(dst, 0, sizeof(*dst));
  2396. snprintf(dst->name, sizeof(dst->name), "%s", ifa->ifa_name);
  2397. const struct sockaddr_in *sin = (const struct sockaddr_in *)ifa->ifa_addr;
  2398. dst->ip_be = sin->sin_addr.s_addr;
  2399. if (ifa->ifa_netmask && ifa->ifa_netmask->sa_family == AF_INET) {
  2400. const struct sockaddr_in *sm = (const struct sockaddr_in *)ifa->ifa_netmask;
  2401. dst->mask_be = sm->sin_addr.s_addr;
  2402. }
  2403. if (ifa->ifa_ifu.ifu_broadaddr && ifa->ifa_ifu.ifu_broadaddr->sa_family == AF_INET &&
  2404. (ifa->ifa_flags & IFF_BROADCAST)) {
  2405. const struct sockaddr_in *sb = (const struct sockaddr_in *)ifa->ifa_ifu.ifu_broadaddr;
  2406. dst->bcast_be = sb->sin_addr.s_addr;
  2407. } else {
  2408. dst->bcast_be = dst->ip_be | (~dst->mask_be);
  2409. }
  2410. dst->ifindex = if_nametoindex(ifa->ifa_name);
  2411. dst->is_up = (ifa->ifa_flags & IFF_UP) ? 1 : 0;
  2412. dst->is_loopback = (ifa->ifa_flags & IFF_LOOPBACK) ? 1 : 0;
  2413. if (io_fd >= 0) {
  2414. struct ifreq ifr;
  2415. memset(&ifr, 0, sizeof(ifr));
  2416. snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifa->ifa_name);
  2417. if (ioctl(io_fd, SIOCGIFHWADDR, &ifr) == 0) {
  2418. memcpy(dst->mac, ifr.ifr_hwaddr.sa_data, 6);
  2419. }
  2420. }
  2421. n++;
  2422. }
  2423. if (io_fd >= 0) close(io_fd);
  2424. freeifaddrs(ifas);
  2425. return n;
  2426. }
  2427. int c_udp_bind_dhcp_socket(const char *iface, int port, int reuse_port) {
  2428. if (port < 0 || port > 65535) return -1;
  2429. int fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  2430. if (fd < 0) return -1;
  2431. int one = 1;
  2432. (void)setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  2433. #ifdef SO_REUSEPORT
  2434. if (reuse_port) {
  2435. (void)setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
  2436. }
  2437. #endif
  2438. (void)setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));
  2439. (void)setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &one, sizeof(one));
  2440. if (iface && iface[0] != '\0') {
  2441. size_t ilen = strlen(iface);
  2442. if (ilen < IFNAMSIZ) {
  2443. /* Best effort: requires CAP_NET_RAW; if EPERM, keep INADDR_ANY and filter by ifindex in userspace */
  2444. (void)setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface, (socklen_t)(ilen + 1));
  2445. }
  2446. }
  2447. struct sockaddr_in addr;
  2448. memset(&addr, 0, sizeof(addr));
  2449. addr.sin_family = AF_INET;
  2450. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  2451. addr.sin_port = htons((uint16_t)port);
  2452. if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
  2453. close(fd);
  2454. return -1;
  2455. }
  2456. return fd;
  2457. }
  2458. ssize_t c_udp_recv_pktinfo(
  2459. int fd,
  2460. uint8_t *buf,
  2461. size_t cap,
  2462. uint32_t *out_peer_ip_be,
  2463. uint16_t *out_peer_port,
  2464. uint32_t *out_local_ip_be,
  2465. uint32_t *out_ifindex) {
  2466. if (fd < 0 || !buf || cap == 0) return -1;
  2467. if (out_peer_ip_be) *out_peer_ip_be = 0;
  2468. if (out_peer_port) *out_peer_port = 0;
  2469. if (out_local_ip_be) *out_local_ip_be = 0;
  2470. if (out_ifindex) *out_ifindex = 0;
  2471. struct sockaddr_in peer;
  2472. memset(&peer, 0, sizeof(peer));
  2473. struct iovec iov = { .iov_base = buf, .iov_len = cap };
  2474. uint8_t cbuf[256];
  2475. struct msghdr msg;
  2476. memset(&msg, 0, sizeof(msg));
  2477. msg.msg_name = &peer;
  2478. msg.msg_namelen = sizeof(peer);
  2479. msg.msg_iov = &iov;
  2480. msg.msg_iovlen = 1;
  2481. msg.msg_control = cbuf;
  2482. msg.msg_controllen = sizeof(cbuf);
  2483. ssize_t n = recvmsg(fd, &msg, 0);
  2484. if (n < 0) {
  2485. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
  2486. return -1;
  2487. }
  2488. if (out_peer_ip_be) *out_peer_ip_be = peer.sin_addr.s_addr;
  2489. if (out_peer_port) *out_peer_port = ntohs(peer.sin_port);
  2490. for (struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); cm != NULL; cm = CMSG_NXTHDR(&msg, cm)) {
  2491. if (cm->cmsg_level == IPPROTO_IP && cm->cmsg_type == IP_PKTINFO &&
  2492. cm->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo))) {
  2493. struct in_pktinfo pi;
  2494. memcpy(&pi, CMSG_DATA(cm), sizeof(pi));
  2495. if (out_local_ip_be) *out_local_ip_be = pi.ipi_spec_dst.s_addr;
  2496. if (out_ifindex) *out_ifindex = (uint32_t)pi.ipi_ifindex;
  2497. break;
  2498. }
  2499. }
  2500. return n;
  2501. }
  2502. ssize_t c_udp_send_pktinfo(
  2503. int fd,
  2504. const uint8_t *buf,
  2505. size_t len,
  2506. uint32_t dst_ip_be,
  2507. uint16_t dst_port,
  2508. uint32_t src_ip_be,
  2509. uint32_t ifindex) {
  2510. if (fd < 0 || !buf || len == 0) return -1;
  2511. struct sockaddr_in dst;
  2512. memset(&dst, 0, sizeof(dst));
  2513. dst.sin_family = AF_INET;
  2514. dst.sin_addr.s_addr = dst_ip_be;
  2515. dst.sin_port = htons(dst_port);
  2516. struct iovec iov = { .iov_base = (void *)buf, .iov_len = len };
  2517. uint8_t cbuf[CMSG_SPACE(sizeof(struct in_pktinfo))];
  2518. memset(cbuf, 0, sizeof(cbuf));
  2519. struct msghdr msg;
  2520. memset(&msg, 0, sizeof(msg));
  2521. msg.msg_name = &dst;
  2522. msg.msg_namelen = sizeof(dst);
  2523. msg.msg_iov = &iov;
  2524. msg.msg_iovlen = 1;
  2525. if (ifindex > 0 || src_ip_be != 0) {
  2526. msg.msg_control = cbuf;
  2527. msg.msg_controllen = sizeof(cbuf);
  2528. struct cmsghdr *cm = CMSG_FIRSTHDR(&msg);
  2529. cm->cmsg_level = IPPROTO_IP;
  2530. cm->cmsg_type = IP_PKTINFO;
  2531. cm->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
  2532. struct in_pktinfo pi;
  2533. memset(&pi, 0, sizeof(pi));
  2534. pi.ipi_ifindex = (int)ifindex;
  2535. pi.ipi_spec_dst.s_addr = src_ip_be;
  2536. memcpy(CMSG_DATA(cm), &pi, sizeof(pi));
  2537. }
  2538. ssize_t n = sendmsg(fd, &msg, MSG_NOSIGNAL);
  2539. if (n < 0 && (ifindex > 0 || src_ip_be != 0)) {
  2540. /* Fallback without IP_PKTINFO if routing table rejects pinned spec_dst (e.g. loopback tests) */
  2541. msg.msg_control = NULL;
  2542. msg.msg_controllen = 0;
  2543. n = sendmsg(fd, &msg, MSG_NOSIGNAL);
  2544. }
  2545. return n;
  2546. }