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 static struct BB_applet *applet_using;
82 extern void show_usage(void)
84 const char *format_string;
85 const char *usage_string = usage_messages;
88 for (i = applet_using - applets; i > 0; ) {
89 if (!*usage_string++) {
93 format_string = "%s\n\nUsage: %s %s\n\n";
94 if(*usage_string == 0)
95 format_string = "%s\n\nNo help available.\n\n";
96 fprintf(stderr, format_string,
97 full_version, applet_using->name, usage_string);
102 static void verror_msg(const char *s, va_list p)
105 fprintf(stderr, "%s: ", applet_name);
106 vfprintf(stderr, s, p);
109 extern void error_msg(const char *s, ...)
119 extern void error_msg_and_die(const char *s, ...)
130 static void vperror_msg(const char *s, va_list p)
136 fprintf(stderr, "%s%s\n", s, strerror(err));
139 extern void perror_msg(const char *s, ...)
148 extern void perror_msg_and_die(const char *s, ...)
158 #if defined BB_INIT || defined BB_MKSWAP || defined BB_MOUNT || defined BB_NFSMOUNT
159 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
160 * so, for example, to check if the kernel is greater than 2.2.11:
161 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
163 extern int get_kernel_revision(void)
169 if (uname(&name) == -1) {
170 perror_msg("cannot get system information");
176 for (i=0 ; i<3 ; i++) {
177 r = r * 256 + atoi(strtok(s, "."));
186 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
187 _syscall1(int, sysinfo, struct sysinfo *, info);
190 #if defined BB_MOUNT || defined BB_UMOUNT
192 /* Include our own version of <sys/mount.h>, since libc5 doesn't
193 * know about umount2 */
194 extern _syscall1(int, umount, const char *, special_file);
195 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
196 const char *, fstype, unsigned long int, rwflag, const void *, data);
198 # warning This kernel does not support the umount2 syscall
199 # warning The umount2 system call is being stubbed out...
200 int umount2(const char * special_file, int flags)
202 /* BusyBox was compiled against a kernel that did not support
203 * the umount2 system call. To make this application work,
204 * you will need to recompile with a kernel supporting the
205 * umount2 system call.
207 fprintf(stderr, "\n\nTo make this application work, you will need to recompile\n");
208 fprintf(stderr, "with a kernel supporting the umount2 system call. -Erik\n\n");
213 extern _syscall2(int, umount2, const char *, special_file, int, flags);
219 #if defined BB_FEATURE_NEW_MODULE_INTERFACE && ( defined BB_INSMOD || defined BB_LSMOD )
220 #ifndef __NR_query_module
221 static const int __NR_query_module = 167;
223 _syscall5(int, query_module, const char *, name, int, which,
224 void *, buf, size_t, bufsize, size_t*, ret);
228 #if defined (BB_CP_MV) || defined (BB_DU)
230 #define HASH_SIZE 311 /* Should be prime */
231 #define hash_inode(i) ((i) % HASH_SIZE)
233 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
236 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
237 * `ino_dev_hashtable', else return 0
239 * If NAME is a non-NULL pointer to a character pointer, and there is
240 * a match, then set *NAME to the value of the name slot in that
243 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
245 ino_dev_hashtable_bucket_t *bucket;
247 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
248 while (bucket != NULL) {
249 if ((bucket->ino == statbuf->st_ino) &&
250 (bucket->dev == statbuf->st_dev))
252 if (name) *name = bucket->name;
255 bucket = bucket->next;
260 /* Add statbuf to statbuf hash table */
261 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
265 ino_dev_hashtable_bucket_t *bucket;
267 i = hash_inode(statbuf->st_ino);
268 s = name ? strlen(name) : 0;
269 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
270 bucket->ino = statbuf->st_ino;
271 bucket->dev = statbuf->st_dev;
273 strcpy(bucket->name, name);
275 bucket->name[0] = '\0';
276 bucket->next = ino_dev_hashtable[i];
277 ino_dev_hashtable[i] = bucket;
280 /* Clear statbuf hash table */
281 void reset_ino_dev_hashtable(void)
284 ino_dev_hashtable_bucket_t *bucket;
286 for (i = 0; i < HASH_SIZE; i++) {
287 while (ino_dev_hashtable[i] != NULL) {
288 bucket = ino_dev_hashtable[i]->next;
289 free(ino_dev_hashtable[i]);
290 ino_dev_hashtable[i] = bucket;
295 #endif /* BB_CP_MV || BB_DU */
297 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_DPKG_DEB)
299 * Return TRUE if a fileName is a directory.
300 * Nonexistant files return FALSE.
302 int is_directory(const char *fileName, const int followLinks, struct stat *statBuf)
307 if (statBuf == NULL) {
308 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
312 if (followLinks == TRUE)
313 status = stat(fileName, statBuf);
315 status = lstat(fileName, statBuf);
317 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
330 #if defined BB_AR || defined BB_CP_MV
332 * Copy chunksize bytes between two file descriptors
334 int copy_file_chunk(int srcfd, int dstfd, size_t chunksize)
337 char buffer[BUFSIZ]; /* BUFSIZ is declared in stdio.h */
339 while (chunksize > 0) {
340 if (chunksize > BUFSIZ)
344 if (full_write(dstfd, buffer, full_read(srcfd, buffer, size)) < size)
353 #if defined (BB_CP_MV) || defined BB_DPKG
355 * Copy one file to another, while possibly preserving its modes, times, and
356 * modes. Returns TRUE if successful, or FALSE on a failure with an error
357 * message output. (Failure is not indicated if attributes cannot be set.)
361 copy_file(const char *srcName, const char *destName,
362 int setModes, int followLinks, int forceFlag)
367 struct stat srcStatBuf;
368 struct stat dstStatBuf;
369 struct utimbuf times;
371 if (followLinks == TRUE)
372 status = stat(srcName, &srcStatBuf);
374 status = lstat(srcName, &srcStatBuf);
377 perror_msg("%s", srcName);
381 if (followLinks == TRUE)
382 status = stat(destName, &dstStatBuf);
384 status = lstat(destName, &dstStatBuf);
386 if (status < 0 || forceFlag==TRUE) {
388 dstStatBuf.st_ino = -1;
389 dstStatBuf.st_dev = -1;
392 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
393 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
394 error_msg("Copying file \"%s\" to itself", srcName);
398 if (S_ISDIR(srcStatBuf.st_mode)) {
399 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
400 /* Make sure the directory is writable */
401 status = mkdir(destName, 0777777 ^ umask(0));
402 if (status < 0 && errno != EEXIST) {
403 perror_msg("%s", destName);
406 } else if (S_ISLNK(srcStatBuf.st_mode)) {
407 char link_val[BUFSIZ + 1];
410 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
411 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
412 link_size = readlink(srcName, &link_val[0], BUFSIZ);
414 perror_msg("%s", srcName);
417 link_val[link_size] = '\0';
418 status = symlink(link_val, destName);
420 perror_msg("%s", destName);
423 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
424 if (setModes == TRUE) {
425 /* Try to set owner, but fail silently like GNU cp */
426 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
430 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
431 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
432 if (mkfifo(destName, 0644) < 0) {
433 perror_msg("%s", destName);
436 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
437 || S_ISSOCK(srcStatBuf.st_mode)) {
438 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
439 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
440 perror_msg("%s", destName);
443 } else if (S_ISREG(srcStatBuf.st_mode)) {
444 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
445 rfd = open(srcName, O_RDONLY);
447 perror_msg("%s", srcName);
451 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
454 perror_msg("%s", destName);
459 if (copy_file_chunk(rfd, wfd, srcStatBuf.st_size)==FALSE)
463 if (close(wfd) < 0) {
468 if (setModes == TRUE) {
469 /* This is fine, since symlinks never get here */
470 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0)
471 perror_msg_and_die("%s", destName);
472 if (chmod(destName, srcStatBuf.st_mode) < 0)
473 perror_msg_and_die("%s", destName);
474 times.actime = srcStatBuf.st_atime;
475 times.modtime = srcStatBuf.st_mtime;
476 if (utime(destName, ×) < 0)
477 perror_msg_and_die("%s", destName);
483 perror_msg("%s", destName);
489 #endif /* BB_CP_MV */
493 #if defined BB_TAR || defined BB_LS ||defined BB_AR
495 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
496 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
498 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
499 static const mode_t SBIT[] = {
505 /* The 9 mode bits to test */
506 static const mode_t MBIT[] = {
507 S_IRUSR, S_IWUSR, S_IXUSR,
508 S_IRGRP, S_IWGRP, S_IXGRP,
509 S_IROTH, S_IWOTH, S_IXOTH
512 static const char MODE1[] = "rwxrwxrwx";
513 static const char MODE0[] = "---------";
514 static const char SMODE1[] = "..s..s..t";
515 static const char SMODE0[] = "..S..S..T";
518 * Return the standard ls-like mode string from a file mode.
519 * This is static and so is overwritten on each call.
521 const char *mode_string(int mode)
527 buf[0] = TYPECHAR(mode);
528 for (i = 0; i < 9; i++) {
530 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
532 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
536 #endif /* BB_TAR || BB_LS */
539 #if defined BB_TAR || defined BB_AR
541 * Return the standard ls-like time string from a time_t
542 * This is static and so is overwritten on each call.
544 const char *time_string(time_t timeVal)
552 str = ctime(&timeVal);
554 strcpy(buf, &str[4]);
557 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
558 strcpy(&buf[7], &str[20]);
564 #endif /* BB_TAR || BB_AR */
566 #if defined BB_DD || defined BB_NC || defined BB_TAIL || defined BB_TAR || defined BB_AR || defined BB_CP_MV
568 * Write all of the supplied buffer out to a file.
569 * This does multiple writes as necessary.
570 * Returns the amount written, or -1 on an error.
572 int full_write(int fd, const char *buf, int len)
580 cc = write(fd, buf, len);
594 #if defined BB_AR || defined BB_CP_MV || defined BB_SH || defined BB_TAR
596 * Read all of the supplied buffer from a file.
597 * This does multiple reads as necessary.
598 * Returns the amount read, or -1 on an error.
599 * A short read is returned on an end of file.
601 int full_read(int fd, char *buf, int len)
609 cc = read(fd, buf, len);
624 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
627 #if defined (BB_CHMOD_CHOWN_CHGRP) \
628 || defined (BB_CP_MV) \
629 || defined (BB_FIND) \
630 || defined (BB_INSMOD) \
636 * Walk down all the directories under the specified
637 * location, and do something (something specified
638 * by the fileAction and dirAction function pointers).
640 * Unfortunately, while nftw(3) could replace this and reduce
641 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
642 * and so isn't sufficiently portable to take over since glibc2.1
643 * is so stinking huge.
645 int recursive_action(const char *fileName,
646 int recurse, int followLinks, int depthFirst,
647 int (*fileAction) (const char *fileName,
648 struct stat * statbuf,
650 int (*dirAction) (const char *fileName,
651 struct stat * statbuf,
659 if (followLinks == TRUE)
660 status = stat(fileName, &statbuf);
662 status = lstat(fileName, &statbuf);
665 #ifdef BB_DEBUG_PRINT_SCAFFOLD
667 "status=%d followLinks=%d TRUE=%d\n",
668 status, followLinks, TRUE);
670 perror_msg("%s", fileName);
674 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
675 if (fileAction == NULL)
678 return fileAction(fileName, &statbuf, userData);
681 if (recurse == FALSE) {
682 if (S_ISDIR(statbuf.st_mode)) {
683 if (dirAction != NULL)
684 return (dirAction(fileName, &statbuf, userData));
690 if (S_ISDIR(statbuf.st_mode)) {
693 if (dirAction != NULL && depthFirst == FALSE) {
694 status = dirAction(fileName, &statbuf, userData);
695 if (status == FALSE) {
696 perror_msg("%s", fileName);
698 } else if (status == SKIP)
701 dir = opendir(fileName);
703 perror_msg("%s", fileName);
706 while ((next = readdir(dir)) != NULL) {
707 char nextFile[BUFSIZ + 1];
709 if ((strcmp(next->d_name, "..") == 0)
710 || (strcmp(next->d_name, ".") == 0)) {
713 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
714 error_msg(name_too_long);
717 memset(nextFile, 0, sizeof(nextFile));
718 sprintf(nextFile, "%s/%s", fileName, next->d_name);
720 recursive_action(nextFile, TRUE, followLinks, depthFirst,
721 fileAction, dirAction, userData);
722 if (status == FALSE) {
727 status = closedir(dir);
729 perror_msg("%s", fileName);
732 if (dirAction != NULL && depthFirst == TRUE) {
733 status = dirAction(fileName, &statbuf, userData);
734 if (status == FALSE) {
735 perror_msg("%s", fileName);
740 if (fileAction == NULL)
743 return fileAction(fileName, &statbuf, userData);
748 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
752 #if defined (BB_TAR) || defined (BB_MKDIR)
754 * Attempt to create the directories along the specified path, except for
755 * the final component. The mode is given for the final directory only,
756 * while all previous ones get default protections. Errors are not reported
757 * here, as failures to restore files can be reported later.
759 extern int create_path(const char *name, int mode)
763 char buf[BUFSIZ + 1];
767 for (cp = buf; *cp == '/'; cp++);
768 cp = strchr(cp, '/');
771 cp = strchr(cp + 1, '/');
773 retVal = mkdir(buf, cp ? 0777 : mode);
774 if (retVal != 0 && errno != EEXIST) {
775 perror_msg("%s", buf);
782 #endif /* BB_TAR || BB_MKDIR */
786 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
787 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
788 /* [ugoa]{+|-|=}[rwxst] */
790 extern int parse_mode(const char *s, mode_t * theMode)
792 static const mode_t group_set[] = {
793 S_ISUID | S_IRWXU, /* u */
794 S_ISGID | S_IRWXG, /* g */
796 S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO /* a */
799 static const mode_t mode_set[] = {
800 S_IRUSR | S_IRGRP | S_IROTH, /* r */
801 S_IWUSR | S_IWGRP | S_IWOTH, /* w */
802 S_IXUSR | S_IXGRP | S_IXOTH, /* x */
803 S_ISUID | S_ISGID, /* s */
807 static const char group_string[] = "ugoa";
808 static const char mode_string[] = "rwxst";
813 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
828 if ((c = *s++) == '\0') {
831 for (p=group_string ; *p ; p++) {
833 groups |= group_set[(int)(p-group_string)];
842 if (groups == 0) { /* The default is "all" */
843 groups |= S_ISUID | S_ISGID | S_ISVTX
844 | S_IRWXU | S_IRWXG | S_IRWXO;
848 if ((c < '0') || (c > '7') || (mode | groups)) {
851 *theMode = strtol(--s, NULL, 8);
857 if (((c = *s++) != '\0') && (c != ',')) {
858 for (p=mode_string ; *p ; p++) {
860 mode |= mode_set[(int)(p-mode_string)];
864 break; /* We're done so break out of loop.*/
868 andMode &= ~(groups); /* Now fall through. */
870 orMode |= mode & groups;
873 andMode &= ~(mode & groups);
874 orMode &= ~(mode & groups);
886 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
892 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
893 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
894 || defined BB_LOGNAME || defined BB_WHOAMI || defined BB_SH
896 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_ID
897 /* returns a uid given a username */
898 long my_getpwnam(const char *name)
900 struct passwd *myuser;
902 myuser = getpwnam(name);
904 error_msg_and_die("unknown user name: %s", name);
906 return myuser->pw_uid;
909 /* returns a gid given a group name */
910 long my_getgrnam(const char *name)
912 struct group *mygroup;
914 mygroup = getgrnam(name);
916 error_msg_and_die("unknown group name: %s", name);
918 return (mygroup->gr_gid);
922 /* gets a username given a uid */
923 void my_getpwuid(char *name, long uid)
925 struct passwd *myuser;
927 myuser = getpwuid(uid);
929 sprintf(name, "%-8ld ", (long)uid);
931 strcpy(name, myuser->pw_name);
934 /* gets a groupname given a gid */
935 void my_getgrgid(char *group, long gid)
937 struct group *mygroup;
939 mygroup = getgrgid(gid);
941 sprintf(group, "%-8ld ", (long)gid);
943 strcpy(group, mygroup->gr_name);
947 /* gets a gid given a user name */
948 long my_getpwnamegid(const char *name)
950 struct group *mygroup;
951 struct passwd *myuser;
953 myuser=getpwnam(name);
955 error_msg_and_die("unknown user name: %s", name);
957 mygroup = getgrgid(myuser->pw_gid);
959 error_msg_and_die("unknown gid %ld", (long)myuser->pw_gid);
961 return mygroup->gr_gid;
965 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
966 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
969 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
971 /* From <linux/kd.h> */
972 static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
973 static const int KB_84 = 0x01;
974 static const int KB_101 = 0x02; /* this is what we always answer */
976 int is_a_console(int fd)
981 return (ioctl(fd, KDGKBTYPE, &arg) == 0
982 && ((arg == KB_101) || (arg == KB_84)));
985 static int open_a_console(char *fnam)
990 fd = open(fnam, O_RDWR);
992 /* if failed, try read-only */
993 if (fd < 0 && errno == EACCES)
994 fd = open(fnam, O_RDONLY);
996 /* if failed, try write-only */
997 if (fd < 0 && errno == EACCES)
998 fd = open(fnam, O_WRONLY);
1000 /* if failed, fail */
1004 /* if not a console, fail */
1005 if (!is_a_console(fd)) {
1015 * Get an fd for use with kbd/console ioctls.
1016 * We try several things because opening /dev/console will fail
1017 * if someone else used X (which does a chown on /dev/console).
1019 * if tty_name is non-NULL, try this one instead.
1022 int get_console_fd(char *tty_name)
1027 if (-1 == (fd = open_a_console(tty_name)))
1033 fd = open_a_console("/dev/tty");
1037 fd = open_a_console("/dev/tty0");
1041 fd = open_a_console("/dev/console");
1045 for (fd = 0; fd < 3; fd++)
1046 if (is_a_console(fd))
1049 error_msg("Couldnt get a file descriptor referring to the console");
1050 return -1; /* total failure */
1054 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1057 #if defined BB_FIND || defined BB_INSMOD
1059 * Routine to see if a text string is matched by a wildcard pattern.
1060 * Returns TRUE if the text is matched, or FALSE if it is not matched
1061 * or if the pattern is invalid.
1062 * * matches zero or more characters
1063 * ? matches a single character
1064 * [abc] matches 'a', 'b' or 'c'
1065 * \c quotes character c
1066 * Adapted from code written by Ingo Wilken, and
1067 * then taken from sash, Copyright (c) 1999 by David I. Bell
1068 * Permission is granted to use, distribute, or modify this source,
1069 * provided that this copyright notice remains intact.
1070 * Permission to distribute this code under the GPL has been granted.
1072 extern int check_wildcard_match(const char *text, const char *pattern)
1074 const char *retryPat;
1075 const char *retryText;
1083 while (*text || *pattern) {
1095 while ((ch = *pattern++) != ']') {
1106 if (found == FALSE && len!=0) {
1109 if (found == TRUE) {
1110 if (strlen(pattern)==0 && len==1) {
1119 /* fall into next case */
1122 if (*text++ == '\0')
1133 /* fall into next case */
1151 if (pattern == NULL)
1157 #endif /* BB_FIND || BB_INSMOD */
1162 #if defined BB_DF || defined BB_MTAB
1165 * Given a block device, find the mount table entry if that block device
1168 * Given any other file (or directory), find the mount table entry for its
1171 extern struct mntent *find_mount_point(const char *name, const char *table)
1176 struct mntent *mountEntry;
1178 if (stat(name, &s) != 0)
1181 if ((s.st_mode & S_IFMT) == S_IFBLK)
1182 mountDevice = s.st_rdev;
1184 mountDevice = s.st_dev;
1187 if ((mountTable = setmntent(table, "r")) == 0)
1190 while ((mountEntry = getmntent(mountTable)) != 0) {
1191 if (strcmp(name, mountEntry->mnt_dir) == 0
1192 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1194 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1196 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1199 endmntent(mountTable);
1202 #endif /* BB_DF || BB_MTAB */
1204 #if defined BB_INIT || defined BB_SYSLOGD
1205 /* try to open up the specified device */
1206 extern int device_open(char *device, int mode)
1210 m = mode | O_NONBLOCK;
1212 /* Retry up to 5 times */
1213 for (f = 0; f < 5; f++)
1214 if ((fd = open(device, m, 0600)) >= 0)
1218 /* Reset original flags. */
1220 fcntl(fd, F_SETFL, mode);
1223 #endif /* BB_INIT BB_SYSLOGD */
1226 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1227 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1228 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1231 #if defined BB_FEATURE_USE_DEVPS_PATCH
1232 /* find_pid_by_name()
1234 * This finds the pid of the specified process,
1235 * by using the /dev/ps device driver.
1237 * Returns a list of all matching PIDs
1239 extern pid_t* find_pid_by_name( char* pidName)
1242 char device[] = "/dev/ps";
1244 pid_t* pid_array = NULL;
1245 pid_t* pidList=NULL;
1248 fd = open(device, O_RDONLY);
1250 perror_msg_and_die("open failed for `%s'", device);
1252 /* Find out how many processes there are */
1253 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1254 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1256 /* Allocate some memory -- grab a few extras just in case
1257 * some new processes start up while we wait. The kernel will
1258 * just ignore any extras if we give it too many, and will trunc.
1259 * the list if we give it too few. */
1260 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1261 pid_array[0] = num_pids+10;
1263 /* Now grab the pid list */
1264 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1265 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1267 /* Now search for a match */
1268 for (i=1, j=0; i<pid_array[0] ; i++) {
1270 struct pid_info info;
1272 info.pid = pid_array[i];
1273 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1274 perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1276 /* Make sure we only match on the process name */
1277 p=info.command_line+1;
1278 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1284 if ((strstr(info.command_line, pidName) != NULL)
1285 && (strlen(pidName) == strlen(info.command_line))) {
1286 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1287 pidList[j++]=info.pid;
1297 if (close (fd) != 0)
1298 perror_msg_and_die("close failed for `%s'", device);
1302 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1304 /* find_pid_by_name()
1306 * This finds the pid of the specified process.
1307 * Currently, it's implemented by rummaging through
1308 * the proc filesystem.
1310 * Returns a list of all matching PIDs
1312 extern pid_t* find_pid_by_name( char* pidName)
1315 struct dirent *next;
1316 pid_t* pidList=NULL;
1319 dir = opendir("/proc");
1321 perror_msg_and_die("Cannot open /proc");
1323 while ((next = readdir(dir)) != NULL) {
1328 /* If it isn't a number, we don't want it */
1329 if (!isdigit(*next->d_name))
1332 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1333 status = fopen(filename, "r");
1337 fgets(buffer, 256, status);
1340 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1341 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1342 pidList[i++]=strtol(next->d_name, NULL, 0);
1350 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1351 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1354 /* this should really be farmed out to libbusybox.a */
1355 extern void *xmalloc(size_t size)
1357 void *ptr = malloc(size);
1360 error_msg_and_die(memory_exhausted);
1364 extern void *xrealloc(void *old, size_t size)
1366 void *ptr = realloc(old, size);
1368 error_msg_and_die(memory_exhausted);
1372 extern void *xcalloc(size_t nmemb, size_t size)
1374 void *ptr = calloc(nmemb, size);
1376 error_msg_and_die(memory_exhausted);
1381 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || \
1382 defined BB_WGET || defined BB_DPKG_DEB || defined BB_TAR || \
1385 extern char * xstrdup (const char *s) {
1394 error_msg_and_die(memory_exhausted);
1401 #if defined BB_NFSMOUNT
1402 extern char * xstrndup (const char *s, int n) {
1406 error_msg_and_die("xstrndup bug");
1410 return safe_strncpy(t,s,n);
1414 #if defined BB_IFCONFIG || defined BB_ROUTE || defined BB_NFSMOUNT || \
1415 defined BB_FEATURE_MOUNT_LOOP
1416 /* Like strncpy but make sure the resulting string is always 0 terminated. */
1417 extern char * safe_strncpy(char *dst, const char *src, size_t size)
1420 return strncpy(dst, src, size-1);
1424 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1425 extern int vdprintf(int d, const char *format, va_list ap)
1430 len = vsprintf(buf, format, ap);
1431 return write(d, buf, len);
1433 #endif /* BB_SYSLOGD */
1436 #if defined BB_FEATURE_MOUNT_LOOP
1438 #include "loop.h" /* Pull in loop device support */
1440 extern int del_loop(const char *device)
1444 if ((fd = open(device, O_RDONLY)) < 0) {
1445 perror_msg("%s", device);
1448 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1449 perror_msg("ioctl: LOOP_CLR_FD");
1456 extern int set_loop(const char *device, const char *file, int offset,
1459 struct loop_info loopinfo;
1462 mode = *loopro ? O_RDONLY : O_RDWR;
1463 if ((ffd = open(file, mode)) < 0 && !*loopro
1464 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1465 perror_msg("%s", file);
1468 if ((fd = open(device, mode)) < 0) {
1470 perror_msg("%s", device);
1473 *loopro = (mode == O_RDONLY);
1475 memset(&loopinfo, 0, sizeof(loopinfo));
1476 safe_strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1478 loopinfo.lo_offset = offset;
1480 loopinfo.lo_encrypt_key_size = 0;
1481 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1482 perror_msg("ioctl: LOOP_SET_FD");
1487 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1488 (void) ioctl(fd, LOOP_CLR_FD, 0);
1489 perror_msg("ioctl: LOOP_SET_STATUS");
1499 extern char *find_unused_loop_device(void)
1503 struct stat statbuf;
1504 struct loop_info loopinfo;
1506 for (i = 0; i <= 7; i++) {
1507 sprintf(dev, "/dev/loop%d", i);
1508 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1509 if ((fd = open(dev, O_RDONLY)) >= 0) {
1510 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) != 0) {
1511 if (errno == ENXIO) { /* probably free */
1522 #endif /* BB_FEATURE_MOUNT_LOOP */
1524 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1525 extern int find_real_root_device_name(char* name)
1528 struct dirent *entry;
1529 struct stat statBuf, rootStat;
1530 char fileName[BUFSIZ];
1532 if (stat("/", &rootStat) != 0) {
1533 error_msg("could not stat '/'");
1537 dir = opendir("/dev");
1539 error_msg("could not open '/dev'");
1543 while((entry = readdir(dir)) != NULL) {
1545 /* Must skip ".." since that is "/", and so we
1546 * would get a false positive on ".." */
1547 if (strcmp(entry->d_name, "..") == 0)
1550 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1552 if (stat(fileName, &statBuf) != 0)
1554 /* Some char devices have the same dev_t as block
1555 * devices, so make sure this is a block device */
1556 if (! S_ISBLK(statBuf.st_mode))
1558 if (statBuf.st_rdev == rootStat.st_rdev) {
1559 strcpy(name, fileName);
1569 /* get_line_from_file() - This function reads an entire line from a text file
1570 * up to a newline. It returns a malloc'ed char * which must be stored and
1571 * free'ed by the caller. */
1572 extern char *get_line_from_file(FILE *file)
1574 static const int GROWBY = 80; /* how large we will grow strings by */
1578 char *linebuf = NULL;
1585 /* grow the line buffer as necessary */
1586 while (idx > linebufsz-2)
1587 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1588 linebuf[idx++] = (char)ch;
1589 if ((char)ch == '\n')
1601 extern void print_file(FILE *file)
1605 while ((c = getc(file)) != EOF)
1611 extern int print_file_by_name(char *filename)
1614 if ((file = wfopen(filename, "r")) == NULL)
1621 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1622 char process_escape_sequence(char **ptr)
1624 static const char charmap[] = {
1625 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', 0,
1626 '\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '\\' };
1636 for ( num_digits = 0 ; num_digits < 3 ; ++num_digits) {
1637 if ((*q < '0') || (*q > '7')) { /* not a digit? */
1640 n = n * 8 + (*q++ - '0');
1643 if (num_digits == 0) { /* mnemonic escape sequence? */
1644 for (p=charmap ; *p ; p++) {
1650 n = *(p+(sizeof(charmap)/2));
1653 /* doesn't hurt to fall through to here from mnemonic case */
1654 if (n > UCHAR_MAX) { /* is octal code too big for a char? */
1655 n /= 8; /* adjust value and */
1656 --q; /* back up one char */
1664 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1665 ! defined BB_FEATURE_USE_DEVPS_PATCH || defined BB_WGET
1666 char *get_last_path_component(char *path)
1668 char *s=path+strlen(path)-1;
1670 /* strip trailing slashes */
1671 while (s != path && *s == '/') {
1675 /* find last component */
1676 s = strrchr(path, '/');
1677 if (s == NULL || s[1] == '\0')
1684 #if defined BB_GREP || defined BB_SED
1686 void xregcomp(regex_t *preg, const char *regex, int cflags)
1689 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1690 int errmsgsz = regerror(ret, preg, NULL, 0);
1691 char *errmsg = xmalloc(errmsgsz);
1692 regerror(ret, preg, errmsg, errmsgsz);
1693 error_msg_and_die("xregcomp: %s", errmsg);
1698 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1699 FILE *wfopen(const char *path, const char *mode)
1702 if ((fp = fopen(path, mode)) == NULL) {
1703 perror_msg("%s", path);
1710 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1711 || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1712 || defined BB_WC || defined BB_CMP || defined BB_SORT || defined BB_WGET \
1713 || defined BB_MOUNT || defined BB_ROUTE
1714 FILE *xfopen(const char *path, const char *mode)
1717 if ((fp = fopen(path, mode)) == NULL)
1718 perror_msg_and_die("%s", path);
1723 static int applet_name_compare(const void *x, const void *y)
1725 const char *name = x;
1726 const struct BB_applet *applet = y;
1728 return strcmp(name, applet->name);
1731 extern size_t NUM_APPLETS;
1733 struct BB_applet *find_applet_by_name(const char *name)
1735 return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
1736 applet_name_compare);
1739 void run_applet_by_name(const char *name, int argc, char **argv)
1741 /* Do a binary search to find the applet entry given the name. */
1742 if ((applet_using = find_applet_by_name(name)) != NULL) {
1743 applet_name = applet_using->name;
1744 if (argv[1] && strcmp(argv[1], "--help") == 0)
1746 exit((*(applet_using->main)) (argc, argv));
1750 #if defined BB_DD || defined BB_TAIL || defined BB_STTY
1751 unsigned long parse_number(const char *numstr,
1752 const struct suffix_mult *suffixes)
1754 const struct suffix_mult *sm;
1755 unsigned long int ret;
1759 ret = strtoul(numstr, &end, 10);
1761 error_msg_and_die("invalid number `%s'", numstr);
1762 while (end[0] != '\0') {
1766 len = strlen(sm->suffix);
1767 if (strncmp(sm->suffix, end, len) == 0) {
1778 error_msg_and_die("invalid number `%s'", numstr);
1784 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1785 ssize_t safe_read(int fd, void *buf, size_t count)
1790 n = read(fd, buf, count);
1791 } while (n < 0 && errno == EINTR);
1797 #ifdef BB_FEATURE_HUMAN_READABLE
1798 const char *format(unsigned long val, unsigned long hr)
1800 static const char strings[] = { '0', 0, 'k', 0, 'M', 0, 'G', 0 };
1801 static const char fmt[] = "%lu";
1802 static const char fmt_u[] = "%lu.%lu%s";
1804 static char str[10];
1806 unsigned long frac __attribute__ ((unused)); /* 'may be uninitialized' warning is ok */
1811 if(val == 0) { /* This may be omitted to reduce size */
1812 return strings; /* at the cost of speed. */
1821 while ((val >= KILOBYTE) && (*u != 'G')) {
1824 frac = (((val % KILOBYTE) * 10) + (KILOBYTE/2)) / KILOBYTE;
1826 if (frac >= 10) { /* We need to round up here. */
1833 /* If f==fmt then 'frac' and 'u' are ignored and need not be set. */
1834 snprintf(str, sizeof(str), f, val, frac, u);
1840 #if defined(BB_GREP) || defined(BB_HOSTNAME) || defined(BB_SED) || defined(BB_TAR) || defined(BB_WGET) || defined(BB_XARGS)
1843 size_t len = strlen(s);
1848 if (s[len-1] == '\n')
1856 c-file-style: "linux"