libbb.h 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Busybox main internal header file
  4. *
  5. * Based in part on code from sash, Copyright (c) 1999 by David I. Bell
  6. * Permission has been granted to redistribute this code under GPL.
  7. *
  8. * Licensed under GPLv2, see file LICENSE in this source tree.
  9. */
  10. #ifndef LIBBB_H
  11. #define LIBBB_H 1
  12. #include "platform.h"
  13. #include <ctype.h>
  14. #include <dirent.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <inttypes.h>
  18. #include <netdb.h>
  19. #include <setjmp.h>
  20. #include <signal.h>
  21. #include <paths.h>
  22. #if defined __UCLIBC__ /* TODO: and glibc? */
  23. /* use inlined versions of these: */
  24. # define sigfillset(s) __sigfillset(s)
  25. # define sigemptyset(s) __sigemptyset(s)
  26. # define sigisemptyset(s) __sigisemptyset(s)
  27. #endif
  28. #include <stdint.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <stdarg.h>
  32. #include <stddef.h>
  33. #include <string.h>
  34. /* There are two incompatible basename's, let's not use them! */
  35. /* See the dirname/basename man page for details */
  36. #include <libgen.h> /* dirname,basename */
  37. #undef basename
  38. #define basename dont_use_basename
  39. #include <poll.h>
  40. #include <sys/ioctl.h>
  41. #include <sys/mman.h>
  42. #include <sys/resource.h>
  43. #include <sys/socket.h>
  44. #include <sys/stat.h>
  45. #include <sys/time.h>
  46. #include <sys/types.h>
  47. #if !defined(major) || defined(__GLIBC__)
  48. # include <sys/sysmacros.h>
  49. #endif
  50. #include <sys/wait.h>
  51. #include <termios.h>
  52. #include <time.h>
  53. #include <sys/param.h>
  54. #include <pwd.h>
  55. #include <grp.h>
  56. #if ENABLE_FEATURE_SHADOWPASSWDS
  57. # if !ENABLE_USE_BB_SHADOW
  58. /* If using busybox's shadow implementation, do not include the shadow.h
  59. * header as the toolchain may not provide it at all.
  60. */
  61. # include <shadow.h>
  62. # endif
  63. #endif
  64. #if defined(ANDROID) || defined(__ANDROID__)
  65. # define endpwent() ((void)0)
  66. # define endgrent() ((void)0)
  67. #endif
  68. #ifdef HAVE_MNTENT_H
  69. # include <mntent.h>
  70. #endif
  71. #ifdef HAVE_SYS_STATFS_H
  72. # include <sys/statfs.h>
  73. #endif
  74. /* Don't do this here:
  75. * #include <sys/sysinfo.h>
  76. * Some linux/ includes pull in conflicting definition
  77. * of struct sysinfo (only in some toolchanins), which breaks build.
  78. * Include sys/sysinfo.h only in those files which need it.
  79. */
  80. #if ENABLE_SELINUX
  81. # include <selinux/selinux.h>
  82. # include <selinux/context.h>
  83. #endif
  84. #if ENABLE_FEATURE_UTMP
  85. # if defined __UCLIBC__ && ( \
  86. (UCLIBC_VERSION >= KERNEL_VERSION(0, 9, 32) \
  87. && UCLIBC_VERSION < KERNEL_VERSION(0, 9, 34) \
  88. && defined __UCLIBC_HAS_UTMPX__ \
  89. ) || ( \
  90. UCLIBC_VERSION >= KERNEL_VERSION(0, 9, 34) \
  91. ) \
  92. )
  93. # include <utmpx.h>
  94. # elif defined __UCLIBC__
  95. # include <utmp.h>
  96. # define utmpx utmp
  97. # define setutxent setutent
  98. # define endutxent endutent
  99. # define getutxent getutent
  100. # define getutxid getutid
  101. # define getutxline getutline
  102. # define pututxline pututline
  103. # define utmpxname utmpname
  104. # define updwtmpx updwtmp
  105. # define _PATH_UTMPX _PATH_UTMP
  106. # else
  107. # if !defined(__FreeBSD__)
  108. # include <utmp.h>
  109. # else
  110. # define _PATH_UTMPX "/var/run/utx.active"
  111. # endif
  112. # include <utmpx.h>
  113. # if defined _PATH_UTMP && !defined _PATH_UTMPX
  114. # define _PATH_UTMPX _PATH_UTMP
  115. # endif
  116. # endif
  117. #endif
  118. #if ENABLE_LOCALE_SUPPORT
  119. # include <locale.h>
  120. #else
  121. # define setlocale(x,y) ((void)0)
  122. #endif
  123. #ifdef DMALLOC
  124. # include <dmalloc.h>
  125. #endif
  126. /* Just in case libc doesn't define some of these... */
  127. #ifndef _PATH_PASSWD
  128. #define _PATH_PASSWD "/etc/passwd"
  129. #endif
  130. #ifndef _PATH_GROUP
  131. #define _PATH_GROUP "/etc/group"
  132. #endif
  133. #ifndef _PATH_SHADOW
  134. #define _PATH_SHADOW "/etc/shadow"
  135. #endif
  136. #ifndef _PATH_GSHADOW
  137. #define _PATH_GSHADOW "/etc/gshadow"
  138. #endif
  139. #if defined __FreeBSD__ || defined __OpenBSD__
  140. # include <netinet/in.h>
  141. # include <arpa/inet.h>
  142. #elif defined __APPLE__
  143. # include <netinet/in.h>
  144. #else
  145. # include <arpa/inet.h>
  146. //This breaks on bionic:
  147. //# if !defined(__socklen_t_defined) && !defined(_SOCKLEN_T_DECLARED)
  148. ///* We #define socklen_t *after* includes, otherwise we get
  149. // * typedef redefinition errors from system headers
  150. // * (in case "is it defined already" detection above failed)
  151. // */
  152. //# define socklen_t bb_socklen_t
  153. // typedef unsigned socklen_t;
  154. //# endif
  155. //if this is still needed, add a fix along the lines of
  156. // ifdef SPECIFIC_BROKEN_LIBC_CHECK / typedef socklen_t / endif
  157. //in platform.h instead!
  158. #endif
  159. #ifndef HAVE_CLEARENV
  160. # define clearenv() do { if (environ) environ[0] = NULL; } while (0)
  161. #endif
  162. #ifndef HAVE_FDATASYNC
  163. # define fdatasync fsync
  164. #endif
  165. #ifndef HAVE_XTABS
  166. # define XTABS TAB3
  167. #endif
  168. /*
  169. * Use '%m' to append error string on platforms that support it,
  170. * '%s' and strerror() on those that don't.
  171. */
  172. #ifdef HAVE_PRINTF_PERCENTM
  173. # define STRERROR_FMT "%m"
  174. # define STRERROR_ERRNO /*nothing*/
  175. #else
  176. # define STRERROR_FMT "%s"
  177. # define STRERROR_ERRNO ,strerror(errno)
  178. #endif
  179. /* Some libc's forget to declare these, do it ourself */
  180. extern char **environ;
  181. /* klogctl is in libc's klog.h, but we cheat and not #include that */
  182. int klogctl(int type, char *b, int len);
  183. #ifndef PATH_MAX
  184. # define PATH_MAX 256
  185. #endif
  186. #ifndef BUFSIZ
  187. # define BUFSIZ 4096
  188. #endif
  189. /* Busybox does not use threads, we can speed up stdio. */
  190. #ifdef HAVE_UNLOCKED_STDIO
  191. # undef getc
  192. # define getc(stream) getc_unlocked(stream)
  193. # undef getchar
  194. # define getchar() getchar_unlocked()
  195. # undef putc
  196. # define putc(c,stream) putc_unlocked(c,stream)
  197. # undef putchar
  198. # define putchar(c) putchar_unlocked(c)
  199. # undef fgetc
  200. # define fgetc(stream) getc_unlocked(stream)
  201. # undef fputc
  202. # define fputc(c,stream) putc_unlocked(c,stream)
  203. #endif
  204. /* Above functions are required by POSIX.1-2008, below ones are extensions */
  205. #ifdef HAVE_UNLOCKED_LINE_OPS
  206. # undef fgets
  207. # define fgets(s,n,stream) fgets_unlocked(s,n,stream)
  208. # undef fputs
  209. # define fputs(s,stream) fputs_unlocked(s,stream)
  210. /* musl <= 1.1.15 does not support fflush_unlocked(NULL) */
  211. //# undef fflush
  212. //# define fflush(stream) fflush_unlocked(stream)
  213. # undef feof
  214. # define feof(stream) feof_unlocked(stream)
  215. # undef ferror
  216. # define ferror(stream) ferror_unlocked(stream)
  217. # undef fileno
  218. # define fileno(stream) fileno_unlocked(stream)
  219. #endif
  220. /* Make all declarations hidden (-fvisibility flag only affects definitions) */
  221. /* (don't include system headers after this until corresponding pop!) */
  222. PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN
  223. #if ENABLE_USE_BB_PWD_GRP
  224. # include "pwd_.h"
  225. # include "grp_.h"
  226. #endif
  227. #if ENABLE_FEATURE_SHADOWPASSWDS
  228. # if ENABLE_USE_BB_SHADOW
  229. # include "shadow_.h"
  230. # endif
  231. #endif
  232. /* Tested to work correctly with all int types (IIRC :]) */
  233. #define MAXINT(T) (T)( \
  234. ((T)-1) > 0 \
  235. ? (T)-1 \
  236. : (T)~((T)1 << (sizeof(T)*8-1)) \
  237. )
  238. #define MININT(T) (T)( \
  239. ((T)-1) > 0 \
  240. ? (T)0 \
  241. : ((T)1 << (sizeof(T)*8-1)) \
  242. )
  243. /* Large file support */
  244. /* Note that CONFIG_LFS=y forces bbox to be built with all common ops
  245. * (stat, lseek etc) mapped to "largefile" variants by libc.
  246. * Practically it means that open() automatically has O_LARGEFILE added
  247. * and all filesize/file_offset parameters and struct members are "large"
  248. * (in today's world - signed 64bit). For full support of large files,
  249. * we need a few helper #defines (below) and careful use of off_t
  250. * instead of int/ssize_t. No lseek64(), O_LARGEFILE etc necessary */
  251. #if ENABLE_LFS
  252. /* CONFIG_LFS is on */
  253. # if ULONG_MAX > 0xffffffff
  254. /* "long" is long enough on this system */
  255. typedef unsigned long uoff_t;
  256. # define XATOOFF(a) xatoul_range((a), 0, LONG_MAX)
  257. /* usage: sz = BB_STRTOOFF(s, NULL, 10); if (errno || sz < 0) die(); */
  258. # define BB_STRTOOFF bb_strtoul
  259. # define STRTOOFF strtoul
  260. /* usage: printf("size: %"OFF_FMT"d (%"OFF_FMT"x)\n", sz, sz); */
  261. # define OFF_FMT "l"
  262. # else
  263. /* "long" is too short, need "long long" */
  264. typedef unsigned long long uoff_t;
  265. # define XATOOFF(a) xatoull_range((a), 0, LLONG_MAX)
  266. # define BB_STRTOOFF bb_strtoull
  267. # define STRTOOFF strtoull
  268. # define OFF_FMT "ll"
  269. # endif
  270. #else
  271. /* CONFIG_LFS is off */
  272. # if UINT_MAX == 0xffffffff
  273. /* While sizeof(off_t) == sizeof(int), off_t is typedef'ed to long anyway.
  274. * gcc will throw warnings on printf("%d", off_t). Crap... */
  275. typedef unsigned long uoff_t;
  276. # define XATOOFF(a) xatoi_positive(a)
  277. # define BB_STRTOOFF bb_strtou
  278. # define STRTOOFF strtol
  279. # define OFF_FMT "l"
  280. # else
  281. typedef unsigned long uoff_t;
  282. # define XATOOFF(a) xatoul_range((a), 0, LONG_MAX)
  283. # define BB_STRTOOFF bb_strtoul
  284. # define STRTOOFF strtol
  285. # define OFF_FMT "l"
  286. # endif
  287. #endif
  288. /* scary. better ideas? (but do *test* them first!) */
  289. #define OFF_T_MAX ((off_t)~((off_t)1 << (sizeof(off_t)*8-1)))
  290. /* Users report bionic to use 32-bit off_t even if LARGEFILE support is requested.
  291. * On musl, !ENABLE_LFS on 32-bit arches thinks that off_t is 32-bit.
  292. * We misdetected that. Don't let it build:
  293. */
  294. struct BUG_off_t_size_is_misdetected {
  295. char BUG_off_t_size_is_misdetected[sizeof(off_t) == sizeof(uoff_t) ? 1 : -1];
  296. };
  297. /* Some useful definitions */
  298. #undef FALSE
  299. #define FALSE ((int) 0)
  300. #undef TRUE
  301. #define TRUE ((int) 1)
  302. #undef SKIP
  303. #define SKIP ((int) 2)
  304. /* Macros for min/max. */
  305. #ifndef MIN
  306. #define MIN(a,b) (((a)<(b))?(a):(b))
  307. #endif
  308. #ifndef MAX
  309. #define MAX(a,b) (((a)>(b))?(a):(b))
  310. #endif
  311. /* buffer allocation schemes */
  312. #if ENABLE_FEATURE_BUFFERS_GO_ON_STACK
  313. #define RESERVE_CONFIG_BUFFER(buffer,len) char buffer[len]
  314. #define RESERVE_CONFIG_UBUFFER(buffer,len) unsigned char buffer[len]
  315. #define RELEASE_CONFIG_BUFFER(buffer) ((void)0)
  316. #else
  317. #if ENABLE_FEATURE_BUFFERS_GO_IN_BSS
  318. #define RESERVE_CONFIG_BUFFER(buffer,len) static char buffer[len]
  319. #define RESERVE_CONFIG_UBUFFER(buffer,len) static unsigned char buffer[len]
  320. #define RELEASE_CONFIG_BUFFER(buffer) ((void)0)
  321. #else
  322. #define RESERVE_CONFIG_BUFFER(buffer,len) char *buffer = xmalloc(len)
  323. #define RESERVE_CONFIG_UBUFFER(buffer,len) unsigned char *buffer = xmalloc(len)
  324. #define RELEASE_CONFIG_BUFFER(buffer) free(buffer)
  325. #endif
  326. #endif
  327. #if defined(errno)
  328. /* If errno is a define, assume it's "define errno (*__errno_location())"
  329. * and we will cache it's result in this variable */
  330. extern int *const bb_errno;
  331. #undef errno
  332. #define errno (*bb_errno)
  333. #define bb_cached_errno_ptr 1
  334. #endif
  335. #if !(ULONG_MAX > 0xffffffff)
  336. /* Only 32-bit CPUs need this, 64-bit ones use inlined version */
  337. uint64_t bb_bswap_64(uint64_t x) FAST_FUNC;
  338. #endif
  339. unsigned long FAST_FUNC isqrt(unsigned long long N);
  340. unsigned long long monotonic_ns(void) FAST_FUNC;
  341. unsigned long long monotonic_us(void) FAST_FUNC;
  342. unsigned long long monotonic_ms(void) FAST_FUNC;
  343. unsigned monotonic_sec(void) FAST_FUNC;
  344. extern void chomp(char *s) FAST_FUNC;
  345. extern char *trim(char *s) FAST_FUNC;
  346. extern char *skip_whitespace(const char *) FAST_FUNC;
  347. extern char *skip_non_whitespace(const char *) FAST_FUNC;
  348. extern char *skip_dev_pfx(const char *tty_name) FAST_FUNC;
  349. extern char *strrstr(const char *haystack, const char *needle) FAST_FUNC;
  350. /* dmalloc will redefine these to it's own implementation. It is safe
  351. * to have the prototypes here unconditionally. */
  352. void *malloc_or_warn(size_t size) FAST_FUNC RETURNS_MALLOC;
  353. void *xmalloc(size_t size) FAST_FUNC RETURNS_MALLOC;
  354. void *xzalloc(size_t size) FAST_FUNC RETURNS_MALLOC;
  355. void *xrealloc(void *old, size_t size) FAST_FUNC;
  356. /* After v = xrealloc_vector(v, SHIFT, idx) it's ok to use
  357. * at least v[idx] and v[idx+1], for all idx values.
  358. * SHIFT specifies how many new elements are added (1:2, 2:4, ..., 8:256...)
  359. * when all elements are used up. New elements are zeroed out.
  360. * xrealloc_vector(v, SHIFT, idx) *MUST* be called with consecutive IDXs -
  361. * skipping an index is a bad bug - it may miss a realloc!
  362. */
  363. #define xrealloc_vector(vector, shift, idx) \
  364. xrealloc_vector_helper((vector), (sizeof((vector)[0]) << 8) + (shift), (idx))
  365. void* xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx) FAST_FUNC;
  366. char *xstrdup(const char *s) FAST_FUNC RETURNS_MALLOC;
  367. char *xstrndup(const char *s, int n) FAST_FUNC RETURNS_MALLOC;
  368. void *xmemdup(const void *s, int n) FAST_FUNC RETURNS_MALLOC;
  369. void *mmap_read(int fd, size_t size) FAST_FUNC;
  370. void *mmap_anon(size_t size) FAST_FUNC;
  371. void *xmmap_anon(size_t size) FAST_FUNC;
  372. #if defined(__x86_64__) || defined(i386)
  373. # define BB_ARCH_FIXED_PAGESIZE 4096
  374. #elif defined(__arm__) /* only 32bit, 64bit ARM has variable page size */
  375. # define BB_ARCH_FIXED_PAGESIZE 4096
  376. #else /* if defined(ARCH) */
  377. /* add you favorite arch today! */
  378. //From Linux kernel inspection:
  379. //xtenza,s390[x],riscv,nios2,csky,sparc32: fixed 4k pages
  380. //sparc64,alpha,openrisc: fixed 8k pages
  381. #endif
  382. #if defined BB_ARCH_FIXED_PAGESIZE
  383. # define IF_VARIABLE_ARCH_PAGESIZE(...) /*nothing*/
  384. # define bb_getpagesize() BB_ARCH_FIXED_PAGESIZE
  385. # define INIT_PAGESIZE(var) ((void)0)
  386. # define cached_pagesize(var) BB_ARCH_FIXED_PAGESIZE
  387. #else
  388. # define IF_VARIABLE_ARCH_PAGESIZE(...) __VA_ARGS__
  389. # define bb_getpagesize() getpagesize()
  390. # define INIT_PAGESIZE(var) ((var) = getpagesize())
  391. # define cached_pagesize(var) (var)
  392. #endif
  393. //TODO: supply a pointer to char[11] buffer (avoid statics)?
  394. extern const char *bb_mode_string(mode_t mode) FAST_FUNC;
  395. extern int is_directory(const char *name, int followLinks) FAST_FUNC;
  396. enum { /* cp.c, mv.c, install.c depend on these values. CAREFUL when changing them! */
  397. FILEUTILS_PRESERVE_STATUS = 1 << 0, /* -p */
  398. FILEUTILS_DEREFERENCE = 1 << 1, /* !-d */
  399. FILEUTILS_RECUR = 1 << 2, /* -R */
  400. FILEUTILS_FORCE = 1 << 3, /* -f */
  401. FILEUTILS_INTERACTIVE = 1 << 4, /* -i */
  402. FILEUTILS_MAKE_HARDLINK = 1 << 5, /* -l */
  403. FILEUTILS_MAKE_SOFTLINK = 1 << 6, /* -s */
  404. FILEUTILS_DEREF_SOFTLINK = 1 << 7, /* -L */
  405. FILEUTILS_DEREFERENCE_L0 = 1 << 8, /* -H */
  406. /* -a = -pdR (mapped in cp.c) */
  407. /* -r = -dR (mapped in cp.c) */
  408. /* -P = -d (mapped in cp.c) */
  409. FILEUTILS_VERBOSE = (1 << 12) * ENABLE_FEATURE_VERBOSE, /* -v */
  410. FILEUTILS_UPDATE = 1 << 13, /* -u */
  411. FILEUTILS_NO_TARGET_DIR = 1 << 14, /* -T */
  412. #if ENABLE_SELINUX
  413. FILEUTILS_PRESERVE_SECURITY_CONTEXT = 1 << 15, /* -c */
  414. #endif
  415. FILEUTILS_RMDEST = 1 << (16 - !ENABLE_SELINUX), /* --remove-destination */
  416. /* bit 17 skipped for "cp --parents" */
  417. FILEUTILS_REFLINK = 1 << (18 - !ENABLE_SELINUX), /* cp --reflink=auto */
  418. FILEUTILS_REFLINK_ALWAYS = 1 << (19 - !ENABLE_SELINUX), /* cp --reflink[=always] */
  419. /*
  420. * Hole. cp may have some bits set here,
  421. * they should not affect remove_file()/copy_file()
  422. */
  423. #if ENABLE_SELINUX
  424. FILEUTILS_SET_SECURITY_CONTEXT = 1 << 30,
  425. #endif
  426. FILEUTILS_IGNORE_CHMOD_ERR = 1 << 31,
  427. };
  428. #define FILEUTILS_CP_OPTSTR "pdRfilsLHarPvuT" IF_SELINUX("c")
  429. extern int remove_file(const char *path, int flags) FAST_FUNC;
  430. /* NB: without FILEUTILS_RECUR in flags, it will basically "cat"
  431. * the source, not copy (unless "source" is a directory).
  432. * This makes "cp /dev/null file" and "install /dev/null file" (!!!)
  433. * work coreutils-compatibly. */
  434. extern int copy_file(const char *source, const char *dest, int flags) FAST_FUNC;
  435. enum {
  436. ACTION_RECURSE = (1 << 0),
  437. ACTION_FOLLOWLINKS = (1 << 1),
  438. ACTION_FOLLOWLINKS_L0 = (1 << 2),
  439. ACTION_DEPTHFIRST = (1 << 3),
  440. ACTION_QUIET = (1 << 4),
  441. ACTION_DANGLING_OK = (1 << 5),
  442. };
  443. typedef uint8_t recurse_flags_t;
  444. typedef struct recursive_state {
  445. unsigned flags;
  446. unsigned depth;
  447. void *userData;
  448. int FAST_FUNC (*fileAction)(struct recursive_state *state, const char *fileName, struct stat* statbuf);
  449. int FAST_FUNC (*dirAction)(struct recursive_state *state, const char *fileName, struct stat* statbuf);
  450. } recursive_state_t;
  451. int recursive_action(const char *fileName, unsigned flags,
  452. int FAST_FUNC (*fileAction)(struct recursive_state *state, const char *fileName, struct stat* statbuf),
  453. int FAST_FUNC (*dirAction)(struct recursive_state *state, const char *fileName, struct stat* statbuf),
  454. void *userData
  455. ) FAST_FUNC;
  456. extern int device_open(const char *device, int mode) FAST_FUNC;
  457. enum { GETPTY_BUFSIZE = 16 }; /* more than enough for "/dev/ttyXXX" */
  458. extern int xgetpty(char *line) FAST_FUNC;
  459. extern int get_console_fd_or_die(void) FAST_FUNC;
  460. extern void console_make_active(int fd, const int vt_num) FAST_FUNC;
  461. extern char *find_block_device(const char *path) FAST_FUNC;
  462. /* bb_copyfd_XX print read/write errors and return -1 if they occur */
  463. extern off_t bb_copyfd_eof(int fd1, int fd2) FAST_FUNC;
  464. extern off_t bb_copyfd_size(int fd1, int fd2, off_t size) FAST_FUNC;
  465. extern void bb_copyfd_exact_size(int fd1, int fd2, off_t size) FAST_FUNC;
  466. /* "short" copy can be detected by return value < size */
  467. /* this helper yells "short read!" if param is not -1 */
  468. extern void complain_copyfd_and_die(off_t sz) NORETURN FAST_FUNC;
  469. extern char bb_process_escape_sequence(const char **ptr) FAST_FUNC;
  470. char* strcpy_and_process_escape_sequences(char *dst, const char *src) FAST_FUNC;
  471. /* xxxx_strip version can modify its parameter:
  472. * "/" -> "/"
  473. * "abc" -> "abc"
  474. * "abc/def" -> "def"
  475. * "abc/def/" -> "def" !!
  476. */
  477. char *bb_get_last_path_component_strip(char *path) FAST_FUNC;
  478. /* "abc/def/" -> "" and it never modifies 'path' */
  479. char *bb_get_last_path_component_nostrip(const char *path) FAST_FUNC;
  480. /* Simpler version: does not special case "/" string */
  481. const char *bb_basename(const char *name) FAST_FUNC;
  482. /* NB: can violate const-ness (similarly to strchr) */
  483. char *last_char_is(const char *s, int c) FAST_FUNC;
  484. const char* endofname(const char *name) FAST_FUNC;
  485. char *is_prefixed_with(const char *string, const char *key) FAST_FUNC;
  486. char *is_suffixed_with(const char *string, const char *key) FAST_FUNC;
  487. int ndelay_on(int fd) FAST_FUNC;
  488. int ndelay_off(int fd) FAST_FUNC;
  489. void close_on_exec_on(int fd) FAST_FUNC;
  490. void xdup2(int, int) FAST_FUNC;
  491. void xmove_fd(int, int) FAST_FUNC;
  492. DIR *xopendir(const char *path) FAST_FUNC;
  493. DIR *warn_opendir(const char *path) FAST_FUNC;
  494. char *xmalloc_realpath(const char *path) FAST_FUNC RETURNS_MALLOC;
  495. char *xmalloc_realpath_coreutils(const char *path) FAST_FUNC RETURNS_MALLOC;
  496. char *xmalloc_readlink(const char *path) FAST_FUNC RETURNS_MALLOC;
  497. char *xmalloc_readlink_or_warn(const char *path) FAST_FUNC RETURNS_MALLOC;
  498. /* !RETURNS_MALLOC: it's a realloc-like function */
  499. char *xrealloc_getcwd_or_warn(char *cwd) FAST_FUNC;
  500. char *xmalloc_follow_symlinks(const char *path) FAST_FUNC RETURNS_MALLOC;
  501. enum {
  502. /* bb_signals(BB_FATAL_SIGS, handler) catches all signals which
  503. * otherwise would kill us, except for those resulting from bugs:
  504. * SIGSEGV, SIGILL, SIGFPE.
  505. * Other fatal signals not included (TODO?):
  506. * SIGBUS Bus error (bad memory access)
  507. * SIGPOLL Pollable event. Synonym of SIGIO
  508. * SIGPROF Profiling timer expired
  509. * SIGSYS Bad argument to routine
  510. * SIGTRAP Trace/breakpoint trap
  511. *
  512. * The only known arch with some of these sigs not fitting
  513. * into 32 bits is parisc (SIGXCPU=33, SIGXFSZ=34, SIGSTKFLT=36).
  514. * Dance around with long long to guard against that...
  515. */
  516. BB_FATAL_SIGS = (int)(0
  517. + (1LL << SIGHUP)
  518. + (1LL << SIGINT)
  519. + (1LL << SIGTERM)
  520. + (1LL << SIGPIPE) // Write to pipe with no readers
  521. + (1LL << SIGQUIT) // Quit from keyboard
  522. + (1LL << SIGABRT) // Abort signal from abort(3)
  523. + (1LL << SIGALRM) // Timer signal from alarm(2)
  524. + (1LL << SIGVTALRM) // Virtual alarm clock
  525. + (1LL << SIGXCPU) // CPU time limit exceeded
  526. + (1LL << SIGXFSZ) // File size limit exceeded
  527. + (1LL << SIGUSR1) // Yes kids, these are also fatal!
  528. + (1LL << SIGUSR2)
  529. + 0),
  530. };
  531. void bb_signals(int sigs, void (*f)(int)) FAST_FUNC;
  532. /* Unlike signal() and bb_signals, sets handler with sigaction()
  533. * and in a way that while signal handler is run, no other signals
  534. * will be blocked; syscalls will not be restarted: */
  535. void bb_signals_recursive_norestart(int sigs, void (*f)(int)) FAST_FUNC;
  536. /* syscalls like read() will be interrupted with EINTR: */
  537. void signal_no_SA_RESTART_empty_mask(int sig, void (*handler)(int)) FAST_FUNC;
  538. /* syscalls like read() won't be interrupted (though select/poll will be): */
  539. void signal_SA_RESTART_empty_mask(int sig, void (*handler)(int)) FAST_FUNC;
  540. void wait_for_any_sig(void) FAST_FUNC;
  541. void kill_myself_with_sig(int sig) NORETURN FAST_FUNC;
  542. void sig_block(int sig) FAST_FUNC;
  543. void sig_unblock(int sig) FAST_FUNC;
  544. /* Will do sigaction(signum, act, NULL): */
  545. int sigaction_set(int sig, const struct sigaction *act) FAST_FUNC;
  546. /* SIG_BLOCK/SIG_UNBLOCK all signals: */
  547. int sigprocmask_allsigs(int how) FAST_FUNC;
  548. /* Return old set in the same set: */
  549. int sigprocmask2(int how, sigset_t *set) FAST_FUNC;
  550. /* Standard handler which just records signo */
  551. extern smallint bb_got_signal;
  552. void record_signo(int signo); /* not FAST_FUNC! */
  553. void xsetgid(gid_t gid) FAST_FUNC;
  554. void xsetuid(uid_t uid) FAST_FUNC;
  555. void xsetegid(gid_t egid) FAST_FUNC;
  556. void xseteuid(uid_t euid) FAST_FUNC;
  557. void xchdir(const char *path) FAST_FUNC;
  558. void xfchdir(int fd) FAST_FUNC;
  559. void xchroot(const char *path) FAST_FUNC;
  560. void xsetenv(const char *key, const char *value) FAST_FUNC;
  561. void bb_unsetenv(const char *key) FAST_FUNC;
  562. void bb_unsetenv_and_free(char *key) FAST_FUNC;
  563. void xunlink(const char *pathname) FAST_FUNC;
  564. void xstat(const char *pathname, struct stat *buf) FAST_FUNC;
  565. void xfstat(int fd, struct stat *buf, const char *errmsg) FAST_FUNC;
  566. int open3_or_warn(const char *pathname, int flags, int mode) FAST_FUNC;
  567. int open_or_warn(const char *pathname, int flags) FAST_FUNC;
  568. int xopen3(const char *pathname, int flags, int mode) FAST_FUNC;
  569. int xopen(const char *pathname, int flags) FAST_FUNC;
  570. int xopen_nonblocking(const char *pathname) FAST_FUNC;
  571. int xopen_as_uid_gid(const char *pathname, int flags, uid_t u, gid_t g) FAST_FUNC;
  572. int open_or_warn_stdin(const char *pathname) FAST_FUNC;
  573. int xopen_stdin(const char *pathname) FAST_FUNC;
  574. void xrename(const char *oldpath, const char *newpath) FAST_FUNC;
  575. int rename_or_warn(const char *oldpath, const char *newpath) FAST_FUNC;
  576. off_t xlseek(int fd, off_t offset, int whence) FAST_FUNC;
  577. int xmkstemp(char *template) FAST_FUNC;
  578. off_t fdlength(int fd) FAST_FUNC;
  579. uoff_t FAST_FUNC get_volume_size_in_bytes(int fd,
  580. const char *override,
  581. unsigned override_units,
  582. int extend);
  583. void xpipe(int filedes[2]) FAST_FUNC;
  584. /* In this form code with pipes is much more readable */
  585. struct fd_pair { int rd; int wr; };
  586. #define piped_pair(pair) pipe(&((pair).rd))
  587. #define xpiped_pair(pair) xpipe(&((pair).rd))
  588. /* Useful for having small structure members/global variables */
  589. typedef int8_t socktype_t;
  590. typedef int8_t family_t;
  591. struct BUG_too_small {
  592. char BUG_socktype_t_too_small[(0
  593. | SOCK_STREAM
  594. | SOCK_DGRAM
  595. | SOCK_RDM
  596. | SOCK_SEQPACKET
  597. | SOCK_RAW
  598. ) <= 127 ? 1 : -1];
  599. char BUG_family_t_too_small[(0
  600. | AF_UNSPEC
  601. | AF_INET
  602. | AF_INET6
  603. | AF_UNIX
  604. #ifdef AF_PACKET
  605. | AF_PACKET
  606. #endif
  607. #ifdef AF_NETLINK
  608. | AF_NETLINK
  609. #endif
  610. /* | AF_DECnet */
  611. /* | AF_IPX */
  612. ) <= 127 ? 1 : -1];
  613. };
  614. void parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
  615. time_t validate_tm_time(const char *date_str, struct tm *ptm) FAST_FUNC;
  616. char *strftime_HHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
  617. char *strftime_YYYYMMDDHHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
  618. void xgettimeofday(struct timeval *tv) FAST_FUNC;
  619. void xsettimeofday(const struct timeval *tv) FAST_FUNC;
  620. int xsocket(int domain, int type, int protocol) FAST_FUNC;
  621. void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen) FAST_FUNC;
  622. void xlisten(int s, int backlog) FAST_FUNC;
  623. void xconnect(int s, const struct sockaddr *s_addr, socklen_t addrlen) FAST_FUNC;
  624. ssize_t xsendto(int s, const void *buf, size_t len, const struct sockaddr *to,
  625. socklen_t tolen) FAST_FUNC;
  626. int setsockopt_int(int fd, int level, int optname, int optval) FAST_FUNC;
  627. int setsockopt_1(int fd, int level, int optname) FAST_FUNC;
  628. int setsockopt_SOL_SOCKET_int(int fd, int optname, int optval) FAST_FUNC;
  629. int setsockopt_SOL_SOCKET_1(int fd, int optname) FAST_FUNC;
  630. /* SO_REUSEADDR allows a server to rebind to an address that is already
  631. * "in use" by old connections to e.g. previous server instance which is
  632. * killed or crashed. Without it bind will fail until all such connections
  633. * time out. Linux does not allow multiple live binds on same ip:port
  634. * regardless of SO_REUSEADDR (unlike some other flavors of Unix).
  635. * Turn it on before you call bind(). */
  636. void setsockopt_reuseaddr(int fd) FAST_FUNC; /* On Linux this never fails. */
  637. int setsockopt_keepalive(int fd) FAST_FUNC;
  638. int setsockopt_broadcast(int fd) FAST_FUNC;
  639. int setsockopt_bindtodevice(int fd, const char *iface) FAST_FUNC;
  640. int bb_getsockname(int sockfd, void *addr, socklen_t addrlen) FAST_FUNC;
  641. /* NB: returns port in host byte order */
  642. unsigned bb_lookup_port(const char *port, const char *protocol, unsigned default_port) FAST_FUNC;
  643. #if ENABLE_FEATURE_ETC_SERVICES
  644. # define bb_lookup_std_port(portstr, protocol, portnum) bb_lookup_port(portstr, protocol, portnum)
  645. #else
  646. # define bb_lookup_std_port(portstr, protocol, portnum) (portnum)
  647. #endif
  648. typedef struct len_and_sockaddr {
  649. socklen_t len;
  650. union {
  651. struct sockaddr sa;
  652. struct sockaddr_in sin;
  653. #if ENABLE_FEATURE_IPV6
  654. struct sockaddr_in6 sin6;
  655. #endif
  656. } u;
  657. } len_and_sockaddr;
  658. enum {
  659. LSA_LEN_SIZE = offsetof(len_and_sockaddr, u),
  660. LSA_SIZEOF_SA = sizeof(
  661. union {
  662. struct sockaddr sa;
  663. struct sockaddr_in sin;
  664. #if ENABLE_FEATURE_IPV6
  665. struct sockaddr_in6 sin6;
  666. #endif
  667. }
  668. )
  669. };
  670. /* Create stream socket, and allocate suitable lsa.
  671. * (lsa of correct size and lsa->sa.sa_family (AF_INET/AF_INET6))
  672. * af == AF_UNSPEC will result in trying to create IPv6 socket,
  673. * and if kernel doesn't support it, fall back to IPv4.
  674. * This is useful if you plan to bind to resulting local lsa.
  675. */
  676. int xsocket_type(len_and_sockaddr **lsap, int af, int sock_type) FAST_FUNC;
  677. int xsocket_stream(len_and_sockaddr **lsap) FAST_FUNC;
  678. /* Create server socket bound to bindaddr:port. bindaddr can be NULL,
  679. * numeric IP ("N.N.N.N") or numeric IPv6 address,
  680. * and can have ":PORT" suffix (for IPv6 use "[X:X:...:X]:PORT").
  681. * Only if there is no suffix, port argument is used */
  682. /* NB: these set SO_REUSEADDR before bind */
  683. int create_and_bind_stream_or_die(const char *bindaddr, int port) FAST_FUNC;
  684. int create_and_bind_dgram_or_die(const char *bindaddr, int port) FAST_FUNC;
  685. int create_and_bind_to_netlink(int proto, int grp, unsigned rcvbuf) FAST_FUNC;
  686. /* Create client TCP socket connected to peer:port. Peer cannot be NULL.
  687. * Peer can be numeric IP ("N.N.N.N"), numeric IPv6 address or hostname,
  688. * and can have ":PORT" suffix (for IPv6 use "[X:X:...:X]:PORT").
  689. * If there is no suffix, port argument is used */
  690. int create_and_connect_stream_or_die(const char *peer, int port) FAST_FUNC;
  691. /* Connect to peer identified by lsa */
  692. int xconnect_stream(const len_and_sockaddr *lsa) FAST_FUNC;
  693. /* Get local address of bound or accepted socket */
  694. len_and_sockaddr *get_sock_lsa(int fd) FAST_FUNC RETURNS_MALLOC;
  695. /* Get remote address of connected or accepted socket */
  696. len_and_sockaddr *get_peer_lsa(int fd) FAST_FUNC RETURNS_MALLOC;
  697. /* Return malloc'ed len_and_sockaddr with socket address of host:port
  698. * Currently will return IPv4 or IPv6 sockaddrs only
  699. * (depending on host), but in theory nothing prevents e.g.
  700. * UNIX socket address being returned, IPX sockaddr etc...
  701. * On error does bb_error_msg and returns NULL */
  702. len_and_sockaddr* host2sockaddr(const char *host, int port) FAST_FUNC RETURNS_MALLOC;
  703. /* Version which dies on error */
  704. len_and_sockaddr* xhost2sockaddr(const char *host, int port) FAST_FUNC RETURNS_MALLOC;
  705. len_and_sockaddr* xdotted2sockaddr(const char *host, int port) FAST_FUNC RETURNS_MALLOC;
  706. /* Same, useful if you want to force family (e.g. IPv6) */
  707. #if !ENABLE_FEATURE_IPV6
  708. #define host_and_af2sockaddr(host, port, af) host2sockaddr((host), (port))
  709. #define xhost_and_af2sockaddr(host, port, af) xhost2sockaddr((host), (port))
  710. #else
  711. len_and_sockaddr* host_and_af2sockaddr(const char *host, int port, sa_family_t af) FAST_FUNC RETURNS_MALLOC;
  712. len_and_sockaddr* xhost_and_af2sockaddr(const char *host, int port, sa_family_t af) FAST_FUNC RETURNS_MALLOC;
  713. #endif
  714. /* Assign sin[6]_port member if the socket is an AF_INET[6] one,
  715. * otherwise no-op. Useful for ftp.
  716. * NB: does NOT do htons() internally, just direct assignment. */
  717. void set_nport(struct sockaddr *sa, unsigned port) FAST_FUNC;
  718. /* Retrieve sin[6]_port or return -1 for non-INET[6] lsa's */
  719. int get_nport(const struct sockaddr *sa) FAST_FUNC;
  720. /* Reverse DNS. Returns NULL on failure. */
  721. char* xmalloc_sockaddr2host(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  722. /* This one doesn't append :PORTNUM */
  723. char* xmalloc_sockaddr2host_noport(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  724. /* This one also doesn't fall back to dotted IP (returns NULL) */
  725. char* xmalloc_sockaddr2hostonly_noport(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  726. /* inet_[ap]ton on steroids */
  727. char* xmalloc_sockaddr2dotted(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  728. char* xmalloc_sockaddr2dotted_noport(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  729. // "old" (ipv4 only) API
  730. // users: traceroute.c hostname.c - use _list_ of all IPs
  731. struct hostent *xgethostbyname(const char *name) FAST_FUNC;
  732. // Also mount.c and inetd.c are using gethostbyname(),
  733. // + inet_common.c has additional IPv4-only stuff
  734. struct tls_aes {
  735. uint32_t key[60];
  736. unsigned rounds;
  737. };
  738. #define TLS_MAX_MAC_SIZE 32
  739. #define TLS_MAX_KEY_SIZE 32
  740. #define TLS_MAX_IV_SIZE 4
  741. struct tls_handshake_data; /* opaque */
  742. typedef struct tls_state {
  743. unsigned flags;
  744. int ofd;
  745. int ifd;
  746. unsigned min_encrypted_len_on_read;
  747. uint16_t cipher_id;
  748. unsigned MAC_size;
  749. unsigned key_size;
  750. unsigned IV_size;
  751. uint8_t *outbuf;
  752. int outbuf_size;
  753. int inbuf_size;
  754. int ofs_to_buffered;
  755. int buffered_size;
  756. uint8_t *inbuf;
  757. struct tls_handshake_data *hsd;
  758. // RFC 5246
  759. // sequence number
  760. // Each connection state contains a sequence number, which is
  761. // maintained separately for read and write states. The sequence
  762. // number MUST be set to zero whenever a connection state is made the
  763. // active state. Sequence numbers are of type uint64 and may not
  764. // exceed 2^64-1.
  765. /*uint64_t read_seq64_be;*/
  766. uint64_t write_seq64_be;
  767. /*uint8_t *server_write_MAC_key;*/
  768. uint8_t *client_write_key;
  769. uint8_t *server_write_key;
  770. uint8_t *client_write_IV;
  771. uint8_t *server_write_IV;
  772. uint8_t client_write_MAC_key[TLS_MAX_MAC_SIZE];
  773. uint8_t server_write_MAC_k__[TLS_MAX_MAC_SIZE];
  774. uint8_t client_write_k__[TLS_MAX_KEY_SIZE];
  775. uint8_t server_write_k__[TLS_MAX_KEY_SIZE];
  776. uint8_t client_write_I_[TLS_MAX_IV_SIZE];
  777. uint8_t server_write_I_[TLS_MAX_IV_SIZE];
  778. struct tls_aes aes_encrypt;
  779. struct tls_aes aes_decrypt;
  780. uint8_t H[16]; //used by AES_GCM
  781. } tls_state_t;
  782. static inline tls_state_t *new_tls_state(void)
  783. {
  784. tls_state_t *tls = xzalloc(sizeof(*tls));
  785. return tls;
  786. }
  787. void tls_handshake(tls_state_t *tls, const char *sni) FAST_FUNC;
  788. #define TLSLOOP_EXIT_ON_LOCAL_EOF (1 << 0)
  789. void tls_run_copy_loop(tls_state_t *tls, unsigned flags) FAST_FUNC;
  790. void socket_want_pktinfo(int fd) FAST_FUNC;
  791. ssize_t send_to_from(int fd, void *buf, size_t len, int flags,
  792. const struct sockaddr *to,
  793. const struct sockaddr *from,
  794. socklen_t tolen) FAST_FUNC;
  795. ssize_t recv_from_to(int fd, void *buf, size_t len, int flags,
  796. struct sockaddr *from,
  797. struct sockaddr *to,
  798. socklen_t sa_size) FAST_FUNC;
  799. uint16_t inet_cksum(const void *addr, int len) FAST_FUNC;
  800. int parse_pasv_epsv(char *buf) FAST_FUNC;
  801. /* 0 if argv[0] is NULL: */
  802. unsigned string_array_len(char **argv) FAST_FUNC;
  803. void overlapping_strcpy(char *dst, const char *src) FAST_FUNC;
  804. char *safe_strncpy(char *dst, const char *src, size_t size) FAST_FUNC;
  805. char *strncpy_IFNAMSIZ(char *dst, const char *src) FAST_FUNC;
  806. unsigned count_strstr(const char *str, const char *sub) FAST_FUNC;
  807. char *xmalloc_substitute_string(const char *src, int count, const char *sub, const char *repl) FAST_FUNC;
  808. /* Guaranteed to NOT be a macro (smallest code). Saves nearly 2k on uclibc.
  809. * But potentially slow, don't use in one-billion-times loops */
  810. int bb_putchar(int ch) FAST_FUNC;
  811. /* Note: does not use stdio, writes to fd 2 directly */
  812. int bb_putchar_stderr(char ch) FAST_FUNC;
  813. int fputs_stdout(const char *s) FAST_FUNC;
  814. char *xasprintf(const char *format, ...) __attribute__ ((format(printf, 1, 2))) FAST_FUNC RETURNS_MALLOC;
  815. char *auto_string(char *str) FAST_FUNC;
  816. // gcc-4.1.1 still isn't good enough at optimizing it
  817. // (+200 bytes compared to macro)
  818. //static ALWAYS_INLINE
  819. //int LONE_DASH(const char *s) { return s[0] == '-' && !s[1]; }
  820. //static ALWAYS_INLINE
  821. //int NOT_LONE_DASH(const char *s) { return s[0] != '-' || s[1]; }
  822. #define LONE_DASH(s) ((s)[0] == '-' && !(s)[1])
  823. #define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
  824. #define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
  825. #define NOT_LONE_CHAR(s,c) ((s)[0] != (c) || (s)[1])
  826. #define DOT_OR_DOTDOT(s) ((s)[0] == '.' && (!(s)[1] || ((s)[1] == '.' && !(s)[2])))
  827. typedef struct uni_stat_t {
  828. unsigned byte_count;
  829. unsigned unicode_count;
  830. unsigned unicode_width;
  831. } uni_stat_t;
  832. /* Returns a string with unprintable chars replaced by '?' or
  833. * SUBST_WCHAR. This function is unicode-aware. */
  834. const char* FAST_FUNC printable_string(const char *str);
  835. const char* FAST_FUNC printable_string2(uni_stat_t *stats, const char *str);
  836. /* Prints unprintable char ch as ^C or M-c to file
  837. * (M-c is used only if ch is ORed with PRINTABLE_META),
  838. * else it is printed as-is (except for ch = 0x9b) */
  839. enum { PRINTABLE_META = 0x100 };
  840. void fputc_printable(int ch, FILE *file) FAST_FUNC;
  841. /* Return a string that is the printable representation of character ch.
  842. * Buffer must hold at least four characters. */
  843. enum {
  844. VISIBLE_ENDLINE = 1 << 0,
  845. VISIBLE_SHOW_TABS = 1 << 1,
  846. };
  847. void visible(unsigned ch, char *buf, int flags) FAST_FUNC;
  848. extern ssize_t safe_read(int fd, void *buf, size_t count) FAST_FUNC;
  849. extern ssize_t nonblock_immune_read(int fd, void *buf, size_t count) FAST_FUNC;
  850. // NB: will return short read on error, not -1,
  851. // if some data was read before error occurred
  852. extern ssize_t full_read(int fd, void *buf, size_t count) FAST_FUNC;
  853. extern void xread(int fd, void *buf, size_t count) FAST_FUNC;
  854. extern unsigned char xread_char(int fd) FAST_FUNC;
  855. extern ssize_t read_close(int fd, void *buf, size_t maxsz) FAST_FUNC;
  856. extern ssize_t open_read_close(const char *filename, void *buf, size_t maxsz) FAST_FUNC;
  857. // Reads one line a-la fgets (but doesn't save terminating '\n').
  858. // Reads byte-by-byte. Useful when it is important to not read ahead.
  859. // Bytes are appended to pfx (which must be malloced, or NULL).
  860. extern char *xmalloc_reads(int fd, size_t *maxsz_p) FAST_FUNC;
  861. /* Reads block up to *maxsz_p (default: INT_MAX - 4095) */
  862. extern void *xmalloc_read(int fd, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  863. extern void *xmalloc_read_with_initial_buf(int fd, size_t *maxsz_p, char *buf, size_t total) FAST_FUNC;
  864. /* Returns NULL if file can't be opened (default max size: INT_MAX - 4095) */
  865. extern void *xmalloc_open_read_close(const char *filename, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  866. /* Never returns NULL */
  867. extern void *xmalloc_xopen_read_close(const char *filename, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  868. #if defined(ARG_MAX) && (ARG_MAX >= 60*1024 || !defined(_SC_ARG_MAX))
  869. /* Use _constant_ maximum if: defined && (big enough || no variable one exists) */
  870. # define bb_arg_max() ((unsigned)ARG_MAX)
  871. #elif defined(_SC_ARG_MAX)
  872. /* Else use variable one (a bit more expensive) */
  873. unsigned bb_arg_max(void) FAST_FUNC;
  874. #else
  875. /* If all else fails */
  876. # define bb_arg_max() ((unsigned)(32 * 1024))
  877. #endif
  878. unsigned bb_clk_tck(void) FAST_FUNC;
  879. #define SEAMLESS_COMPRESSION (0 \
  880. || ENABLE_FEATURE_SEAMLESS_XZ \
  881. || ENABLE_FEATURE_SEAMLESS_LZMA \
  882. || ENABLE_FEATURE_SEAMLESS_BZ2 \
  883. || ENABLE_FEATURE_SEAMLESS_GZ \
  884. || ENABLE_FEATURE_SEAMLESS_Z)
  885. #if SEAMLESS_COMPRESSION
  886. /* Autodetects gzip/bzip2 formats. fd may be in the middle of the file! */
  887. int setup_unzip_on_fd(int fd, int fail_if_not_compressed) FAST_FUNC;
  888. /* Autodetects .gz etc */
  889. extern int open_zipped(const char *fname, int fail_if_not_compressed) FAST_FUNC;
  890. extern void *xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  891. #else
  892. # define setup_unzip_on_fd(...) (0)
  893. # define open_zipped(fname, fail_if_not_compressed) open((fname), O_RDONLY);
  894. # define xmalloc_open_zipped_read_close(fname, maxsz_p) xmalloc_open_read_close((fname), (maxsz_p))
  895. #endif
  896. /* lzma has no signature, need a little helper. NB: exist only for ENABLE_FEATURE_SEAMLESS_LZMA=y */
  897. void setup_lzma_on_fd(int fd) FAST_FUNC;
  898. extern ssize_t safe_write(int fd, const void *buf, size_t count) FAST_FUNC;
  899. // NB: will return short write on error, not -1,
  900. // if some data was written before error occurred
  901. extern ssize_t full_write(int fd, const void *buf, size_t count) FAST_FUNC;
  902. extern void xwrite(int fd, const void *buf, size_t count) FAST_FUNC;
  903. extern void xwrite_str(int fd, const char *str) FAST_FUNC;
  904. extern ssize_t full_write1_str(const char *str) FAST_FUNC;
  905. extern ssize_t full_write2_str(const char *str) FAST_FUNC;
  906. extern void xopen_xwrite_close(const char* file, const char *str) FAST_FUNC;
  907. /* Close fd, but check for failures (some types of write errors) */
  908. extern void xclose(int fd) FAST_FUNC;
  909. /* Reads and prints to stdout till eof, then closes FILE. Exits on error: */
  910. extern void xprint_and_close_file(FILE *file) FAST_FUNC;
  911. /* Reads a line from a text file, up to a newline or NUL byte, inclusive.
  912. * Returns malloc'ed char*. If end is NULL '\n' isn't considered
  913. * end of line. If end isn't NULL, length of the chunk is stored in it.
  914. * Returns NULL if EOF/error.
  915. */
  916. extern char *bb_get_chunk_from_file(FILE *file, size_t *end) FAST_FUNC;
  917. /* Reads up to (and including) TERMINATING_STRING: */
  918. extern char *xmalloc_fgets_str(FILE *file, const char *terminating_string) FAST_FUNC RETURNS_MALLOC;
  919. /* Same, with limited max size, and returns the length (excluding NUL): */
  920. extern char *xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  921. /* Chops off TERMINATING_STRING from the end: */
  922. extern char *xmalloc_fgetline_str(FILE *file, const char *terminating_string) FAST_FUNC RETURNS_MALLOC;
  923. /* Reads up to (and including) "\n" or NUL byte: */
  924. extern char *xmalloc_fgets(FILE *file) FAST_FUNC RETURNS_MALLOC;
  925. /* Chops off '\n' from the end, unlike fgets: */
  926. extern char *xmalloc_fgetline(FILE *file) FAST_FUNC RETURNS_MALLOC;
  927. /* Same, but doesn't try to conserve space (may have some slack after the end) */
  928. /* extern char *xmalloc_fgetline_fast(FILE *file) FAST_FUNC RETURNS_MALLOC; */
  929. void die_if_ferror(FILE *file, const char *msg) FAST_FUNC;
  930. void die_if_ferror_stdout(void) FAST_FUNC;
  931. int fflush_all(void) FAST_FUNC;
  932. void fflush_stdout_and_exit(int retval) NORETURN FAST_FUNC;
  933. int fclose_if_not_stdin(FILE *file) FAST_FUNC;
  934. FILE* xfopen(const char *filename, const char *mode) FAST_FUNC;
  935. /* Prints warning to stderr and returns NULL on failure: */
  936. FILE* fopen_or_warn(const char *filename, const char *mode) FAST_FUNC;
  937. /* "Opens" stdin if filename is special, else just opens file: */
  938. FILE* xfopen_stdin(const char *filename) FAST_FUNC;
  939. FILE* fopen_or_warn_stdin(const char *filename) FAST_FUNC;
  940. FILE* fopen_for_read(const char *path) FAST_FUNC;
  941. FILE* xfopen_for_read(const char *path) FAST_FUNC;
  942. FILE* fopen_for_write(const char *path) FAST_FUNC;
  943. FILE* xfopen_for_write(const char *path) FAST_FUNC;
  944. FILE* xfdopen_for_read(int fd) FAST_FUNC;
  945. FILE* xfdopen_for_write(int fd) FAST_FUNC;
  946. int bb_pstrcmp(const void *a, const void *b) /* not FAST_FUNC! */;
  947. void qsort_string_vector(char **sv, unsigned count) FAST_FUNC;
  948. /* Wrapper which restarts poll on EINTR or ENOMEM.
  949. * On other errors complains [perror("poll")] and returns.
  950. * Warning! May take (much) longer than timeout_ms to return!
  951. * If this is a problem, use bare poll and open-code EINTR/ENOMEM handling */
  952. int safe_poll(struct pollfd *ufds, nfds_t nfds, int timeout_ms) FAST_FUNC;
  953. char *safe_gethostname(void) FAST_FUNC;
  954. /* Convert each alpha char in str to lower-case */
  955. char* str_tolower(char *str) FAST_FUNC;
  956. char *utoa(unsigned n) FAST_FUNC;
  957. char *itoa(int n) FAST_FUNC;
  958. /* Returns a pointer past the formatted number, does NOT null-terminate */
  959. char *utoa_to_buf(unsigned n, char *buf, unsigned buflen) FAST_FUNC;
  960. char *itoa_to_buf(int n, char *buf, unsigned buflen) FAST_FUNC;
  961. /* Intelligent formatters of bignums */
  962. char *smart_ulltoa4(unsigned long long ul, char buf[4], const char *scale) FAST_FUNC;
  963. char *smart_ulltoa5(unsigned long long ul, char buf[5], const char *scale) FAST_FUNC;
  964. /* If block_size == 0, display size without fractional part,
  965. * else display (size * block_size) with one decimal digit.
  966. * If display_unit == 0, show value no bigger than 1024 with suffix (K,M,G...),
  967. * else divide by display_unit and do not use suffix. */
  968. #define HUMAN_READABLE_MAX_WIDTH 7 /* "1024.0G" */
  969. #define HUMAN_READABLE_MAX_WIDTH_STR "7"
  970. //TODO: provide pointer to buf (avoid statics)?
  971. const char *make_human_readable_str(unsigned long long size,
  972. unsigned long block_size, unsigned long display_unit) FAST_FUNC;
  973. /* Put a string of hex bytes ("1b2e66fe"...), return advanced pointer */
  974. char *bin2hex(char *dst, const char *src, int count) FAST_FUNC;
  975. /* Reverse */
  976. char* hex2bin(char *dst, const char *src, int count) FAST_FUNC;
  977. /* Generate a UUID */
  978. void generate_uuid(uint8_t *buf) FAST_FUNC;
  979. /* Last element is marked by mult == 0 */
  980. struct suffix_mult {
  981. char suffix[4];
  982. uint32_t mult;
  983. };
  984. #define ALIGN_SUFFIX ALIGN4
  985. extern const struct suffix_mult bkm_suffixes[];
  986. #define km_suffixes (bkm_suffixes + 1)
  987. extern const struct suffix_mult cwbkMG_suffixes[];
  988. #define kMG_suffixes (cwbkMG_suffixes + 3)
  989. extern const struct suffix_mult kmg_i_suffixes[];
  990. #include "xatonum.h"
  991. /* Specialized: */
  992. /* Using xatoi() instead of naive atoi() is not always convenient -
  993. * in many places people want *non-negative* values, but store them
  994. * in signed int. Therefore we need this one:
  995. * dies if input is not in [0, INT_MAX] range. Also will reject '-0' etc.
  996. * It should really be named xatoi_nonnegative (since it allows 0),
  997. * but that would be too long.
  998. */
  999. int xatoi_positive(const char *numstr) FAST_FUNC;
  1000. /* Useful for reading port numbers */
  1001. uint16_t xatou16(const char *numstr) FAST_FUNC;
  1002. #if ENABLE_FLOAT_DURATION
  1003. typedef double duration_t;
  1004. void sleep_for_duration(duration_t duration) FAST_FUNC;
  1005. #define DURATION_FMT "f"
  1006. #else
  1007. typedef unsigned duration_t;
  1008. #define sleep_for_duration(duration) sleep(duration)
  1009. #define DURATION_FMT "u"
  1010. #endif
  1011. duration_t parse_duration_str(char *str) FAST_FUNC;
  1012. /* These parse entries in /etc/passwd and /etc/group. This is desirable
  1013. * for BusyBox since we want to avoid using the glibc NSS stuff, which
  1014. * increases target size and is often not needed on embedded systems. */
  1015. long xuname2uid(const char *name) FAST_FUNC;
  1016. long xgroup2gid(const char *name) FAST_FUNC;
  1017. /* wrapper: allows string to contain numeric uid or gid */
  1018. unsigned long get_ug_id(const char *s, long FAST_FUNC (*xname2id)(const char *)) FAST_FUNC;
  1019. struct bb_uidgid_t {
  1020. uid_t uid;
  1021. gid_t gid;
  1022. };
  1023. /* always sets uid and gid; returns 0 on failure */
  1024. int get_uidgid(struct bb_uidgid_t*, const char*) FAST_FUNC;
  1025. /* always sets uid and gid; exits on failure */
  1026. void xget_uidgid(struct bb_uidgid_t*, const char*) FAST_FUNC;
  1027. /* chown-like handling of "user[:[group]" */
  1028. void parse_chown_usergroup_or_die(struct bb_uidgid_t *u, char *user_group) FAST_FUNC;
  1029. struct passwd* xgetpwnam(const char *name) FAST_FUNC;
  1030. struct group* xgetgrnam(const char *name) FAST_FUNC;
  1031. struct passwd* xgetpwuid(uid_t uid) FAST_FUNC;
  1032. struct group* xgetgrgid(gid_t gid) FAST_FUNC;
  1033. char* xuid2uname(uid_t uid) FAST_FUNC;
  1034. char* xgid2group(gid_t gid) FAST_FUNC;
  1035. char* uid2uname(uid_t uid) FAST_FUNC;
  1036. char* gid2group(gid_t gid) FAST_FUNC;
  1037. char* uid2uname_utoa(uid_t uid) FAST_FUNC;
  1038. char* gid2group_utoa(gid_t gid) FAST_FUNC;
  1039. /* versions which cache results (useful for ps, ls etc) */
  1040. const char* get_cached_username(uid_t uid) FAST_FUNC;
  1041. const char* get_cached_groupname(gid_t gid) FAST_FUNC;
  1042. void clear_username_cache(void) FAST_FUNC;
  1043. /* internally usernames are saved in fixed-sized char[] buffers */
  1044. enum { USERNAME_MAX_SIZE = 32 - sizeof(uid_t) };
  1045. #if ENABLE_FEATURE_CHECK_NAMES
  1046. void die_if_bad_username(const char* name) FAST_FUNC;
  1047. #else
  1048. #define die_if_bad_username(name) ((void)(name))
  1049. #endif
  1050. /*
  1051. * Returns (-1) terminated malloced result of getgroups().
  1052. * Reallocs group_array (useful for repeated calls).
  1053. * ngroups is an initial size of array. It is rounded up to 32 for realloc.
  1054. * ngroups is updated on return.
  1055. * ngroups can be NULL: bb_getgroups(NULL, NULL) is valid usage.
  1056. * Dies on errors (on Linux, only xrealloc can cause this, not internal getgroups call).
  1057. */
  1058. gid_t *bb_getgroups(int *ngroups, gid_t *group_array) FAST_FUNC;
  1059. #if ENABLE_FEATURE_UTMP
  1060. void FAST_FUNC write_new_utmp(pid_t pid, int new_type, const char *tty_name, const char *username, const char *hostname);
  1061. void FAST_FUNC update_utmp(pid_t pid, int new_type, const char *tty_name, const char *username, const char *hostname);
  1062. void FAST_FUNC update_utmp_DEAD_PROCESS(pid_t pid);
  1063. #else
  1064. # define write_new_utmp(pid, new_type, tty_name, username, hostname) ((void)0)
  1065. # define update_utmp(pid, new_type, tty_name, username, hostname) ((void)0)
  1066. # define update_utmp_DEAD_PROCESS(pid) ((void)0)
  1067. #endif
  1068. int file_is_executable(const char *name) FAST_FUNC;
  1069. char *find_executable(const char *filename, char **PATHp) FAST_FUNC;
  1070. int executable_exists(const char *filename) FAST_FUNC;
  1071. /* BB_EXECxx always execs (it's not doing NOFORK/NOEXEC stuff),
  1072. * but it may exec busybox and call applet instead of searching PATH.
  1073. */
  1074. #if ENABLE_FEATURE_PREFER_APPLETS
  1075. int BB_EXECVP(const char *file, char *const argv[]) FAST_FUNC;
  1076. #define BB_EXECLP(prog,cmd,...) \
  1077. do { \
  1078. if (find_applet_by_name(prog) >= 0) \
  1079. execlp(bb_busybox_exec_path, cmd, __VA_ARGS__); \
  1080. execlp(prog, cmd, __VA_ARGS__); \
  1081. } while (0)
  1082. #else
  1083. #define BB_EXECVP(prog,cmd) execvp(prog,cmd)
  1084. #define BB_EXECLP(prog,cmd,...) execlp(prog,cmd,__VA_ARGS__)
  1085. #endif
  1086. void BB_EXECVP_or_die(char **argv) NORETURN FAST_FUNC;
  1087. /* xvfork() can't be a _function_, return after vfork in child mangles stack
  1088. * in the parent. It must be a macro. */
  1089. #define xvfork() \
  1090. ({ \
  1091. pid_t bb__xvfork_pid = vfork(); \
  1092. if (bb__xvfork_pid < 0) \
  1093. bb_simple_perror_msg_and_die("vfork"); \
  1094. bb__xvfork_pid; \
  1095. })
  1096. #if BB_MMU
  1097. pid_t xfork(void) FAST_FUNC;
  1098. #endif
  1099. void xvfork_parent_waits_and_exits(void) FAST_FUNC;
  1100. /* NOMMU friendy fork+exec: */
  1101. pid_t spawn(char **argv) FAST_FUNC;
  1102. pid_t xspawn(char **argv) FAST_FUNC;
  1103. pid_t safe_waitpid(pid_t pid, int *wstat, int options) FAST_FUNC;
  1104. pid_t wait_any_nohang(int *wstat) FAST_FUNC;
  1105. /* wait4pid: unlike waitpid, waits ONLY for one process.
  1106. * Returns sig + 0x180 if child is killed by signal.
  1107. * It's safe to pass negative 'pids' from failed [v]fork -
  1108. * wait4pid will return -1 (and will not clobber [v]fork's errno).
  1109. * IOW: rc = wait4pid(spawn(argv));
  1110. * if (rc < 0) bb_perror_msg("%s", argv[0]);
  1111. * if (rc > 0) bb_error_msg("exit code: %d", rc & 0xff);
  1112. */
  1113. int wait4pid(pid_t pid) FAST_FUNC;
  1114. int wait_for_exitstatus(pid_t pid) FAST_FUNC;
  1115. /************************************************************************/
  1116. /* spawn_and_wait/run_nofork_applet/run_applet_no_and_exit need to work */
  1117. /* carefully together to reinit some global state while not disturbing */
  1118. /* other. Be careful if you change them. Consult docs/nofork_noexec.txt */
  1119. /************************************************************************/
  1120. /* Same as wait4pid(spawn(argv)), but with NOFORK/NOEXEC if configured: */
  1121. int spawn_and_wait(char **argv) FAST_FUNC;
  1122. /* Does NOT check that applet is NOFORK, just blindly runs it */
  1123. int run_nofork_applet(int applet_no, char **argv) FAST_FUNC;
  1124. void run_noexec_applet_and_exit(int a, const char *name, char **argv) NORETURN FAST_FUNC;
  1125. #ifndef BUILD_INDIVIDUAL
  1126. int find_applet_by_name(const char *name) FAST_FUNC;
  1127. void run_applet_no_and_exit(int a, const char *name, char **argv) NORETURN FAST_FUNC;
  1128. #endif
  1129. void show_usage_if_dash_dash_help(int applet_no, char **argv) FAST_FUNC;
  1130. #if defined(__linux__)
  1131. void set_task_comm(const char *comm) FAST_FUNC;
  1132. #else
  1133. # define set_task_comm(name) ((void)0)
  1134. #endif
  1135. /* Helpers for daemonization.
  1136. *
  1137. * bb_daemonize(flags) = daemonize, does not compile on NOMMU
  1138. *
  1139. * bb_daemonize_or_rexec(flags, argv) = daemonizes on MMU (and ignores argv),
  1140. * rexec's itself on NOMMU with argv passed as command line.
  1141. * Thus bb_daemonize_or_rexec may cause your <applet>_main() to be re-executed
  1142. * from the start. (It will detect it and not reexec again second time).
  1143. * You have to audit carefully that you don't do something twice as a result
  1144. * (opening files/sockets, parsing config files etc...)!
  1145. *
  1146. * Both of the above will redirect fd 0,1,2 to /dev/null and drop ctty
  1147. * (will do setsid()).
  1148. *
  1149. * fork_or_rexec(argv) = bare-bones fork on MMU,
  1150. * "vfork + re-exec ourself" on NOMMU. No fd redirection, no setsid().
  1151. * On MMU ignores argv.
  1152. *
  1153. * Helper for network daemons in foreground mode:
  1154. *
  1155. * bb_sanitize_stdio() = make sure that fd 0,1,2 are opened by opening them
  1156. * to /dev/null if they are not.
  1157. */
  1158. enum {
  1159. DAEMON_CHDIR_ROOT = 1 << 0,
  1160. DAEMON_DEVNULL_STDIO = 1 << 1,
  1161. DAEMON_CLOSE_EXTRA_FDS = 1 << 2,
  1162. DAEMON_ONLY_SANITIZE = 1 << 3, /* internal use */
  1163. //DAEMON_DOUBLE_FORK = 1 << 4, /* double fork to avoid controlling tty */
  1164. };
  1165. #if BB_MMU
  1166. enum { re_execed = 0 };
  1167. # define fork_or_rexec(argv) xfork()
  1168. # define bb_daemonize_or_rexec(flags, argv) bb_daemonize_or_rexec(flags)
  1169. # define bb_daemonize(flags) bb_daemonize_or_rexec(flags, bogus)
  1170. #else
  1171. extern bool re_execed;
  1172. /* Note: re_exec() and fork_or_rexec() do argv[0][0] |= 0x80 on NOMMU!
  1173. * _Parent_ needs to undo it if it doesn't want to have argv[0] mangled.
  1174. */
  1175. void re_exec(char **argv) NORETURN FAST_FUNC;
  1176. pid_t fork_or_rexec(char **argv) FAST_FUNC;
  1177. int BUG_fork_is_unavailable_on_nommu(void) FAST_FUNC;
  1178. int BUG_daemon_is_unavailable_on_nommu(void) FAST_FUNC;
  1179. void BUG_bb_daemonize_is_unavailable_on_nommu(void) FAST_FUNC;
  1180. # define fork() BUG_fork_is_unavailable_on_nommu()
  1181. # define xfork() BUG_fork_is_unavailable_on_nommu()
  1182. # define daemon(a,b) BUG_daemon_is_unavailable_on_nommu()
  1183. # define bb_daemonize(a) BUG_bb_daemonize_is_unavailable_on_nommu()
  1184. #endif
  1185. void bb_daemonize_or_rexec(int flags, char **argv) FAST_FUNC;
  1186. void bb_sanitize_stdio(void) FAST_FUNC;
  1187. #define bb_daemon_helper(arg) bb_daemonize_or_rexec((arg) | DAEMON_ONLY_SANITIZE, NULL)
  1188. /* Clear dangerous stuff, set PATH. Return 1 if was run by different user. */
  1189. int sanitize_env_if_suid(void) FAST_FUNC;
  1190. /* For top, ps. Some argv[i] are replaced by malloced "-opt" strings */
  1191. void make_all_argv_opts(char **argv) FAST_FUNC;
  1192. char* single_argv(char **argv) FAST_FUNC;
  1193. extern const char *const bb_argv_dash[]; /* { "-", NULL } */
  1194. extern uint32_t option_mask32;
  1195. uint32_t getopt32(char **argv, const char *applet_opts, ...) FAST_FUNC;
  1196. # define No_argument "\0"
  1197. # define Required_argument "\001"
  1198. # define Optional_argument "\002"
  1199. #if ENABLE_LONG_OPTS
  1200. uint32_t getopt32long(char **argv, const char *optstring, const char *longopts, ...) FAST_FUNC;
  1201. #else
  1202. #define getopt32long(argv,optstring,longopts,...) \
  1203. getopt32(argv,optstring,##__VA_ARGS__)
  1204. #endif
  1205. /* BSD-derived getopt() functions require that optind be set to 1 in
  1206. * order to reset getopt() state. This used to be generally accepted
  1207. * way of resetting getopt(). However, glibc's getopt()
  1208. * has additional getopt() state beyond optind (specifically, glibc
  1209. * extensions such as '+' and '-' at the start of the string), and requires
  1210. * that optind be set to zero to reset its state. BSD-derived versions
  1211. * of getopt() misbehaved if optind is set to 0 in order to reset getopt(),
  1212. * and glibc's getopt() used to coredump if optind is set 1 in order
  1213. * to reset getopt().
  1214. * Then BSD introduced additional variable "optreset" which should be
  1215. * set to 1 in order to reset getopt(). Sigh. Standards, anyone?
  1216. *
  1217. * By ~2008, OpenBSD 3.4 was changed to survive glibc-like optind = 0
  1218. * (to interpret it as if optreset was set).
  1219. */
  1220. #if 1 /*def __GLIBC__*/
  1221. #define GETOPT_RESET() (optind = 0)
  1222. #else /* BSD style */
  1223. #define GETOPT_RESET() (optind = 1)
  1224. #endif
  1225. /* Having next pointer as a first member allows easy creation
  1226. * of "llist-compatible" structs, and using llist_FOO functions
  1227. * on them.
  1228. */
  1229. typedef struct llist_t {
  1230. struct llist_t *link;
  1231. char *data;
  1232. } llist_t;
  1233. void llist_add_to(llist_t **old_head, void *data) FAST_FUNC;
  1234. void llist_add_to_end(llist_t **list_head, void *data) FAST_FUNC;
  1235. void *llist_pop(llist_t **elm) FAST_FUNC;
  1236. void llist_unlink(llist_t **head, llist_t *elm) FAST_FUNC;
  1237. void llist_free(llist_t *elm, void (*freeit)(void *data)) FAST_FUNC;
  1238. llist_t *llist_rev(llist_t *list) FAST_FUNC;
  1239. llist_t *llist_find_str(llist_t *first, const char *str) FAST_FUNC;
  1240. /* BTW, surprisingly, changing API to
  1241. * llist_t *llist_add_to(llist_t *old_head, void *data)
  1242. * etc does not result in smaller code... */
  1243. /* start_stop_daemon and udhcpc are special - they want
  1244. * to create pidfiles regardless of FEATURE_PIDFILE */
  1245. #if ENABLE_FEATURE_PIDFILE || defined(WANT_PIDFILE)
  1246. /* True only if we created pidfile which is *file*, not /dev/null etc */
  1247. extern smallint wrote_pidfile;
  1248. void write_pidfile(const char *path) FAST_FUNC;
  1249. void write_pidfile_std_path_and_ext(const char *path) FAST_FUNC;
  1250. void remove_pidfile_std_path_and_ext(const char *path) FAST_FUNC;
  1251. #define remove_pidfile(path) do { if (wrote_pidfile) unlink(path); } while (0)
  1252. #else
  1253. enum { wrote_pidfile = 0 };
  1254. #define write_pidfile_std_path_and_ext(path) ((void)0)
  1255. #define remove_pidfile_std_path_and_ext(path) ((void)0)
  1256. #define write_pidfile(path) ((void)0)
  1257. #define remove_pidfile(path) ((void)0)
  1258. #endif
  1259. enum {
  1260. LOGMODE_NONE = 0,
  1261. LOGMODE_STDIO = (1 << 0),
  1262. LOGMODE_SYSLOG = (1 << 1) * ENABLE_FEATURE_SYSLOG,
  1263. LOGMODE_BOTH = LOGMODE_SYSLOG + LOGMODE_STDIO,
  1264. };
  1265. extern const char *msg_eol;
  1266. extern smallint logmode;
  1267. extern uint8_t xfunc_error_retval;
  1268. extern void (*die_func)(void);
  1269. void xfunc_die(void) NORETURN FAST_FUNC;
  1270. void bb_show_usage(void) NORETURN FAST_FUNC;
  1271. void bb_error_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  1272. void bb_simple_error_msg(const char *s) FAST_FUNC;
  1273. void bb_error_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))) FAST_FUNC;
  1274. void bb_simple_error_msg_and_die(const char *s) NORETURN FAST_FUNC;
  1275. void bb_perror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  1276. void bb_simple_perror_msg(const char *s) FAST_FUNC;
  1277. void bb_perror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))) FAST_FUNC;
  1278. void bb_simple_perror_msg_and_die(const char *s) NORETURN FAST_FUNC;
  1279. void bb_herror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  1280. void bb_simple_herror_msg(const char *s) FAST_FUNC;
  1281. void bb_herror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))) FAST_FUNC;
  1282. void bb_simple_herror_msg_and_die(const char *s) NORETURN FAST_FUNC;
  1283. void bb_perror_nomsg_and_die(void) NORETURN FAST_FUNC;
  1284. void bb_perror_nomsg(void) FAST_FUNC;
  1285. void bb_verror_msg(const char *s, va_list p, const char *strerr) FAST_FUNC;
  1286. void bb_die_memory_exhausted(void) NORETURN FAST_FUNC;
  1287. void bb_logenv_override(void) FAST_FUNC;
  1288. #if ENABLE_FEATURE_SYSLOG_INFO
  1289. void bb_info_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  1290. void bb_simple_info_msg(const char *s) FAST_FUNC;
  1291. void bb_vinfo_msg(const char *s, va_list p) FAST_FUNC;
  1292. #else
  1293. #define bb_info_msg bb_error_msg
  1294. #define bb_simple_info_msg bb_simple_error_msg
  1295. #define bb_vinfo_msg(s,p) bb_verror_msg(s,p,NULL)
  1296. #endif
  1297. #if ENABLE_WARN_SIMPLE_MSG
  1298. /* If enabled, cause calls to bb_error_msg() et al that only take a single
  1299. * parameter to generate a warning.
  1300. */
  1301. static inline void __attribute__ ((deprecated("use bb_simple_error_msg instead")))
  1302. bb_not_simple_error_msg(const char *s) { bb_simple_error_msg(s); }
  1303. static inline void __attribute__ ((deprecated("use bb_simple_error_msg_and_die instead"))) NORETURN
  1304. bb_not_simple_error_msg_and_die(const char *s) { bb_simple_error_msg_and_die(s); }
  1305. static inline void __attribute__ ((deprecated("use bb_simple_perror_msg instead")))
  1306. bb_not_simple_perror_msg(const char *s) { bb_simple_perror_msg(s); }
  1307. static inline void __attribute__ ((deprecated("use bb_simple_perror_msg_and_die instead"))) NORETURN
  1308. bb_not_simple_perror_msg_and_die(const char *s) { bb_simple_perror_msg_and_die(s); }
  1309. static inline void __attribute__ ((deprecated("use bb_simple_herror_msg instead")))
  1310. bb_not_simple_herror_msg(const char *s) { bb_simple_herror_msg(s); }
  1311. static inline void __attribute__ ((deprecated("use bb_simple_herror_msg_and_die instead"))) NORETURN
  1312. bb_not_simple_herror_msg_and_die(const char *s) { bb_simple_herror_msg_and_die(s); }
  1313. static inline void __attribute__ ((deprecated("use bb_simple_info_msg instead")))
  1314. bb_not_simple_info_msg(const char *s) { bb_simple_info_msg(s); }
  1315. /* Override bb_error_msg() and related functions with macros that will
  1316. * substitute them for the equivalent bb_not_simple_error_msg() function when
  1317. * they are used with only a single parameter. Macro approach inspired by
  1318. * https://gustedt.wordpress.com/2010/06/08/detect-empty-macro-arguments and
  1319. * https://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99
  1320. */
  1321. #define _ARG18(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, ...) _17
  1322. #define BB_MSG_KIND(...) _ARG18(__VA_ARGS__, , , , , , , , , , , , , , , , , _not_simple)
  1323. #define _BB_MSG(name, kind, ...) bb##kind##name(__VA_ARGS__)
  1324. #define BB_MSG(name, kind, ...) _BB_MSG(name, kind, __VA_ARGS__)
  1325. #define bb_error_msg(...) BB_MSG(_error_msg, BB_MSG_KIND(__VA_ARGS__), __VA_ARGS__)
  1326. #define bb_error_msg_and_die(...) BB_MSG(_error_msg_and_die, BB_MSG_KIND(__VA_ARGS__), __VA_ARGS__)
  1327. #define bb_perror_msg(...) BB_MSG(_perror_msg, BB_MSG_KIND(__VA_ARGS__), __VA_ARGS__)
  1328. #define bb_perror_msg_and_die(...) BB_MSG(_perror_msg_and_die, BB_MSG_KIND(__VA_ARGS__), __VA_ARGS__)
  1329. #define bb_herror_msg(...) BB_MSG(_herror_msg, BB_MSG_KIND(__VA_ARGS__), __VA_ARGS__)
  1330. #define bb_herror_msg_and_die(...) BB_MSG(_herror_msg_and_die, BB_MSG_KIND(__VA_ARGS__), __VA_ARGS__)
  1331. #if ENABLE_FEATURE_SYSLOG_INFO
  1332. #define bb_info_msg(...) BB_MSG(_info_msg, BB_MSG_KIND(__VA_ARGS__), __VA_ARGS__)
  1333. #endif
  1334. #endif
  1335. /* We need to export XXX_main from libbusybox
  1336. * only if we build "individual" binaries
  1337. */
  1338. #if ENABLE_FEATURE_INDIVIDUAL
  1339. #define MAIN_EXTERNALLY_VISIBLE EXTERNALLY_VISIBLE
  1340. #else
  1341. #define MAIN_EXTERNALLY_VISIBLE
  1342. #endif
  1343. /* Embedded script support */
  1344. char *get_script_content(unsigned n) FAST_FUNC;
  1345. int scripted_main(int argc, char** argv) MAIN_EXTERNALLY_VISIBLE;
  1346. /* Applets which are useful from another applets */
  1347. int bb_cat(char** argv) FAST_FUNC;
  1348. int ash_main(int argc, char** argv)
  1349. #if ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH
  1350. MAIN_EXTERNALLY_VISIBLE
  1351. #endif
  1352. ;
  1353. int hush_main(int argc, char** argv)
  1354. #if ENABLE_HUSH || ENABLE_SH_IS_HUSH || ENABLE_BASH_IS_HUSH
  1355. MAIN_EXTERNALLY_VISIBLE
  1356. #endif
  1357. ;
  1358. /* If shell needs them, they exist even if not enabled as applets */
  1359. int echo_main(int argc, char** argv) IF_ECHO(MAIN_EXTERNALLY_VISIBLE);
  1360. int printf_main(int argc, char **argv) IF_PRINTF(MAIN_EXTERNALLY_VISIBLE);
  1361. int test_main(int argc, char **argv)
  1362. #if ENABLE_TEST || ENABLE_TEST1 || ENABLE_TEST2
  1363. MAIN_EXTERNALLY_VISIBLE
  1364. #endif
  1365. ;
  1366. int kill_main(int argc, char **argv)
  1367. #if ENABLE_KILL || ENABLE_KILLALL || ENABLE_KILLALL5
  1368. MAIN_EXTERNALLY_VISIBLE
  1369. #endif
  1370. ;
  1371. /* Similar, but used by chgrp, not shell */
  1372. int chown_main(int argc, char **argv) IF_CHOWN(MAIN_EXTERNALLY_VISIBLE);
  1373. /* Used by ftpd */
  1374. int ls_main(int argc, char **argv) IF_LS(MAIN_EXTERNALLY_VISIBLE);
  1375. /* Don't need IF_xxx() guard for these */
  1376. int gunzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1377. int bunzip2_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1378. #if ENABLE_ROUTE
  1379. void bb_displayroutes(int noresolve, int netstatfmt) FAST_FUNC;
  1380. #endif
  1381. struct number_state {
  1382. unsigned width;
  1383. unsigned start;
  1384. unsigned inc;
  1385. const char *sep;
  1386. const char *empty_str;
  1387. smallint all, nonempty;
  1388. };
  1389. int print_numbered_lines(struct number_state *ns, const char *filename) FAST_FUNC;
  1390. /* Networking */
  1391. /* This structure defines protocol families and their handlers. */
  1392. struct aftype {
  1393. const char *name;
  1394. const char *title;
  1395. int af;
  1396. int alen;
  1397. char* FAST_FUNC (*print)(unsigned char *);
  1398. const char* FAST_FUNC (*sprint)(struct sockaddr *, int numeric);
  1399. int FAST_FUNC (*input)(/*int type,*/ const char *bufp, struct sockaddr *);
  1400. void FAST_FUNC (*herror)(char *text);
  1401. int FAST_FUNC (*rprint)(int options);
  1402. int FAST_FUNC (*rinput)(int typ, int ext, char **argv);
  1403. /* may modify src */
  1404. int FAST_FUNC (*getmask)(char *src, struct sockaddr *mask, char *name);
  1405. };
  1406. /* This structure defines hardware protocols and their handlers. */
  1407. struct hwtype {
  1408. const char *name;
  1409. const char *title;
  1410. int type;
  1411. int alen;
  1412. char* FAST_FUNC (*print)(unsigned char *);
  1413. int FAST_FUNC (*input)(const char *, struct sockaddr *);
  1414. int FAST_FUNC (*activate)(int fd);
  1415. int suppress_null_addr;
  1416. };
  1417. #define IFNAME_SHOW_DOWNED_TOO ((char*)(intptr_t)1)
  1418. int display_interfaces(char *ifname) FAST_FUNC;
  1419. int in_ether(const char *bufp, struct sockaddr *sap) FAST_FUNC;
  1420. #if ENABLE_FEATURE_HWIB
  1421. int in_ib(const char *bufp, struct sockaddr *sap) FAST_FUNC;
  1422. #else
  1423. #define in_ib(a, b) 1 /* fail */
  1424. #endif
  1425. const struct aftype *get_aftype(const char *name) FAST_FUNC;
  1426. const struct hwtype *get_hwtype(const char *name) FAST_FUNC;
  1427. const struct hwtype *get_hwntype(int type) FAST_FUNC;
  1428. extern int fstype_matches(const char *fstype, const char *comma_list) FAST_FUNC;
  1429. #ifdef HAVE_MNTENT_H
  1430. extern struct mntent *find_mount_point(const char *name, int subdir_too) FAST_FUNC;
  1431. #endif
  1432. extern void erase_mtab(const char * name) FAST_FUNC;
  1433. extern unsigned int tty_baud_to_value(speed_t speed) FAST_FUNC;
  1434. extern speed_t tty_value_to_baud(unsigned int value) FAST_FUNC;
  1435. #if ENABLE_DESKTOP
  1436. extern void bb_warn_ignoring_args(char *arg) FAST_FUNC;
  1437. #else
  1438. # define bb_warn_ignoring_args(arg) ((void)0)
  1439. #endif
  1440. extern int get_linux_version_code(void) FAST_FUNC;
  1441. char *query_loop(const char *device) FAST_FUNC;
  1442. int get_free_loop(void) FAST_FUNC;
  1443. int del_loop(const char *device) FAST_FUNC;
  1444. /*
  1445. * If *devname is not NULL, use that name, otherwise try to find free one,
  1446. * malloc and return it in *devname.
  1447. * return value is the opened fd to the loop device, or < on error
  1448. */
  1449. int set_loop(char **devname, const char *file, unsigned long long offset,
  1450. unsigned long long sizelimit, unsigned flags) FAST_FUNC;
  1451. /* These constants match linux/loop.h (without BB_ prefix): */
  1452. #define BB_LO_FLAGS_READ_ONLY 1
  1453. #define BB_LO_FLAGS_AUTOCLEAR 4
  1454. #define BB_LO_FLAGS_PARTSCAN 8
  1455. /* Returns malloced str */
  1456. char *bb_ask_noecho(int fd, int timeout, const char *prompt) FAST_FUNC;
  1457. /* Like bb_ask_noecho, but asks on stdin with no timeout. */
  1458. char *bb_ask_noecho_stdin(const char *prompt) FAST_FUNC;
  1459. int bb_ask_y_confirmation_FILE(FILE *fp) FAST_FUNC;
  1460. int bb_ask_y_confirmation(void) FAST_FUNC;
  1461. /* Returns -1 if input is invalid. current_mode is a base for e.g. "u+rw" */
  1462. int bb_parse_mode(const char* s, unsigned cur_mode) FAST_FUNC;
  1463. /*
  1464. * Config file parser
  1465. */
  1466. enum {
  1467. PARSE_COLLAPSE = 0x00010000, // treat consecutive delimiters as one
  1468. PARSE_TRIM = 0x00020000, // trim leading and trailing delimiters
  1469. // TODO: COLLAPSE and TRIM seem to always go in pair
  1470. PARSE_GREEDY = 0x00040000, // last token takes entire remainder of the line
  1471. PARSE_MIN_DIE = 0x00100000, // die if < min tokens found
  1472. // keep a copy of current line
  1473. PARSE_KEEP_COPY = 0x00200000 * ENABLE_FEATURE_CROND_D,
  1474. PARSE_EOL_COMMENTS = 0x00400000, // comments are recognized even if they aren't the first char
  1475. PARSE_ALT_COMMENTS = 0x00800000, // delim[0] and delim[1] are two different allowed comment chars
  1476. // (so far, delim[0] will only work as comment char for full-line comment)
  1477. // (IOW: it works as if PARSE_EOL_COMMENTS is not set. sysctl applet is okay with this)
  1478. PARSE_WS_COMMENTS = 0x01000000, // comments are recognized even if there is whitespace before
  1479. // ("line start><space><tab><space>#comment" is also comment, not only "line start>#comment")
  1480. // NORMAL is:
  1481. // * remove leading and trailing delimiters and collapse
  1482. // multiple delimiters into one
  1483. // * warn and continue if less than mintokens delimiters found
  1484. // * grab everything into last token
  1485. // * comments are recognized even if they aren't the first char
  1486. PARSE_NORMAL = PARSE_COLLAPSE | PARSE_TRIM | PARSE_GREEDY | PARSE_EOL_COMMENTS,
  1487. };
  1488. typedef struct parser_t {
  1489. FILE *fp;
  1490. char *data;
  1491. char *line, *nline;
  1492. size_t line_alloc, nline_alloc;
  1493. int lineno;
  1494. } parser_t;
  1495. parser_t* config_open(const char *filename) FAST_FUNC;
  1496. parser_t* config_open2(const char *filename, FILE* FAST_FUNC (*fopen_func)(const char *path)) FAST_FUNC;
  1497. /* delims[0] is a comment char (use '\0' to disable), the rest are token delimiters */
  1498. int config_read(parser_t *parser, char **tokens, unsigned flags, const char *delims) FAST_FUNC;
  1499. #define config_read(parser, tokens, max, min, str, flags) \
  1500. config_read(parser, tokens, ((flags) | (((min) & 0xFF) << 8) | ((max) & 0xFF)), str)
  1501. void config_close(parser_t *parser) FAST_FUNC;
  1502. /* Concatenate path and filename to new allocated buffer.
  1503. * Add "/" only as needed (no duplicate "//" are produced).
  1504. * If path is NULL, it is assumed to be "/".
  1505. * filename should not be NULL. */
  1506. char *concat_path_file(const char *path, const char *filename) FAST_FUNC;
  1507. /* Returns NULL on . and .. */
  1508. char *concat_subpath_file(const char *path, const char *filename) FAST_FUNC;
  1509. int bb_make_directory(char *path, long mode, int flags) FAST_FUNC;
  1510. int get_signum(const char *name) FAST_FUNC;
  1511. const char *get_signame(int number) FAST_FUNC;
  1512. void print_signames(void) FAST_FUNC;
  1513. char *bb_simplify_path(const char *path) FAST_FUNC;
  1514. /* Returns ptr to NUL */
  1515. char *bb_simplify_abs_path_inplace(char *path) FAST_FUNC;
  1516. void pause_after_failed_login(void) FAST_FUNC;
  1517. void bb_do_delay(unsigned seconds) FAST_FUNC;
  1518. void msleep(unsigned ms) FAST_FUNC;
  1519. void sleep1(void) FAST_FUNC;
  1520. void change_identity(const struct passwd *pw) FAST_FUNC;
  1521. void exec_shell(const char *shell, int loginshell, const char **args) NORETURN FAST_FUNC;
  1522. void exec_login_shell(const char *shell) NORETURN FAST_FUNC;
  1523. void exec_prog_or_SHELL(char **argv) NORETURN FAST_FUNC;
  1524. /* Returns $SHELL, getpwuid(getuid())->pw_shell, or DEFAULT_SHELL.
  1525. * Note that getpwuid result might need xstrdup'ing
  1526. * if there is a possibility of intervening getpwxxx() calls.
  1527. */
  1528. const char *get_shell_name(void) FAST_FUNC;
  1529. #if ENABLE_FEATURE_SETPRIV_CAPABILITIES || ENABLE_RUN_INIT
  1530. unsigned cap_name_to_number(const char *cap) FAST_FUNC;
  1531. void printf_cap(const char *pfx, unsigned cap_no) FAST_FUNC;
  1532. void drop_capability(int cap_ordinal) FAST_FUNC;
  1533. /* Structures inside "struct caps" are Linux-specific and libcap-specific: */
  1534. #define DEFINE_STRUCT_CAPS \
  1535. struct caps { \
  1536. struct __user_cap_header_struct header; \
  1537. unsigned u32s; \
  1538. struct __user_cap_data_struct data[2]; \
  1539. }
  1540. void getcaps(void *caps) FAST_FUNC;
  1541. #endif
  1542. #if ENABLE_SELINUX
  1543. extern void renew_current_security_context(void) FAST_FUNC;
  1544. extern void set_current_security_context(security_context_t sid) FAST_FUNC;
  1545. extern context_t set_security_context_component(security_context_t cur_context,
  1546. char *user, char *role, char *type, char *range) FAST_FUNC;
  1547. extern void setfscreatecon_or_die(security_context_t scontext) FAST_FUNC;
  1548. extern void selinux_preserve_fcontext(int fdesc) FAST_FUNC;
  1549. #else
  1550. #define selinux_preserve_fcontext(fdesc) ((void)0)
  1551. #endif
  1552. extern void selinux_or_die(void) FAST_FUNC;
  1553. /* setup_environment:
  1554. * if chdir pw->pw_dir: ok: else if to_tmp == 1: goto /tmp else: goto / or die
  1555. * if clear_env = 1: cd(pw->pw_dir), clear environment, then set
  1556. * TERM=(old value)
  1557. * USER=pw->pw_name, LOGNAME=pw->pw_name
  1558. * PATH=bb_default_[root_]path
  1559. * HOME=pw->pw_dir
  1560. * SHELL=shell
  1561. * else if change_env = 1:
  1562. * if not root (if pw->pw_uid != 0):
  1563. * USER=pw->pw_name, LOGNAME=pw->pw_name
  1564. * HOME=pw->pw_dir
  1565. * SHELL=shell
  1566. * else does nothing
  1567. *
  1568. * NB: CHANGEENV and CLEARENV use setenv() - this leaks memory!
  1569. * If setup_environment() is used is vforked child, this leaks memory _in parent too_!
  1570. */
  1571. #define SETUP_ENV_CHANGEENV (1 << 0)
  1572. #define SETUP_ENV_CLEARENV (1 << 1)
  1573. #define SETUP_ENV_TO_TMP (1 << 2)
  1574. #define SETUP_ENV_NO_CHDIR (1 << 4)
  1575. void setup_environment(const char *shell, int flags, const struct passwd *pw) FAST_FUNC;
  1576. void nuke_str(char *str) FAST_FUNC;
  1577. #if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
  1578. int is_tty_secure(const char *short_tty) FAST_FUNC;
  1579. #else
  1580. static ALWAYS_INLINE int is_tty_secure(const char *short_tty UNUSED_PARAM) { return 1; }
  1581. #endif
  1582. #define CHECKPASS_PW_HAS_EMPTY_PASSWORD 2
  1583. int check_password(const struct passwd *pw, const char *plaintext) FAST_FUNC;
  1584. int ask_and_check_password_extended(const struct passwd *pw, int timeout, const char *prompt) FAST_FUNC;
  1585. int ask_and_check_password(const struct passwd *pw) FAST_FUNC;
  1586. /* Returns a malloced string */
  1587. #if !ENABLE_USE_BB_CRYPT
  1588. #define pw_encrypt(clear, salt, cleanup) pw_encrypt(clear, salt)
  1589. #endif
  1590. extern char *pw_encrypt(const char *clear, const char *salt, int cleanup) FAST_FUNC;
  1591. extern int obscure(const char *old, const char *newval, const struct passwd *pwdp) FAST_FUNC;
  1592. /*
  1593. * rnd is additional random input. New one is returned.
  1594. * Useful if you call crypt_make_salt many times in a row:
  1595. * rnd = crypt_make_salt(buf1, 4, 0);
  1596. * rnd = crypt_make_salt(buf2, 4, rnd);
  1597. * rnd = crypt_make_salt(buf3, 4, rnd);
  1598. * (otherwise we risk having same salt generated)
  1599. */
  1600. extern int crypt_make_salt(char *p, int cnt /*, int rnd*/) FAST_FUNC;
  1601. /* "$N$" + sha_salt_16_bytes + NUL */
  1602. #define MAX_PW_SALT_LEN (3 + 16 + 1)
  1603. extern char* crypt_make_pw_salt(char p[MAX_PW_SALT_LEN], const char *algo) FAST_FUNC;
  1604. /* Returns number of lines changed, or -1 on error */
  1605. #if !(ENABLE_FEATURE_ADDUSER_TO_GROUP || ENABLE_FEATURE_DEL_USER_FROM_GROUP)
  1606. #define update_passwd(filename, username, data, member) \
  1607. update_passwd(filename, username, data)
  1608. #endif
  1609. extern int update_passwd(const char *filename,
  1610. const char *username,
  1611. const char *data,
  1612. const char *member) FAST_FUNC;
  1613. int index_in_str_array(const char *const string_array[], const char *key) FAST_FUNC;
  1614. int index_in_strings(const char *strings, const char *key) FAST_FUNC;
  1615. int index_in_substr_array(const char *const string_array[], const char *key) FAST_FUNC;
  1616. int index_in_substrings(const char *strings, const char *key) FAST_FUNC;
  1617. const char *nth_string(const char *strings, int n) FAST_FUNC;
  1618. extern void print_login_issue(const char *issue_file, const char *tty) FAST_FUNC;
  1619. extern void print_login_prompt(void) FAST_FUNC;
  1620. char *xmalloc_ttyname(int fd) FAST_FUNC RETURNS_MALLOC;
  1621. /* NB: typically you want to pass fd 0, not 1. Think 'applet | grep something' */
  1622. int get_terminal_width_height(int fd, unsigned *width, unsigned *height) FAST_FUNC;
  1623. int get_terminal_width(int fd) FAST_FUNC;
  1624. int tcsetattr_stdin_TCSANOW(const struct termios *tp) FAST_FUNC;
  1625. #define TERMIOS_CLEAR_ISIG (1 << 0)
  1626. #define TERMIOS_RAW_CRNL_INPUT (1 << 1)
  1627. #define TERMIOS_RAW_CRNL_OUTPUT (1 << 2)
  1628. #define TERMIOS_RAW_CRNL (TERMIOS_RAW_CRNL_INPUT|TERMIOS_RAW_CRNL_OUTPUT)
  1629. #define TERMIOS_RAW_INPUT (1 << 3)
  1630. int get_termios_and_make_raw(int fd, struct termios *newterm, struct termios *oldterm, int flags) FAST_FUNC;
  1631. int set_termios_to_raw(int fd, struct termios *oldterm, int flags) FAST_FUNC;
  1632. /* NB: "unsigned request" is crucial! "int request" will break some arches! */
  1633. int ioctl_or_perror(int fd, unsigned request, void *argp, const char *fmt,...) __attribute__ ((format (printf, 4, 5))) FAST_FUNC;
  1634. int ioctl_or_perror_and_die(int fd, unsigned request, void *argp, const char *fmt,...) __attribute__ ((format (printf, 4, 5))) FAST_FUNC;
  1635. #if ENABLE_IOCTL_HEX2STR_ERROR
  1636. int bb_ioctl_or_warn(int fd, unsigned request, void *argp, const char *ioctl_name) FAST_FUNC;
  1637. int bb_xioctl(int fd, unsigned request, void *argp, const char *ioctl_name) FAST_FUNC;
  1638. #define ioctl_or_warn(fd,request,argp) bb_ioctl_or_warn(fd,request,argp,#request)
  1639. #define xioctl(fd,request,argp) bb_xioctl(fd,request,argp,#request)
  1640. #else
  1641. int bb_ioctl_or_warn(int fd, unsigned request, void *argp) FAST_FUNC;
  1642. int bb_xioctl(int fd, unsigned request, void *argp) FAST_FUNC;
  1643. #define ioctl_or_warn(fd,request,argp) bb_ioctl_or_warn(fd,request,argp)
  1644. #define xioctl(fd,request,argp) bb_xioctl(fd,request,argp)
  1645. #endif
  1646. char *is_in_ino_dev_hashtable(const struct stat *statbuf) FAST_FUNC;
  1647. void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name) FAST_FUNC;
  1648. void reset_ino_dev_hashtable(void) FAST_FUNC;
  1649. #ifdef __GLIBC__
  1650. /* At least glibc has horrendously large inline for this, so wrap it */
  1651. unsigned long long bb_makedev(unsigned major, unsigned minor) FAST_FUNC;
  1652. #undef makedev
  1653. #define makedev(a,b) bb_makedev(a,b)
  1654. #endif
  1655. /* "Keycodes" that report an escape sequence.
  1656. * We use something which fits into signed char,
  1657. * yet doesn't represent any valid Unicode character.
  1658. * Also, -1 is reserved for error indication and we don't use it. */
  1659. enum {
  1660. KEYCODE_UP = -2,
  1661. KEYCODE_DOWN = -3,
  1662. KEYCODE_RIGHT = -4,
  1663. KEYCODE_LEFT = -5,
  1664. KEYCODE_HOME = -6,
  1665. KEYCODE_END = -7,
  1666. KEYCODE_INSERT = -8,
  1667. KEYCODE_DELETE = -9,
  1668. KEYCODE_PAGEUP = -10,
  1669. KEYCODE_PAGEDOWN = -11,
  1670. KEYCODE_BACKSPACE = -12, /* Used only if Alt/Ctrl/Shifted */
  1671. KEYCODE_D = -13, /* Used only if Alted */
  1672. #if 0
  1673. KEYCODE_FUN1 = ,
  1674. KEYCODE_FUN2 = ,
  1675. KEYCODE_FUN3 = ,
  1676. KEYCODE_FUN4 = ,
  1677. KEYCODE_FUN5 = ,
  1678. KEYCODE_FUN6 = ,
  1679. KEYCODE_FUN7 = ,
  1680. KEYCODE_FUN8 = ,
  1681. KEYCODE_FUN9 = ,
  1682. KEYCODE_FUN10 = ,
  1683. KEYCODE_FUN11 = ,
  1684. KEYCODE_FUN12 = ,
  1685. #endif
  1686. /* ^^^^^ Be sure that last defined value is small enough.
  1687. * Current read_key() code allows going up to -32 (0xfff..fffe0).
  1688. * This gives three upper bits in LSB to play with:
  1689. * KEYCODE_foo values are 0xfff..fffXX, lowest XX bits are: scavvvvv,
  1690. * s=0 if SHIFT, c=0 if CTRL, a=0 if ALT,
  1691. * vvvvv bits are the same for same key regardless of "shift bits".
  1692. */
  1693. //KEYCODE_SHIFT_... = KEYCODE_... & ~0x80,
  1694. KEYCODE_CTRL_RIGHT = KEYCODE_RIGHT & ~0x40,
  1695. KEYCODE_CTRL_LEFT = KEYCODE_LEFT & ~0x40,
  1696. KEYCODE_ALT_RIGHT = KEYCODE_RIGHT & ~0x20,
  1697. KEYCODE_ALT_LEFT = KEYCODE_LEFT & ~0x20,
  1698. KEYCODE_ALT_BACKSPACE = KEYCODE_BACKSPACE & ~0x20,
  1699. KEYCODE_ALT_D = KEYCODE_D & ~0x20,
  1700. KEYCODE_CURSOR_POS = -0x100, /* 0xfff..fff00 */
  1701. /* How long is the longest ESC sequence we know?
  1702. * We want it big enough to be able to contain
  1703. * cursor position sequence "ESC [ 9999 ; 9999 R"
  1704. */
  1705. KEYCODE_BUFFER_SIZE = 16
  1706. };
  1707. /* Note: fd may be in blocking or non-blocking mode, both make sense.
  1708. * For one, less uses non-blocking mode.
  1709. * Only the first read syscall inside read_key may block indefinitely
  1710. * (unless fd is in non-blocking mode),
  1711. * subsequent reads will time out after a few milliseconds.
  1712. * Return of -1 means EOF or error (errno == 0 on EOF).
  1713. * buffer[0] is used as a counter of buffered chars and must be 0
  1714. * on first call.
  1715. * timeout:
  1716. * -2: do not poll(-1) for input - read() it, return on EAGAIN at once
  1717. * -1: poll(-1) (i.e. block even on NONBLOCKed fd)
  1718. * >=0: poll() for TIMEOUT milliseconds, return -1/EAGAIN on timeout
  1719. */
  1720. int64_t read_key(int fd, char *buffer, int timeout) FAST_FUNC;
  1721. void read_key_ungets(char *buffer, const char *str, unsigned len) FAST_FUNC;
  1722. #if ENABLE_FEATURE_EDITING
  1723. /* It's NOT just ENABLEd or disabled. It's a number: */
  1724. # if defined CONFIG_FEATURE_EDITING_HISTORY && CONFIG_FEATURE_EDITING_HISTORY > 0
  1725. # define MAX_HISTORY (CONFIG_FEATURE_EDITING_HISTORY + 0)
  1726. unsigned size_from_HISTFILESIZE(const char *hp) FAST_FUNC;
  1727. # else
  1728. # define MAX_HISTORY 0
  1729. # endif
  1730. typedef const char *get_exe_name_t(int i) FAST_FUNC;
  1731. typedef struct line_input_t {
  1732. int flags;
  1733. int timeout;
  1734. # if ENABLE_FEATURE_TAB_COMPLETION
  1735. # if ENABLE_SHELL_ASH
  1736. const char *path_lookup;
  1737. # define EDITING_HAS_path_lookup 1
  1738. # else
  1739. # define EDITING_HAS_path_lookup 0
  1740. # endif
  1741. # if ENABLE_SHELL_ASH || ENABLE_SHELL_HUSH
  1742. /* function to fetch additional application-specific names to match */
  1743. get_exe_name_t *get_exe_name;
  1744. # define EDITING_HAS_get_exe_name 1
  1745. # else
  1746. # define EDITING_HAS_get_exe_name 0
  1747. # endif
  1748. # endif
  1749. # if MAX_HISTORY
  1750. int cnt_history;
  1751. int cur_history;
  1752. int max_history; /* must never be <= 0 */
  1753. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1754. /* meaning of this field depends on FEATURE_EDITING_SAVE_ON_EXIT:
  1755. * if !FEATURE_EDITING_SAVE_ON_EXIT: "how many lines are
  1756. * in on-disk history"
  1757. * if FEATURE_EDITING_SAVE_ON_EXIT: "how many in-memory lines are
  1758. * also in on-disk history (and thus need to be skipped on save)"
  1759. */
  1760. unsigned cnt_history_in_file;
  1761. const char *hist_file;
  1762. # endif
  1763. char *history[MAX_HISTORY + 1];
  1764. # endif
  1765. } line_input_t;
  1766. enum {
  1767. DO_HISTORY = 1 * (MAX_HISTORY > 0),
  1768. TAB_COMPLETION = 2 * ENABLE_FEATURE_TAB_COMPLETION,
  1769. USERNAME_COMPLETION = 4 * ENABLE_FEATURE_USERNAME_COMPLETION,
  1770. VI_MODE = 8 * ENABLE_FEATURE_EDITING_VI,
  1771. WITH_PATH_LOOKUP = 0x10,
  1772. FOR_SHELL = DO_HISTORY | TAB_COMPLETION | USERNAME_COMPLETION,
  1773. };
  1774. line_input_t *new_line_input_t(int flags) FAST_FUNC;
  1775. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1776. void free_line_input_t(line_input_t *n) FAST_FUNC;
  1777. #else
  1778. # define free_line_input_t(n) free(n)
  1779. #endif
  1780. /*
  1781. * maxsize must be >= 2.
  1782. * Returns:
  1783. * -1 on read errors or EOF, or on bare Ctrl-D,
  1784. * 0 on ctrl-C (the line entered is still returned in 'command'),
  1785. * >0 length of input string, including terminating '\n'
  1786. */
  1787. int read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize) FAST_FUNC;
  1788. void show_history(const line_input_t *st) FAST_FUNC;
  1789. # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1790. void save_history(line_input_t *st);
  1791. # endif
  1792. #else
  1793. #define MAX_HISTORY 0
  1794. int read_line_input(const char* prompt, char* command, int maxsize) FAST_FUNC;
  1795. #define read_line_input(state, prompt, command, maxsize) \
  1796. read_line_input(prompt, command, maxsize)
  1797. #endif
  1798. #ifndef EDITING_HAS_get_exe_name
  1799. # define EDITING_HAS_get_exe_name 0
  1800. #endif
  1801. #ifndef COMM_LEN
  1802. # ifdef TASK_COMM_LEN
  1803. enum { COMM_LEN = TASK_COMM_LEN };
  1804. # else
  1805. /* synchronize with sizeof(task_struct.comm) in /usr/include/linux/sched.h */
  1806. enum { COMM_LEN = 16 };
  1807. # endif
  1808. #endif
  1809. struct smaprec {
  1810. unsigned long mapped_rw;
  1811. unsigned long mapped_ro;
  1812. unsigned long shared_clean;
  1813. unsigned long shared_dirty;
  1814. unsigned long private_clean;
  1815. unsigned long private_dirty;
  1816. unsigned long stack;
  1817. unsigned long smap_pss, smap_swap;
  1818. unsigned long smap_size;
  1819. // For mixed 32/64 userspace, 32-bit pmap still needs
  1820. // 64-bit field here to correctly show 64-bit processes:
  1821. unsigned long long smap_start;
  1822. // (strictly speaking, other fields need to be wider too,
  1823. // but they are in kbytes, not bytes, and they hold sizes,
  1824. // not start addresses, sizes tend to be less than 4 terabytes)
  1825. char smap_mode[5];
  1826. char *smap_name;
  1827. };
  1828. #if !ENABLE_PMAP
  1829. #define procps_read_smaps(pid, total, cb, data) \
  1830. procps_read_smaps(pid, total)
  1831. #endif
  1832. int FAST_FUNC procps_read_smaps(pid_t pid, struct smaprec *total,
  1833. void (*cb)(struct smaprec *, void *), void *data);
  1834. typedef struct procps_status_t {
  1835. DIR *dir;
  1836. IF_FEATURE_SHOW_THREADS(DIR *task_dir;)
  1837. uint8_t shift_pages_to_bytes;
  1838. uint8_t shift_pages_to_kb;
  1839. /* Fields are set to 0/NULL if failed to determine (or not requested) */
  1840. uint16_t argv_len;
  1841. char *argv0;
  1842. char *exe;
  1843. IF_SELINUX(char *context;)
  1844. IF_FEATURE_SHOW_THREADS(unsigned main_thread_pid;)
  1845. /* Everything below must contain no ptrs to malloc'ed data:
  1846. * it is memset(0) for each process in procps_scan() */
  1847. unsigned long vsz, rss; /* we round it to kbytes */
  1848. unsigned long stime, utime;
  1849. unsigned long start_time;
  1850. unsigned pid;
  1851. unsigned ppid;
  1852. unsigned pgid;
  1853. unsigned sid;
  1854. unsigned uid;
  1855. unsigned gid;
  1856. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  1857. unsigned ruid;
  1858. unsigned rgid;
  1859. int niceness;
  1860. #endif
  1861. unsigned tty_major,tty_minor;
  1862. #if ENABLE_FEATURE_TOPMEM
  1863. struct smaprec smaps;
  1864. #endif
  1865. char state[4];
  1866. /* basename of executable in exec(2), read from /proc/N/stat
  1867. * (if executable is symlink or script, it is NOT replaced
  1868. * by link target or interpreter name) */
  1869. char comm[COMM_LEN];
  1870. /* user/group? - use passwd/group parsing functions */
  1871. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  1872. int last_seen_on_cpu;
  1873. #endif
  1874. } procps_status_t;
  1875. /* flag bits for procps_scan(xx, flags) calls */
  1876. enum {
  1877. PSSCAN_PID = 1 << 0,
  1878. PSSCAN_PPID = 1 << 1,
  1879. PSSCAN_PGID = 1 << 2,
  1880. PSSCAN_SID = 1 << 3,
  1881. PSSCAN_UIDGID = 1 << 4,
  1882. PSSCAN_COMM = 1 << 5,
  1883. /* PSSCAN_CMD = 1 << 6, - use read_cmdline instead */
  1884. PSSCAN_ARGV0 = 1 << 7,
  1885. PSSCAN_EXE = 1 << 8,
  1886. PSSCAN_STATE = 1 << 9,
  1887. PSSCAN_VSZ = 1 << 10,
  1888. PSSCAN_RSS = 1 << 11,
  1889. PSSCAN_STIME = 1 << 12,
  1890. PSSCAN_UTIME = 1 << 13,
  1891. PSSCAN_TTY = 1 << 14,
  1892. PSSCAN_SMAPS = (1 << 15) * ENABLE_FEATURE_TOPMEM,
  1893. /* NB: used by find_pid_by_name(). Any applet using it
  1894. * needs to be mentioned here. */
  1895. PSSCAN_ARGVN = (1 << 16) * (ENABLE_KILLALL
  1896. || ENABLE_PGREP || ENABLE_PKILL
  1897. || ENABLE_PIDOF
  1898. || ENABLE_SESTATUS
  1899. ),
  1900. PSSCAN_CONTEXT = (1 << 17) * ENABLE_SELINUX,
  1901. PSSCAN_START_TIME = 1 << 18,
  1902. PSSCAN_CPU = (1 << 19) * ENABLE_FEATURE_TOP_SMP_PROCESS,
  1903. PSSCAN_NICE = (1 << 20) * ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS,
  1904. PSSCAN_RUIDGID = (1 << 21) * ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS,
  1905. PSSCAN_TASKS = (1 << 22) * ENABLE_FEATURE_SHOW_THREADS,
  1906. };
  1907. //procps_status_t* alloc_procps_scan(void) FAST_FUNC;
  1908. void free_procps_scan(procps_status_t* sp) FAST_FUNC;
  1909. procps_status_t* procps_scan(procps_status_t* sp, int flags) FAST_FUNC;
  1910. /* Format cmdline (up to col chars) into char buf[size] */
  1911. /* Puts [comm] if cmdline is empty (-> process is a kernel thread) */
  1912. void read_cmdline(char *buf, int size, unsigned pid, const char *comm) FAST_FUNC;
  1913. pid_t *find_pid_by_name(const char* procName) FAST_FUNC;
  1914. pid_t *pidlist_reverse(pid_t *pidList) FAST_FUNC;
  1915. int starts_with_cpu(const char *str) FAST_FUNC;
  1916. unsigned get_cpu_count(void) FAST_FUNC;
  1917. /* Use strict=1 if you process input from untrusted source:
  1918. * it will return NULL on invalid %xx (bad hex chars)
  1919. * and str + 1 if decoded char is / or NUL.
  1920. * In non-strict mode, it always succeeds (returns str),
  1921. * and also it additionally decoded '+' to space.
  1922. */
  1923. char *percent_decode_in_place(char *str, int strict) FAST_FUNC;
  1924. extern const char bb_uuenc_tbl_base64[] ALIGN1;
  1925. extern const char bb_uuenc_tbl_base32[] ALIGN1;
  1926. extern const char bb_uuenc_tbl_std[] ALIGN1;
  1927. void bb_uuencode(char *store, const void *s, int length, const char *tbl) FAST_FUNC;
  1928. enum {
  1929. BASE64_FLAG_UU_STOP = 0x100,
  1930. BASE64_32 = 0x200, /* base32 */
  1931. /* Sign-extends to a value which never matches fgetc result: */
  1932. BASE64_FLAG_NO_STOP_CHAR = 0x80,
  1933. };
  1934. char *decode_base64(char *dst, const char **pp_src) FAST_FUNC;
  1935. char *decode_base32(char *dst, const char **pp_src) FAST_FUNC;
  1936. void read_base64(FILE *src_stream, FILE *dst_stream, int flags) FAST_FUNC;
  1937. typedef struct md5_ctx_t {
  1938. uint8_t wbuffer[64]; /* always correctly aligned for uint64_t */
  1939. void (*process_block)(struct md5_ctx_t*) FAST_FUNC;
  1940. uint64_t total64; /* must be directly before hash[] */
  1941. uint32_t hash[8]; /* 4 elements for md5, 5 for sha1, 8 for sha256 */
  1942. } md5_ctx_t;
  1943. typedef struct md5_ctx_t sha1_ctx_t;
  1944. typedef struct md5_ctx_t sha256_ctx_t;
  1945. typedef struct sha512_ctx_t {
  1946. uint64_t total64[2]; /* must be directly before hash[] */
  1947. uint64_t hash[8];
  1948. uint8_t wbuffer[128]; /* always correctly aligned for uint64_t */
  1949. } sha512_ctx_t;
  1950. typedef struct sha3_ctx_t {
  1951. uint64_t state[25];
  1952. unsigned bytes_queued;
  1953. unsigned input_block_bytes;
  1954. } sha3_ctx_t;
  1955. void md5_begin(md5_ctx_t *ctx) FAST_FUNC;
  1956. void md5_hash(md5_ctx_t *ctx, const void *buffer, size_t len) FAST_FUNC;
  1957. unsigned md5_end(md5_ctx_t *ctx, void *resbuf) FAST_FUNC;
  1958. void sha1_begin(sha1_ctx_t *ctx) FAST_FUNC;
  1959. #define sha1_hash md5_hash
  1960. unsigned sha1_end(sha1_ctx_t *ctx, void *resbuf) FAST_FUNC;
  1961. void sha256_begin(sha256_ctx_t *ctx) FAST_FUNC;
  1962. #define sha256_hash md5_hash
  1963. #define sha256_end sha1_end
  1964. void sha512_begin(sha512_ctx_t *ctx) FAST_FUNC;
  1965. void sha512_hash(sha512_ctx_t *ctx, const void *buffer, size_t len) FAST_FUNC;
  1966. unsigned sha512_end(sha512_ctx_t *ctx, void *resbuf) FAST_FUNC;
  1967. void sha3_begin(sha3_ctx_t *ctx) FAST_FUNC;
  1968. void sha3_hash(sha3_ctx_t *ctx, const void *buffer, size_t len) FAST_FUNC;
  1969. unsigned sha3_end(sha3_ctx_t *ctx, void *resbuf) FAST_FUNC;
  1970. /* TLS benefits from knowing that sha1 and sha256 share these. Give them "agnostic" names too */
  1971. typedef struct md5_ctx_t md5sha_ctx_t;
  1972. #define md5sha_hash md5_hash
  1973. #define sha_end sha1_end
  1974. enum {
  1975. MD5_OUTSIZE = 16,
  1976. SHA1_OUTSIZE = 20,
  1977. SHA256_OUTSIZE = 32,
  1978. SHA512_OUTSIZE = 64,
  1979. SHA3_OUTSIZE = 28,
  1980. };
  1981. extern uint32_t *global_crc32_table;
  1982. uint32_t *crc32_filltable(uint32_t *tbl256, int endian) FAST_FUNC;
  1983. uint32_t *crc32_new_table_le(void) FAST_FUNC;
  1984. uint32_t *global_crc32_new_table_le(void) FAST_FUNC;
  1985. uint32_t crc32_block_endian1(uint32_t val, const void *buf, unsigned len, uint32_t *crc_table) FAST_FUNC;
  1986. uint32_t crc32_block_endian0(uint32_t val, const void *buf, unsigned len, uint32_t *crc_table) FAST_FUNC;
  1987. typedef struct masks_labels_t {
  1988. const char *labels;
  1989. const int masks[];
  1990. } masks_labels_t;
  1991. int print_flags_separated(const int *masks, const char *labels,
  1992. int flags, const char *separator) FAST_FUNC;
  1993. int print_flags(const masks_labels_t *ml, int flags) FAST_FUNC;
  1994. typedef struct bb_progress_t {
  1995. unsigned last_size;
  1996. unsigned last_update_sec;
  1997. unsigned last_change_sec;
  1998. unsigned start_sec;
  1999. /*unsigned last_eta;*/
  2000. const char *curfile;
  2001. } bb_progress_t;
  2002. #define is_bb_progress_inited(p) ((p)->curfile != NULL)
  2003. #define bb_progress_free(p) do { \
  2004. if (ENABLE_UNICODE_SUPPORT) free((char*)((p)->curfile)); \
  2005. (p)->curfile = NULL; \
  2006. } while (0)
  2007. void bb_progress_init(bb_progress_t *p, const char *curfile) FAST_FUNC;
  2008. int bb_progress_update(bb_progress_t *p,
  2009. uoff_t beg_range,
  2010. uoff_t transferred,
  2011. uoff_t totalsize) FAST_FUNC;
  2012. unsigned ubi_devnum_from_devname(const char *str) FAST_FUNC;
  2013. int ubi_get_volid_by_name(unsigned ubi_devnum, const char *vol_name) FAST_FUNC;
  2014. extern const char *applet_name;
  2015. /* Some older linkers don't perform string merging, we used to have common strings
  2016. * as global arrays to do it by hand. But:
  2017. * (1) newer linkers do it themselves,
  2018. * (2) however, they DONT merge string constants with global arrays,
  2019. * even if the value is the same (!). Thus global arrays actually
  2020. * increased size a bit: for example, "/etc/passwd" string from libc
  2021. * wasn't merged with bb_path_passwd_file[] array!
  2022. * Therefore now we use #defines.
  2023. */
  2024. /* "BusyBox vN.N.N (timestamp or extra_version)" */
  2025. extern const char bb_banner[] ALIGN1;
  2026. extern const char bb_msg_memory_exhausted[] ALIGN1;
  2027. extern const char bb_msg_invalid_date[] ALIGN1;
  2028. #define bb_msg_read_error "read error"
  2029. #define bb_msg_write_error "write error"
  2030. extern const char bb_msg_unknown[] ALIGN1;
  2031. extern const char bb_msg_can_not_create_raw_socket[] ALIGN1;
  2032. extern const char bb_msg_perm_denied_are_you_root[] ALIGN1;
  2033. extern const char bb_msg_you_must_be_root[] ALIGN1;
  2034. extern const char bb_msg_requires_arg[] ALIGN1;
  2035. extern const char bb_msg_invalid_arg_to[] ALIGN1;
  2036. extern const char bb_msg_standard_input[] ALIGN1;
  2037. extern const char bb_msg_standard_output[] ALIGN1;
  2038. /* NB: (bb_hexdigits_upcase[i] | 0x20) -> lowercase hex digit */
  2039. extern const char bb_hexdigits_upcase[] ALIGN1;
  2040. extern const char bb_path_wtmp_file[] ALIGN1;
  2041. /* Busybox mount uses either /proc/mounts or /etc/mtab to
  2042. * get the list of currently mounted filesystems */
  2043. #define bb_path_mtab_file IF_FEATURE_MTAB_SUPPORT("/etc/mtab")IF_NOT_FEATURE_MTAB_SUPPORT("/proc/mounts")
  2044. #define bb_path_passwd_file _PATH_PASSWD
  2045. #define bb_path_group_file _PATH_GROUP
  2046. #define bb_path_shadow_file _PATH_SHADOW
  2047. #define bb_path_gshadow_file _PATH_GSHADOW
  2048. #define bb_path_motd_file "/etc/motd"
  2049. #define bb_dev_null "/dev/null"
  2050. extern const char bb_busybox_exec_path[] ALIGN1;
  2051. /* allow default system PATH to be extended via CFLAGS */
  2052. #ifndef BB_ADDITIONAL_PATH
  2053. #define BB_ADDITIONAL_PATH ""
  2054. #endif
  2055. #define BB_PATH_ROOT_PATH "PATH=/sbin:/usr/sbin:/bin:/usr/bin" BB_ADDITIONAL_PATH
  2056. extern const char bb_PATH_root_path[] ALIGN1; /* BB_PATH_ROOT_PATH */
  2057. #define bb_default_root_path (bb_PATH_root_path + sizeof("PATH"))
  2058. /* util-linux manpage says /sbin:/bin:/usr/sbin:/usr/bin,
  2059. * but I want to save a few bytes here:
  2060. */
  2061. #define bb_default_path (bb_PATH_root_path + sizeof("PATH=/sbin:/usr/sbin"))
  2062. extern const int const_int_0;
  2063. //extern const int const_int_1;
  2064. /* This struct is deliberately not defined. */
  2065. /* See docs/keep_data_small.txt */
  2066. struct globals;
  2067. /* '*const' ptr makes gcc optimize code much better.
  2068. * Magic prevents ptr_to_globals from going into rodata.
  2069. * If you want to assign a value, use SET_PTR_TO_GLOBALS(x) */
  2070. extern struct globals *const ptr_to_globals;
  2071. #if defined(__clang_major__) && __clang_major__ >= 9
  2072. /* Clang/llvm drops assignment to "constant" storage. Silently.
  2073. * Needs serious convincing to not eliminate the store.
  2074. */
  2075. static ALWAYS_INLINE void* not_const_pp(const void *p)
  2076. {
  2077. void *pp;
  2078. __asm__ __volatile__(
  2079. "# forget that p points to const"
  2080. : /*outputs*/ "=r" (pp)
  2081. : /*inputs*/ "0" (p)
  2082. );
  2083. return pp;
  2084. }
  2085. #else
  2086. static ALWAYS_INLINE void* not_const_pp(const void *p) { return (void*)p; }
  2087. #endif
  2088. /* At least gcc 3.4.6 on mipsel system needs optimization barrier */
  2089. #define barrier() __asm__ __volatile__("":::"memory")
  2090. #define SET_PTR_TO_GLOBALS(x) do { \
  2091. (*(struct globals**)not_const_pp(&ptr_to_globals)) = (void*)(x); \
  2092. barrier(); \
  2093. } while (0)
  2094. #define FREE_PTR_TO_GLOBALS() do { \
  2095. if (ENABLE_FEATURE_CLEAN_UP) { \
  2096. free(ptr_to_globals); \
  2097. } \
  2098. } while (0)
  2099. /* You can change LIBBB_DEFAULT_LOGIN_SHELL, but don't use it,
  2100. * use bb_default_login_shell and following defines.
  2101. * If you change LIBBB_DEFAULT_LOGIN_SHELL,
  2102. * don't forget to change increment constant. */
  2103. #define LIBBB_DEFAULT_LOGIN_SHELL "-/bin/sh"
  2104. extern const char bb_default_login_shell[] ALIGN1;
  2105. /* "/bin/sh" */
  2106. #define DEFAULT_SHELL (bb_default_login_shell+1)
  2107. /* "sh" */
  2108. #define DEFAULT_SHELL_SHORT_NAME (bb_default_login_shell+6)
  2109. /* The following devices are the same on all systems. */
  2110. #define CURRENT_TTY "/dev/tty"
  2111. #define DEV_CONSOLE "/dev/console"
  2112. #if defined(__FreeBSD_kernel__)
  2113. # define CURRENT_VC CURRENT_TTY
  2114. # define VC_1 "/dev/ttyv0"
  2115. # define VC_2 "/dev/ttyv1"
  2116. # define VC_3 "/dev/ttyv2"
  2117. # define VC_4 "/dev/ttyv3"
  2118. # define VC_5 "/dev/ttyv4"
  2119. # define VC_FORMAT "/dev/ttyv%d"
  2120. #elif defined(__GNU__)
  2121. # define CURRENT_VC CURRENT_TTY
  2122. # define VC_1 "/dev/tty1"
  2123. # define VC_2 "/dev/tty2"
  2124. # define VC_3 "/dev/tty3"
  2125. # define VC_4 "/dev/tty4"
  2126. # define VC_5 "/dev/tty5"
  2127. # define VC_FORMAT "/dev/tty%d"
  2128. #elif ENABLE_FEATURE_DEVFS
  2129. /*Linux, obsolete devfs names */
  2130. # define CURRENT_VC "/dev/vc/0"
  2131. # define VC_1 "/dev/vc/1"
  2132. # define VC_2 "/dev/vc/2"
  2133. # define VC_3 "/dev/vc/3"
  2134. # define VC_4 "/dev/vc/4"
  2135. # define VC_5 "/dev/vc/5"
  2136. # define VC_FORMAT "/dev/vc/%d"
  2137. # define LOOP_FORMAT "/dev/loop/%u"
  2138. # define LOOP_NAMESIZE (sizeof("/dev/loop/") + sizeof(int)*3 + 1)
  2139. # define LOOP_NAME "/dev/loop/"
  2140. # define FB_0 "/dev/fb/0"
  2141. #else
  2142. /*Linux, normal names */
  2143. # define CURRENT_VC "/dev/tty0"
  2144. # define VC_1 "/dev/tty1"
  2145. # define VC_2 "/dev/tty2"
  2146. # define VC_3 "/dev/tty3"
  2147. # define VC_4 "/dev/tty4"
  2148. # define VC_5 "/dev/tty5"
  2149. # define VC_FORMAT "/dev/tty%d"
  2150. # define LOOP_FORMAT "/dev/loop%u"
  2151. # define LOOP_NAMESIZE (sizeof("/dev/loop") + sizeof(int)*3 + 1)
  2152. # define LOOP_NAME "/dev/loop"
  2153. # define FB_0 "/dev/fb0"
  2154. #endif
  2155. // storage helpers for mk*fs utilities
  2156. char BUG_wrong_field_size(void);
  2157. #define STORE_LE(field, value) \
  2158. do { \
  2159. if (sizeof(field) == 4) \
  2160. field = SWAP_LE32((uint32_t)(value)); \
  2161. else if (sizeof(field) == 2) \
  2162. field = SWAP_LE16((uint16_t)(value)); \
  2163. else if (sizeof(field) == 1) \
  2164. field = (uint8_t)(value); \
  2165. else \
  2166. BUG_wrong_field_size(); \
  2167. } while (0)
  2168. #define FETCH_LE32(field) \
  2169. (sizeof(field) == 4 ? SWAP_LE32(field) : BUG_wrong_field_size())
  2170. #define ARRAY_SIZE(x) ((unsigned)(sizeof(x) / sizeof((x)[0])))
  2171. #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
  2172. /* We redefine ctype macros. Unicode-correct handling of char types
  2173. * can't be done with such byte-oriented operations anyway,
  2174. * we don't lose anything.
  2175. */
  2176. #undef isalnum
  2177. #undef isalpha
  2178. #undef isascii
  2179. #undef isblank
  2180. #undef iscntrl
  2181. #undef isdigit
  2182. #undef isgraph
  2183. #undef islower
  2184. #undef isprint
  2185. #undef ispunct
  2186. #undef isspace
  2187. #undef isupper
  2188. #undef isxdigit
  2189. #undef toupper
  2190. #undef tolower
  2191. /* We save ~500 bytes on isdigit alone.
  2192. * BTW, x86 likes (unsigned char) cast more than (unsigned). */
  2193. /* These work the same for ASCII and Unicode,
  2194. * assuming no one asks "is this a *Unicode* letter?" using isalpha(letter) */
  2195. #define isascii(a) ((unsigned char)(a) <= 0x7f)
  2196. #define isdigit(a) ((unsigned char)((a) - '0') <= 9)
  2197. #define isupper(a) ((unsigned char)((a) - 'A') <= ('Z' - 'A'))
  2198. #define islower(a) ((unsigned char)((a) - 'a') <= ('z' - 'a'))
  2199. #define isalpha(a) ((unsigned char)(((a)|0x20) - 'a') <= ('z' - 'a'))
  2200. #define isblank(a) ({ unsigned char bb__isblank = (a); bb__isblank == ' ' || bb__isblank == '\t'; })
  2201. #define iscntrl(a) ({ unsigned char bb__iscntrl = (a); bb__iscntrl < ' ' || bb__iscntrl == 0x7f; })
  2202. /* In POSIX/C locale isspace is only these chars: "\t\n\v\f\r" and space.
  2203. * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
  2204. */
  2205. #define isspace(a) ({ unsigned char bb__isspace = (a) - 9; bb__isspace == (' ' - 9) || bb__isspace <= (13 - 9); })
  2206. // Unsafe wrt NUL: #define ispunct(a) (strchr("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", (a)) != NULL)
  2207. #define ispunct(a) (strchrnul("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", (a))[0])
  2208. // Bigger code: #define isalnum(a) ({ unsigned char bb__isalnum = (a) - '0'; bb__isalnum <= 9 || ((bb__isalnum - ('A' - '0')) & 0xdf) <= 25; })
  2209. #define isalnum(a) bb_ascii_isalnum(a)
  2210. static ALWAYS_INLINE int bb_ascii_isalnum(unsigned char a)
  2211. {
  2212. unsigned char b = a - '0';
  2213. if (b <= 9)
  2214. return (b <= 9);
  2215. b = (a|0x20) - 'a';
  2216. return b <= 'z' - 'a';
  2217. }
  2218. #define isxdigit(a) bb_ascii_isxdigit(a)
  2219. static ALWAYS_INLINE int bb_ascii_isxdigit(unsigned char a)
  2220. {
  2221. unsigned char b = a - '0';
  2222. if (b <= 9)
  2223. return (b <= 9);
  2224. b = (a|0x20) - 'a';
  2225. return b <= 'f' - 'a';
  2226. }
  2227. #define toupper(a) bb_ascii_toupper(a)
  2228. static ALWAYS_INLINE unsigned char bb_ascii_toupper(unsigned char a)
  2229. {
  2230. unsigned char b = a - 'a';
  2231. if (b <= ('z' - 'a'))
  2232. a -= 'a' - 'A';
  2233. return a;
  2234. }
  2235. #define tolower(a) bb_ascii_tolower(a)
  2236. static ALWAYS_INLINE unsigned char bb_ascii_tolower(unsigned char a)
  2237. {
  2238. unsigned char b = a - 'A';
  2239. if (b <= ('Z' - 'A'))
  2240. a += 'a' - 'A';
  2241. return a;
  2242. }
  2243. /* In ASCII and Unicode, these are likely to be very different.
  2244. * Let's prevent ambiguous usage from the start */
  2245. #define isgraph(a) isgraph_is_ambiguous_dont_use(a)
  2246. #define isprint(a) isprint_is_ambiguous_dont_use(a)
  2247. /* NB: must not treat EOF as isgraph or isprint */
  2248. #define isgraph_asciionly(a) ((unsigned)((a) - 0x21) <= 0x7e - 0x21)
  2249. #define isprint_asciionly(a) ((unsigned)((a) - 0x20) <= 0x7e - 0x20)
  2250. /* Simple unit-testing framework */
  2251. typedef void (*bbunit_testfunc)(void);
  2252. struct bbunit_listelem {
  2253. const char* name;
  2254. bbunit_testfunc testfunc;
  2255. };
  2256. void bbunit_registertest(struct bbunit_listelem* test);
  2257. void bbunit_settestfailed(void);
  2258. #define BBUNIT_DEFINE_TEST(NAME) \
  2259. static void bbunit_##NAME##_test(void); \
  2260. static struct bbunit_listelem bbunit_##NAME##_elem = { \
  2261. .name = #NAME, \
  2262. .testfunc = bbunit_##NAME##_test, \
  2263. }; \
  2264. static void INIT_FUNC bbunit_##NAME##_register(void) \
  2265. { \
  2266. bbunit_registertest(&bbunit_##NAME##_elem); \
  2267. } \
  2268. static void bbunit_##NAME##_test(void)
  2269. /*
  2270. * Both 'goto bbunit_end' and 'break' are here only to get rid
  2271. * of compiler warnings.
  2272. */
  2273. #define BBUNIT_ENDTEST \
  2274. do { \
  2275. goto bbunit_end; \
  2276. bbunit_end: \
  2277. break; \
  2278. } while (0)
  2279. #define BBUNIT_PRINTASSERTFAIL \
  2280. do { \
  2281. bb_error_msg( \
  2282. "[ERROR] Assertion failed in file %s, line %d", \
  2283. __FILE__, __LINE__); \
  2284. } while (0)
  2285. #define BBUNIT_ASSERTION_FAILED \
  2286. do { \
  2287. bbunit_settestfailed(); \
  2288. goto bbunit_end; \
  2289. } while (0)
  2290. /*
  2291. * Assertions.
  2292. * For now we only offer assertions which cause tests to fail
  2293. * immediately. In the future 'expects' might be added too -
  2294. * similar to those offered by the gtest framework.
  2295. */
  2296. #define BBUNIT_ASSERT_EQ(EXPECTED, ACTUAL) \
  2297. do { \
  2298. if ((EXPECTED) != (ACTUAL)) { \
  2299. BBUNIT_PRINTASSERTFAIL; \
  2300. bb_error_msg("[ERROR] '%s' isn't equal to '%s'", \
  2301. #EXPECTED, #ACTUAL); \
  2302. BBUNIT_ASSERTION_FAILED; \
  2303. } \
  2304. } while (0)
  2305. #define BBUNIT_ASSERT_NOTEQ(EXPECTED, ACTUAL) \
  2306. do { \
  2307. if ((EXPECTED) == (ACTUAL)) { \
  2308. BBUNIT_PRINTASSERTFAIL; \
  2309. bb_error_msg("[ERROR] '%s' is equal to '%s'", \
  2310. #EXPECTED, #ACTUAL); \
  2311. BBUNIT_ASSERTION_FAILED; \
  2312. } \
  2313. } while (0)
  2314. #define BBUNIT_ASSERT_NOTNULL(PTR) \
  2315. do { \
  2316. if ((PTR) == NULL) { \
  2317. BBUNIT_PRINTASSERTFAIL; \
  2318. bb_error_msg("[ERROR] '%s' is NULL!", #PTR); \
  2319. BBUNIT_ASSERTION_FAILED; \
  2320. } \
  2321. } while (0)
  2322. #define BBUNIT_ASSERT_NULL(PTR) \
  2323. do { \
  2324. if ((PTR) != NULL) { \
  2325. BBUNIT_PRINTASSERTFAIL; \
  2326. bb_error_msg("[ERROR] '%s' is not NULL!", #PTR); \
  2327. BBUNIT_ASSERTION_FAILED; \
  2328. } \
  2329. } while (0)
  2330. #define BBUNIT_ASSERT_FALSE(STATEMENT) \
  2331. do { \
  2332. if ((STATEMENT)) { \
  2333. BBUNIT_PRINTASSERTFAIL; \
  2334. bb_error_msg("[ERROR] Statement '%s' evaluated to true!", \
  2335. #STATEMENT); \
  2336. BBUNIT_ASSERTION_FAILED; \
  2337. } \
  2338. } while (0)
  2339. #define BBUNIT_ASSERT_TRUE(STATEMENT) \
  2340. do { \
  2341. if (!(STATEMENT)) { \
  2342. BBUNIT_PRINTASSERTFAIL; \
  2343. bb_error_msg("[ERROR] Statement '%s' evaluated to false!", \
  2344. #STATEMENT); \
  2345. BBUNIT_ASSERTION_FAILED; \
  2346. } \
  2347. } while (0)
  2348. #define BBUNIT_ASSERT_STREQ(STR1, STR2) \
  2349. do { \
  2350. if (strcmp(STR1, STR2) != 0) { \
  2351. BBUNIT_PRINTASSERTFAIL; \
  2352. bb_error_msg("[ERROR] Strings '%s' and '%s' " \
  2353. "are not the same", STR1, STR2); \
  2354. BBUNIT_ASSERTION_FAILED; \
  2355. } \
  2356. } while (0)
  2357. #define BBUNIT_ASSERT_STRNOTEQ(STR1, STR2) \
  2358. do { \
  2359. if (strcmp(STR1, STR2) == 0) { \
  2360. BBUNIT_PRINTASSERTFAIL; \
  2361. bb_error_msg("[ERROR] Strings '%s' and '%s' " \
  2362. "are the same, but were " \
  2363. "expected to differ", STR1, STR2); \
  2364. BBUNIT_ASSERTION_FAILED; \
  2365. } \
  2366. } while (0)
  2367. POP_SAVED_FUNCTION_VISIBILITY
  2368. #endif