libbb.h 77 KB

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