3
0

libbb.h 69 KB

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