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