1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) tons of folks. Tracking down who wrote what
6 * isn't something I'm going to worry about... If you wrote something
7 * here, please feel free to acknowledge your work.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * Based in part on code from sash, Copyright (c) 1999 by David I. Bell
24 * Permission has been granted to redistribute this code under the GPL.
40 #include <sys/ioctl.h>
41 #include <sys/utsname.h> /* for uname(2) */
44 #if defined (BB_CHMOD_CHOWN_CHGRP) \
45 || defined (BB_CP_MV) \
46 || defined (BB_FIND) \
47 || defined (BB_INSMOD) \
51 /* same conditions as recursive_action */
52 #define bb_need_name_too_long
54 #define bb_need_memory_exhausted
55 #define bb_need_full_version
56 #define BB_DECLARE_EXTERN
59 #include "pwd_grp/pwd.h"
60 #include "pwd_grp/grp.h"
62 /* for the _syscall() macros */
63 #include <sys/syscall.h>
64 #include <linux/unistd.h>
66 /* Busybox mount uses either /proc/mounts or /dev/mtab to
67 * get the list of currently mounted filesystems */
68 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
70 const char mtab_file[] = "/etc/mtab";
72 # if defined BB_FEATURE_USE_DEVPS_PATCH
73 const char mtab_file[] = "/dev/mtab";
75 const char mtab_file[] = "/proc/mounts";
80 #if defined(BB_KLOGD) || defined(BB_LOGGER)
84 static struct BB_applet *applet_using;
86 extern void show_usage(void)
88 const char *format_string;
89 const char *usage_string = usage_messages;
92 for (i = applet_using - applets; i > 0; ) {
93 if (!*usage_string++) {
97 format_string = "%s\n\nUsage: %s %s\n\n";
98 if(*usage_string == 0)
99 format_string = "%s\n\nNo help available.\n\n";
100 fprintf(stderr, format_string,
101 full_version, applet_using->name, usage_string);
106 static void verror_msg(const char *s, va_list p)
109 fprintf(stderr, "%s: ", applet_name);
110 vfprintf(stderr, s, p);
113 extern void error_msg(const char *s, ...)
123 extern void error_msg_and_die(const char *s, ...)
134 static void vperror_msg(const char *s, va_list p)
140 fprintf(stderr, "%s%s\n", s, strerror(err));
143 extern void perror_msg(const char *s, ...)
152 extern void perror_msg_and_die(const char *s, ...)
162 #if defined BB_INIT || defined BB_MKSWAP || defined BB_MOUNT || defined BB_NFSMOUNT || defined BB_FEATURE_IFCONFIG_STATUS
163 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
164 * so, for example, to check if the kernel is greater than 2.2.11:
165 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
167 extern int get_kernel_revision(void)
173 if (uname(&name) == -1) {
174 perror_msg("cannot get system information");
180 for (i=0 ; i<3 ; i++) {
181 r = r * 256 + atoi(strtok(s, "."));
190 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
191 _syscall1(int, sysinfo, struct sysinfo *, info);
194 #if defined BB_MOUNT || defined BB_UMOUNT
196 /* Include our own version of <sys/mount.h>, since libc5 doesn't
197 * know about umount2 */
198 extern _syscall1(int, umount, const char *, special_file);
199 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
200 const char *, fstype, unsigned long int, rwflag, const void *, data);
202 # warning This kernel does not support the umount2 syscall
203 # warning The umount2 system call is being stubbed out...
204 int umount2(const char * special_file, int flags)
206 /* BusyBox was compiled against a kernel that did not support
207 * the umount2 system call. To make this application work,
208 * you will need to recompile with a kernel supporting the
209 * umount2 system call.
211 fprintf(stderr, "\n\nTo make this application work, you will need to recompile\n");
212 fprintf(stderr, "with a kernel supporting the umount2 system call. -Erik\n\n");
217 extern _syscall2(int, umount2, const char *, special_file, int, flags);
223 #if defined BB_FEATURE_NEW_MODULE_INTERFACE && ( defined BB_INSMOD || defined BB_LSMOD )
224 #ifndef __NR_query_module
225 static const int __NR_query_module = 167;
227 _syscall5(int, query_module, const char *, name, int, which,
228 void *, buf, size_t, bufsize, size_t*, ret);
232 #if defined (BB_CP_MV) || defined (BB_DU)
234 #define HASH_SIZE 311 /* Should be prime */
235 #define hash_inode(i) ((i) % HASH_SIZE)
237 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
240 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
241 * `ino_dev_hashtable', else return 0
243 * If NAME is a non-NULL pointer to a character pointer, and there is
244 * a match, then set *NAME to the value of the name slot in that
247 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
249 ino_dev_hashtable_bucket_t *bucket;
251 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
252 while (bucket != NULL) {
253 if ((bucket->ino == statbuf->st_ino) &&
254 (bucket->dev == statbuf->st_dev))
256 if (name) *name = bucket->name;
259 bucket = bucket->next;
264 /* Add statbuf to statbuf hash table */
265 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
269 ino_dev_hashtable_bucket_t *bucket;
271 i = hash_inode(statbuf->st_ino);
272 s = name ? strlen(name) : 0;
273 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
274 bucket->ino = statbuf->st_ino;
275 bucket->dev = statbuf->st_dev;
277 strcpy(bucket->name, name);
279 bucket->name[0] = '\0';
280 bucket->next = ino_dev_hashtable[i];
281 ino_dev_hashtable[i] = bucket;
284 /* Clear statbuf hash table */
285 void reset_ino_dev_hashtable(void)
288 ino_dev_hashtable_bucket_t *bucket;
290 for (i = 0; i < HASH_SIZE; i++) {
291 while (ino_dev_hashtable[i] != NULL) {
292 bucket = ino_dev_hashtable[i]->next;
293 free(ino_dev_hashtable[i]);
294 ino_dev_hashtable[i] = bucket;
299 #endif /* BB_CP_MV || BB_DU */
301 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_DPKG_DEB)
303 * Return TRUE if a fileName is a directory.
304 * Nonexistant files return FALSE.
306 int is_directory(const char *fileName, const int followLinks, struct stat *statBuf)
311 if (statBuf == NULL) {
312 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
316 if (followLinks == TRUE)
317 status = stat(fileName, statBuf);
319 status = lstat(fileName, statBuf);
321 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
334 #if defined BB_AR || defined BB_CP_MV
336 * Copy chunksize bytes between two file descriptors
338 int copy_file_chunk(int srcfd, int dstfd, size_t chunksize)
341 char buffer[BUFSIZ]; /* BUFSIZ is declared in stdio.h */
343 while (chunksize > 0) {
344 if (chunksize > BUFSIZ)
348 if (full_write(dstfd, buffer, full_read(srcfd, buffer, size)) < size)
357 #if defined (BB_CP_MV) || defined BB_DPKG
359 * Copy one file to another, while possibly preserving its modes, times, and
360 * modes. Returns TRUE if successful, or FALSE on a failure with an error
361 * message output. (Failure is not indicated if attributes cannot be set.)
365 copy_file(const char *srcName, const char *destName,
366 int setModes, int followLinks, int forceFlag)
371 struct stat srcStatBuf;
372 struct stat dstStatBuf;
373 struct utimbuf times;
375 if (followLinks == TRUE)
376 status = stat(srcName, &srcStatBuf);
378 status = lstat(srcName, &srcStatBuf);
381 perror_msg("%s", srcName);
385 if (followLinks == TRUE)
386 status = stat(destName, &dstStatBuf);
388 status = lstat(destName, &dstStatBuf);
390 if (status < 0 || forceFlag==TRUE) {
392 dstStatBuf.st_ino = -1;
393 dstStatBuf.st_dev = -1;
396 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
397 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
398 error_msg("Copying file \"%s\" to itself", srcName);
402 if (S_ISDIR(srcStatBuf.st_mode)) {
403 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
404 /* Make sure the directory is writable */
405 status = mkdir(destName, 0777777 ^ umask(0));
406 if (status < 0 && errno != EEXIST) {
407 perror_msg("%s", destName);
410 } else if (S_ISLNK(srcStatBuf.st_mode)) {
411 char link_val[BUFSIZ + 1];
414 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
415 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
416 link_size = readlink(srcName, &link_val[0], BUFSIZ);
418 perror_msg("%s", srcName);
421 link_val[link_size] = '\0';
422 status = symlink(link_val, destName);
424 perror_msg("%s", destName);
427 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
428 if (setModes == TRUE) {
429 /* Try to set owner, but fail silently like GNU cp */
430 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
434 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
435 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
436 if (mkfifo(destName, 0644) < 0) {
437 perror_msg("%s", destName);
440 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
441 || S_ISSOCK(srcStatBuf.st_mode)) {
442 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
443 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
444 perror_msg("%s", destName);
447 } else if (S_ISREG(srcStatBuf.st_mode)) {
448 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
449 rfd = open(srcName, O_RDONLY);
451 perror_msg("%s", srcName);
455 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
458 perror_msg("%s", destName);
463 if (copy_file_chunk(rfd, wfd, srcStatBuf.st_size)==FALSE)
467 if (close(wfd) < 0) {
472 if (setModes == TRUE) {
473 /* This is fine, since symlinks never get here */
474 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0)
475 perror_msg_and_die("%s", destName);
476 if (chmod(destName, srcStatBuf.st_mode) < 0)
477 perror_msg_and_die("%s", destName);
478 times.actime = srcStatBuf.st_atime;
479 times.modtime = srcStatBuf.st_mtime;
480 if (utime(destName, ×) < 0)
481 perror_msg_and_die("%s", destName);
487 perror_msg("%s", destName);
493 #endif /* BB_CP_MV */
497 #if defined BB_TAR || defined BB_LS ||defined BB_AR
499 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
500 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
502 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
503 static const mode_t SBIT[] = {
509 /* The 9 mode bits to test */
510 static const mode_t MBIT[] = {
511 S_IRUSR, S_IWUSR, S_IXUSR,
512 S_IRGRP, S_IWGRP, S_IXGRP,
513 S_IROTH, S_IWOTH, S_IXOTH
516 static const char MODE1[] = "rwxrwxrwx";
517 static const char MODE0[] = "---------";
518 static const char SMODE1[] = "..s..s..t";
519 static const char SMODE0[] = "..S..S..T";
522 * Return the standard ls-like mode string from a file mode.
523 * This is static and so is overwritten on each call.
525 const char *mode_string(int mode)
531 buf[0] = TYPECHAR(mode);
532 for (i = 0; i < 9; i++) {
534 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
536 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
540 #endif /* BB_TAR || BB_LS */
543 #if defined BB_TAR || defined BB_AR
545 * Return the standard ls-like time string from a time_t
546 * This is static and so is overwritten on each call.
548 const char *time_string(time_t timeVal)
556 str = ctime(&timeVal);
558 strcpy(buf, &str[4]);
561 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
562 strcpy(&buf[7], &str[20]);
568 #endif /* BB_TAR || BB_AR */
570 #if defined BB_DD || defined BB_NC || defined BB_TAIL || defined BB_TAR || defined BB_AR || defined BB_CP_MV
572 * Write all of the supplied buffer out to a file.
573 * This does multiple writes as necessary.
574 * Returns the amount written, or -1 on an error.
576 int full_write(int fd, const char *buf, int len)
584 cc = write(fd, buf, len);
598 #if defined BB_AR || defined BB_CP_MV || defined BB_SH || defined BB_TAR
600 * Read all of the supplied buffer from a file.
601 * This does multiple reads as necessary.
602 * Returns the amount read, or -1 on an error.
603 * A short read is returned on an end of file.
605 int full_read(int fd, char *buf, int len)
613 cc = read(fd, buf, len);
628 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
631 #if defined (BB_CHMOD_CHOWN_CHGRP) \
632 || defined (BB_CP_MV) \
633 || defined (BB_FIND) \
634 || defined (BB_INSMOD) \
640 * Walk down all the directories under the specified
641 * location, and do something (something specified
642 * by the fileAction and dirAction function pointers).
644 * Unfortunately, while nftw(3) could replace this and reduce
645 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
646 * and so isn't sufficiently portable to take over since glibc2.1
647 * is so stinking huge.
649 int recursive_action(const char *fileName,
650 int recurse, int followLinks, int depthFirst,
651 int (*fileAction) (const char *fileName,
652 struct stat * statbuf,
654 int (*dirAction) (const char *fileName,
655 struct stat * statbuf,
663 if (followLinks == TRUE)
664 status = stat(fileName, &statbuf);
666 status = lstat(fileName, &statbuf);
669 #ifdef BB_DEBUG_PRINT_SCAFFOLD
671 "status=%d followLinks=%d TRUE=%d\n",
672 status, followLinks, TRUE);
674 perror_msg("%s", fileName);
678 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
679 if (fileAction == NULL)
682 return fileAction(fileName, &statbuf, userData);
685 if (recurse == FALSE) {
686 if (S_ISDIR(statbuf.st_mode)) {
687 if (dirAction != NULL)
688 return (dirAction(fileName, &statbuf, userData));
694 if (S_ISDIR(statbuf.st_mode)) {
697 if (dirAction != NULL && depthFirst == FALSE) {
698 status = dirAction(fileName, &statbuf, userData);
699 if (status == FALSE) {
700 perror_msg("%s", fileName);
702 } else if (status == SKIP)
705 dir = opendir(fileName);
707 perror_msg("%s", fileName);
711 while ((next = readdir(dir)) != NULL) {
712 char nextFile[PATH_MAX];
714 if ((strcmp(next->d_name, "..") == 0)
715 || (strcmp(next->d_name, ".") == 0)) {
718 if (strlen(fileName) + strlen(next->d_name) + 1 > PATH_MAX) {
719 error_msg(name_too_long);
722 memset(nextFile, 0, sizeof(nextFile));
723 if (fileName[strlen(fileName)-1] == '/')
724 sprintf(nextFile, "%s%s", fileName, next->d_name);
726 sprintf(nextFile, "%s/%s", fileName, next->d_name);
727 if (recursive_action(nextFile, TRUE, followLinks, depthFirst,
728 fileAction, dirAction, userData) == FALSE) {
733 if (dirAction != NULL && depthFirst == TRUE) {
734 if (dirAction(fileName, &statbuf, userData) == FALSE) {
735 perror_msg("%s", fileName);
742 if (fileAction == NULL)
745 return fileAction(fileName, &statbuf, userData);
750 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
754 #if defined (BB_TAR) || defined (BB_MKDIR)
756 * Attempt to create the directories along the specified path, except for
757 * the final component. The mode is given for the final directory only,
758 * while all previous ones get default protections. Errors are not reported
759 * here, as failures to restore files can be reported later.
761 extern int create_path(const char *name, int mode)
765 char buf[BUFSIZ + 1];
769 for (cp = buf; *cp == '/'; cp++);
770 cp = strchr(cp, '/');
773 cp = strchr(cp + 1, '/');
775 retVal = mkdir(buf, cp ? 0777 : mode);
776 if (retVal != 0 && errno != EEXIST) {
777 perror_msg("%s", buf);
784 #endif /* BB_TAR || BB_MKDIR */
788 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
789 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
790 /* [ugoa]{+|-|=}[rwxst] */
792 extern int parse_mode(const char *s, mode_t * theMode)
794 static const mode_t group_set[] = {
795 S_ISUID | S_IRWXU, /* u */
796 S_ISGID | S_IRWXG, /* g */
798 S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO /* a */
801 static const mode_t mode_set[] = {
802 S_IRUSR | S_IRGRP | S_IROTH, /* r */
803 S_IWUSR | S_IWGRP | S_IWOTH, /* w */
804 S_IXUSR | S_IXGRP | S_IXOTH, /* x */
805 S_ISUID | S_ISGID, /* s */
809 static const char group_string[] = "ugoa";
810 static const char mode_string[] = "rwxst";
815 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
830 if ((c = *s++) == '\0') {
833 for (p=group_string ; *p ; p++) {
835 groups |= group_set[(int)(p-group_string)];
844 if (groups == 0) { /* The default is "all" */
845 groups |= S_ISUID | S_ISGID | S_ISVTX
846 | S_IRWXU | S_IRWXG | S_IRWXO;
850 if ((c < '0') || (c > '7') || (mode | groups)) {
853 *theMode = strtol(--s, NULL, 8);
859 if (((c = *s++) != '\0') && (c != ',')) {
860 for (p=mode_string ; *p ; p++) {
862 mode |= mode_set[(int)(p-mode_string)];
866 break; /* We're done so break out of loop.*/
870 andMode &= ~(groups); /* Now fall through. */
872 orMode |= mode & groups;
875 andMode &= ~(mode & groups);
876 orMode &= ~(mode & groups);
888 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
894 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
895 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
896 || defined BB_LOGNAME || defined BB_WHOAMI || defined BB_SH
898 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_ID
899 /* returns a uid given a username */
900 long my_getpwnam(const char *name)
902 struct passwd *myuser;
904 myuser = getpwnam(name);
906 error_msg_and_die("unknown user name: %s", name);
908 return myuser->pw_uid;
911 /* returns a gid given a group name */
912 long my_getgrnam(const char *name)
914 struct group *mygroup;
916 mygroup = getgrnam(name);
918 error_msg_and_die("unknown group name: %s", name);
920 return (mygroup->gr_gid);
924 /* gets a username given a uid */
925 void my_getpwuid(char *name, long uid)
927 struct passwd *myuser;
929 myuser = getpwuid(uid);
931 sprintf(name, "%-8ld ", (long)uid);
933 strcpy(name, myuser->pw_name);
936 /* gets a groupname given a gid */
937 void my_getgrgid(char *group, long gid)
939 struct group *mygroup;
941 mygroup = getgrgid(gid);
943 sprintf(group, "%-8ld ", (long)gid);
945 strcpy(group, mygroup->gr_name);
949 /* gets a gid given a user name */
950 long my_getpwnamegid(const char *name)
952 struct group *mygroup;
953 struct passwd *myuser;
955 myuser=getpwnam(name);
957 error_msg_and_die("unknown user name: %s", name);
959 mygroup = getgrgid(myuser->pw_gid);
961 error_msg_and_die("unknown gid %ld", (long)myuser->pw_gid);
963 return mygroup->gr_gid;
967 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
968 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
971 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
973 /* From <linux/kd.h> */
974 static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
975 static const int KB_84 = 0x01;
976 static const int KB_101 = 0x02; /* this is what we always answer */
978 int is_a_console(int fd)
983 return (ioctl(fd, KDGKBTYPE, &arg) == 0
984 && ((arg == KB_101) || (arg == KB_84)));
987 static int open_a_console(char *fnam)
992 fd = open(fnam, O_RDWR);
994 /* if failed, try read-only */
995 if (fd < 0 && errno == EACCES)
996 fd = open(fnam, O_RDONLY);
998 /* if failed, try write-only */
999 if (fd < 0 && errno == EACCES)
1000 fd = open(fnam, O_WRONLY);
1002 /* if failed, fail */
1006 /* if not a console, fail */
1007 if (!is_a_console(fd)) {
1017 * Get an fd for use with kbd/console ioctls.
1018 * We try several things because opening /dev/console will fail
1019 * if someone else used X (which does a chown on /dev/console).
1021 * if tty_name is non-NULL, try this one instead.
1024 int get_console_fd(char *tty_name)
1029 if (-1 == (fd = open_a_console(tty_name)))
1035 fd = open_a_console("/dev/tty");
1039 fd = open_a_console("/dev/tty0");
1043 fd = open_a_console("/dev/console");
1047 for (fd = 0; fd < 3; fd++)
1048 if (is_a_console(fd))
1051 error_msg("Couldnt get a file descriptor referring to the console");
1052 return -1; /* total failure */
1056 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1059 #if defined BB_FIND || defined BB_INSMOD
1061 * Routine to see if a text string is matched by a wildcard pattern.
1062 * Returns TRUE if the text is matched, or FALSE if it is not matched
1063 * or if the pattern is invalid.
1064 * * matches zero or more characters
1065 * ? matches a single character
1066 * [abc] matches 'a', 'b' or 'c'
1067 * \c quotes character c
1068 * Adapted from code written by Ingo Wilken, and
1069 * then taken from sash, Copyright (c) 1999 by David I. Bell
1070 * Permission is granted to use, distribute, or modify this source,
1071 * provided that this copyright notice remains intact.
1072 * Permission to distribute this code under the GPL has been granted.
1074 extern int check_wildcard_match(const char *text, const char *pattern)
1076 const char *retryPat;
1077 const char *retryText;
1085 while (*text || *pattern) {
1097 while ((ch = *pattern++) != ']') {
1108 if (found == FALSE && len!=0) {
1111 if (found == TRUE) {
1112 if (strlen(pattern)==0 && len==1) {
1121 /* fall into next case */
1124 if (*text++ == '\0')
1135 /* fall into next case */
1153 if (pattern == NULL)
1159 #endif /* BB_FIND || BB_INSMOD */
1164 #if defined BB_DF || defined BB_MTAB
1167 * Given a block device, find the mount table entry if that block device
1170 * Given any other file (or directory), find the mount table entry for its
1173 extern struct mntent *find_mount_point(const char *name, const char *table)
1178 struct mntent *mountEntry;
1180 if (stat(name, &s) != 0)
1183 if ((s.st_mode & S_IFMT) == S_IFBLK)
1184 mountDevice = s.st_rdev;
1186 mountDevice = s.st_dev;
1189 if ((mountTable = setmntent(table, "r")) == 0)
1192 while ((mountEntry = getmntent(mountTable)) != 0) {
1193 if (strcmp(name, mountEntry->mnt_dir) == 0
1194 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1196 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1198 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1201 endmntent(mountTable);
1204 #endif /* BB_DF || BB_MTAB */
1206 #if defined BB_INIT || defined BB_SYSLOGD
1207 /* try to open up the specified device */
1208 extern int device_open(char *device, int mode)
1212 m = mode | O_NONBLOCK;
1214 /* Retry up to 5 times */
1215 for (f = 0; f < 5; f++)
1216 if ((fd = open(device, m, 0600)) >= 0)
1220 /* Reset original flags. */
1222 fcntl(fd, F_SETFL, mode);
1225 #endif /* BB_INIT BB_SYSLOGD */
1228 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1229 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1230 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1233 #if defined BB_FEATURE_USE_DEVPS_PATCH
1234 /* find_pid_by_name()
1236 * This finds the pid of the specified process,
1237 * by using the /dev/ps device driver.
1239 * Returns a list of all matching PIDs
1241 extern pid_t* find_pid_by_name( char* pidName)
1244 char device[] = "/dev/ps";
1246 pid_t* pid_array = NULL;
1247 pid_t* pidList=NULL;
1250 fd = open(device, O_RDONLY);
1252 perror_msg_and_die("open failed for `%s'", device);
1254 /* Find out how many processes there are */
1255 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1256 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1258 /* Allocate some memory -- grab a few extras just in case
1259 * some new processes start up while we wait. The kernel will
1260 * just ignore any extras if we give it too many, and will trunc.
1261 * the list if we give it too few. */
1262 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1263 pid_array[0] = num_pids+10;
1265 /* Now grab the pid list */
1266 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1267 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1269 /* Now search for a match */
1270 for (i=1, j=0; i<pid_array[0] ; i++) {
1272 struct pid_info info;
1274 info.pid = pid_array[i];
1275 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1276 perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1278 /* Make sure we only match on the process name */
1279 p=info.command_line+1;
1280 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1286 if ((strstr(info.command_line, pidName) != NULL)
1287 && (strlen(pidName) == strlen(info.command_line))) {
1288 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1289 pidList[j++]=info.pid;
1299 if (close (fd) != 0)
1300 perror_msg_and_die("close failed for `%s'", device);
1304 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1306 /* find_pid_by_name()
1308 * This finds the pid of the specified process.
1309 * Currently, it's implemented by rummaging through
1310 * the proc filesystem.
1312 * Returns a list of all matching PIDs
1314 extern pid_t* find_pid_by_name( char* pidName)
1317 struct dirent *next;
1318 pid_t* pidList=NULL;
1321 dir = opendir("/proc");
1323 perror_msg_and_die("Cannot open /proc");
1325 while ((next = readdir(dir)) != NULL) {
1330 /* If it isn't a number, we don't want it */
1331 if (!isdigit(*next->d_name))
1334 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1335 status = fopen(filename, "r");
1339 fgets(buffer, 256, status);
1342 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1343 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1344 pidList[i++]=strtol(next->d_name, NULL, 0);
1352 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1353 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1356 /* this should really be farmed out to libbusybox.a */
1357 extern void *xmalloc(size_t size)
1359 void *ptr = malloc(size);
1362 error_msg_and_die(memory_exhausted);
1366 extern void *xrealloc(void *old, size_t size)
1368 void *ptr = realloc(old, size);
1370 error_msg_and_die(memory_exhausted);
1374 extern void *xcalloc(size_t nmemb, size_t size)
1376 void *ptr = calloc(nmemb, size);
1378 error_msg_and_die(memory_exhausted);
1383 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || \
1384 defined BB_WGET || defined BB_DPKG_DEB || defined BB_TAR || \
1387 extern char * xstrdup (const char *s) {
1396 error_msg_and_die(memory_exhausted);
1403 #if defined BB_NFSMOUNT
1404 extern char * xstrndup (const char *s, int n) {
1408 error_msg_and_die("xstrndup bug");
1412 return safe_strncpy(t,s,n);
1416 #if defined BB_IFCONFIG || defined BB_ROUTE || defined BB_NFSMOUNT || \
1417 defined BB_FEATURE_MOUNT_LOOP
1418 /* Like strncpy but make sure the resulting string is always 0 terminated. */
1419 extern char * safe_strncpy(char *dst, const char *src, size_t size)
1422 return strncpy(dst, src, size-1);
1426 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1427 extern int vdprintf(int d, const char *format, va_list ap)
1432 len = vsprintf(buf, format, ap);
1433 return write(d, buf, len);
1435 #endif /* BB_SYSLOGD */
1438 #if defined BB_FEATURE_MOUNT_LOOP
1440 #include "loop.h" /* Pull in loop device support */
1442 extern int del_loop(const char *device)
1446 if ((fd = open(device, O_RDONLY)) < 0) {
1447 perror_msg("%s", device);
1450 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1451 perror_msg("ioctl: LOOP_CLR_FD");
1458 extern int set_loop(const char *device, const char *file, int offset,
1461 struct loop_info loopinfo;
1464 mode = *loopro ? O_RDONLY : O_RDWR;
1465 if ((ffd = open(file, mode)) < 0 && !*loopro
1466 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1467 perror_msg("%s", file);
1470 if ((fd = open(device, mode)) < 0) {
1472 perror_msg("%s", device);
1475 *loopro = (mode == O_RDONLY);
1477 memset(&loopinfo, 0, sizeof(loopinfo));
1478 safe_strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1480 loopinfo.lo_offset = offset;
1482 loopinfo.lo_encrypt_key_size = 0;
1483 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1484 perror_msg("ioctl: LOOP_SET_FD");
1489 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1490 (void) ioctl(fd, LOOP_CLR_FD, 0);
1491 perror_msg("ioctl: LOOP_SET_STATUS");
1501 extern char *find_unused_loop_device(void)
1505 struct stat statbuf;
1506 struct loop_info loopinfo;
1508 for (i = 0; i <= 7; i++) {
1509 sprintf(dev, "/dev/loop%d", i);
1510 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1511 if ((fd = open(dev, O_RDONLY)) >= 0) {
1512 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) != 0) {
1513 if (errno == ENXIO) { /* probably free */
1524 #endif /* BB_FEATURE_MOUNT_LOOP */
1526 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1527 extern int find_real_root_device_name(char* name)
1530 struct dirent *entry;
1531 struct stat statBuf, rootStat;
1532 char fileName[BUFSIZ];
1534 if (stat("/", &rootStat) != 0) {
1535 error_msg("could not stat '/'");
1539 dir = opendir("/dev");
1541 error_msg("could not open '/dev'");
1545 while((entry = readdir(dir)) != NULL) {
1547 /* Must skip ".." since that is "/", and so we
1548 * would get a false positive on ".." */
1549 if (strcmp(entry->d_name, "..") == 0)
1552 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1554 if (stat(fileName, &statBuf) != 0)
1556 /* Some char devices have the same dev_t as block
1557 * devices, so make sure this is a block device */
1558 if (! S_ISBLK(statBuf.st_mode))
1560 if (statBuf.st_rdev == rootStat.st_rdev) {
1561 strcpy(name, fileName);
1571 /* get_line_from_file() - This function reads an entire line from a text file
1572 * up to a newline. It returns a malloc'ed char * which must be stored and
1573 * free'ed by the caller. */
1574 extern char *get_line_from_file(FILE *file)
1576 static const int GROWBY = 80; /* how large we will grow strings by */
1580 char *linebuf = NULL;
1587 /* grow the line buffer as necessary */
1588 while (idx > linebufsz-2)
1589 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1590 linebuf[idx++] = (char)ch;
1591 if ((char)ch == '\n')
1603 extern void print_file(FILE *file)
1607 while ((c = getc(file)) != EOF)
1613 extern int print_file_by_name(char *filename)
1616 if ((file = wfopen(filename, "r")) == NULL)
1623 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1624 char process_escape_sequence(char **ptr)
1626 static const char charmap[] = {
1627 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', 0,
1628 '\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '\\' };
1638 for ( num_digits = 0 ; num_digits < 3 ; ++num_digits) {
1639 if ((*q < '0') || (*q > '7')) { /* not a digit? */
1642 n = n * 8 + (*q++ - '0');
1645 if (num_digits == 0) { /* mnemonic escape sequence? */
1646 for (p=charmap ; *p ; p++) {
1652 n = *(p+(sizeof(charmap)/2));
1655 /* doesn't hurt to fall through to here from mnemonic case */
1656 if (n > UCHAR_MAX) { /* is octal code too big for a char? */
1657 n /= 8; /* adjust value and */
1658 --q; /* back up one char */
1666 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1667 ! defined BB_FEATURE_USE_DEVPS_PATCH || defined BB_WGET
1668 char *get_last_path_component(char *path)
1670 char *s=path+strlen(path)-1;
1672 /* strip trailing slashes */
1673 while (s != path && *s == '/') {
1677 /* find last component */
1678 s = strrchr(path, '/');
1679 if (s == NULL || s[1] == '\0')
1686 #if defined BB_GREP || defined BB_SED
1688 void xregcomp(regex_t *preg, const char *regex, int cflags)
1691 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1692 int errmsgsz = regerror(ret, preg, NULL, 0);
1693 char *errmsg = xmalloc(errmsgsz);
1694 regerror(ret, preg, errmsg, errmsgsz);
1695 error_msg_and_die("xregcomp: %s", errmsg);
1700 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1701 FILE *wfopen(const char *path, const char *mode)
1704 if ((fp = fopen(path, mode)) == NULL) {
1705 perror_msg("%s", path);
1712 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1713 || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1714 || defined BB_WC || defined BB_CMP || defined BB_SORT || defined BB_WGET \
1715 || defined BB_MOUNT || defined BB_ROUTE || defined BB_MKFS_MINIX
1716 FILE *xfopen(const char *path, const char *mode)
1719 if ((fp = fopen(path, mode)) == NULL)
1720 perror_msg_and_die("%s", path);
1725 static int applet_name_compare(const void *x, const void *y)
1727 const char *name = x;
1728 const struct BB_applet *applet = y;
1730 return strcmp(name, applet->name);
1733 extern size_t NUM_APPLETS;
1735 struct BB_applet *find_applet_by_name(const char *name)
1737 return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
1738 applet_name_compare);
1741 void run_applet_by_name(const char *name, int argc, char **argv)
1743 /* Do a binary search to find the applet entry given the name. */
1744 if ((applet_using = find_applet_by_name(name)) != NULL) {
1745 applet_name = applet_using->name;
1746 if (argv[1] && strcmp(argv[1], "--help") == 0)
1748 exit((*(applet_using->main)) (argc, argv));
1752 #if defined BB_DD || defined BB_TAIL || defined BB_STTY
1753 unsigned long parse_number(const char *numstr,
1754 const struct suffix_mult *suffixes)
1756 const struct suffix_mult *sm;
1757 unsigned long int ret;
1761 ret = strtoul(numstr, &end, 10);
1763 error_msg_and_die("invalid number `%s'", numstr);
1764 while (end[0] != '\0') {
1768 len = strlen(sm->suffix);
1769 if (strncmp(sm->suffix, end, len) == 0) {
1780 error_msg_and_die("invalid number `%s'", numstr);
1786 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1787 ssize_t safe_read(int fd, void *buf, size_t count)
1792 n = read(fd, buf, count);
1793 } while (n < 0 && errno == EINTR);
1799 #ifdef BB_FEATURE_HUMAN_READABLE
1800 const char *make_human_readable_str(unsigned long val, unsigned long hr)
1803 static char str[10] = "\0";
1804 static const char strings[] = { 'k', 'M', 'G', 'T', 0 };
1805 unsigned long divisor = 1;
1810 snprintf(str, 9, "%ld", val/hr);
1812 while(val >= divisor && i <= 4) {
1813 divisor=divisor<<10, i++;
1815 divisor=divisor>>10, i--;
1816 snprintf(str, 9, "%.1Lf%c", (long double)(val)/divisor, strings[i]);
1822 #if defined(BB_GREP) || defined(BB_HOSTNAME) || defined(BB_SED) || defined(BB_TAR) || defined(BB_WGET) || defined(BB_XARGS) || defined(BB_SH)
1825 size_t len = strlen(s);
1830 if (s[len-1] == '\n')
1835 #if defined(BB_KLOGD) || defined(BB_LOGGER)
1836 void syslog_msg_with_name(const char *name, int facility, int pri, const char *msg)
1838 openlog(name, 0, facility);
1839 syslog(pri, "%s", msg);
1843 void syslog_msg(int facility, int pri, const char *msg)
1845 syslog_msg_with_name(applet_using->name, facility, pri, msg);
1852 /* trim trailing whitespace */
1853 while (isspace(s[strlen(s)-1]))
1854 s[strlen(s)-1]='\0';
1856 /* trim leading whitespace */
1857 memmove(s, &s[strspn(s, " \n\r\t\v")], strlen(s));
1862 #ifdef BB_FEATURE_RM_INTERACTIVE
1863 #if defined (BB_CP_MV) || defined (BB_RM)
1864 int ask_confirmation()
1872 ret = ((c=='y')||(c=='Y')) ? 1 : 0;
1883 c-file-style: "linux"