libbb.h 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Busybox main internal header file
  4. *
  5. * Based in part on code from sash, Copyright (c) 1999 by David I. Bell
  6. * Permission has been granted to redistribute this code under the GPL.
  7. *
  8. * Licensed under the GPL version 2, see the file LICENSE in this tarball.
  9. */
  10. #ifndef __LIBBUSYBOX_H__
  11. #define __LIBBUSYBOX_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 <mntent.h>
  19. #include <netdb.h>
  20. #include <setjmp.h>
  21. #include <signal.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <stdarg.h>
  25. #include <stddef.h>
  26. #include <string.h>
  27. /* #include <strings.h> - said to be obsolete */
  28. #include <sys/poll.h>
  29. #include <sys/ioctl.h>
  30. #include <sys/mman.h>
  31. #include <sys/socket.h>
  32. #include <sys/stat.h>
  33. #include <sys/statfs.h>
  34. #include <sys/time.h>
  35. #include <sys/types.h>
  36. #include <sys/wait.h>
  37. #include <termios.h>
  38. #include <time.h>
  39. #include <unistd.h>
  40. #include <utime.h>
  41. #if ENABLE_SELINUX
  42. #include <selinux/selinux.h>
  43. #include <selinux/context.h>
  44. #include <selinux/flask.h>
  45. #include <selinux/av_permissions.h>
  46. #endif
  47. #if ENABLE_LOCALE_SUPPORT
  48. #include <locale.h>
  49. #else
  50. #define setlocale(x,y) ((void)0)
  51. #endif
  52. #include "pwd_.h"
  53. #include "grp_.h"
  54. /* ifdef it out, because it may include <shadow.h> */
  55. /* and we may not even _have_ <shadow.h>! */
  56. #if ENABLE_FEATURE_SHADOWPASSWDS
  57. #include "shadow_.h"
  58. #endif
  59. /* Try to pull in PATH_MAX */
  60. #include <limits.h>
  61. #include <sys/param.h>
  62. #ifndef PATH_MAX
  63. #define PATH_MAX 256
  64. #endif
  65. /* Tested to work correctly (IIRC :]) */
  66. #define MAXINT(T) (T)( \
  67. ((T)-1) > 0 \
  68. ? (T)-1 \
  69. : (T)~((T)1 << (sizeof(T)*8-1)) \
  70. )
  71. #define MININT(T) (T)( \
  72. ((T)-1) > 0 \
  73. ? (T)0 \
  74. : ((T)1 << (sizeof(T)*8-1)) \
  75. )
  76. /* Large file support */
  77. /* Note that CONFIG_LFS forces bbox to be built with all common ops
  78. * (stat, lseek etc) mapped to "largefile" variants by libc.
  79. * Practically it means that open() automatically has O_LARGEFILE added
  80. * and all filesize/file_offset parameters and struct members are "large"
  81. * (in today's world - signed 64bit). For full support of large files,
  82. * we need a few helper #defines (below) and careful use of off_t
  83. * instead of int/ssize_t. No lseek64(), O_LARGEFILE etc necessary */
  84. #if ENABLE_LFS
  85. /* CONFIG_LFS is on */
  86. # if ULONG_MAX > 0xffffffff
  87. /* "long" is long enough on this system */
  88. # define XATOOFF(a) xatoul_range(a, 0, LONG_MAX)
  89. /* usage: sz = BB_STRTOOFF(s, NULL, 10); if (errno || sz < 0) die(); */
  90. # define BB_STRTOOFF bb_strtoul
  91. # define STRTOOFF strtoul
  92. /* usage: printf("size: %"OFF_FMT"d (%"OFF_FMT"x)\n", sz, sz); */
  93. # define OFF_FMT "l"
  94. # else
  95. /* "long" is too short, need "long long" */
  96. # define XATOOFF(a) xatoull_range(a, 0, LLONG_MAX)
  97. # define BB_STRTOOFF bb_strtoull
  98. # define STRTOOFF strtoull
  99. # define OFF_FMT "ll"
  100. # endif
  101. #else
  102. /* CONFIG_LFS is off */
  103. # if UINT_MAX == 0xffffffff
  104. /* While sizeof(off_t) == sizeof(int), off_t is typedef'ed to long anyway.
  105. * gcc will throw warnings on printf("%d", off_t). Crap... */
  106. # define XATOOFF(a) xatoi_u(a)
  107. # define BB_STRTOOFF bb_strtou
  108. # define STRTOOFF strtol
  109. # define OFF_FMT "l"
  110. # else
  111. # define XATOOFF(a) xatoul_range(a, 0, LONG_MAX)
  112. # define BB_STRTOOFF bb_strtoul
  113. # define STRTOOFF strtol
  114. # define OFF_FMT "l"
  115. # endif
  116. #endif
  117. /* scary. better ideas? (but do *test* them first!) */
  118. #define OFF_T_MAX ((off_t)~((off_t)1 << (sizeof(off_t)*8-1)))
  119. /* Some useful definitions */
  120. #undef FALSE
  121. #define FALSE ((int) 0)
  122. #undef TRUE
  123. #define TRUE ((int) 1)
  124. #undef SKIP
  125. #define SKIP ((int) 2)
  126. /* for mtab.c */
  127. #define MTAB_GETMOUNTPT '1'
  128. #define MTAB_GETDEVICE '2'
  129. #define BUF_SIZE 8192
  130. #define EXPAND_ALLOC 1024
  131. /* Macros for min/max. */
  132. #ifndef MIN
  133. #define MIN(a,b) (((a)<(b))?(a):(b))
  134. #endif
  135. #ifndef MAX
  136. #define MAX(a,b) (((a)>(b))?(a):(b))
  137. #endif
  138. /* buffer allocation schemes */
  139. #if ENABLE_FEATURE_BUFFERS_GO_ON_STACK
  140. #define RESERVE_CONFIG_BUFFER(buffer,len) char buffer[len]
  141. #define RESERVE_CONFIG_UBUFFER(buffer,len) unsigned char buffer[len]
  142. #define RELEASE_CONFIG_BUFFER(buffer) ((void)0)
  143. #else
  144. #if ENABLE_FEATURE_BUFFERS_GO_IN_BSS
  145. #define RESERVE_CONFIG_BUFFER(buffer,len) static char buffer[len]
  146. #define RESERVE_CONFIG_UBUFFER(buffer,len) static unsigned char buffer[len]
  147. #define RELEASE_CONFIG_BUFFER(buffer) ((void)0)
  148. #else
  149. #define RESERVE_CONFIG_BUFFER(buffer,len) char *buffer = xmalloc(len)
  150. #define RESERVE_CONFIG_UBUFFER(buffer,len) unsigned char *buffer = xmalloc(len)
  151. #define RELEASE_CONFIG_BUFFER(buffer) free(buffer)
  152. #endif
  153. #endif
  154. #if defined(__GLIBC__)
  155. /* glibc uses __errno_location() to get a ptr to errno */
  156. /* We can just memorize it once - no multithreading in busybox :) */
  157. extern int *const bb_errno;
  158. #undef errno
  159. #define errno (*bb_errno)
  160. #endif
  161. #if defined(__GLIBC__) && __GLIBC__ < 2
  162. int vdprintf(int d, const char *format, va_list ap);
  163. #endif
  164. // This is declared here rather than #including <libgen.h> in order to avoid
  165. // confusing the two versions of basename. See the dirname/basename man page
  166. // for details.
  167. char *dirname(char *path);
  168. /* Include our own copy of struct sysinfo to avoid binary compatibility
  169. * problems with Linux 2.4, which changed things. Grumble, grumble. */
  170. struct sysinfo {
  171. long uptime; /* Seconds since boot */
  172. unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
  173. unsigned long totalram; /* Total usable main memory size */
  174. unsigned long freeram; /* Available memory size */
  175. unsigned long sharedram; /* Amount of shared memory */
  176. unsigned long bufferram; /* Memory used by buffers */
  177. unsigned long totalswap; /* Total swap space size */
  178. unsigned long freeswap; /* swap space still available */
  179. unsigned short procs; /* Number of current processes */
  180. unsigned short pad; /* Padding needed for m68k */
  181. unsigned long totalhigh; /* Total high memory size */
  182. unsigned long freehigh; /* Available high memory size */
  183. unsigned int mem_unit; /* Memory unit size in bytes */
  184. char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding: libc5 uses this.. */
  185. };
  186. int sysinfo(struct sysinfo* info);
  187. unsigned long long monotonic_us(void);
  188. unsigned monotonic_sec(void);
  189. extern void chomp(char *s);
  190. extern void trim(char *s);
  191. extern char *skip_whitespace(const char *);
  192. extern char *skip_non_whitespace(const char *);
  193. //TODO: supply a pointer to char[11] buffer (avoid statics)?
  194. extern const char *bb_mode_string(mode_t mode);
  195. extern int is_directory(const char *name, int followLinks, struct stat *statBuf);
  196. extern int remove_file(const char *path, int flags);
  197. extern int copy_file(const char *source, const char *dest, int flags);
  198. enum {
  199. ACTION_RECURSE = (1 << 0),
  200. ACTION_FOLLOWLINKS = (1 << 1),
  201. ACTION_FOLLOWLINKS_L0 = (1 << 2),
  202. ACTION_DEPTHFIRST = (1 << 3),
  203. /*ACTION_REVERSE = (1 << 4), - unused */
  204. };
  205. extern int recursive_action(const char *fileName, unsigned flags,
  206. int (*fileAction) (const char *fileName, struct stat* statbuf, void* userData, int depth),
  207. int (*dirAction) (const char *fileName, struct stat* statbuf, void* userData, int depth),
  208. void* userData, unsigned depth);
  209. extern int device_open(const char *device, int mode);
  210. extern int get_console_fd(void);
  211. extern char *find_block_device(const char *path);
  212. /* bb_copyfd_XX print read/write errors and return -1 if they occur */
  213. extern off_t bb_copyfd_eof(int fd1, int fd2);
  214. extern off_t bb_copyfd_size(int fd1, int fd2, off_t size);
  215. extern void bb_copyfd_exact_size(int fd1, int fd2, off_t size);
  216. /* "short" copy can be detected by return value < size */
  217. /* this helper yells "short read!" if param is not -1 */
  218. extern void complain_copyfd_and_die(off_t sz) ATTRIBUTE_NORETURN;
  219. extern char bb_process_escape_sequence(const char **ptr);
  220. /* xxxx_strip version can modify its parameter:
  221. * "/" -> "/"
  222. * "abc" -> "abc"
  223. * "abc/def" -> "def"
  224. * "abc/def/" -> "def" !!
  225. */
  226. extern char *bb_get_last_path_component_strip(char *path);
  227. /* "abc/def/" -> "" and it never modifies 'path' */
  228. extern char *bb_get_last_path_component_nostrip(const char *path);
  229. int ndelay_on(int fd);
  230. int ndelay_off(int fd);
  231. int close_on_exec_on(int fd);
  232. void xdup2(int, int);
  233. void xmove_fd(int, int);
  234. DIR *xopendir(const char *path);
  235. DIR *warn_opendir(const char *path);
  236. /* UNUSED: char *xmalloc_realpath(const char *path); */
  237. char *xmalloc_readlink(const char *path);
  238. char *xmalloc_readlink_or_warn(const char *path);
  239. char *xrealloc_getcwd_or_warn(char *cwd);
  240. //TODO: signal(sid, f) is the same? then why?
  241. extern void sig_catch(int,void (*)(int));
  242. //#define sig_ignore(s) (sig_catch((s), SIG_IGN))
  243. //#define sig_uncatch(s) (sig_catch((s), SIG_DFL))
  244. extern void sig_block(int);
  245. extern void sig_unblock(int);
  246. /* UNUSED: extern void sig_blocknone(void); */
  247. extern void sig_pause(void);
  248. void xsetgid(gid_t gid);
  249. void xsetuid(uid_t uid);
  250. void xchdir(const char *path);
  251. void xsetenv(const char *key, const char *value);
  252. void xunlink(const char *pathname);
  253. void xstat(const char *pathname, struct stat *buf);
  254. int xopen(const char *pathname, int flags);
  255. int xopen3(const char *pathname, int flags, int mode);
  256. int open_or_warn(const char *pathname, int flags);
  257. int open3_or_warn(const char *pathname, int flags, int mode);
  258. void xpipe(int filedes[2]);
  259. off_t xlseek(int fd, off_t offset, int whence);
  260. off_t fdlength(int fd);
  261. int xsocket(int domain, int type, int protocol);
  262. void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
  263. void xlisten(int s, int backlog);
  264. void xconnect(int s, const struct sockaddr *s_addr, socklen_t addrlen);
  265. ssize_t xsendto(int s, const void *buf, size_t len, const struct sockaddr *to,
  266. socklen_t tolen);
  267. /* SO_REUSEADDR allows a server to rebind to an address that is already
  268. * "in use" by old connections to e.g. previous server instance which is
  269. * killed or crashed. Without it bind will fail until all such connections
  270. * time out. Linux does not allow multiple live binds on same ip:port
  271. * regardless of SO_REUSEADDR (unlike some other flavors of Unix).
  272. * Turn it on before you call bind(). */
  273. void setsockopt_reuseaddr(int fd); /* On Linux this never fails. */
  274. int setsockopt_broadcast(int fd);
  275. /* NB: returns port in host byte order */
  276. unsigned bb_lookup_port(const char *port, const char *protocol, unsigned default_port);
  277. typedef struct len_and_sockaddr {
  278. socklen_t len;
  279. union {
  280. struct sockaddr sa;
  281. struct sockaddr_in sin;
  282. #if ENABLE_FEATURE_IPV6
  283. struct sockaddr_in6 sin6;
  284. #endif
  285. };
  286. } len_and_sockaddr;
  287. enum {
  288. LSA_SIZEOF_SA = sizeof(
  289. union {
  290. struct sockaddr sa;
  291. struct sockaddr_in sin;
  292. #if ENABLE_FEATURE_IPV6
  293. struct sockaddr_in6 sin6;
  294. #endif
  295. }
  296. )
  297. };
  298. /* Create stream socket, and allocate suitable lsa.
  299. * (lsa of correct size and lsa->sa.sa_family (AF_INET/AF_INET6))
  300. * af == AF_UNSPEC will result in trying to create IPv6 socket,
  301. * and if kernel doesn't support it, IPv4.
  302. */
  303. int xsocket_type(len_and_sockaddr **lsap, USE_FEATURE_IPV6(int af,) int sock_type);
  304. int xsocket_stream(len_and_sockaddr **lsap);
  305. /* Create server socket bound to bindaddr:port. bindaddr can be NULL,
  306. * numeric IP ("N.N.N.N") or numeric IPv6 address,
  307. * and can have ":PORT" suffix (for IPv6 use "[X:X:...:X]:PORT").
  308. * Only if there is no suffix, port argument is used */
  309. /* NB: these set SO_REUSEADDR before bind */
  310. int create_and_bind_stream_or_die(const char *bindaddr, int port);
  311. int create_and_bind_dgram_or_die(const char *bindaddr, int port);
  312. /* Create client TCP socket connected to peer:port. Peer cannot be NULL.
  313. * Peer can be numeric IP ("N.N.N.N"), numeric IPv6 address or hostname,
  314. * and can have ":PORT" suffix (for IPv6 use "[X:X:...:X]:PORT").
  315. * If there is no suffix, port argument is used */
  316. int create_and_connect_stream_or_die(const char *peer, int port);
  317. /* Connect to peer identified by lsa */
  318. int xconnect_stream(const len_and_sockaddr *lsa);
  319. /* Return malloc'ed len_and_sockaddr with socket address of host:port
  320. * Currently will return IPv4 or IPv6 sockaddrs only
  321. * (depending on host), but in theory nothing prevents e.g.
  322. * UNIX socket address being returned, IPX sockaddr etc...
  323. * On error does bb_error_msg and returns NULL */
  324. len_and_sockaddr* host2sockaddr(const char *host, int port);
  325. /* Version which dies on error */
  326. len_and_sockaddr* xhost2sockaddr(const char *host, int port);
  327. len_and_sockaddr* xdotted2sockaddr(const char *host, int port);
  328. #if ENABLE_FEATURE_IPV6
  329. /* Same, useful if you want to force family (e.g. IPv6) */
  330. len_and_sockaddr* host_and_af2sockaddr(const char *host, int port, sa_family_t af);
  331. len_and_sockaddr* xhost_and_af2sockaddr(const char *host, int port, sa_family_t af);
  332. #else
  333. /* [we evaluate af: think about "host_and_af2sockaddr(..., af++)"] */
  334. #define host_and_af2sockaddr(host, port, af) ((void)(af), host2sockaddr((host), (port)))
  335. #define xhost_and_af2sockaddr(host, port, af) ((void)(af), xhost2sockaddr((host), (port)))
  336. #endif
  337. /* Assign sin[6]_port member if the socket is an AF_INET[6] one,
  338. * otherwise no-op. Useful for ftp.
  339. * NB: does NOT do htons() internally, just direct assignment. */
  340. void set_nport(len_and_sockaddr *lsa, unsigned port);
  341. /* Retrieve sin[6]_port or return -1 for non-INET[6] lsa's */
  342. int get_nport(const struct sockaddr *sa);
  343. /* Reverse DNS. Returns NULL on failure. */
  344. char* xmalloc_sockaddr2host(const struct sockaddr *sa);
  345. /* This one doesn't append :PORTNUM */
  346. char* xmalloc_sockaddr2host_noport(const struct sockaddr *sa);
  347. /* This one also doesn't fall back to dotted IP (returns NULL) */
  348. char* xmalloc_sockaddr2hostonly_noport(const struct sockaddr *sa);
  349. /* inet_[ap]ton on steroids */
  350. char* xmalloc_sockaddr2dotted(const struct sockaddr *sa);
  351. char* xmalloc_sockaddr2dotted_noport(const struct sockaddr *sa);
  352. // "old" (ipv4 only) API
  353. // users: traceroute.c hostname.c - use _list_ of all IPs
  354. struct hostent *xgethostbyname(const char *name);
  355. // Also mount.c and inetd.c are using gethostbyname(),
  356. // + inet_common.c has additional IPv4-only stuff
  357. void socket_want_pktinfo(int fd);
  358. ssize_t send_to_from(int fd, void *buf, size_t len, int flags,
  359. const struct sockaddr *from, const struct sockaddr *to,
  360. socklen_t tolen);
  361. ssize_t recv_from_to(int fd, void *buf, size_t len, int flags,
  362. struct sockaddr *from, struct sockaddr *to,
  363. socklen_t sa_size);
  364. char *xstrdup(const char *s);
  365. char *xstrndup(const char *s, int n);
  366. char *safe_strncpy(char *dst, const char *src, size_t size);
  367. /* Guaranteed to NOT be a macro (smallest code). Saves nearly 2k on uclibc.
  368. * But potentially slow, don't use in one-billion-times loops */
  369. int bb_putchar(int ch);
  370. char *xasprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
  371. // gcc-4.1.1 still isn't good enough at optimizing it
  372. // (+200 bytes compared to macro)
  373. //static ALWAYS_INLINE
  374. //int LONE_DASH(const char *s) { return s[0] == '-' && !s[1]; }
  375. //static ALWAYS_INLINE
  376. //int NOT_LONE_DASH(const char *s) { return s[0] != '-' || s[1]; }
  377. #define LONE_DASH(s) ((s)[0] == '-' && !(s)[1])
  378. #define NOT_LONE_DASH(s) ((s)[0] != '-' || (s)[1])
  379. #define LONE_CHAR(s,c) ((s)[0] == (c) && !(s)[1])
  380. #define NOT_LONE_CHAR(s,c) ((s)[0] != (c) || (s)[1])
  381. #define DOT_OR_DOTDOT(s) ((s)[0] == '.' && (!(s)[1] || ((s)[1] == '.' && !(s)[2])))
  382. /* dmalloc will redefine these to it's own implementation. It is safe
  383. * to have the prototypes here unconditionally. */
  384. extern void *malloc_or_warn(size_t size);
  385. extern void *xmalloc(size_t size);
  386. extern void *xzalloc(size_t size);
  387. extern void *xrealloc(void *old, size_t size);
  388. extern ssize_t safe_read(int fd, void *buf, size_t count);
  389. extern ssize_t full_read(int fd, void *buf, size_t count);
  390. extern void xread(int fd, void *buf, size_t count);
  391. extern unsigned char xread_char(int fd);
  392. // Read one line a-la fgets. Uses one read(), works only on seekable streams
  393. extern char *reads(int fd, char *buf, size_t count);
  394. // Read one line a-la fgets. Reads byte-by-byte.
  395. // Useful when it is important to not read ahead.
  396. extern char *xmalloc_reads(int fd, char *pfx);
  397. extern ssize_t read_close(int fd, void *buf, size_t count);
  398. extern ssize_t open_read_close(const char *filename, void *buf, size_t count);
  399. extern void *xmalloc_open_read_close(const char *filename, size_t *sizep);
  400. extern ssize_t safe_write(int fd, const void *buf, size_t count);
  401. extern ssize_t full_write(int fd, const void *buf, size_t count);
  402. extern void xwrite(int fd, const void *buf, size_t count);
  403. /* Reads and prints to stdout till eof, then closes FILE. Exits on error: */
  404. extern void xprint_and_close_file(FILE *file);
  405. extern char *xmalloc_fgets(FILE *file);
  406. /* Read up to (and including) TERMINATING_STRING: */
  407. extern char *xmalloc_fgets_str(FILE *file, const char *terminating_string);
  408. /* Chops off '\n' from the end, unlike fgets: */
  409. extern char *xmalloc_getline(FILE *file);
  410. extern char *bb_get_chunk_from_file(FILE *file, int *end);
  411. extern void die_if_ferror(FILE *file, const char *msg);
  412. extern void die_if_ferror_stdout(void);
  413. extern void xfflush_stdout(void);
  414. extern void fflush_stdout_and_exit(int retval) ATTRIBUTE_NORETURN;
  415. extern int fclose_if_not_stdin(FILE *file);
  416. extern FILE *xfopen(const char *filename, const char *mode);
  417. /* Prints warning to stderr and returns NULL on failure: */
  418. extern FILE *fopen_or_warn(const char *filename, const char *mode);
  419. /* "Opens" stdin if filename is special, else just opens file: */
  420. extern FILE *fopen_or_warn_stdin(const char *filename);
  421. /* Wrapper which restarts poll on EINTR or ENOMEM.
  422. * On other errors complains [perror("poll")] and returns.
  423. * Warning! May take (much) longer than timeout_ms to return!
  424. * If this is a problem, use bare poll and open-code EINTR/ENOMEM handling */
  425. int safe_poll(struct pollfd *ufds, nfds_t nfds, int timeout_ms);
  426. /* Convert each alpha char in str to lower-case */
  427. char* str_tolower(char *str);
  428. char *utoa(unsigned n);
  429. char *itoa(int n);
  430. /* Returns a pointer past the formatted number, does NOT null-terminate */
  431. char *utoa_to_buf(unsigned n, char *buf, unsigned buflen);
  432. char *itoa_to_buf(int n, char *buf, unsigned buflen);
  433. void smart_ulltoa5(unsigned long long ul, char buf[5]);
  434. //TODO: provide pointer to buf (avoid statics)?
  435. const char *make_human_readable_str(unsigned long long size,
  436. unsigned long block_size, unsigned long display_unit);
  437. /* Put a string of hex bytes ("1b2e66fe"...), return advanced pointer */
  438. char *bin2hex(char *buf, const char *cp, int count);
  439. /* Last element is marked by mult == 0 */
  440. struct suffix_mult {
  441. char suffix[4];
  442. unsigned mult;
  443. };
  444. #include "xatonum.h"
  445. /* Specialized: */
  446. /* Using xatoi() instead of naive atoi() is not always convenient -
  447. * in many places people want *non-negative* values, but store them
  448. * in signed int. Therefore we need this one:
  449. * dies if input is not in [0, INT_MAX] range. Also will reject '-0' etc */
  450. int xatoi_u(const char *numstr);
  451. /* Useful for reading port numbers */
  452. uint16_t xatou16(const char *numstr);
  453. /* These parse entries in /etc/passwd and /etc/group. This is desirable
  454. * for BusyBox since we want to avoid using the glibc NSS stuff, which
  455. * increases target size and is often not needed on embedded systems. */
  456. long xuname2uid(const char *name);
  457. long xgroup2gid(const char *name);
  458. /* wrapper: allows string to contain numeric uid or gid */
  459. unsigned long get_ug_id(const char *s, long (*xname2id)(const char *));
  460. /* from chpst. Does not die, returns 0 on failure */
  461. struct bb_uidgid_t {
  462. uid_t uid;
  463. gid_t gid;
  464. };
  465. /* always sets uid and gid */
  466. int get_uidgid(struct bb_uidgid_t*, const char*, int numeric_ok);
  467. /* chown-like handling of "user[:[group]" */
  468. void parse_chown_usergroup_or_die(struct bb_uidgid_t *u, char *user_group);
  469. /* bb_getpwuid, bb_getgrgid:
  470. * bb_getXXXid(buf, bufsz, id) - copy user/group name or id
  471. * as a string to buf, return user/group name or NULL
  472. * bb_getXXXid(NULL, 0, id) - return user/group name or NULL
  473. * bb_getXXXid(NULL, -1, id) - return user/group name or exit
  474. */
  475. char *bb_getpwuid(char *name, int bufsize, long uid);
  476. char *bb_getgrgid(char *group, int bufsize, long gid);
  477. /* versions which cache results (useful for ps, ls etc) */
  478. const char* get_cached_username(uid_t uid);
  479. const char* get_cached_groupname(gid_t gid);
  480. void clear_username_cache(void);
  481. /* internally usernames are saved in fixed-sized char[] buffers */
  482. enum { USERNAME_MAX_SIZE = 16 - sizeof(int) };
  483. struct bb_applet;
  484. int execable_file(const char *name);
  485. char *find_execable(const char *filename);
  486. int exists_execable(const char *filename);
  487. /* BB_EXECxx always execs (it's not doing NOFORK/NOEXEC stuff),
  488. * but it may exec busybox and call applet instead of searching PATH.
  489. */
  490. #if ENABLE_FEATURE_PREFER_APPLETS
  491. int bb_execvp(const char *file, char *const argv[]);
  492. #define BB_EXECVP(prog,cmd) bb_execvp(prog,cmd)
  493. #define BB_EXECLP(prog,cmd,...) \
  494. execlp((find_applet_by_name(prog)) ? CONFIG_BUSYBOX_EXEC_PATH : prog, \
  495. cmd, __VA_ARGS__)
  496. #else
  497. #define BB_EXECVP(prog,cmd) execvp(prog,cmd)
  498. #define BB_EXECLP(prog,cmd,...) execlp(prog,cmd, __VA_ARGS__)
  499. #endif
  500. /* NOMMU friendy fork+exec */
  501. pid_t spawn(char **argv);
  502. pid_t xspawn(char **argv);
  503. /* Unlike waitpid, waits ONLY for one process,
  504. * It's safe to pass negative 'pids' from failed [v]fork -
  505. * wait4pid will return -1 (and will not clobber [v]fork's errno).
  506. * IOW: rc = wait4pid(spawn(argv));
  507. * if (rc < 0) bb_perror_msg("%s", argv[0]);
  508. * if (rc > 0) bb_error_msg("exit code: %d", rc);
  509. */
  510. int wait4pid(int pid);
  511. int wait_pid(int *wstat, int pid);
  512. int wait_nohang(int *wstat);
  513. #define wait_crashed(w) ((w) & 127)
  514. #define wait_exitcode(w) ((w) >> 8)
  515. #define wait_stopsig(w) ((w) >> 8)
  516. #define wait_stopped(w) (((w) & 127) == 127)
  517. /* wait4pid(spawn(argv)) + NOFORK/NOEXEC (if configured) */
  518. int spawn_and_wait(char **argv);
  519. struct nofork_save_area {
  520. jmp_buf die_jmp;
  521. const char *applet_name;
  522. int xfunc_error_retval;
  523. uint32_t option_mask32;
  524. int die_sleep;
  525. smallint saved;
  526. };
  527. void save_nofork_data(struct nofork_save_area *save);
  528. void restore_nofork_data(struct nofork_save_area *save);
  529. /* Does NOT check that applet is NOFORK, just blindly runs it */
  530. int run_nofork_applet(const struct bb_applet *a, char **argv);
  531. int run_nofork_applet_prime(struct nofork_save_area *old, const struct bb_applet *a, char **argv);
  532. /* Helpers for daemonization.
  533. *
  534. * bb_daemonize(flags) = daemonize, does not compile on NOMMU
  535. *
  536. * bb_daemonize_or_rexec(flags, argv) = daemonizes on MMU (and ignores argv),
  537. * rexec's itself on NOMMU with argv passed as command line.
  538. * Thus bb_daemonize_or_rexec may cause your <applet>_main() to be re-executed
  539. * from the start. (It will detect it and not reexec again second time).
  540. * You have to audit carefully that you don't do something twice as a result
  541. * (opening files/sockets, parsing config files etc...)!
  542. *
  543. * Both of the above will redirect fd 0,1,2 to /dev/null and drop ctty
  544. * (will do setsid()).
  545. *
  546. * forkexit_or_rexec(argv) = bare-bones "fork + parent exits" on MMU,
  547. * "vfork + re-exec ourself" on NOMMU. No fd redirection, no setsid().
  548. * Currently used for openvt. On MMU ignores argv.
  549. *
  550. * Helper for network daemons in foreground mode:
  551. *
  552. * bb_sanitize_stdio() = make sure that fd 0,1,2 are opened by opening them
  553. * to /dev/null if they are not.
  554. */
  555. enum {
  556. DAEMON_CHDIR_ROOT = 1,
  557. DAEMON_DEVNULL_STDIO = 2,
  558. DAEMON_CLOSE_EXTRA_FDS = 4,
  559. DAEMON_ONLY_SANITIZE = 8, /* internal use */
  560. };
  561. #if BB_MMU
  562. void forkexit_or_rexec(void);
  563. enum { re_execed = 0 };
  564. # define forkexit_or_rexec(argv) forkexit_or_rexec()
  565. # define bb_daemonize_or_rexec(flags, argv) bb_daemonize_or_rexec(flags)
  566. # define bb_daemonize(flags) bb_daemonize_or_rexec(flags, bogus)
  567. #else
  568. void re_exec(char **argv) ATTRIBUTE_NORETURN;
  569. void forkexit_or_rexec(char **argv);
  570. extern bool re_execed;
  571. # define fork() BUG_fork_is_unavailable_on_nommu()
  572. # define daemon(a,b) BUG_daemon_is_unavailable_on_nommu()
  573. # define bb_daemonize(a) BUG_bb_daemonize_is_unavailable_on_nommu()
  574. #endif
  575. void bb_daemonize_or_rexec(int flags, char **argv);
  576. void bb_sanitize_stdio(void);
  577. extern const char *opt_complementary;
  578. #if ENABLE_GETOPT_LONG
  579. #define No_argument "\0"
  580. #define Required_argument "\001"
  581. #define Optional_argument "\002"
  582. extern const char *applet_long_options;
  583. #endif
  584. extern uint32_t option_mask32;
  585. extern uint32_t getopt32(char **argv, const char *applet_opts, ...);
  586. typedef struct llist_t {
  587. char *data;
  588. struct llist_t *link;
  589. } llist_t;
  590. void llist_add_to(llist_t **old_head, void *data);
  591. void llist_add_to_end(llist_t **list_head, void *data);
  592. void *llist_pop(llist_t **elm);
  593. void llist_unlink(llist_t **head, llist_t *elm);
  594. void llist_free(llist_t *elm, void (*freeit)(void *data));
  595. llist_t *llist_rev(llist_t *list);
  596. /* BTW, surprisingly, changing API to
  597. * llist_t *llist_add_to(llist_t *old_head, void *data)
  598. * etc does not result in smaller code... */
  599. /* start_stop_daemon and udhcpc are special - they want
  600. * to create pidfiles regardless of FEATURE_PIDFILE */
  601. #if ENABLE_FEATURE_PIDFILE || defined(WANT_PIDFILE)
  602. /* True only if we created pidfile which is *file*, not /dev/null etc */
  603. extern smallint wrote_pidfile;
  604. void write_pidfile(const char *path);
  605. #define remove_pidfile(path) do { if (wrote_pidfile) unlink(path); } while (0)
  606. #else
  607. enum { wrote_pidfile = 0 };
  608. #define write_pidfile(path) ((void)0)
  609. #define remove_pidfile(path) ((void)0)
  610. #endif
  611. enum {
  612. LOGMODE_NONE = 0,
  613. LOGMODE_STDIO = (1 << 0),
  614. LOGMODE_SYSLOG = (1 << 1) * ENABLE_FEATURE_SYSLOG,
  615. LOGMODE_BOTH = LOGMODE_SYSLOG + LOGMODE_STDIO,
  616. };
  617. extern const char *msg_eol;
  618. extern smallint logmode;
  619. extern int die_sleep;
  620. extern int xfunc_error_retval;
  621. extern jmp_buf die_jmp;
  622. extern void xfunc_die(void) ATTRIBUTE_NORETURN;
  623. extern void bb_show_usage(void) ATTRIBUTE_NORETURN;
  624. extern void bb_error_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
  625. extern void bb_error_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
  626. extern void bb_perror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
  627. extern void bb_simple_perror_msg(const char *s);
  628. extern void bb_perror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
  629. extern void bb_simple_perror_msg_and_die(const char *s) __attribute__ ((noreturn));
  630. extern void bb_herror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
  631. extern void bb_herror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
  632. extern void bb_perror_nomsg_and_die(void) ATTRIBUTE_NORETURN;
  633. extern void bb_perror_nomsg(void);
  634. extern void bb_info_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
  635. extern void bb_verror_msg(const char *s, va_list p, const char *strerr);
  636. /* We need to export XXX_main from libbusybox
  637. * only if we build "individual" binaries
  638. */
  639. #if ENABLE_FEATURE_INDIVIDUAL
  640. #define MAIN_EXTERNALLY_VISIBLE EXTERNALLY_VISIBLE
  641. #else
  642. #define MAIN_EXTERNALLY_VISIBLE
  643. #endif
  644. /* applets which are useful from another applets */
  645. int bb_cat(char** argv);
  646. int bb_echo(char** argv);
  647. int test_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  648. int kill_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  649. #if ENABLE_ROUTE
  650. void bb_displayroutes(int noresolve, int netstatfmt);
  651. #endif
  652. int chown_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  653. #if ENABLE_GUNZIP
  654. int gunzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  655. #endif
  656. #if ENABLE_BUNZIP2
  657. int bunzip2_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  658. #endif
  659. int bbunpack(char **argv,
  660. char* (*make_new_name)(char *filename),
  661. USE_DESKTOP(long long) int (*unpacker)(void)
  662. );
  663. /* Networking */
  664. int create_icmp_socket(void);
  665. int create_icmp6_socket(void);
  666. /* interface.c */
  667. /* This structure defines protocol families and their handlers. */
  668. struct aftype {
  669. const char *name;
  670. const char *title;
  671. int af;
  672. int alen;
  673. char *(*print) (unsigned char *);
  674. const char *(*sprint) (struct sockaddr *, int numeric);
  675. int (*input) (/*int type,*/ const char *bufp, struct sockaddr *);
  676. void (*herror) (char *text);
  677. int (*rprint) (int options);
  678. int (*rinput) (int typ, int ext, char **argv);
  679. /* may modify src */
  680. int (*getmask) (char *src, struct sockaddr * mask, char *name);
  681. };
  682. /* This structure defines hardware protocols and their handlers. */
  683. struct hwtype {
  684. const char *name;
  685. const char *title;
  686. int type;
  687. int alen;
  688. char *(*print) (unsigned char *);
  689. int (*input) (const char *, struct sockaddr *);
  690. int (*activate) (int fd);
  691. int suppress_null_addr;
  692. };
  693. extern smallint interface_opt_a;
  694. int display_interfaces(char *ifname);
  695. const struct aftype *get_aftype(const char *name);
  696. const struct hwtype *get_hwtype(const char *name);
  697. const struct hwtype *get_hwntype(int type);
  698. #ifndef BUILD_INDIVIDUAL
  699. extern const struct bb_applet *find_applet_by_name(const char *name);
  700. /* Returns only if applet is not found. */
  701. extern void run_applet_and_exit(const char *name, char **argv);
  702. extern void run_appletstruct_and_exit(const struct bb_applet *a, char **argv) ATTRIBUTE_NORETURN;
  703. #endif
  704. extern int match_fstype(const struct mntent *mt, const char *fstypes);
  705. extern struct mntent *find_mount_point(const char *name, const char *table);
  706. extern void erase_mtab(const char * name);
  707. extern unsigned int tty_baud_to_value(speed_t speed);
  708. extern speed_t tty_value_to_baud(unsigned int value);
  709. extern void bb_warn_ignoring_args(int n);
  710. extern int get_linux_version_code(void);
  711. extern char *query_loop(const char *device);
  712. extern int del_loop(const char *device);
  713. /* If *devname is not NULL, use that name, otherwise try to find free one,
  714. * malloc and return it in *devname.
  715. * return value: 1: read-only loopdev was setup, 0: rw, < 0: error */
  716. extern int set_loop(char **devname, const char *file, unsigned long long offset);
  717. //TODO: pass buf pointer or return allocated buf (avoid statics)?
  718. char *bb_askpass(int timeout, const char * prompt);
  719. int bb_ask_confirmation(void);
  720. int klogctl(int type, char * b, int len);
  721. extern int bb_parse_mode(const char* s, mode_t* theMode);
  722. char *concat_path_file(const char *path, const char *filename);
  723. char *concat_subpath_file(const char *path, const char *filename);
  724. const char *bb_basename(const char *name);
  725. /* NB: can violate const-ness (similarly to strchr) */
  726. char *last_char_is(const char *s, int c);
  727. USE_DESKTOP(long long) int uncompress(int fd_in, int fd_out);
  728. int inflate(int in, int out);
  729. int bb_make_directory(char *path, long mode, int flags);
  730. int get_signum(const char *name);
  731. const char *get_signame(int number);
  732. void print_signames(void);
  733. char *bb_simplify_path(const char *path);
  734. #define FAIL_DELAY 3
  735. extern void bb_do_delay(int seconds);
  736. extern void change_identity(const struct passwd *pw);
  737. extern const char *change_identity_e2str(const struct passwd *pw);
  738. extern void run_shell(const char *shell, int loginshell, const char *command, const char **additional_args) ATTRIBUTE_NORETURN;
  739. extern void run_shell(const char *shell, int loginshell, const char *command, const char **additional_args);
  740. #if ENABLE_SELINUX
  741. extern void renew_current_security_context(void);
  742. extern void set_current_security_context(security_context_t sid);
  743. extern context_t set_security_context_component(security_context_t cur_context,
  744. char *user, char *role, char *type, char *range);
  745. extern void setfscreatecon_or_die(security_context_t scontext);
  746. extern void selinux_preserve_fcontext(int fdesc);
  747. #else
  748. #define selinux_preserve_fcontext(fdesc) ((void)0)
  749. #endif
  750. extern void selinux_or_die(void);
  751. extern int restricted_shell(const char *shell);
  752. /* setup_environment:
  753. * if loginshell = 1: cd(pw->pw_dir), clear environment, then set
  754. * TERM=(old value)
  755. * USER=pw->pw_name, LOGNAME=pw->pw_name
  756. * PATH=bb_default_[root_]path
  757. * HOME=pw->pw_dir
  758. * SHELL=shell
  759. * else if changeenv = 1:
  760. * if not root (if pw->pw_uid != 0):
  761. * USER=pw->pw_name, LOGNAME=pw->pw_name
  762. * HOME=pw->pw_dir
  763. * SHELL=shell
  764. * else does nothing
  765. */
  766. extern void setup_environment(const char *shell, int loginshell, int changeenv, const struct passwd *pw);
  767. extern int correct_password(const struct passwd *pw);
  768. /* Returns a ptr to static storage */
  769. extern char *pw_encrypt(const char *clear, const char *salt);
  770. extern int obscure(const char *old, const char *newval, const struct passwd *pwdp);
  771. int index_in_str_array(const char *const string_array[], const char *key);
  772. int index_in_strings(const char *strings, const char *key);
  773. int index_in_substr_array(const char *const string_array[], const char *key);
  774. int index_in_substrings(const char *strings, const char *key);
  775. const char *nth_string(const char *strings, int n);
  776. extern void print_login_issue(const char *issue_file, const char *tty);
  777. extern void print_login_prompt(void);
  778. /* rnd is additional random input. New one is returned.
  779. * Useful if you call crypt_make_salt many times in a row:
  780. * rnd = crypt_make_salt(buf1, 4, 0);
  781. * rnd = crypt_make_salt(buf2, 4, rnd);
  782. * rnd = crypt_make_salt(buf3, 4, rnd);
  783. * (otherwise we risk having same salt generated)
  784. */
  785. extern int crypt_make_salt(char *p, int cnt, int rnd);
  786. /* Returns number of lines changed, or -1 on error */
  787. extern int update_passwd(const char *filename, const char *username,
  788. const char *new_pw);
  789. /* NB: typically you want to pass fd 0, not 1. Think 'applet | grep something' */
  790. int get_terminal_width_height(int fd, int *width, int *height);
  791. int ioctl_or_perror(int fd, int request, void *argp, const char *fmt,...) __attribute__ ((format (printf, 4, 5)));
  792. void ioctl_or_perror_and_die(int fd, int request, void *argp, const char *fmt,...) __attribute__ ((format (printf, 4, 5)));
  793. #if ENABLE_IOCTL_HEX2STR_ERROR
  794. int bb_ioctl_or_warn(int fd, int request, void *argp, const char *ioctl_name);
  795. void bb_xioctl(int fd, int request, void *argp, const char *ioctl_name);
  796. #define ioctl_or_warn(fd,request,argp) bb_ioctl_or_warn(fd,request,argp,#request)
  797. #define xioctl(fd,request,argp) bb_xioctl(fd,request,argp,#request)
  798. #else
  799. int bb_ioctl_or_warn(int fd, int request, void *argp);
  800. void bb_xioctl(int fd, int request, void *argp);
  801. #define ioctl_or_warn(fd,request,argp) bb_ioctl_or_warn(fd,request,argp)
  802. #define xioctl(fd,request,argp) bb_xioctl(fd,request,argp)
  803. #endif
  804. char *is_in_ino_dev_hashtable(const struct stat *statbuf);
  805. void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name);
  806. void reset_ino_dev_hashtable(void);
  807. #ifdef __GLIBC__
  808. /* At least glibc has horrendously large inline for this, so wrap it */
  809. unsigned long long bb_makedev(unsigned int major, unsigned int minor);
  810. #undef makedev
  811. #define makedev(a,b) bb_makedev(a,b)
  812. #endif
  813. #if ENABLE_FEATURE_EDITING
  814. /* It's NOT just ENABLEd or disabled. It's a number: */
  815. #ifdef CONFIG_FEATURE_EDITING_HISTORY
  816. #define MAX_HISTORY (CONFIG_FEATURE_EDITING_HISTORY + 0)
  817. #else
  818. #define MAX_HISTORY 0
  819. #endif
  820. typedef struct line_input_t {
  821. int flags;
  822. const char *path_lookup;
  823. #if MAX_HISTORY
  824. int cnt_history;
  825. int cur_history;
  826. USE_FEATURE_EDITING_SAVEHISTORY(const char *hist_file;)
  827. char *history[MAX_HISTORY + 1];
  828. #endif
  829. } line_input_t;
  830. enum {
  831. DO_HISTORY = 1 * (MAX_HISTORY > 0),
  832. SAVE_HISTORY = 2 * (MAX_HISTORY > 0) * ENABLE_FEATURE_EDITING_SAVEHISTORY,
  833. TAB_COMPLETION = 4 * ENABLE_FEATURE_TAB_COMPLETION,
  834. USERNAME_COMPLETION = 8 * ENABLE_FEATURE_USERNAME_COMPLETION,
  835. VI_MODE = 0x10 * ENABLE_FEATURE_EDITING_VI,
  836. WITH_PATH_LOOKUP = 0x20,
  837. FOR_SHELL = DO_HISTORY | SAVE_HISTORY | TAB_COMPLETION | USERNAME_COMPLETION,
  838. };
  839. line_input_t *new_line_input_t(int flags);
  840. /* Returns:
  841. * -1 on read errors or EOF, or on bare Ctrl-D.
  842. * 0 on ctrl-C,
  843. * >0 length of input string, including terminating '\n'
  844. * [is this true? stores "" in 'command' if return value is 0 or -1]
  845. */
  846. int read_line_input(const char* prompt, char* command, int maxsize, line_input_t *state);
  847. #else
  848. int read_line_input(const char* prompt, char* command, int maxsize);
  849. #define read_line_input(prompt, command, maxsize, state) \
  850. read_line_input(prompt, command, maxsize)
  851. #endif
  852. #ifndef COMM_LEN
  853. #ifdef TASK_COMM_LEN
  854. enum { COMM_LEN = TASK_COMM_LEN };
  855. #else
  856. /* synchronize with sizeof(task_struct.comm) in /usr/include/linux/sched.h */
  857. enum { COMM_LEN = 16 };
  858. #endif
  859. #endif
  860. typedef struct procps_status_t {
  861. DIR *dir;
  862. uint8_t shift_pages_to_bytes;
  863. uint8_t shift_pages_to_kb;
  864. /* Fields are set to 0/NULL if failed to determine (or not requested) */
  865. char *argv0;
  866. USE_SELINUX(char *context;)
  867. /* Everything below must contain no ptrs to malloc'ed data:
  868. * it is memset(0) for each process in procps_scan() */
  869. unsigned long vsz, rss; /* we round it to kbytes */
  870. unsigned long stime, utime;
  871. unsigned pid;
  872. unsigned ppid;
  873. unsigned pgid;
  874. unsigned sid;
  875. unsigned uid;
  876. unsigned gid;
  877. unsigned tty_major,tty_minor;
  878. #if ENABLE_FEATURE_TOPMEM
  879. unsigned long mapped_rw;
  880. unsigned long mapped_ro;
  881. unsigned long shared_clean;
  882. unsigned long shared_dirty;
  883. unsigned long private_clean;
  884. unsigned long private_dirty;
  885. unsigned long stack;
  886. #endif
  887. char state[4];
  888. /* basename of executable in exec(2), read from /proc/N/stat
  889. * (if executable is symlink or script, it is NOT replaced
  890. * by link target or interpreter name) */
  891. char comm[COMM_LEN];
  892. /* user/group? - use passwd/group parsing functions */
  893. } procps_status_t;
  894. enum {
  895. PSSCAN_PID = 1 << 0,
  896. PSSCAN_PPID = 1 << 1,
  897. PSSCAN_PGID = 1 << 2,
  898. PSSCAN_SID = 1 << 3,
  899. PSSCAN_UIDGID = 1 << 4,
  900. PSSCAN_COMM = 1 << 5,
  901. /* PSSCAN_CMD = 1 << 6, - use read_cmdline instead */
  902. PSSCAN_ARGV0 = 1 << 7,
  903. /* PSSCAN_EXE = 1 << 8, - not implemented */
  904. PSSCAN_STATE = 1 << 9,
  905. PSSCAN_VSZ = 1 << 10,
  906. PSSCAN_RSS = 1 << 11,
  907. PSSCAN_STIME = 1 << 12,
  908. PSSCAN_UTIME = 1 << 13,
  909. PSSCAN_TTY = 1 << 14,
  910. PSSCAN_SMAPS = (1 << 15) * ENABLE_FEATURE_TOPMEM,
  911. PSSCAN_ARGVN = (1 << 16) * (ENABLE_PGREP | ENABLE_PKILL),
  912. USE_SELINUX(PSSCAN_CONTEXT = 1 << 17,)
  913. /* These are all retrieved from proc/NN/stat in one go: */
  914. PSSCAN_STAT = PSSCAN_PPID | PSSCAN_PGID | PSSCAN_SID
  915. | PSSCAN_COMM | PSSCAN_STATE
  916. | PSSCAN_VSZ | PSSCAN_RSS
  917. | PSSCAN_STIME | PSSCAN_UTIME
  918. | PSSCAN_TTY,
  919. };
  920. procps_status_t* alloc_procps_scan(int flags);
  921. void free_procps_scan(procps_status_t* sp);
  922. procps_status_t* procps_scan(procps_status_t* sp, int flags);
  923. /* Format cmdline (up to col chars) into char buf[col+1] */
  924. /* Puts [comm] if cmdline is empty (-> process is a kernel thread) */
  925. void read_cmdline(char *buf, int col, unsigned pid, const char *comm);
  926. pid_t *find_pid_by_name(const char* procName);
  927. pid_t *pidlist_reverse(pid_t *pidList);
  928. extern const char bb_uuenc_tbl_base64[];
  929. extern const char bb_uuenc_tbl_std[];
  930. void bb_uuencode(char *store, const void *s, int length, const char *tbl);
  931. typedef struct sha1_ctx_t {
  932. uint32_t count[2];
  933. uint32_t hash[5];
  934. uint32_t wbuf[16];
  935. } sha1_ctx_t;
  936. void sha1_begin(sha1_ctx_t *ctx);
  937. void sha1_hash(const void *data, size_t length, sha1_ctx_t *ctx);
  938. void *sha1_end(void *resbuf, sha1_ctx_t *ctx);
  939. typedef struct md5_ctx_t {
  940. uint32_t A;
  941. uint32_t B;
  942. uint32_t C;
  943. uint32_t D;
  944. uint64_t total;
  945. uint32_t buflen;
  946. char buffer[128];
  947. } md5_ctx_t;
  948. void md5_begin(md5_ctx_t *ctx);
  949. void md5_hash(const void *data, size_t length, md5_ctx_t *ctx);
  950. void *md5_end(void *resbuf, md5_ctx_t *ctx);
  951. uint32_t *crc32_filltable(uint32_t *tbl256, int endian);
  952. enum { /* DO NOT CHANGE THESE VALUES! cp.c, mv.c, install.c depend on them. */
  953. FILEUTILS_PRESERVE_STATUS = 1,
  954. FILEUTILS_DEREFERENCE = 2,
  955. FILEUTILS_RECUR = 4,
  956. FILEUTILS_FORCE = 8,
  957. FILEUTILS_INTERACTIVE = 0x10,
  958. FILEUTILS_MAKE_HARDLINK = 0x20,
  959. FILEUTILS_MAKE_SOFTLINK = 0x40,
  960. #if ENABLE_SELINUX
  961. FILEUTILS_PRESERVE_SECURITY_CONTEXT = 0x80,
  962. FILEUTILS_SET_SECURITY_CONTEXT = 0x100
  963. #endif
  964. };
  965. #define FILEUTILS_CP_OPTSTR "pdRfils" USE_SELINUX("c")
  966. extern const char *applet_name;
  967. /* "BusyBox vN.N.N (timestamp or extra_vestion)" */
  968. extern const char bb_banner[];
  969. extern const char bb_msg_memory_exhausted[];
  970. extern const char bb_msg_invalid_date[];
  971. extern const char bb_msg_read_error[];
  972. extern const char bb_msg_write_error[];
  973. extern const char bb_msg_unknown[];
  974. extern const char bb_msg_can_not_create_raw_socket[];
  975. extern const char bb_msg_perm_denied_are_you_root[];
  976. extern const char bb_msg_requires_arg[];
  977. extern const char bb_msg_invalid_arg[];
  978. extern const char bb_msg_standard_input[];
  979. extern const char bb_msg_standard_output[];
  980. extern const char bb_str_default[];
  981. /* NB: (bb_hexdigits_upcase[i] | 0x20) -> lowercase hex digit */
  982. extern const char bb_hexdigits_upcase[];
  983. extern const char bb_path_mtab_file[];
  984. extern const char bb_path_passwd_file[];
  985. extern const char bb_path_shadow_file[];
  986. extern const char bb_path_gshadow_file[];
  987. extern const char bb_path_group_file[];
  988. extern const char bb_path_motd_file[];
  989. extern const char bb_path_wtmp_file[];
  990. extern const char bb_dev_null[];
  991. extern const char bb_busybox_exec_path[];
  992. /* util-linux manpage says /sbin:/bin:/usr/sbin:/usr/bin,
  993. * but I want to save a few bytes here */
  994. extern const char bb_PATH_root_path[]; /* "PATH=/sbin:/usr/sbin:/bin:/usr/bin" */
  995. #define bb_default_root_path (bb_PATH_root_path + sizeof("PATH"))
  996. #define bb_default_path (bb_PATH_root_path + sizeof("PATH=/sbin:/usr/sbin"))
  997. extern const int const_int_0;
  998. extern const int const_int_1;
  999. #ifndef BUFSIZ
  1000. #define BUFSIZ 4096
  1001. #endif
  1002. /* Providing hard guarantee on minimum size (think of BUFSIZ == 128) */
  1003. enum { COMMON_BUFSIZE = (BUFSIZ >= 256*sizeof(void*) ? BUFSIZ+1 : 256*sizeof(void*)) };
  1004. extern char bb_common_bufsiz1[COMMON_BUFSIZE];
  1005. /* This struct is deliberately not defined. */
  1006. /* See docs/keep_data_small.txt */
  1007. struct globals;
  1008. /* '*const' ptr makes gcc optimize code much better.
  1009. * Magic prevents ptr_to_globals from going into rodata.
  1010. * If you want to assign a value, use PTR_TO_GLOBALS = xxx */
  1011. extern struct globals *const ptr_to_globals;
  1012. #define PTR_TO_GLOBALS (*(struct globals**)&ptr_to_globals)
  1013. /* You can change LIBBB_DEFAULT_LOGIN_SHELL, but don't use it,
  1014. * use bb_default_login_shell and following defines.
  1015. * If you change LIBBB_DEFAULT_LOGIN_SHELL,
  1016. * don't forget to change increment constant. */
  1017. #define LIBBB_DEFAULT_LOGIN_SHELL "-/bin/sh"
  1018. extern const char bb_default_login_shell[];
  1019. /* "/bin/sh" */
  1020. #define DEFAULT_SHELL (bb_default_login_shell+1)
  1021. /* "sh" */
  1022. #define DEFAULT_SHELL_SHORT_NAME (bb_default_login_shell+6)
  1023. #if ENABLE_FEATURE_DEVFS
  1024. # define CURRENT_VC "/dev/vc/0"
  1025. # define VC_1 "/dev/vc/1"
  1026. # define VC_2 "/dev/vc/2"
  1027. # define VC_3 "/dev/vc/3"
  1028. # define VC_4 "/dev/vc/4"
  1029. # define VC_5 "/dev/vc/5"
  1030. #if defined(__sh__) || defined(__H8300H__) || defined(__H8300S__)
  1031. /* Yes, this sucks, but both SH (including sh64) and H8 have a SCI(F) for their
  1032. respective serial ports .. as such, we can't use the common device paths for
  1033. these. -- PFM */
  1034. # define SC_0 "/dev/ttsc/0"
  1035. # define SC_1 "/dev/ttsc/1"
  1036. # define SC_FORMAT "/dev/ttsc/%d"
  1037. #else
  1038. # define SC_0 "/dev/tts/0"
  1039. # define SC_1 "/dev/tts/1"
  1040. # define SC_FORMAT "/dev/tts/%d"
  1041. #endif
  1042. # define VC_FORMAT "/dev/vc/%d"
  1043. # define LOOP_FORMAT "/dev/loop/%d"
  1044. # define LOOP_NAMESIZE (sizeof("/dev/loop/") + sizeof(int)*3 + 1)
  1045. # define LOOP_NAME "/dev/loop/"
  1046. # define FB_0 "/dev/fb/0"
  1047. #else
  1048. # define CURRENT_VC "/dev/tty0"
  1049. # define VC_1 "/dev/tty1"
  1050. # define VC_2 "/dev/tty2"
  1051. # define VC_3 "/dev/tty3"
  1052. # define VC_4 "/dev/tty4"
  1053. # define VC_5 "/dev/tty5"
  1054. #if defined(__sh__) || defined(__H8300H__) || defined(__H8300S__)
  1055. # define SC_0 "/dev/ttySC0"
  1056. # define SC_1 "/dev/ttySC1"
  1057. # define SC_FORMAT "/dev/ttySC%d"
  1058. #else
  1059. # define SC_0 "/dev/ttyS0"
  1060. # define SC_1 "/dev/ttyS1"
  1061. # define SC_FORMAT "/dev/ttyS%d"
  1062. #endif
  1063. # define VC_FORMAT "/dev/tty%d"
  1064. # define LOOP_FORMAT "/dev/loop%d"
  1065. # define LOOP_NAMESIZE (sizeof("/dev/loop") + sizeof(int)*3 + 1)
  1066. # define LOOP_NAME "/dev/loop"
  1067. # define FB_0 "/dev/fb0"
  1068. #endif
  1069. /* The following devices are the same on devfs and non-devfs systems. */
  1070. #define CURRENT_TTY "/dev/tty"
  1071. #define DEV_CONSOLE "/dev/console"
  1072. #ifndef RB_POWER_OFF
  1073. /* Stop system and switch power off if possible. */
  1074. #define RB_POWER_OFF 0x4321fedc
  1075. #endif
  1076. /* Make sure we call functions instead of macros. */
  1077. #undef isalnum
  1078. #undef isalpha
  1079. #undef isascii
  1080. #undef isblank
  1081. #undef iscntrl
  1082. #undef isgraph
  1083. #undef islower
  1084. #undef isprint
  1085. #undef ispunct
  1086. #undef isspace
  1087. #undef isupper
  1088. #undef isxdigit
  1089. /* This one is more efficient - we save ~400 bytes */
  1090. #undef isdigit
  1091. #define isdigit(a) ((unsigned)((a) - '0') <= 9)
  1092. #ifdef DMALLOC
  1093. #include <dmalloc.h>
  1094. #endif
  1095. #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  1096. #endif /* __LIBBUSYBOX_H__ */