libbb.h 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  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 the GPL.
  7. *
  8. * Licensed under the GPL version 2, see the file LICENSE in this tarball.
  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 <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <stdarg.h>
  25. #include <stddef.h>
  26. #include <string.h>
  27. #include <sys/poll.h>
  28. #include <sys/ioctl.h>
  29. #include <sys/mman.h>
  30. #include <sys/socket.h>
  31. #include <sys/stat.h>
  32. #include <sys/time.h>
  33. #include <sys/types.h>
  34. #include <sys/wait.h>
  35. #include <termios.h>
  36. #include <time.h>
  37. #include <unistd.h>
  38. /* Try to pull in PATH_MAX */
  39. #include <limits.h>
  40. #include <sys/param.h>
  41. #ifdef HAVE_MNTENT_H
  42. #include <mntent.h>
  43. #endif
  44. #ifdef HAVE_SYS_STATFS_H
  45. #include <sys/statfs.h>
  46. #endif
  47. #if ENABLE_SELINUX
  48. #include <selinux/selinux.h>
  49. #include <selinux/context.h>
  50. #include <selinux/flask.h>
  51. #include <selinux/av_permissions.h>
  52. #endif
  53. #if ENABLE_LOCALE_SUPPORT
  54. # include <locale.h>
  55. #else
  56. # define setlocale(x,y) ((void)0)
  57. #endif
  58. #ifdef DMALLOC
  59. # include <dmalloc.h>
  60. #endif
  61. #include <pwd.h>
  62. #include <grp.h>
  63. #if ENABLE_FEATURE_SHADOWPASSWDS
  64. # if !ENABLE_USE_BB_SHADOW
  65. /* If using busybox's shadow implementation, do not include the shadow.h
  66. * header as the toolchain may not provide it at all.
  67. */
  68. # include <shadow.h>
  69. # endif
  70. #endif
  71. #if defined __FreeBSD__
  72. # include <netinet/in.h>
  73. # include <arpa/inet.h>
  74. #elif defined __APPLE__
  75. # include <netinet/in.h>
  76. #else
  77. # include <arpa/inet.h>
  78. # if !defined(__socklen_t_defined) && !defined(_SOCKLEN_T_DECLARED)
  79. /* We #define socklen_t *after* includes, otherwise we get
  80. * typedef redefinition errors from system headers
  81. * (in case "is it defined already" detection above failed)
  82. */
  83. # define socklen_t bb_socklen_t
  84. typedef unsigned socklen_t;
  85. # endif
  86. #endif
  87. /* Some libc's forget to declare these, do it ourself */
  88. extern char **environ;
  89. #if defined(__GLIBC__) && __GLIBC__ < 2
  90. int vdprintf(int d, const char *format, va_list ap);
  91. #endif
  92. /* klogctl is in libc's klog.h, but we cheat and not #include that */
  93. int klogctl(int type, char *b, int len);
  94. /* This is declared here rather than #including <libgen.h> in order to avoid
  95. * confusing the two versions of basename. See the dirname/basename man page
  96. * for details. */
  97. #if !defined __FreeBSD__
  98. char *dirname(char *path);
  99. #endif
  100. /* Include our own copy of struct sysinfo to avoid binary compatibility
  101. * problems with Linux 2.4, which changed things. Grumble, grumble. */
  102. struct sysinfo {
  103. long uptime; /* Seconds since boot */
  104. unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
  105. unsigned long totalram; /* Total usable main memory size */
  106. unsigned long freeram; /* Available memory size */
  107. unsigned long sharedram; /* Amount of shared memory */
  108. unsigned long bufferram; /* Memory used by buffers */
  109. unsigned long totalswap; /* Total swap space size */
  110. unsigned long freeswap; /* swap space still available */
  111. unsigned short procs; /* Number of current processes */
  112. unsigned short pad; /* Padding needed for m68k */
  113. unsigned long totalhigh; /* Total high memory size */
  114. unsigned long freehigh; /* Available high memory size */
  115. unsigned int mem_unit; /* Memory unit size in bytes */
  116. char _f[20 - 2 * sizeof(long) - sizeof(int)]; /* Padding: libc5 uses this.. */
  117. };
  118. int sysinfo(struct sysinfo* info);
  119. #ifndef PATH_MAX
  120. # define PATH_MAX 256
  121. #endif
  122. #ifndef BUFSIZ
  123. # define BUFSIZ 4096
  124. #endif
  125. /* Make all declarations hidden (-fvisibility flag only affects definitions) */
  126. /* (don't include system headers after this until corresponding pop!) */
  127. PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN
  128. #if ENABLE_USE_BB_PWD_GRP
  129. # include "pwd_.h"
  130. # include "grp_.h"
  131. #endif
  132. #if ENABLE_FEATURE_SHADOWPASSWDS
  133. # if ENABLE_USE_BB_SHADOW
  134. # include "shadow_.h"
  135. # endif
  136. #endif
  137. /* Tested to work correctly with all int types (IIRC :]) */
  138. #define MAXINT(T) (T)( \
  139. ((T)-1) > 0 \
  140. ? (T)-1 \
  141. : (T)~((T)1 << (sizeof(T)*8-1)) \
  142. )
  143. #define MININT(T) (T)( \
  144. ((T)-1) > 0 \
  145. ? (T)0 \
  146. : ((T)1 << (sizeof(T)*8-1)) \
  147. )
  148. /* Large file support */
  149. /* Note that CONFIG_LFS=y forces bbox to be built with all common ops
  150. * (stat, lseek etc) mapped to "largefile" variants by libc.
  151. * Practically it means that open() automatically has O_LARGEFILE added
  152. * and all filesize/file_offset parameters and struct members are "large"
  153. * (in today's world - signed 64bit). For full support of large files,
  154. * we need a few helper #defines (below) and careful use of off_t
  155. * instead of int/ssize_t. No lseek64(), O_LARGEFILE etc necessary */
  156. #if ENABLE_LFS
  157. /* CONFIG_LFS is on */
  158. # if ULONG_MAX > 0xffffffff
  159. /* "long" is long enough on this system */
  160. typedef unsigned long uoff_t;
  161. # define XATOOFF(a) xatoul_range(a, 0, LONG_MAX)
  162. /* usage: sz = BB_STRTOOFF(s, NULL, 10); if (errno || sz < 0) die(); */
  163. # define BB_STRTOOFF bb_strtoul
  164. # define STRTOOFF strtoul
  165. /* usage: printf("size: %"OFF_FMT"d (%"OFF_FMT"x)\n", sz, sz); */
  166. # define OFF_FMT "l"
  167. # else
  168. /* "long" is too short, need "long long" */
  169. typedef unsigned long long uoff_t;
  170. # define XATOOFF(a) xatoull_range(a, 0, LLONG_MAX)
  171. # define BB_STRTOOFF bb_strtoull
  172. # define STRTOOFF strtoull
  173. # define OFF_FMT "ll"
  174. # endif
  175. #else
  176. /* CONFIG_LFS is off */
  177. # if UINT_MAX == 0xffffffff
  178. /* While sizeof(off_t) == sizeof(int), off_t is typedef'ed to long anyway.
  179. * gcc will throw warnings on printf("%d", off_t). Crap... */
  180. typedef unsigned long uoff_t;
  181. # define XATOOFF(a) xatoi_u(a)
  182. # define BB_STRTOOFF bb_strtou
  183. # define STRTOOFF strtol
  184. # define OFF_FMT "l"
  185. # else
  186. typedef unsigned long uoff_t;
  187. # define XATOOFF(a) xatoul_range(a, 0, LONG_MAX)
  188. # define BB_STRTOOFF bb_strtoul
  189. # define STRTOOFF strtol
  190. # define OFF_FMT "l"
  191. # endif
  192. #endif
  193. /* scary. better ideas? (but do *test* them first!) */
  194. #define OFF_T_MAX ((off_t)~((off_t)1 << (sizeof(off_t)*8-1)))
  195. /* Some useful definitions */
  196. #undef FALSE
  197. #define FALSE ((int) 0)
  198. #undef TRUE
  199. #define TRUE ((int) 1)
  200. #undef SKIP
  201. #define SKIP ((int) 2)
  202. /* for mtab.c */
  203. #define MTAB_GETMOUNTPT '1'
  204. #define MTAB_GETDEVICE '2'
  205. #define BUF_SIZE 8192
  206. #define EXPAND_ALLOC 1024
  207. /* Macros for min/max. */
  208. #ifndef MIN
  209. #define MIN(a,b) (((a)<(b))?(a):(b))
  210. #endif
  211. #ifndef MAX
  212. #define MAX(a,b) (((a)>(b))?(a):(b))
  213. #endif
  214. /* buffer allocation schemes */
  215. #if ENABLE_FEATURE_BUFFERS_GO_ON_STACK
  216. #define RESERVE_CONFIG_BUFFER(buffer,len) char buffer[len]
  217. #define RESERVE_CONFIG_UBUFFER(buffer,len) unsigned char buffer[len]
  218. #define RELEASE_CONFIG_BUFFER(buffer) ((void)0)
  219. #else
  220. #if ENABLE_FEATURE_BUFFERS_GO_IN_BSS
  221. #define RESERVE_CONFIG_BUFFER(buffer,len) static char buffer[len]
  222. #define RESERVE_CONFIG_UBUFFER(buffer,len) static unsigned char buffer[len]
  223. #define RELEASE_CONFIG_BUFFER(buffer) ((void)0)
  224. #else
  225. #define RESERVE_CONFIG_BUFFER(buffer,len) char *buffer = xmalloc(len)
  226. #define RESERVE_CONFIG_UBUFFER(buffer,len) unsigned char *buffer = xmalloc(len)
  227. #define RELEASE_CONFIG_BUFFER(buffer) free(buffer)
  228. #endif
  229. #endif
  230. #if defined(__GLIBC__)
  231. /* glibc uses __errno_location() to get a ptr to errno */
  232. /* We can just memorize it once - no multithreading in busybox :) */
  233. extern int *const bb_errno;
  234. #undef errno
  235. #define errno (*bb_errno)
  236. #endif
  237. unsigned long long monotonic_ns(void) FAST_FUNC;
  238. unsigned long long monotonic_us(void) FAST_FUNC;
  239. unsigned long long monotonic_ms(void) FAST_FUNC;
  240. unsigned monotonic_sec(void) FAST_FUNC;
  241. extern void chomp(char *s) FAST_FUNC;
  242. extern void trim(char *s) FAST_FUNC;
  243. extern char *skip_whitespace(const char *) FAST_FUNC;
  244. extern char *skip_non_whitespace(const char *) FAST_FUNC;
  245. extern char *skip_dev_pfx(const char *tty_name) FAST_FUNC;
  246. extern char *strrstr(const char *haystack, const char *needle) FAST_FUNC;
  247. //TODO: supply a pointer to char[11] buffer (avoid statics)?
  248. extern const char *bb_mode_string(mode_t mode) FAST_FUNC;
  249. extern int is_directory(const char *name, int followLinks, struct stat *statBuf) FAST_FUNC;
  250. enum { /* DO NOT CHANGE THESE VALUES! cp.c, mv.c, install.c depend on them. */
  251. FILEUTILS_PRESERVE_STATUS = 1 << 0, /* -p */
  252. FILEUTILS_DEREFERENCE = 1 << 1, /* !-d */
  253. FILEUTILS_RECUR = 1 << 2, /* -R */
  254. FILEUTILS_FORCE = 1 << 3, /* -f */
  255. FILEUTILS_INTERACTIVE = 1 << 4, /* -i */
  256. FILEUTILS_MAKE_HARDLINK = 1 << 5, /* -l */
  257. FILEUTILS_MAKE_SOFTLINK = 1 << 6, /* -s */
  258. FILEUTILS_DEREF_SOFTLINK = 1 << 7, /* -L */
  259. FILEUTILS_DEREFERENCE_L0 = 1 << 8, /* -H */
  260. #if ENABLE_SELINUX
  261. FILEUTILS_PRESERVE_SECURITY_CONTEXT = 1 << 9, /* -c */
  262. FILEUTILS_SET_SECURITY_CONTEXT = 1 << 10,
  263. #endif
  264. };
  265. #define FILEUTILS_CP_OPTSTR "pdRfilsLH" IF_SELINUX("c")
  266. extern int remove_file(const char *path, int flags) FAST_FUNC;
  267. /* NB: without FILEUTILS_RECUR in flags, it will basically "cat"
  268. * the source, not copy (unless "source" is a directory).
  269. * This makes "cp /dev/null file" and "install /dev/null file" (!!!)
  270. * work coreutils-compatibly. */
  271. extern int copy_file(const char *source, const char *dest, int flags) FAST_FUNC;
  272. enum {
  273. ACTION_RECURSE = (1 << 0),
  274. ACTION_FOLLOWLINKS = (1 << 1),
  275. ACTION_FOLLOWLINKS_L0 = (1 << 2),
  276. ACTION_DEPTHFIRST = (1 << 3),
  277. /*ACTION_REVERSE = (1 << 4), - unused */
  278. ACTION_QUIET = (1 << 5),
  279. ACTION_DANGLING_OK = (1 << 6),
  280. };
  281. typedef uint8_t recurse_flags_t;
  282. extern int recursive_action(const char *fileName, unsigned flags,
  283. int FAST_FUNC (*fileAction)(const char *fileName, struct stat* statbuf, void* userData, int depth),
  284. int FAST_FUNC (*dirAction)(const char *fileName, struct stat* statbuf, void* userData, int depth),
  285. void* userData, unsigned depth) FAST_FUNC;
  286. extern int device_open(const char *device, int mode) FAST_FUNC;
  287. enum { GETPTY_BUFSIZE = 16 }; /* more than enough for "/dev/ttyXXX" */
  288. extern int xgetpty(char *line) FAST_FUNC;
  289. extern int get_console_fd_or_die(void) FAST_FUNC;
  290. extern void console_make_active(int fd, const int vt_num) FAST_FUNC;
  291. extern char *find_block_device(const char *path) FAST_FUNC;
  292. /* bb_copyfd_XX print read/write errors and return -1 if they occur */
  293. extern off_t bb_copyfd_eof(int fd1, int fd2) FAST_FUNC;
  294. extern off_t bb_copyfd_size(int fd1, int fd2, off_t size) FAST_FUNC;
  295. extern void bb_copyfd_exact_size(int fd1, int fd2, off_t size) FAST_FUNC;
  296. /* "short" copy can be detected by return value < size */
  297. /* this helper yells "short read!" if param is not -1 */
  298. extern void complain_copyfd_and_die(off_t sz) NORETURN FAST_FUNC;
  299. extern char bb_process_escape_sequence(const char **ptr) FAST_FUNC;
  300. /* xxxx_strip version can modify its parameter:
  301. * "/" -> "/"
  302. * "abc" -> "abc"
  303. * "abc/def" -> "def"
  304. * "abc/def/" -> "def" !!
  305. */
  306. extern char *bb_get_last_path_component_strip(char *path) FAST_FUNC;
  307. /* "abc/def/" -> "" and it never modifies 'path' */
  308. extern char *bb_get_last_path_component_nostrip(const char *path) FAST_FUNC;
  309. int ndelay_on(int fd) FAST_FUNC;
  310. int ndelay_off(int fd) FAST_FUNC;
  311. int close_on_exec_on(int fd) FAST_FUNC;
  312. void xdup2(int, int) FAST_FUNC;
  313. void xmove_fd(int, int) FAST_FUNC;
  314. DIR *xopendir(const char *path) FAST_FUNC;
  315. DIR *warn_opendir(const char *path) FAST_FUNC;
  316. char *xmalloc_realpath(const char *path) FAST_FUNC RETURNS_MALLOC;
  317. char *xmalloc_readlink(const char *path) FAST_FUNC RETURNS_MALLOC;
  318. char *xmalloc_readlink_or_warn(const char *path) FAST_FUNC RETURNS_MALLOC;
  319. /* !RETURNS_MALLOC: it's a realloc-like function */
  320. char *xrealloc_getcwd_or_warn(char *cwd) FAST_FUNC;
  321. char *xmalloc_follow_symlinks(const char *path) FAST_FUNC RETURNS_MALLOC;
  322. enum {
  323. /* bb_signals(BB_FATAL_SIGS, handler) catches all signals which
  324. * otherwise would kill us, except for those resulting from bugs:
  325. * SIGSEGV, SIGILL, SIGFPE.
  326. * Other fatal signals not included (TODO?):
  327. * SIGBUS Bus error (bad memory access)
  328. * SIGPOLL Pollable event. Synonym of SIGIO
  329. * SIGPROF Profiling timer expired
  330. * SIGSYS Bad argument to routine
  331. * SIGTRAP Trace/breakpoint trap
  332. *
  333. * The only known arch with some of these sigs not fitting
  334. * into 32 bits is parisc (SIGXCPU=33, SIGXFSZ=34, SIGSTKFLT=36).
  335. * Dance around with long long to guard against that...
  336. */
  337. BB_FATAL_SIGS = (int)(0
  338. + (1LL << SIGHUP)
  339. + (1LL << SIGINT)
  340. + (1LL << SIGTERM)
  341. + (1LL << SIGPIPE) // Write to pipe with no readers
  342. + (1LL << SIGQUIT) // Quit from keyboard
  343. + (1LL << SIGABRT) // Abort signal from abort(3)
  344. + (1LL << SIGALRM) // Timer signal from alarm(2)
  345. + (1LL << SIGVTALRM) // Virtual alarm clock
  346. + (1LL << SIGXCPU) // CPU time limit exceeded
  347. + (1LL << SIGXFSZ) // File size limit exceeded
  348. + (1LL << SIGUSR1) // Yes kids, these are also fatal!
  349. + (1LL << SIGUSR2)
  350. + 0),
  351. };
  352. void bb_signals(int sigs, void (*f)(int)) FAST_FUNC;
  353. /* Unlike signal() and bb_signals, sets handler with sigaction()
  354. * and in a way that while signal handler is run, no other signals
  355. * will be blocked; syscalls will not be restarted: */
  356. void bb_signals_recursive_norestart(int sigs, void (*f)(int)) FAST_FUNC;
  357. /* syscalls like read() will be interrupted with EINTR: */
  358. void signal_no_SA_RESTART_empty_mask(int sig, void (*handler)(int)) FAST_FUNC;
  359. /* syscalls like read() won't be interrupted (though select/poll will be): */
  360. void signal_SA_RESTART_empty_mask(int sig, void (*handler)(int)) FAST_FUNC;
  361. void wait_for_any_sig(void) FAST_FUNC;
  362. void kill_myself_with_sig(int sig) NORETURN FAST_FUNC;
  363. void sig_block(int sig) FAST_FUNC;
  364. void sig_unblock(int sig) FAST_FUNC;
  365. /* Will do sigaction(signum, act, NULL): */
  366. int sigaction_set(int sig, const struct sigaction *act) FAST_FUNC;
  367. /* SIG_BLOCK/SIG_UNBLOCK all signals: */
  368. int sigprocmask_allsigs(int how) FAST_FUNC;
  369. /* Standard handler which just records signo */
  370. extern smallint bb_got_signal;
  371. void record_signo(int signo); /* not FAST_FUNC! */
  372. void xsetgid(gid_t gid) FAST_FUNC;
  373. void xsetuid(uid_t uid) FAST_FUNC;
  374. void xchdir(const char *path) FAST_FUNC;
  375. void xchroot(const char *path) FAST_FUNC;
  376. void xsetenv(const char *key, const char *value) FAST_FUNC;
  377. void bb_unsetenv(const char *key) FAST_FUNC;
  378. void xunlink(const char *pathname) FAST_FUNC;
  379. void xstat(const char *pathname, struct stat *buf) FAST_FUNC;
  380. int xopen(const char *pathname, int flags) FAST_FUNC;
  381. int xopen_nonblocking(const char *pathname) FAST_FUNC;
  382. int xopen3(const char *pathname, int flags, int mode) FAST_FUNC;
  383. int open_or_warn(const char *pathname, int flags) FAST_FUNC;
  384. int open3_or_warn(const char *pathname, int flags, int mode) FAST_FUNC;
  385. int open_or_warn_stdin(const char *pathname) FAST_FUNC;
  386. void xrename(const char *oldpath, const char *newpath) FAST_FUNC;
  387. int rename_or_warn(const char *oldpath, const char *newpath) FAST_FUNC;
  388. off_t xlseek(int fd, off_t offset, int whence) FAST_FUNC;
  389. off_t fdlength(int fd) FAST_FUNC;
  390. uoff_t FAST_FUNC get_volume_size_in_bytes(int fd,
  391. const char *override,
  392. unsigned override_units,
  393. int extend);
  394. void xpipe(int filedes[2]) FAST_FUNC;
  395. /* In this form code with pipes is much more readable */
  396. struct fd_pair { int rd; int wr; };
  397. #define piped_pair(pair) pipe(&((pair).rd))
  398. #define xpiped_pair(pair) xpipe(&((pair).rd))
  399. /* Useful for having small structure members/global variables */
  400. typedef int8_t socktype_t;
  401. typedef int8_t family_t;
  402. struct BUG_too_small {
  403. char BUG_socktype_t_too_small[(0
  404. | SOCK_STREAM
  405. | SOCK_DGRAM
  406. | SOCK_RDM
  407. | SOCK_SEQPACKET
  408. | SOCK_RAW
  409. ) <= 127 ? 1 : -1];
  410. char BUG_family_t_too_small[(0
  411. | AF_UNSPEC
  412. | AF_INET
  413. | AF_INET6
  414. | AF_UNIX
  415. #ifdef AF_PACKET
  416. | AF_PACKET
  417. #endif
  418. #ifdef AF_NETLINK
  419. | AF_NETLINK
  420. #endif
  421. /* | AF_DECnet */
  422. /* | AF_IPX */
  423. ) <= 127 ? 1 : -1];
  424. };
  425. void parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
  426. time_t validate_tm_time(const char *date_str, struct tm *ptm) FAST_FUNC;
  427. int xsocket(int domain, int type, int protocol) FAST_FUNC;
  428. void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen) FAST_FUNC;
  429. void xlisten(int s, int backlog) FAST_FUNC;
  430. void xconnect(int s, const struct sockaddr *s_addr, socklen_t addrlen) FAST_FUNC;
  431. ssize_t xsendto(int s, const void *buf, size_t len, const struct sockaddr *to,
  432. socklen_t tolen) FAST_FUNC;
  433. /* SO_REUSEADDR allows a server to rebind to an address that is already
  434. * "in use" by old connections to e.g. previous server instance which is
  435. * killed or crashed. Without it bind will fail until all such connections
  436. * time out. Linux does not allow multiple live binds on same ip:port
  437. * regardless of SO_REUSEADDR (unlike some other flavors of Unix).
  438. * Turn it on before you call bind(). */
  439. void setsockopt_reuseaddr(int fd) FAST_FUNC; /* On Linux this never fails. */
  440. int setsockopt_broadcast(int fd) FAST_FUNC;
  441. int setsockopt_bindtodevice(int fd, const char *iface) FAST_FUNC;
  442. /* NB: returns port in host byte order */
  443. unsigned bb_lookup_port(const char *port, const char *protocol, unsigned default_port) FAST_FUNC;
  444. typedef struct len_and_sockaddr {
  445. socklen_t len;
  446. union {
  447. struct sockaddr sa;
  448. struct sockaddr_in sin;
  449. #if ENABLE_FEATURE_IPV6
  450. struct sockaddr_in6 sin6;
  451. #endif
  452. } u;
  453. } len_and_sockaddr;
  454. enum {
  455. LSA_LEN_SIZE = offsetof(len_and_sockaddr, u),
  456. LSA_SIZEOF_SA = sizeof(
  457. union {
  458. struct sockaddr sa;
  459. struct sockaddr_in sin;
  460. #if ENABLE_FEATURE_IPV6
  461. struct sockaddr_in6 sin6;
  462. #endif
  463. }
  464. )
  465. };
  466. /* Create stream socket, and allocate suitable lsa.
  467. * (lsa of correct size and lsa->sa.sa_family (AF_INET/AF_INET6))
  468. * af == AF_UNSPEC will result in trying to create IPv6 socket,
  469. * and if kernel doesn't support it, fall back to IPv4.
  470. * This is useful if you plan to bind to resulting local lsa.
  471. */
  472. #if ENABLE_FEATURE_IPV6
  473. int xsocket_type(len_and_sockaddr **lsap, int af, int sock_type) FAST_FUNC;
  474. #else
  475. int xsocket_type(len_and_sockaddr **lsap, int sock_type) FAST_FUNC;
  476. #define xsocket_type(lsap, af, sock_type) xsocket_type((lsap), (sock_type))
  477. #endif
  478. int xsocket_stream(len_and_sockaddr **lsap) FAST_FUNC;
  479. /* Create server socket bound to bindaddr:port. bindaddr can be NULL,
  480. * numeric IP ("N.N.N.N") or numeric IPv6 address,
  481. * and can have ":PORT" suffix (for IPv6 use "[X:X:...:X]:PORT").
  482. * Only if there is no suffix, port argument is used */
  483. /* NB: these set SO_REUSEADDR before bind */
  484. int create_and_bind_stream_or_die(const char *bindaddr, int port) FAST_FUNC;
  485. int create_and_bind_dgram_or_die(const char *bindaddr, int port) FAST_FUNC;
  486. /* Create client TCP socket connected to peer:port. Peer cannot be NULL.
  487. * Peer can be numeric IP ("N.N.N.N"), numeric IPv6 address or hostname,
  488. * and can have ":PORT" suffix (for IPv6 use "[X:X:...:X]:PORT").
  489. * If there is no suffix, port argument is used */
  490. int create_and_connect_stream_or_die(const char *peer, int port) FAST_FUNC;
  491. /* Connect to peer identified by lsa */
  492. int xconnect_stream(const len_and_sockaddr *lsa) FAST_FUNC;
  493. /* Get local address of bound or accepted socket */
  494. len_and_sockaddr *get_sock_lsa(int fd) FAST_FUNC RETURNS_MALLOC;
  495. /* Get remote address of connected or accepted socket */
  496. len_and_sockaddr *get_peer_lsa(int fd) FAST_FUNC RETURNS_MALLOC;
  497. /* Return malloc'ed len_and_sockaddr with socket address of host:port
  498. * Currently will return IPv4 or IPv6 sockaddrs only
  499. * (depending on host), but in theory nothing prevents e.g.
  500. * UNIX socket address being returned, IPX sockaddr etc...
  501. * On error does bb_error_msg and returns NULL */
  502. len_and_sockaddr* host2sockaddr(const char *host, int port) FAST_FUNC RETURNS_MALLOC;
  503. /* Version which dies on error */
  504. len_and_sockaddr* xhost2sockaddr(const char *host, int port) FAST_FUNC RETURNS_MALLOC;
  505. len_and_sockaddr* xdotted2sockaddr(const char *host, int port) FAST_FUNC RETURNS_MALLOC;
  506. /* Same, useful if you want to force family (e.g. IPv6) */
  507. #if !ENABLE_FEATURE_IPV6
  508. #define host_and_af2sockaddr(host, port, af) host2sockaddr((host), (port))
  509. #define xhost_and_af2sockaddr(host, port, af) xhost2sockaddr((host), (port))
  510. #else
  511. len_and_sockaddr* host_and_af2sockaddr(const char *host, int port, sa_family_t af) FAST_FUNC RETURNS_MALLOC;
  512. len_and_sockaddr* xhost_and_af2sockaddr(const char *host, int port, sa_family_t af) FAST_FUNC RETURNS_MALLOC;
  513. #endif
  514. /* Assign sin[6]_port member if the socket is an AF_INET[6] one,
  515. * otherwise no-op. Useful for ftp.
  516. * NB: does NOT do htons() internally, just direct assignment. */
  517. void set_nport(len_and_sockaddr *lsa, unsigned port) FAST_FUNC;
  518. /* Retrieve sin[6]_port or return -1 for non-INET[6] lsa's */
  519. int get_nport(const struct sockaddr *sa) FAST_FUNC;
  520. /* Reverse DNS. Returns NULL on failure. */
  521. char* xmalloc_sockaddr2host(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  522. /* This one doesn't append :PORTNUM */
  523. char* xmalloc_sockaddr2host_noport(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  524. /* This one also doesn't fall back to dotted IP (returns NULL) */
  525. char* xmalloc_sockaddr2hostonly_noport(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  526. /* inet_[ap]ton on steroids */
  527. char* xmalloc_sockaddr2dotted(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  528. char* xmalloc_sockaddr2dotted_noport(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
  529. // "old" (ipv4 only) API
  530. // users: traceroute.c hostname.c - use _list_ of all IPs
  531. struct hostent *xgethostbyname(const char *name) FAST_FUNC;
  532. // Also mount.c and inetd.c are using gethostbyname(),
  533. // + inet_common.c has additional IPv4-only stuff
  534. void socket_want_pktinfo(int fd) FAST_FUNC;
  535. ssize_t send_to_from(int fd, void *buf, size_t len, int flags,
  536. const struct sockaddr *to,
  537. const struct sockaddr *from,
  538. socklen_t tolen) FAST_FUNC;
  539. ssize_t recv_from_to(int fd, void *buf, size_t len, int flags,
  540. struct sockaddr *from,
  541. struct sockaddr *to,
  542. socklen_t sa_size) FAST_FUNC;
  543. char *xstrdup(const char *s) FAST_FUNC RETURNS_MALLOC;
  544. char *xstrndup(const char *s, int n) FAST_FUNC RETURNS_MALLOC;
  545. void overlapping_strcpy(char *dst, const char *src) FAST_FUNC;
  546. char *safe_strncpy(char *dst, const char *src, size_t size) FAST_FUNC;
  547. char *strncpy_IFNAMSIZ(char *dst, const char *src) FAST_FUNC;
  548. /* Guaranteed to NOT be a macro (smallest code). Saves nearly 2k on uclibc.
  549. * But potentially slow, don't use in one-billion-times loops */
  550. int bb_putchar(int ch) FAST_FUNC;
  551. char *xasprintf(const char *format, ...) __attribute__ ((format(printf, 1, 2))) FAST_FUNC RETURNS_MALLOC;
  552. // gcc-4.1.1 still isn't good enough at optimizing it
  553. // (+200 bytes compared to macro)
  554. //static ALWAYS_INLINE
  555. //int LONE_DASH(const char *s) { return s[0] == '-' && !s[1]; }
  556. //static ALWAYS_INLINE
  557. //int NOT_LONE_DASH(const char *s) { return s[0] != '-' || s[1]; }
  558. #define LONE_DASH(s) ((s)[0] == '-' && !(s)[1])
  559. #define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
  560. #define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
  561. #define NOT_LONE_CHAR(s,c) ((s)[0] != (c) || (s)[1])
  562. #define DOT_OR_DOTDOT(s) ((s)[0] == '.' && (!(s)[1] || ((s)[1] == '.' && !(s)[2])))
  563. typedef struct uni_stat_t {
  564. unsigned byte_count;
  565. unsigned unicode_count;
  566. unsigned unicode_width;
  567. } uni_stat_t;
  568. /* Returns a string with unprintable chars replaced by '?' or
  569. * SUBST_WCHAR. This function is unicode-aware. */
  570. const char* FAST_FUNC printable_string(uni_stat_t *stats, const char *str);
  571. /* Prints unprintable char ch as ^C or M-c to file
  572. * (M-c is used only if ch is ORed with PRINTABLE_META),
  573. * else it is printed as-is (except for ch = 0x9b) */
  574. enum { PRINTABLE_META = 0x100 };
  575. void fputc_printable(int ch, FILE *file) FAST_FUNC;
  576. /* dmalloc will redefine these to it's own implementation. It is safe
  577. * to have the prototypes here unconditionally. */
  578. void *malloc_or_warn(size_t size) FAST_FUNC RETURNS_MALLOC;
  579. void *xmalloc(size_t size) FAST_FUNC RETURNS_MALLOC;
  580. void *xzalloc(size_t size) FAST_FUNC RETURNS_MALLOC;
  581. void *xrealloc(void *old, size_t size) FAST_FUNC;
  582. /* After xrealloc_vector(v, 4, idx) it's ok to use
  583. * at least v[idx] and v[idx+1], for all idx values.
  584. * shift specifies how many new elements are added (1: 2, 2: 4... 8: 256...)
  585. * when all elements are used up. New elements are zeroed out. */
  586. #define xrealloc_vector(vector, shift, idx) \
  587. xrealloc_vector_helper((vector), (sizeof((vector)[0]) << 8) + (shift), (idx))
  588. void* xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx) FAST_FUNC;
  589. extern ssize_t safe_read(int fd, void *buf, size_t count) FAST_FUNC;
  590. extern ssize_t nonblock_safe_read(int fd, void *buf, size_t count) FAST_FUNC;
  591. // NB: will return short read on error, not -1,
  592. // if some data was read before error occurred
  593. extern ssize_t full_read(int fd, void *buf, size_t count) FAST_FUNC;
  594. extern void xread(int fd, void *buf, size_t count) FAST_FUNC;
  595. extern unsigned char xread_char(int fd) FAST_FUNC;
  596. extern ssize_t read_close(int fd, void *buf, size_t maxsz) FAST_FUNC;
  597. extern ssize_t open_read_close(const char *filename, void *buf, size_t maxsz) FAST_FUNC;
  598. // Reads one line a-la fgets (but doesn't save terminating '\n').
  599. // Reads byte-by-byte. Useful when it is important to not read ahead.
  600. // Bytes are appended to pfx (which must be malloced, or NULL).
  601. extern char *xmalloc_reads(int fd, char *pfx, size_t *maxsz_p) FAST_FUNC;
  602. /* Reads block up to *maxsz_p (default: INT_MAX - 4095) */
  603. extern void *xmalloc_read(int fd, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  604. /* Returns NULL if file can't be opened (default max size: INT_MAX - 4095) */
  605. extern void *xmalloc_open_read_close(const char *filename, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  606. /* Autodetects gzip/bzip2 formats. fd may be in the middle of the file! */
  607. #if ENABLE_FEATURE_SEAMLESS_LZMA \
  608. || ENABLE_FEATURE_SEAMLESS_BZ2 \
  609. || ENABLE_FEATURE_SEAMLESS_GZ \
  610. /* || ENABLE_FEATURE_SEAMLESS_Z */
  611. extern int setup_unzip_on_fd(int fd /*, int fail_if_not_detected*/) FAST_FUNC;
  612. #else
  613. # define setup_unzip_on_fd(...) ((void)0)
  614. #endif
  615. /* Autodetects .gz etc */
  616. extern int open_zipped(const char *fname) FAST_FUNC;
  617. extern void *xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  618. /* Never returns NULL */
  619. extern void *xmalloc_xopen_read_close(const char *filename, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  620. extern ssize_t safe_write(int fd, const void *buf, size_t count) FAST_FUNC;
  621. // NB: will return short write on error, not -1,
  622. // if some data was written before error occurred
  623. extern ssize_t full_write(int fd, const void *buf, size_t count) FAST_FUNC;
  624. extern void xwrite(int fd, const void *buf, size_t count) FAST_FUNC;
  625. extern void xwrite_str(int fd, const char *str) FAST_FUNC;
  626. extern void xopen_xwrite_close(const char* file, const char *str) FAST_FUNC;
  627. /* Close fd, but check for failures (some types of write errors) */
  628. extern void xclose(int fd) FAST_FUNC;
  629. /* Reads and prints to stdout till eof, then closes FILE. Exits on error: */
  630. extern void xprint_and_close_file(FILE *file) FAST_FUNC;
  631. extern char *bb_get_chunk_from_file(FILE *file, int *end) FAST_FUNC;
  632. extern char *bb_get_chunk_with_continuation(FILE *file, int *end, int *lineno) FAST_FUNC;
  633. /* Reads up to (and including) TERMINATING_STRING: */
  634. extern char *xmalloc_fgets_str(FILE *file, const char *terminating_string) FAST_FUNC RETURNS_MALLOC;
  635. /* Same, with limited max size, and returns the length (excluding NUL): */
  636. extern char *xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
  637. /* Chops off TERMINATING_STRING from the end: */
  638. extern char *xmalloc_fgetline_str(FILE *file, const char *terminating_string) FAST_FUNC RETURNS_MALLOC;
  639. /* Reads up to (and including) "\n" or NUL byte: */
  640. extern char *xmalloc_fgets(FILE *file) FAST_FUNC RETURNS_MALLOC;
  641. /* Chops off '\n' from the end, unlike fgets: */
  642. extern char *xmalloc_fgetline(FILE *file) FAST_FUNC RETURNS_MALLOC;
  643. /* Same, but doesn't try to conserve space (may have some slack after the end) */
  644. /* extern char *xmalloc_fgetline_fast(FILE *file) FAST_FUNC RETURNS_MALLOC; */
  645. void die_if_ferror(FILE *file, const char *msg) FAST_FUNC;
  646. void die_if_ferror_stdout(void) FAST_FUNC;
  647. int fflush_all(void) FAST_FUNC;
  648. void fflush_stdout_and_exit(int retval) NORETURN FAST_FUNC;
  649. int fclose_if_not_stdin(FILE *file) FAST_FUNC;
  650. FILE* xfopen(const char *filename, const char *mode) FAST_FUNC;
  651. /* Prints warning to stderr and returns NULL on failure: */
  652. FILE* fopen_or_warn(const char *filename, const char *mode) FAST_FUNC;
  653. /* "Opens" stdin if filename is special, else just opens file: */
  654. FILE* xfopen_stdin(const char *filename) FAST_FUNC;
  655. FILE* fopen_or_warn_stdin(const char *filename) FAST_FUNC;
  656. FILE* fopen_for_read(const char *path) FAST_FUNC;
  657. FILE* xfopen_for_read(const char *path) FAST_FUNC;
  658. FILE* fopen_for_write(const char *path) FAST_FUNC;
  659. FILE* xfopen_for_write(const char *path) FAST_FUNC;
  660. FILE* xfdopen_for_read(int fd) FAST_FUNC;
  661. FILE* xfdopen_for_write(int fd) FAST_FUNC;
  662. int bb_pstrcmp(const void *a, const void *b) /* not FAST_FUNC! */;
  663. void qsort_string_vector(char **sv, unsigned count) FAST_FUNC;
  664. /* Wrapper which restarts poll on EINTR or ENOMEM.
  665. * On other errors complains [perror("poll")] and returns.
  666. * Warning! May take (much) longer than timeout_ms to return!
  667. * If this is a problem, use bare poll and open-code EINTR/ENOMEM handling */
  668. int safe_poll(struct pollfd *ufds, nfds_t nfds, int timeout_ms) FAST_FUNC;
  669. char *safe_gethostname(void) FAST_FUNC;
  670. char *safe_getdomainname(void) FAST_FUNC;
  671. /* Convert each alpha char in str to lower-case */
  672. char* str_tolower(char *str) FAST_FUNC;
  673. char *utoa(unsigned n) FAST_FUNC;
  674. char *itoa(int n) FAST_FUNC;
  675. /* Returns a pointer past the formatted number, does NOT null-terminate */
  676. char *utoa_to_buf(unsigned n, char *buf, unsigned buflen) FAST_FUNC;
  677. char *itoa_to_buf(int n, char *buf, unsigned buflen) FAST_FUNC;
  678. /* Intelligent formatters of bignums */
  679. void smart_ulltoa4(unsigned long long ul, char buf[5], const char *scale) FAST_FUNC;
  680. void smart_ulltoa5(unsigned long long ul, char buf[5], const char *scale) FAST_FUNC;
  681. /* If block_size == 0, display size without fractional part,
  682. * else display (size * block_size) with one decimal digit.
  683. * If display_unit == 0, show value no bigger than 1024 with suffix (K,M,G...),
  684. * else divide by display_unit and do not use suffix. */
  685. #define HUMAN_READABLE_MAX_WIDTH 7 /* "1024.0G" */
  686. #define HUMAN_READABLE_MAX_WIDTH_STR "7"
  687. //TODO: provide pointer to buf (avoid statics)?
  688. const char *make_human_readable_str(unsigned long long size,
  689. unsigned long block_size, unsigned long display_unit) FAST_FUNC;
  690. /* Put a string of hex bytes ("1b2e66fe"...), return advanced pointer */
  691. char *bin2hex(char *buf, const char *cp, int count) FAST_FUNC;
  692. /* Reverse */
  693. char* hex2bin(char *dst, const char *str, int count) FAST_FUNC;
  694. /* Generate a UUID */
  695. void generate_uuid(uint8_t *buf) FAST_FUNC;
  696. /* Last element is marked by mult == 0 */
  697. struct suffix_mult {
  698. char suffix[4];
  699. unsigned mult;
  700. };
  701. #include "xatonum.h"
  702. /* Specialized: */
  703. /* Using xatoi() instead of naive atoi() is not always convenient -
  704. * in many places people want *non-negative* values, but store them
  705. * in signed int. Therefore we need this one:
  706. * dies if input is not in [0, INT_MAX] range. Also will reject '-0' etc */
  707. int xatoi_u(const char *numstr) FAST_FUNC;
  708. /* Useful for reading port numbers */
  709. uint16_t xatou16(const char *numstr) FAST_FUNC;
  710. /* These parse entries in /etc/passwd and /etc/group. This is desirable
  711. * for BusyBox since we want to avoid using the glibc NSS stuff, which
  712. * increases target size and is often not needed on embedded systems. */
  713. long xuname2uid(const char *name) FAST_FUNC;
  714. long xgroup2gid(const char *name) FAST_FUNC;
  715. /* wrapper: allows string to contain numeric uid or gid */
  716. unsigned long get_ug_id(const char *s, long FAST_FUNC (*xname2id)(const char *)) FAST_FUNC;
  717. /* from chpst. Does not die, returns 0 on failure */
  718. struct bb_uidgid_t {
  719. uid_t uid;
  720. gid_t gid;
  721. };
  722. /* always sets uid and gid */
  723. int get_uidgid(struct bb_uidgid_t*, const char*, int numeric_ok) FAST_FUNC;
  724. /* always sets uid and gid, allows numeric; exits on failure */
  725. void xget_uidgid(struct bb_uidgid_t*, const char*) FAST_FUNC;
  726. /* chown-like handling of "user[:[group]" */
  727. void parse_chown_usergroup_or_die(struct bb_uidgid_t *u, char *user_group) FAST_FUNC;
  728. struct passwd* xgetpwnam(const char *name) FAST_FUNC;
  729. struct group* xgetgrnam(const char *name) FAST_FUNC;
  730. struct passwd* xgetpwuid(uid_t uid) FAST_FUNC;
  731. struct group* xgetgrgid(gid_t gid) FAST_FUNC;
  732. char* xuid2uname(uid_t uid) FAST_FUNC;
  733. char* xgid2group(gid_t gid) FAST_FUNC;
  734. char* uid2uname(uid_t uid) FAST_FUNC;
  735. char* gid2group(gid_t gid) FAST_FUNC;
  736. char* uid2uname_utoa(long uid) FAST_FUNC;
  737. char* gid2group_utoa(long gid) FAST_FUNC;
  738. /* versions which cache results (useful for ps, ls etc) */
  739. const char* get_cached_username(uid_t uid) FAST_FUNC;
  740. const char* get_cached_groupname(gid_t gid) FAST_FUNC;
  741. void clear_username_cache(void) FAST_FUNC;
  742. /* internally usernames are saved in fixed-sized char[] buffers */
  743. enum { USERNAME_MAX_SIZE = 16 - sizeof(int) };
  744. #if ENABLE_FEATURE_CHECK_NAMES
  745. void die_if_bad_username(const char* name) FAST_FUNC;
  746. #else
  747. #define die_if_bad_username(name) ((void)(name))
  748. #endif
  749. #if ENABLE_FEATURE_UTMP
  750. void FAST_FUNC write_new_utmp(pid_t pid, int new_type, const char *tty_name, const char *username, const char *hostname);
  751. void FAST_FUNC update_utmp(pid_t pid, int new_type, const char *tty_name, const char *username, const char *hostname);
  752. #else
  753. # define write_new_utmp(pid, new_type, tty_name, username, hostname) ((void)0)
  754. # define update_utmp(pid, new_type, tty_name, username, hostname) ((void)0)
  755. #endif
  756. int execable_file(const char *name) FAST_FUNC;
  757. char *find_execable(const char *filename, char **PATHp) FAST_FUNC;
  758. int exists_execable(const char *filename) FAST_FUNC;
  759. /* BB_EXECxx always execs (it's not doing NOFORK/NOEXEC stuff),
  760. * but it may exec busybox and call applet instead of searching PATH.
  761. */
  762. #if ENABLE_FEATURE_PREFER_APPLETS
  763. int bb_execvp(const char *file, char *const argv[]) FAST_FUNC;
  764. #define BB_EXECVP(prog,cmd) bb_execvp(prog,cmd)
  765. #define BB_EXECLP(prog,cmd,...) \
  766. execlp((find_applet_by_name(prog) >= 0) ? CONFIG_BUSYBOX_EXEC_PATH : prog, \
  767. cmd, __VA_ARGS__)
  768. #else
  769. #define BB_EXECVP(prog,cmd) execvp(prog,cmd)
  770. #define BB_EXECLP(prog,cmd,...) execlp(prog,cmd, __VA_ARGS__)
  771. #endif
  772. /* NOMMU friendy fork+exec: */
  773. pid_t spawn(char **argv) FAST_FUNC;
  774. pid_t xspawn(char **argv) FAST_FUNC;
  775. pid_t safe_waitpid(pid_t pid, int *wstat, int options) FAST_FUNC;
  776. pid_t wait_any_nohang(int *wstat) FAST_FUNC;
  777. /* wait4pid: unlike waitpid, waits ONLY for one process.
  778. * Returns sig + 0x180 if child is killed by signal.
  779. * It's safe to pass negative 'pids' from failed [v]fork -
  780. * wait4pid will return -1 (and will not clobber [v]fork's errno).
  781. * IOW: rc = wait4pid(spawn(argv));
  782. * if (rc < 0) bb_perror_msg("%s", argv[0]);
  783. * if (rc > 0) bb_error_msg("exit code: %d", rc & 0xff);
  784. */
  785. int wait4pid(pid_t pid) FAST_FUNC;
  786. /* Same as wait4pid(spawn(argv)), but with NOFORK/NOEXEC if configured: */
  787. int spawn_and_wait(char **argv) FAST_FUNC;
  788. struct nofork_save_area {
  789. jmp_buf die_jmp;
  790. const char *applet_name;
  791. int xfunc_error_retval;
  792. uint32_t option_mask32;
  793. int die_sleep;
  794. smallint saved;
  795. };
  796. void save_nofork_data(struct nofork_save_area *save) FAST_FUNC;
  797. void restore_nofork_data(struct nofork_save_area *save) FAST_FUNC;
  798. /* Does NOT check that applet is NOFORK, just blindly runs it */
  799. int run_nofork_applet(int applet_no, char **argv) FAST_FUNC;
  800. int run_nofork_applet_prime(struct nofork_save_area *old, int applet_no, char **argv) FAST_FUNC;
  801. /* Helpers for daemonization.
  802. *
  803. * bb_daemonize(flags) = daemonize, does not compile on NOMMU
  804. *
  805. * bb_daemonize_or_rexec(flags, argv) = daemonizes on MMU (and ignores argv),
  806. * rexec's itself on NOMMU with argv passed as command line.
  807. * Thus bb_daemonize_or_rexec may cause your <applet>_main() to be re-executed
  808. * from the start. (It will detect it and not reexec again second time).
  809. * You have to audit carefully that you don't do something twice as a result
  810. * (opening files/sockets, parsing config files etc...)!
  811. *
  812. * Both of the above will redirect fd 0,1,2 to /dev/null and drop ctty
  813. * (will do setsid()).
  814. *
  815. * fork_or_rexec(argv) = bare-bones "fork" on MMU,
  816. * "vfork + re-exec ourself" on NOMMU. No fd redirection, no setsid().
  817. * On MMU ignores argv.
  818. *
  819. * Helper for network daemons in foreground mode:
  820. *
  821. * bb_sanitize_stdio() = make sure that fd 0,1,2 are opened by opening them
  822. * to /dev/null if they are not.
  823. */
  824. enum {
  825. DAEMON_CHDIR_ROOT = 1,
  826. DAEMON_DEVNULL_STDIO = 2,
  827. DAEMON_CLOSE_EXTRA_FDS = 4,
  828. DAEMON_ONLY_SANITIZE = 8, /* internal use */
  829. };
  830. #if BB_MMU
  831. pid_t fork_or_rexec(void) FAST_FUNC;
  832. enum { re_execed = 0 };
  833. # define fork_or_rexec(argv) fork_or_rexec()
  834. # define bb_daemonize_or_rexec(flags, argv) bb_daemonize_or_rexec(flags)
  835. # define bb_daemonize(flags) bb_daemonize_or_rexec(flags, bogus)
  836. #else
  837. void re_exec(char **argv) NORETURN FAST_FUNC;
  838. pid_t fork_or_rexec(char **argv) FAST_FUNC;
  839. extern bool re_execed;
  840. int BUG_fork_is_unavailable_on_nommu(void) FAST_FUNC;
  841. int BUG_daemon_is_unavailable_on_nommu(void) FAST_FUNC;
  842. void BUG_bb_daemonize_is_unavailable_on_nommu(void) FAST_FUNC;
  843. # define fork() BUG_fork_is_unavailable_on_nommu()
  844. # define daemon(a,b) BUG_daemon_is_unavailable_on_nommu()
  845. # define bb_daemonize(a) BUG_bb_daemonize_is_unavailable_on_nommu()
  846. #endif
  847. void bb_daemonize_or_rexec(int flags, char **argv) FAST_FUNC;
  848. void bb_sanitize_stdio(void) FAST_FUNC;
  849. /* Clear dangerous stuff, set PATH. Return 1 if was run by different user. */
  850. int sanitize_env_if_suid(void) FAST_FUNC;
  851. char* single_argv(char **argv) FAST_FUNC;
  852. extern const char *const bb_argv_dash[]; /* "-", NULL */
  853. extern const char *opt_complementary;
  854. #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG
  855. #define No_argument "\0"
  856. #define Required_argument "\001"
  857. #define Optional_argument "\002"
  858. extern const char *applet_long_options;
  859. #endif
  860. extern uint32_t option_mask32;
  861. extern uint32_t getopt32(char **argv, const char *applet_opts, ...) FAST_FUNC;
  862. typedef struct llist_t {
  863. char *data;
  864. struct llist_t *link;
  865. } llist_t;
  866. void llist_add_to(llist_t **old_head, void *data) FAST_FUNC;
  867. void llist_add_to_end(llist_t **list_head, void *data) FAST_FUNC;
  868. void *llist_pop(llist_t **elm) FAST_FUNC;
  869. void llist_unlink(llist_t **head, llist_t *elm) FAST_FUNC;
  870. void llist_free(llist_t *elm, void (*freeit)(void *data)) FAST_FUNC;
  871. llist_t *llist_rev(llist_t *list) FAST_FUNC;
  872. llist_t *llist_find_str(llist_t *first, const char *str) FAST_FUNC;
  873. /* BTW, surprisingly, changing API to
  874. * llist_t *llist_add_to(llist_t *old_head, void *data)
  875. * etc does not result in smaller code... */
  876. /* start_stop_daemon and udhcpc are special - they want
  877. * to create pidfiles regardless of FEATURE_PIDFILE */
  878. #if ENABLE_FEATURE_PIDFILE || defined(WANT_PIDFILE)
  879. /* True only if we created pidfile which is *file*, not /dev/null etc */
  880. extern smallint wrote_pidfile;
  881. void write_pidfile(const char *path) FAST_FUNC;
  882. #define remove_pidfile(path) do { if (wrote_pidfile) unlink(path); } while (0)
  883. #else
  884. enum { wrote_pidfile = 0 };
  885. #define write_pidfile(path) ((void)0)
  886. #define remove_pidfile(path) ((void)0)
  887. #endif
  888. enum {
  889. LOGMODE_NONE = 0,
  890. LOGMODE_STDIO = (1 << 0),
  891. LOGMODE_SYSLOG = (1 << 1) * ENABLE_FEATURE_SYSLOG,
  892. LOGMODE_BOTH = LOGMODE_SYSLOG + LOGMODE_STDIO,
  893. };
  894. extern const char *msg_eol;
  895. extern smallint logmode;
  896. extern int die_sleep;
  897. extern int xfunc_error_retval;
  898. extern jmp_buf die_jmp;
  899. extern void xfunc_die(void) NORETURN FAST_FUNC;
  900. extern void bb_show_usage(void) NORETURN FAST_FUNC;
  901. extern void bb_error_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  902. extern void bb_error_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))) FAST_FUNC;
  903. extern void bb_perror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  904. extern void bb_simple_perror_msg(const char *s) FAST_FUNC;
  905. extern void bb_perror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))) FAST_FUNC;
  906. extern void bb_simple_perror_msg_and_die(const char *s) NORETURN FAST_FUNC;
  907. extern void bb_herror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  908. extern void bb_herror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))) FAST_FUNC;
  909. extern void bb_perror_nomsg_and_die(void) NORETURN FAST_FUNC;
  910. extern void bb_perror_nomsg(void) FAST_FUNC;
  911. extern void bb_info_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
  912. extern void bb_verror_msg(const char *s, va_list p, const char *strerr) FAST_FUNC;
  913. /* We need to export XXX_main from libbusybox
  914. * only if we build "individual" binaries
  915. */
  916. #if ENABLE_FEATURE_INDIVIDUAL
  917. #define MAIN_EXTERNALLY_VISIBLE EXTERNALLY_VISIBLE
  918. #else
  919. #define MAIN_EXTERNALLY_VISIBLE
  920. #endif
  921. /* Applets which are useful from another applets */
  922. int bb_cat(char** argv);
  923. /* If shell needs them, they exist even if not enabled as applets */
  924. int echo_main(int argc, char** argv) IF_ECHO(MAIN_EXTERNALLY_VISIBLE);
  925. int printf_main(int argc, char **argv) IF_PRINTF(MAIN_EXTERNALLY_VISIBLE);
  926. int test_main(int argc, char **argv) IF_TEST(MAIN_EXTERNALLY_VISIBLE);
  927. int kill_main(int argc, char **argv) IF_KILL(MAIN_EXTERNALLY_VISIBLE);
  928. /* Similar, but used by chgrp, not shell */
  929. int chown_main(int argc, char **argv) IF_CHOWN(MAIN_EXTERNALLY_VISIBLE);
  930. /* Used by ftpd */
  931. int ls_main(int argc, char **argv) IF_LS(MAIN_EXTERNALLY_VISIBLE);
  932. /* Don't need IF_xxx() guard for these */
  933. int gunzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  934. int bunzip2_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  935. #if ENABLE_ROUTE
  936. void bb_displayroutes(int noresolve, int netstatfmt) FAST_FUNC;
  937. #endif
  938. /* Networking */
  939. int create_icmp_socket(void) FAST_FUNC;
  940. int create_icmp6_socket(void) FAST_FUNC;
  941. /* interface.c */
  942. /* This structure defines protocol families and their handlers. */
  943. struct aftype {
  944. const char *name;
  945. const char *title;
  946. int af;
  947. int alen;
  948. char* FAST_FUNC (*print)(unsigned char *);
  949. const char* FAST_FUNC (*sprint)(struct sockaddr *, int numeric);
  950. int FAST_FUNC (*input)(/*int type,*/ const char *bufp, struct sockaddr *);
  951. void FAST_FUNC (*herror)(char *text);
  952. int FAST_FUNC (*rprint)(int options);
  953. int FAST_FUNC (*rinput)(int typ, int ext, char **argv);
  954. /* may modify src */
  955. int FAST_FUNC (*getmask)(char *src, struct sockaddr *mask, char *name);
  956. };
  957. /* This structure defines hardware protocols and their handlers. */
  958. struct hwtype {
  959. const char *name;
  960. const char *title;
  961. int type;
  962. int alen;
  963. char* FAST_FUNC (*print)(unsigned char *);
  964. int FAST_FUNC (*input)(const char *, struct sockaddr *);
  965. int FAST_FUNC (*activate)(int fd);
  966. int suppress_null_addr;
  967. };
  968. extern smallint interface_opt_a;
  969. int display_interfaces(char *ifname) FAST_FUNC;
  970. #if ENABLE_FEATURE_HWIB
  971. int in_ib(const char *bufp, struct sockaddr *sap) FAST_FUNC;
  972. #else
  973. #define in_ib(a, b) 1 /* fail */
  974. #endif
  975. const struct aftype *get_aftype(const char *name) FAST_FUNC;
  976. const struct hwtype *get_hwtype(const char *name) FAST_FUNC;
  977. const struct hwtype *get_hwntype(int type) FAST_FUNC;
  978. #ifndef BUILD_INDIVIDUAL
  979. extern int find_applet_by_name(const char *name) FAST_FUNC;
  980. /* Returns only if applet is not found. */
  981. extern void run_applet_and_exit(const char *name, char **argv) FAST_FUNC;
  982. extern void run_applet_no_and_exit(int a, char **argv) NORETURN FAST_FUNC;
  983. #endif
  984. #ifdef HAVE_MNTENT_H
  985. extern int match_fstype(const struct mntent *mt, const char *fstypes) FAST_FUNC;
  986. extern struct mntent *find_mount_point(const char *name, int subdir_too) FAST_FUNC;
  987. #endif
  988. extern void erase_mtab(const char * name) FAST_FUNC;
  989. extern unsigned int tty_baud_to_value(speed_t speed) FAST_FUNC;
  990. extern speed_t tty_value_to_baud(unsigned int value) FAST_FUNC;
  991. #if ENABLE_DESKTOP
  992. extern void bb_warn_ignoring_args(char *arg) FAST_FUNC;
  993. #else
  994. # define bb_warn_ignoring_args(arg) ((void)0)
  995. #endif
  996. extern int get_linux_version_code(void) FAST_FUNC;
  997. extern char *query_loop(const char *device) FAST_FUNC;
  998. extern int del_loop(const char *device) FAST_FUNC;
  999. /* If *devname is not NULL, use that name, otherwise try to find free one,
  1000. * malloc and return it in *devname.
  1001. * return value: 1: read-only loopdev was setup, 0: rw, < 0: error */
  1002. extern int set_loop(char **devname, const char *file, unsigned long long offset) FAST_FUNC;
  1003. /* Like bb_ask below, but asks on stdin with no timeout. */
  1004. char *bb_ask_stdin(const char * prompt) FAST_FUNC;
  1005. //TODO: pass buf pointer or return allocated buf (avoid statics)?
  1006. char *bb_ask(const int fd, int timeout, const char * prompt) FAST_FUNC;
  1007. int bb_ask_confirmation(void) FAST_FUNC;
  1008. int bb_parse_mode(const char* s, mode_t* theMode) FAST_FUNC;
  1009. /*
  1010. * Config file parser
  1011. */
  1012. enum {
  1013. PARSE_COLLAPSE = 0x00010000, // treat consecutive delimiters as one
  1014. PARSE_TRIM = 0x00020000, // trim leading and trailing delimiters
  1015. // TODO: COLLAPSE and TRIM seem to always go in pair
  1016. PARSE_GREEDY = 0x00040000, // last token takes entire remainder of the line
  1017. PARSE_MIN_DIE = 0x00100000, // die if < min tokens found
  1018. // keep a copy of current line
  1019. PARSE_KEEP_COPY = 0x00200000 * ENABLE_FEATURE_CROND_D,
  1020. // PARSE_ESCAPE = 0x00400000, // process escape sequences in tokens
  1021. // NORMAL is:
  1022. // * remove leading and trailing delimiters and collapse
  1023. // multiple delimiters into one
  1024. // * warn and continue if less than mintokens delimiters found
  1025. // * grab everything into last token
  1026. PARSE_NORMAL = PARSE_COLLAPSE | PARSE_TRIM | PARSE_GREEDY,
  1027. };
  1028. typedef struct parser_t {
  1029. FILE *fp;
  1030. char *line;
  1031. char *data;
  1032. int lineno;
  1033. } parser_t;
  1034. parser_t* config_open(const char *filename) FAST_FUNC;
  1035. parser_t* config_open2(const char *filename, FILE* FAST_FUNC (*fopen_func)(const char *path)) FAST_FUNC;
  1036. int config_read(parser_t *parser, char **tokens, unsigned flags, const char *delims) FAST_FUNC;
  1037. #define config_read(parser, tokens, max, min, str, flags) \
  1038. config_read(parser, tokens, ((flags) | (((min) & 0xFF) << 8) | ((max) & 0xFF)), str)
  1039. void config_close(parser_t *parser) FAST_FUNC;
  1040. /* Concatenate path and filename to new allocated buffer.
  1041. * Add "/" only as needed (no duplicate "//" are produced).
  1042. * If path is NULL, it is assumed to be "/".
  1043. * filename should not be NULL. */
  1044. char *concat_path_file(const char *path, const char *filename) FAST_FUNC;
  1045. char *concat_subpath_file(const char *path, const char *filename) FAST_FUNC;
  1046. const char *bb_basename(const char *name) FAST_FUNC;
  1047. /* NB: can violate const-ness (similarly to strchr) */
  1048. char *last_char_is(const char *s, int c) FAST_FUNC;
  1049. int bb_make_directory(char *path, long mode, int flags) FAST_FUNC;
  1050. int get_signum(const char *name) FAST_FUNC;
  1051. const char *get_signame(int number) FAST_FUNC;
  1052. void print_signames(void) FAST_FUNC;
  1053. char *bb_simplify_path(const char *path) FAST_FUNC;
  1054. /* Returns ptr to NUL */
  1055. char *bb_simplify_abs_path_inplace(char *path) FAST_FUNC;
  1056. #define FAIL_DELAY 3
  1057. extern void bb_do_delay(int seconds) FAST_FUNC;
  1058. extern void change_identity(const struct passwd *pw) FAST_FUNC;
  1059. extern void run_shell(const char *shell, int loginshell, const char *command, const char **additional_args) NORETURN FAST_FUNC;
  1060. extern void run_shell(const char *shell, int loginshell, const char *command, const char **additional_args) FAST_FUNC;
  1061. #if ENABLE_SELINUX
  1062. extern void renew_current_security_context(void) FAST_FUNC;
  1063. extern void set_current_security_context(security_context_t sid) FAST_FUNC;
  1064. extern context_t set_security_context_component(security_context_t cur_context,
  1065. char *user, char *role, char *type, char *range) FAST_FUNC;
  1066. extern void setfscreatecon_or_die(security_context_t scontext) FAST_FUNC;
  1067. extern void selinux_preserve_fcontext(int fdesc) FAST_FUNC;
  1068. #else
  1069. #define selinux_preserve_fcontext(fdesc) ((void)0)
  1070. #endif
  1071. extern void selinux_or_die(void) FAST_FUNC;
  1072. /* setup_environment:
  1073. * if chdir pw->pw_dir: ok: else if to_tmp == 1: goto /tmp else: goto / or die
  1074. * if clear_env = 1: cd(pw->pw_dir), clear environment, then set
  1075. * TERM=(old value)
  1076. * USER=pw->pw_name, LOGNAME=pw->pw_name
  1077. * PATH=bb_default_[root_]path
  1078. * HOME=pw->pw_dir
  1079. * SHELL=shell
  1080. * else if change_env = 1:
  1081. * if not root (if pw->pw_uid != 0):
  1082. * USER=pw->pw_name, LOGNAME=pw->pw_name
  1083. * HOME=pw->pw_dir
  1084. * SHELL=shell
  1085. * else does nothing
  1086. */
  1087. #define SETUP_ENV_CHANGEENV (1 << 0)
  1088. #define SETUP_ENV_CLEARENV (1 << 1)
  1089. #define SETUP_ENV_TO_TMP (1 << 2)
  1090. extern void setup_environment(const char *shell, int flags, const struct passwd *pw) FAST_FUNC;
  1091. extern int correct_password(const struct passwd *pw) FAST_FUNC;
  1092. /* Returns a malloced string */
  1093. #if !ENABLE_USE_BB_CRYPT
  1094. #define pw_encrypt(clear, salt, cleanup) pw_encrypt(clear, salt)
  1095. #endif
  1096. extern char *pw_encrypt(const char *clear, const char *salt, int cleanup) FAST_FUNC;
  1097. extern int obscure(const char *old, const char *newval, const struct passwd *pwdp) FAST_FUNC;
  1098. /* rnd is additional random input. New one is returned.
  1099. * Useful if you call crypt_make_salt many times in a row:
  1100. * rnd = crypt_make_salt(buf1, 4, 0);
  1101. * rnd = crypt_make_salt(buf2, 4, rnd);
  1102. * rnd = crypt_make_salt(buf3, 4, rnd);
  1103. * (otherwise we risk having same salt generated)
  1104. */
  1105. extern int crypt_make_salt(char *p, int cnt, int rnd) FAST_FUNC;
  1106. /* Returns number of lines changed, or -1 on error */
  1107. #if !(ENABLE_FEATURE_ADDUSER_TO_GROUP || ENABLE_FEATURE_DEL_USER_FROM_GROUP)
  1108. #define update_passwd(filename, username, data, member) \
  1109. update_passwd(filename, username, data)
  1110. #endif
  1111. extern int update_passwd(const char *filename,
  1112. const char *username,
  1113. const char *data,
  1114. const char *member) FAST_FUNC;
  1115. int index_in_str_array(const char *const string_array[], const char *key) FAST_FUNC;
  1116. int index_in_strings(const char *strings, const char *key) FAST_FUNC;
  1117. int index_in_substr_array(const char *const string_array[], const char *key) FAST_FUNC;
  1118. int index_in_substrings(const char *strings, const char *key) FAST_FUNC;
  1119. const char *nth_string(const char *strings, int n) FAST_FUNC;
  1120. extern void print_login_issue(const char *issue_file, const char *tty) FAST_FUNC;
  1121. extern void print_login_prompt(void) FAST_FUNC;
  1122. char *xmalloc_ttyname(int fd) FAST_FUNC RETURNS_MALLOC;
  1123. /* NB: typically you want to pass fd 0, not 1. Think 'applet | grep something' */
  1124. int get_terminal_width_height(int fd, unsigned *width, unsigned *height) FAST_FUNC;
  1125. int tcsetattr_stdin_TCSANOW(const struct termios *tp) FAST_FUNC;
  1126. /* NB: "unsigned request" is crucial! "int request" will break some arches! */
  1127. int ioctl_or_perror(int fd, unsigned request, void *argp, const char *fmt,...) __attribute__ ((format (printf, 4, 5))) FAST_FUNC;
  1128. int ioctl_or_perror_and_die(int fd, unsigned request, void *argp, const char *fmt,...) __attribute__ ((format (printf, 4, 5))) FAST_FUNC;
  1129. #if ENABLE_IOCTL_HEX2STR_ERROR
  1130. int bb_ioctl_or_warn(int fd, unsigned request, void *argp, const char *ioctl_name) FAST_FUNC;
  1131. int bb_xioctl(int fd, unsigned request, void *argp, const char *ioctl_name) FAST_FUNC;
  1132. #define ioctl_or_warn(fd,request,argp) bb_ioctl_or_warn(fd,request,argp,#request)
  1133. #define xioctl(fd,request,argp) bb_xioctl(fd,request,argp,#request)
  1134. #else
  1135. int bb_ioctl_or_warn(int fd, unsigned request, void *argp) FAST_FUNC;
  1136. int bb_xioctl(int fd, unsigned request, void *argp) FAST_FUNC;
  1137. #define ioctl_or_warn(fd,request,argp) bb_ioctl_or_warn(fd,request,argp)
  1138. #define xioctl(fd,request,argp) bb_xioctl(fd,request,argp)
  1139. #endif
  1140. char *is_in_ino_dev_hashtable(const struct stat *statbuf) FAST_FUNC;
  1141. void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name) FAST_FUNC;
  1142. void reset_ino_dev_hashtable(void) FAST_FUNC;
  1143. #ifdef __GLIBC__
  1144. /* At least glibc has horrendously large inline for this, so wrap it */
  1145. unsigned long long bb_makedev(unsigned int major, unsigned int minor) FAST_FUNC;
  1146. #undef makedev
  1147. #define makedev(a,b) bb_makedev(a,b)
  1148. #endif
  1149. /* "Keycodes" that report an escape sequence.
  1150. * We use something which fits into signed char,
  1151. * yet doesn't represent any valid Unicode character.
  1152. * Also, -1 is reserved for error indication and we don't use it. */
  1153. enum {
  1154. KEYCODE_UP = -2,
  1155. KEYCODE_DOWN = -3,
  1156. KEYCODE_RIGHT = -4,
  1157. KEYCODE_LEFT = -5,
  1158. KEYCODE_HOME = -6,
  1159. KEYCODE_END = -7,
  1160. KEYCODE_INSERT = -8,
  1161. KEYCODE_DELETE = -9,
  1162. KEYCODE_PAGEUP = -10,
  1163. KEYCODE_PAGEDOWN = -11,
  1164. KEYCODE_CTRL_UP = KEYCODE_UP & ~0x40,
  1165. KEYCODE_CTRL_DOWN = KEYCODE_DOWN & ~0x40,
  1166. KEYCODE_CTRL_RIGHT = KEYCODE_RIGHT & ~0x40,
  1167. KEYCODE_CTRL_LEFT = KEYCODE_LEFT & ~0x40,
  1168. #if 0
  1169. KEYCODE_FUN1 = -12,
  1170. KEYCODE_FUN2 = -13,
  1171. KEYCODE_FUN3 = -14,
  1172. KEYCODE_FUN4 = -15,
  1173. KEYCODE_FUN5 = -16,
  1174. KEYCODE_FUN6 = -17,
  1175. KEYCODE_FUN7 = -18,
  1176. KEYCODE_FUN8 = -19,
  1177. KEYCODE_FUN9 = -20,
  1178. KEYCODE_FUN10 = -21,
  1179. KEYCODE_FUN11 = -22,
  1180. KEYCODE_FUN12 = -23,
  1181. #endif
  1182. KEYCODE_CURSOR_POS = -0x100, /* 0xfff..fff00 */
  1183. /* How long is the longest ESC sequence we know?
  1184. * We want it big enough to be able to contain
  1185. * cursor position sequence "ESC [ 9999 ; 9999 R"
  1186. */
  1187. KEYCODE_BUFFER_SIZE = 16
  1188. };
  1189. /* Note: fd may be in blocking or non-blocking mode, both make sense.
  1190. * For one, less uses non-blocking mode.
  1191. * Only the first read syscall inside read_key may block indefinitely
  1192. * (unless fd is in non-blocking mode),
  1193. * subsequent reads will time out after a few milliseconds.
  1194. * Return of -1 means EOF or error (errno == 0 on EOF).
  1195. * buffer[0] is used as a counter of buffered chars and must be 0
  1196. * on first call.
  1197. * timeout:
  1198. * -2: do not poll for input;
  1199. * -1: poll(-1) (i.e. block);
  1200. * >=0: poll for TIMEOUT milliseconds, return -1/EAGAIN on timeout
  1201. */
  1202. int64_t read_key(int fd, char *buffer, int timeout) FAST_FUNC;
  1203. void read_key_ungets(char *buffer, const char *str, unsigned len) FAST_FUNC;
  1204. #if ENABLE_FEATURE_EDITING
  1205. /* It's NOT just ENABLEd or disabled. It's a number: */
  1206. # ifdef CONFIG_FEATURE_EDITING_HISTORY
  1207. # define MAX_HISTORY (CONFIG_FEATURE_EDITING_HISTORY + 0)
  1208. # else
  1209. # define MAX_HISTORY 0
  1210. # endif
  1211. typedef struct line_input_t {
  1212. int flags;
  1213. const char *path_lookup;
  1214. # if MAX_HISTORY
  1215. int cnt_history;
  1216. int cur_history;
  1217. # if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1218. unsigned cnt_history_in_file;
  1219. const char *hist_file;
  1220. # endif
  1221. char *history[MAX_HISTORY + 1];
  1222. # endif
  1223. } line_input_t;
  1224. enum {
  1225. DO_HISTORY = 1 * (MAX_HISTORY > 0),
  1226. SAVE_HISTORY = 2 * (MAX_HISTORY > 0) * ENABLE_FEATURE_EDITING_SAVEHISTORY,
  1227. TAB_COMPLETION = 4 * ENABLE_FEATURE_TAB_COMPLETION,
  1228. USERNAME_COMPLETION = 8 * ENABLE_FEATURE_USERNAME_COMPLETION,
  1229. VI_MODE = 0x10 * ENABLE_FEATURE_EDITING_VI,
  1230. WITH_PATH_LOOKUP = 0x20,
  1231. FOR_SHELL = DO_HISTORY | SAVE_HISTORY | TAB_COMPLETION | USERNAME_COMPLETION,
  1232. };
  1233. line_input_t *new_line_input_t(int flags) FAST_FUNC;
  1234. /* So far static: void free_line_input_t(line_input_t *n) FAST_FUNC; */
  1235. /* maxsize must be >= 2.
  1236. * Returns:
  1237. * -1 on read errors or EOF, or on bare Ctrl-D,
  1238. * 0 on ctrl-C (the line entered is still returned in 'command'),
  1239. * >0 length of input string, including terminating '\n'
  1240. */
  1241. int read_line_input(const char* prompt, char* command, int maxsize, line_input_t *state) FAST_FUNC;
  1242. #else
  1243. #define MAX_HISTORY 0
  1244. int read_line_input(const char* prompt, char* command, int maxsize) FAST_FUNC;
  1245. #define read_line_input(prompt, command, maxsize, state) \
  1246. read_line_input(prompt, command, maxsize)
  1247. #endif
  1248. #ifndef COMM_LEN
  1249. # ifdef TASK_COMM_LEN
  1250. enum { COMM_LEN = TASK_COMM_LEN };
  1251. # else
  1252. /* synchronize with sizeof(task_struct.comm) in /usr/include/linux/sched.h */
  1253. enum { COMM_LEN = 16 };
  1254. # endif
  1255. #endif
  1256. typedef struct procps_status_t {
  1257. DIR *dir;
  1258. IF_FEATURE_SHOW_THREADS(DIR *task_dir;)
  1259. uint8_t shift_pages_to_bytes;
  1260. uint8_t shift_pages_to_kb;
  1261. /* Fields are set to 0/NULL if failed to determine (or not requested) */
  1262. uint16_t argv_len;
  1263. char *argv0;
  1264. char *exe;
  1265. IF_SELINUX(char *context;)
  1266. /* Everything below must contain no ptrs to malloc'ed data:
  1267. * it is memset(0) for each process in procps_scan() */
  1268. unsigned long vsz, rss; /* we round it to kbytes */
  1269. unsigned long stime, utime;
  1270. unsigned long start_time;
  1271. unsigned pid;
  1272. unsigned ppid;
  1273. unsigned pgid;
  1274. unsigned sid;
  1275. unsigned uid;
  1276. unsigned gid;
  1277. #if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
  1278. unsigned ruid;
  1279. unsigned rgid;
  1280. int niceness;
  1281. #endif
  1282. unsigned tty_major,tty_minor;
  1283. #if ENABLE_FEATURE_TOPMEM
  1284. unsigned long mapped_rw;
  1285. unsigned long mapped_ro;
  1286. unsigned long shared_clean;
  1287. unsigned long shared_dirty;
  1288. unsigned long private_clean;
  1289. unsigned long private_dirty;
  1290. unsigned long stack;
  1291. #endif
  1292. char state[4];
  1293. /* basename of executable in exec(2), read from /proc/N/stat
  1294. * (if executable is symlink or script, it is NOT replaced
  1295. * by link target or interpreter name) */
  1296. char comm[COMM_LEN];
  1297. /* user/group? - use passwd/group parsing functions */
  1298. #if ENABLE_FEATURE_TOP_SMP_PROCESS
  1299. int last_seen_on_cpu;
  1300. #endif
  1301. } procps_status_t;
  1302. /* flag bits for procps_scan(xx, flags) calls */
  1303. enum {
  1304. PSSCAN_PID = 1 << 0,
  1305. PSSCAN_PPID = 1 << 1,
  1306. PSSCAN_PGID = 1 << 2,
  1307. PSSCAN_SID = 1 << 3,
  1308. PSSCAN_UIDGID = 1 << 4,
  1309. PSSCAN_COMM = 1 << 5,
  1310. /* PSSCAN_CMD = 1 << 6, - use read_cmdline instead */
  1311. PSSCAN_ARGV0 = 1 << 7,
  1312. PSSCAN_EXE = 1 << 8,
  1313. PSSCAN_STATE = 1 << 9,
  1314. PSSCAN_VSZ = 1 << 10,
  1315. PSSCAN_RSS = 1 << 11,
  1316. PSSCAN_STIME = 1 << 12,
  1317. PSSCAN_UTIME = 1 << 13,
  1318. PSSCAN_TTY = 1 << 14,
  1319. PSSCAN_SMAPS = (1 << 15) * ENABLE_FEATURE_TOPMEM,
  1320. /* NB: used by find_pid_by_name(). Any applet using it
  1321. * needs to be mentioned here. */
  1322. PSSCAN_ARGVN = (1 << 16) * (ENABLE_KILLALL
  1323. || ENABLE_PGREP || ENABLE_PKILL
  1324. || ENABLE_PIDOF
  1325. || ENABLE_SESTATUS
  1326. ),
  1327. PSSCAN_CONTEXT = (1 << 17) * ENABLE_SELINUX,
  1328. PSSCAN_START_TIME = 1 << 18,
  1329. PSSCAN_CPU = (1 << 19) * ENABLE_FEATURE_TOP_SMP_PROCESS,
  1330. PSSCAN_NICE = (1 << 20) * ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS,
  1331. PSSCAN_RUIDGID = (1 << 21) * ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS,
  1332. PSSCAN_TASKS = (1 << 22) * ENABLE_FEATURE_SHOW_THREADS,
  1333. /* These are all retrieved from proc/NN/stat in one go: */
  1334. PSSCAN_STAT = PSSCAN_PPID | PSSCAN_PGID | PSSCAN_SID
  1335. /**/ | PSSCAN_COMM | PSSCAN_STATE
  1336. /**/ | PSSCAN_VSZ | PSSCAN_RSS
  1337. /**/ | PSSCAN_STIME | PSSCAN_UTIME | PSSCAN_START_TIME
  1338. /**/ | PSSCAN_TTY | PSSCAN_NICE
  1339. /**/ | PSSCAN_CPU
  1340. };
  1341. //procps_status_t* alloc_procps_scan(void) FAST_FUNC;
  1342. void free_procps_scan(procps_status_t* sp) FAST_FUNC;
  1343. procps_status_t* procps_scan(procps_status_t* sp, int flags) FAST_FUNC;
  1344. /* Format cmdline (up to col chars) into char buf[size] */
  1345. /* Puts [comm] if cmdline is empty (-> process is a kernel thread) */
  1346. void read_cmdline(char *buf, int size, unsigned pid, const char *comm) FAST_FUNC;
  1347. pid_t *find_pid_by_name(const char* procName) FAST_FUNC;
  1348. pid_t *pidlist_reverse(pid_t *pidList) FAST_FUNC;
  1349. extern const char bb_uuenc_tbl_base64[];
  1350. extern const char bb_uuenc_tbl_std[];
  1351. void bb_uuencode(char *store, const void *s, int length, const char *tbl) FAST_FUNC;
  1352. typedef struct sha1_ctx_t {
  1353. uint32_t hash[8]; /* 5, +3 elements for sha256 */
  1354. uint64_t total64;
  1355. uint8_t wbuffer[64]; /* NB: always correctly aligned for uint64_t */
  1356. void (*process_block)(struct sha1_ctx_t*) FAST_FUNC;
  1357. } sha1_ctx_t;
  1358. void sha1_begin(sha1_ctx_t *ctx) FAST_FUNC;
  1359. void sha1_hash(const void *data, size_t length, sha1_ctx_t *ctx) FAST_FUNC;
  1360. void sha1_end(void *resbuf, sha1_ctx_t *ctx) FAST_FUNC;
  1361. typedef struct sha1_ctx_t sha256_ctx_t;
  1362. void sha256_begin(sha256_ctx_t *ctx) FAST_FUNC;
  1363. #define sha256_hash sha1_hash
  1364. #define sha256_end sha1_end
  1365. typedef struct sha512_ctx_t {
  1366. uint64_t hash[8];
  1367. uint64_t total64[2];
  1368. uint8_t wbuffer[128]; /* NB: always correctly aligned for uint64_t */
  1369. } sha512_ctx_t;
  1370. void sha512_begin(sha512_ctx_t *ctx) FAST_FUNC;
  1371. void sha512_hash(const void *buffer, size_t len, sha512_ctx_t *ctx) FAST_FUNC;
  1372. void sha512_end(void *resbuf, sha512_ctx_t *ctx) FAST_FUNC;
  1373. #if 1
  1374. typedef struct md5_ctx_t {
  1375. uint32_t A;
  1376. uint32_t B;
  1377. uint32_t C;
  1378. uint32_t D;
  1379. uint64_t total;
  1380. uint32_t buflen;
  1381. char buffer[128];
  1382. } md5_ctx_t;
  1383. #else
  1384. /* libbb/md5prime.c uses a bit different one: */
  1385. typedef struct md5_ctx_t {
  1386. uint32_t state[4]; /* state (ABCD) */
  1387. uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */
  1388. unsigned char buffer[64]; /* input buffer */
  1389. } md5_ctx_t;
  1390. #endif
  1391. void md5_begin(md5_ctx_t *ctx) FAST_FUNC;
  1392. void md5_hash(const void *data, size_t length, md5_ctx_t *ctx) FAST_FUNC;
  1393. void md5_end(void *resbuf, md5_ctx_t *ctx) FAST_FUNC;
  1394. uint32_t *crc32_filltable(uint32_t *tbl256, int endian) FAST_FUNC;
  1395. typedef struct masks_labels_t {
  1396. const char *labels;
  1397. const int masks[];
  1398. } masks_labels_t;
  1399. int print_flags_separated(const int *masks, const char *labels,
  1400. int flags, const char *separator) FAST_FUNC;
  1401. int print_flags(const masks_labels_t *ml, int flags) FAST_FUNC;
  1402. typedef struct bb_progress_t {
  1403. off_t lastsize;
  1404. unsigned lastupdate_sec;
  1405. unsigned start_sec;
  1406. smallint inited;
  1407. } bb_progress_t;
  1408. void bb_progress_init(bb_progress_t *p) FAST_FUNC;
  1409. void bb_progress_update(bb_progress_t *p, const char *curfile,
  1410. off_t beg_range, off_t transferred,
  1411. off_t totalsize) FAST_FUNC;
  1412. extern const char *applet_name;
  1413. /* "BusyBox vN.N.N (timestamp or extra_version)" */
  1414. extern const char bb_banner[];
  1415. extern const char bb_msg_memory_exhausted[];
  1416. extern const char bb_msg_invalid_date[];
  1417. extern const char bb_msg_read_error[];
  1418. extern const char bb_msg_write_error[];
  1419. extern const char bb_msg_unknown[];
  1420. extern const char bb_msg_can_not_create_raw_socket[];
  1421. extern const char bb_msg_perm_denied_are_you_root[];
  1422. extern const char bb_msg_you_must_be_root[];
  1423. extern const char bb_msg_requires_arg[];
  1424. extern const char bb_msg_invalid_arg[];
  1425. extern const char bb_msg_standard_input[];
  1426. extern const char bb_msg_standard_output[];
  1427. extern const char bb_str_default[];
  1428. /* NB: (bb_hexdigits_upcase[i] | 0x20) -> lowercase hex digit */
  1429. extern const char bb_hexdigits_upcase[];
  1430. extern const char bb_path_mtab_file[];
  1431. extern const char bb_path_passwd_file[];
  1432. extern const char bb_path_shadow_file[];
  1433. extern const char bb_path_gshadow_file[];
  1434. extern const char bb_path_group_file[];
  1435. extern const char bb_path_motd_file[];
  1436. extern const char bb_path_wtmp_file[];
  1437. extern const char bb_dev_null[];
  1438. extern const char bb_busybox_exec_path[];
  1439. /* util-linux manpage says /sbin:/bin:/usr/sbin:/usr/bin,
  1440. * but I want to save a few bytes here */
  1441. extern const char bb_PATH_root_path[]; /* "PATH=/sbin:/usr/sbin:/bin:/usr/bin" */
  1442. #define bb_default_root_path (bb_PATH_root_path + sizeof("PATH"))
  1443. #define bb_default_path (bb_PATH_root_path + sizeof("PATH=/sbin:/usr/sbin"))
  1444. extern const int const_int_0;
  1445. extern const int const_int_1;
  1446. /* Providing hard guarantee on minimum size (think of BUFSIZ == 128) */
  1447. enum { COMMON_BUFSIZE = (BUFSIZ >= 256*sizeof(void*) ? BUFSIZ+1 : 256*sizeof(void*)) };
  1448. extern char bb_common_bufsiz1[COMMON_BUFSIZE];
  1449. /* This struct is deliberately not defined. */
  1450. /* See docs/keep_data_small.txt */
  1451. struct globals;
  1452. /* '*const' ptr makes gcc optimize code much better.
  1453. * Magic prevents ptr_to_globals from going into rodata.
  1454. * If you want to assign a value, use SET_PTR_TO_GLOBALS(x) */
  1455. extern struct globals *const ptr_to_globals;
  1456. /* At least gcc 3.4.6 on mipsel system needs optimization barrier */
  1457. #define barrier() __asm__ __volatile__("":::"memory")
  1458. #define SET_PTR_TO_GLOBALS(x) do { \
  1459. (*(struct globals**)&ptr_to_globals) = (void*)(x); \
  1460. barrier(); \
  1461. } while (0)
  1462. /* You can change LIBBB_DEFAULT_LOGIN_SHELL, but don't use it,
  1463. * use bb_default_login_shell and following defines.
  1464. * If you change LIBBB_DEFAULT_LOGIN_SHELL,
  1465. * don't forget to change increment constant. */
  1466. #define LIBBB_DEFAULT_LOGIN_SHELL "-/bin/sh"
  1467. extern const char bb_default_login_shell[];
  1468. /* "/bin/sh" */
  1469. #define DEFAULT_SHELL (bb_default_login_shell+1)
  1470. /* "sh" */
  1471. #define DEFAULT_SHELL_SHORT_NAME (bb_default_login_shell+6)
  1472. #if ENABLE_FEATURE_DEVFS
  1473. # define CURRENT_VC "/dev/vc/0"
  1474. # define VC_1 "/dev/vc/1"
  1475. # define VC_2 "/dev/vc/2"
  1476. # define VC_3 "/dev/vc/3"
  1477. # define VC_4 "/dev/vc/4"
  1478. # define VC_5 "/dev/vc/5"
  1479. #if defined(__sh__) || defined(__H8300H__) || defined(__H8300S__)
  1480. /* Yes, this sucks, but both SH (including sh64) and H8 have a SCI(F) for their
  1481. respective serial ports .. as such, we can't use the common device paths for
  1482. these. -- PFM */
  1483. # define SC_0 "/dev/ttsc/0"
  1484. # define SC_1 "/dev/ttsc/1"
  1485. # define SC_FORMAT "/dev/ttsc/%d"
  1486. #else
  1487. # define SC_0 "/dev/tts/0"
  1488. # define SC_1 "/dev/tts/1"
  1489. # define SC_FORMAT "/dev/tts/%d"
  1490. #endif
  1491. # define VC_FORMAT "/dev/vc/%d"
  1492. # define LOOP_FORMAT "/dev/loop/%d"
  1493. # define LOOP_NAMESIZE (sizeof("/dev/loop/") + sizeof(int)*3 + 1)
  1494. # define LOOP_NAME "/dev/loop/"
  1495. # define FB_0 "/dev/fb/0"
  1496. #else
  1497. # define CURRENT_VC "/dev/tty0"
  1498. # define VC_1 "/dev/tty1"
  1499. # define VC_2 "/dev/tty2"
  1500. # define VC_3 "/dev/tty3"
  1501. # define VC_4 "/dev/tty4"
  1502. # define VC_5 "/dev/tty5"
  1503. #if defined(__sh__) || defined(__H8300H__) || defined(__H8300S__)
  1504. # define SC_0 "/dev/ttySC0"
  1505. # define SC_1 "/dev/ttySC1"
  1506. # define SC_FORMAT "/dev/ttySC%d"
  1507. #else
  1508. # define SC_0 "/dev/ttyS0"
  1509. # define SC_1 "/dev/ttyS1"
  1510. # define SC_FORMAT "/dev/ttyS%d"
  1511. #endif
  1512. # define VC_FORMAT "/dev/tty%d"
  1513. # define LOOP_FORMAT "/dev/loop%d"
  1514. # define LOOP_NAMESIZE (sizeof("/dev/loop") + sizeof(int)*3 + 1)
  1515. # define LOOP_NAME "/dev/loop"
  1516. # define FB_0 "/dev/fb0"
  1517. #endif
  1518. /* The following devices are the same on devfs and non-devfs systems. */
  1519. #define CURRENT_TTY "/dev/tty"
  1520. #define DEV_CONSOLE "/dev/console"
  1521. #define ARRAY_SIZE(x) ((unsigned)(sizeof(x) / sizeof((x)[0])))
  1522. /* We redefine ctype macros. Unicode-correct handling of char types
  1523. * can't be done with such byte-oriented operations anyway,
  1524. * we don't lose anything.
  1525. */
  1526. #undef isalnum
  1527. #undef isalpha
  1528. #undef isascii
  1529. #undef isblank
  1530. #undef iscntrl
  1531. #undef isdigit
  1532. #undef isgraph
  1533. #undef islower
  1534. #undef isprint
  1535. #undef ispunct
  1536. #undef isspace
  1537. #undef isupper
  1538. #undef isxdigit
  1539. #undef toupper
  1540. #undef tolower
  1541. /* We save ~500 bytes on isdigit alone.
  1542. * BTW, x86 likes (unsigned char) cast more than (unsigned). */
  1543. /* These work the same for ASCII and Unicode,
  1544. * assuming no one asks "is this a *Unicode* letter?" using isalpha(letter) */
  1545. #define isascii(a) ((unsigned char)(a) <= 0x7f)
  1546. #define isdigit(a) ((unsigned char)((a) - '0') <= 9)
  1547. #define isupper(a) ((unsigned char)((a) - 'A') <= ('Z' - 'A'))
  1548. #define islower(a) ((unsigned char)((a) - 'a') <= ('z' - 'a'))
  1549. #define isalpha(a) ((unsigned char)(((a)|0x20) - 'a') <= ('z' - 'a'))
  1550. #define isblank(a) ({ unsigned char bb__isblank = (a); bb__isblank == ' ' || bb__isblank == '\t'; })
  1551. #define iscntrl(a) ({ unsigned char bb__iscntrl = (a); bb__iscntrl < ' ' || bb__iscntrl == 0x7f; })
  1552. /* In POSIX/C locale isspace is only these chars: "\t\n\v\f\r" and space.
  1553. * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
  1554. */
  1555. #define isspace(a) ({ unsigned char bb__isspace = (a) - 9; bb__isspace == (' ' - 9) || bb__isspace <= (13 - 9); })
  1556. // Unsafe wrt NUL: #define ispunct(a) (strchr("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", (a)) != NULL)
  1557. #define ispunct(a) (strchrnul("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", (a))[0])
  1558. // Bigger code: #define isalnum(a) ({ unsigned char bb__isalnum = (a) - '0'; bb__isalnum <= 9 || ((bb__isalnum - ('A' - '0')) & 0xdf) <= 25; })
  1559. #define isalnum(a) bb_ascii_isalnum(a)
  1560. static ALWAYS_INLINE int bb_ascii_isalnum(unsigned char a)
  1561. {
  1562. unsigned char b = a - '0';
  1563. if (b <= 9)
  1564. return (b <= 9);
  1565. b = (a|0x20) - 'a';
  1566. return b <= 'z' - 'a';
  1567. }
  1568. #define isxdigit(a) bb_ascii_isxdigit(a)
  1569. static ALWAYS_INLINE int bb_ascii_isxdigit(unsigned char a)
  1570. {
  1571. unsigned char b = a - '0';
  1572. if (b <= 9)
  1573. return (b <= 9);
  1574. b = (a|0x20) - 'a';
  1575. return b <= 'f' - 'a';
  1576. }
  1577. #define toupper(a) bb_ascii_toupper(a)
  1578. static ALWAYS_INLINE unsigned char bb_ascii_toupper(unsigned char a)
  1579. {
  1580. unsigned char b = a - 'a';
  1581. if (b <= ('z' - 'a'))
  1582. a -= 'a' - 'A';
  1583. return a;
  1584. }
  1585. #define tolower(a) bb_ascii_tolower(a)
  1586. static ALWAYS_INLINE unsigned char bb_ascii_tolower(unsigned char a)
  1587. {
  1588. unsigned char b = a - 'A';
  1589. if (b <= ('Z' - 'A'))
  1590. a += 'a' - 'A';
  1591. return a;
  1592. }
  1593. /* In ASCII and Unicode, these are likely to be very different.
  1594. * Let's prevent ambiguous usage from the start */
  1595. #define isgraph(a) isgraph_is_ambiguous_dont_use(a)
  1596. #define isprint(a) isprint_is_ambiguous_dont_use(a)
  1597. /* NB: must not treat EOF as isgraph or isprint */
  1598. #define isgraph_asciionly(a) ((unsigned)((a) - 0x21) <= 0x7e - 0x21)
  1599. #define isprint_asciionly(a) ((unsigned)((a) - 0x20) <= 0x7e - 0x20)
  1600. POP_SAVED_FUNCTION_VISIBILITY
  1601. #endif