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/filesystems or /dev/mtab to get the
67 * list of available filesystems used for the -t auto option */
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
193 static const int __NR_umount2 = 52;
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 _syscall2(int, umount2, const char *, special_file, int, flags);
200 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
201 const char *, fstype, unsigned long int, rwflag, const void *, data);
204 #if defined BB_FEATURE_NEW_MODULE_INTERFACE && ( defined BB_INSMOD || defined BB_LSMOD )
205 #ifndef __NR_query_module
206 static const int __NR_query_module = 167;
208 _syscall5(int, query_module, const char *, name, int, which,
209 void *, buf, size_t, bufsize, size_t*, ret);
213 #if defined (BB_CP_MV) || defined (BB_DU)
215 #define HASH_SIZE 311 /* Should be prime */
216 #define hash_inode(i) ((i) % HASH_SIZE)
218 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
221 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
222 * `ino_dev_hashtable', else return 0
224 * If NAME is a non-NULL pointer to a character pointer, and there is
225 * a match, then set *NAME to the value of the name slot in that
228 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
230 ino_dev_hashtable_bucket_t *bucket;
232 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
233 while (bucket != NULL) {
234 if ((bucket->ino == statbuf->st_ino) &&
235 (bucket->dev == statbuf->st_dev))
237 if (name) *name = bucket->name;
240 bucket = bucket->next;
245 /* Add statbuf to statbuf hash table */
246 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
250 ino_dev_hashtable_bucket_t *bucket;
252 i = hash_inode(statbuf->st_ino);
253 s = name ? strlen(name) : 0;
254 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
255 bucket->ino = statbuf->st_ino;
256 bucket->dev = statbuf->st_dev;
258 strcpy(bucket->name, name);
260 bucket->name[0] = '\0';
261 bucket->next = ino_dev_hashtable[i];
262 ino_dev_hashtable[i] = bucket;
265 /* Clear statbuf hash table */
266 void reset_ino_dev_hashtable(void)
269 ino_dev_hashtable_bucket_t *bucket;
271 for (i = 0; i < HASH_SIZE; i++) {
272 while (ino_dev_hashtable[i] != NULL) {
273 bucket = ino_dev_hashtable[i]->next;
274 free(ino_dev_hashtable[i]);
275 ino_dev_hashtable[i] = bucket;
280 #endif /* BB_CP_MV || BB_DU */
282 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_DPKG_DEB)
284 * Return TRUE if a fileName is a directory.
285 * Nonexistant files return FALSE.
287 int is_directory(const char *fileName, const int followLinks, struct stat *statBuf)
292 if (statBuf == NULL) {
293 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
297 if (followLinks == TRUE)
298 status = stat(fileName, statBuf);
300 status = lstat(fileName, statBuf);
302 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
315 #if defined BB_AR || defined BB_CP_MV
317 * Copy chunksize bytes between two file descriptors
319 int copy_file_chunk(int srcfd, int dstfd, size_t chunksize)
322 char buffer[BUFSIZ]; /* BUFSIZ is declared in stdio.h */
324 while (chunksize > 0) {
325 if (chunksize > BUFSIZ)
329 if (full_write(dstfd, buffer, full_read(srcfd, buffer, size)) < size)
338 #if defined (BB_CP_MV) || defined BB_DPKG
340 * Copy one file to another, while possibly preserving its modes, times, and
341 * modes. Returns TRUE if successful, or FALSE on a failure with an error
342 * message output. (Failure is not indicated if attributes cannot be set.)
346 copy_file(const char *srcName, const char *destName,
347 int setModes, int followLinks, int forceFlag)
352 struct stat srcStatBuf;
353 struct stat dstStatBuf;
354 struct utimbuf times;
356 if (followLinks == TRUE)
357 status = stat(srcName, &srcStatBuf);
359 status = lstat(srcName, &srcStatBuf);
362 perror_msg("%s", srcName);
366 if (followLinks == TRUE)
367 status = stat(destName, &dstStatBuf);
369 status = lstat(destName, &dstStatBuf);
371 if (status < 0 || forceFlag==TRUE) {
373 dstStatBuf.st_ino = -1;
374 dstStatBuf.st_dev = -1;
377 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
378 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
379 error_msg("Copying file \"%s\" to itself", srcName);
383 if (S_ISDIR(srcStatBuf.st_mode)) {
384 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
385 /* Make sure the directory is writable */
386 status = mkdir(destName, 0777777 ^ umask(0));
387 if (status < 0 && errno != EEXIST) {
388 perror_msg("%s", destName);
391 } else if (S_ISLNK(srcStatBuf.st_mode)) {
392 char link_val[BUFSIZ + 1];
395 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
396 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
397 link_size = readlink(srcName, &link_val[0], BUFSIZ);
399 perror_msg("%s", srcName);
402 link_val[link_size] = '\0';
403 status = symlink(link_val, destName);
405 perror_msg("%s", destName);
408 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
409 if (setModes == TRUE) {
410 /* Try to set owner, but fail silently like GNU cp */
411 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
415 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
416 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
417 if (mkfifo(destName, 0644) < 0) {
418 perror_msg("%s", destName);
421 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
422 || S_ISSOCK(srcStatBuf.st_mode)) {
423 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
424 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
425 perror_msg("%s", destName);
428 } else if (S_ISREG(srcStatBuf.st_mode)) {
429 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
430 rfd = open(srcName, O_RDONLY);
432 perror_msg("%s", srcName);
436 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
439 perror_msg("%s", destName);
444 if (copy_file_chunk(rfd, wfd, srcStatBuf.st_size)==FALSE)
448 if (close(wfd) < 0) {
453 if (setModes == TRUE) {
454 /* This is fine, since symlinks never get here */
455 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0)
456 perror_msg_and_die("%s", destName);
457 if (chmod(destName, srcStatBuf.st_mode) < 0)
458 perror_msg_and_die("%s", destName);
459 times.actime = srcStatBuf.st_atime;
460 times.modtime = srcStatBuf.st_mtime;
461 if (utime(destName, ×) < 0)
462 perror_msg_and_die("%s", destName);
468 perror_msg("%s", destName);
474 #endif /* BB_CP_MV */
478 #if defined BB_TAR || defined BB_LS ||defined BB_AR
480 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
481 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
483 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
484 static const mode_t SBIT[] = {
490 /* The 9 mode bits to test */
491 static const mode_t MBIT[] = {
492 S_IRUSR, S_IWUSR, S_IXUSR,
493 S_IRGRP, S_IWGRP, S_IXGRP,
494 S_IROTH, S_IWOTH, S_IXOTH
497 static const char MODE1[] = "rwxrwxrwx";
498 static const char MODE0[] = "---------";
499 static const char SMODE1[] = "..s..s..t";
500 static const char SMODE0[] = "..S..S..T";
503 * Return the standard ls-like mode string from a file mode.
504 * This is static and so is overwritten on each call.
506 const char *mode_string(int mode)
512 buf[0] = TYPECHAR(mode);
513 for (i = 0; i < 9; i++) {
515 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
517 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
521 #endif /* BB_TAR || BB_LS */
524 #if defined BB_TAR || defined BB_AR
526 * Return the standard ls-like time string from a time_t
527 * This is static and so is overwritten on each call.
529 const char *time_string(time_t timeVal)
537 str = ctime(&timeVal);
539 strcpy(buf, &str[4]);
542 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
543 strcpy(&buf[7], &str[20]);
549 #endif /* BB_TAR || BB_AR */
551 #if defined BB_DD || defined BB_NC || defined BB_TAIL || defined BB_TAR || defined BB_AR || defined BB_CP_MV
553 * Write all of the supplied buffer out to a file.
554 * This does multiple writes as necessary.
555 * Returns the amount written, or -1 on an error.
557 int full_write(int fd, const char *buf, int len)
565 cc = write(fd, buf, len);
579 #if defined BB_AR || defined BB_CP_MV || defined BB_SH || defined BB_TAR
581 * Read all of the supplied buffer from a file.
582 * This does multiple reads as necessary.
583 * Returns the amount read, or -1 on an error.
584 * A short read is returned on an end of file.
586 int full_read(int fd, char *buf, int len)
594 cc = read(fd, buf, len);
609 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
612 #if defined (BB_CHMOD_CHOWN_CHGRP) \
613 || defined (BB_CP_MV) \
614 || defined (BB_FIND) \
615 || defined (BB_INSMOD) \
621 * Walk down all the directories under the specified
622 * location, and do something (something specified
623 * by the fileAction and dirAction function pointers).
625 * Unfortunately, while nftw(3) could replace this and reduce
626 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
627 * and so isn't sufficiently portable to take over since glibc2.1
628 * is so stinking huge.
630 int recursive_action(const char *fileName,
631 int recurse, int followLinks, int depthFirst,
632 int (*fileAction) (const char *fileName,
633 struct stat * statbuf,
635 int (*dirAction) (const char *fileName,
636 struct stat * statbuf,
644 if (followLinks == TRUE)
645 status = stat(fileName, &statbuf);
647 status = lstat(fileName, &statbuf);
650 #ifdef BB_DEBUG_PRINT_SCAFFOLD
652 "status=%d followLinks=%d TRUE=%d\n",
653 status, followLinks, TRUE);
655 perror_msg("%s", fileName);
659 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
660 if (fileAction == NULL)
663 return fileAction(fileName, &statbuf, userData);
666 if (recurse == FALSE) {
667 if (S_ISDIR(statbuf.st_mode)) {
668 if (dirAction != NULL)
669 return (dirAction(fileName, &statbuf, userData));
675 if (S_ISDIR(statbuf.st_mode)) {
678 if (dirAction != NULL && depthFirst == FALSE) {
679 status = dirAction(fileName, &statbuf, userData);
680 if (status == FALSE) {
681 perror_msg("%s", fileName);
683 } else if (status == SKIP)
686 dir = opendir(fileName);
688 perror_msg("%s", fileName);
691 while ((next = readdir(dir)) != NULL) {
692 char nextFile[BUFSIZ + 1];
694 if ((strcmp(next->d_name, "..") == 0)
695 || (strcmp(next->d_name, ".") == 0)) {
698 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
699 error_msg(name_too_long);
702 memset(nextFile, 0, sizeof(nextFile));
703 sprintf(nextFile, "%s/%s", fileName, next->d_name);
705 recursive_action(nextFile, TRUE, followLinks, depthFirst,
706 fileAction, dirAction, userData);
707 if (status == FALSE) {
712 status = closedir(dir);
714 perror_msg("%s", fileName);
717 if (dirAction != NULL && depthFirst == TRUE) {
718 status = dirAction(fileName, &statbuf, userData);
719 if (status == FALSE) {
720 perror_msg("%s", fileName);
725 if (fileAction == NULL)
728 return fileAction(fileName, &statbuf, userData);
733 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
737 #if defined (BB_TAR) || defined (BB_MKDIR)
739 * Attempt to create the directories along the specified path, except for
740 * the final component. The mode is given for the final directory only,
741 * while all previous ones get default protections. Errors are not reported
742 * here, as failures to restore files can be reported later.
744 extern int create_path(const char *name, int mode)
748 char buf[BUFSIZ + 1];
752 for (cp = buf; *cp == '/'; cp++);
753 cp = strchr(cp, '/');
756 cp = strchr(cp + 1, '/');
758 retVal = mkdir(buf, cp ? 0777 : mode);
759 if (retVal != 0 && errno != EEXIST) {
760 perror_msg("%s", buf);
767 #endif /* BB_TAR || BB_MKDIR */
771 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
772 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
773 /* [ugoa]{+|-|=}[rwxst] */
775 extern int parse_mode(const char *s, mode_t * theMode)
777 static const mode_t group_set[] = {
778 S_ISUID | S_IRWXU, /* u */
779 S_ISGID | S_IRWXG, /* g */
781 S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO /* a */
784 static const mode_t mode_set[] = {
785 S_IRUSR | S_IRGRP | S_IROTH, /* r */
786 S_IWUSR | S_IWGRP | S_IWOTH, /* w */
787 S_IXUSR | S_IXGRP | S_IXOTH, /* x */
788 S_ISUID | S_ISGID, /* s */
792 static const char group_string[] = "ugoa";
793 static const char mode_string[] = "rwxst";
798 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
813 if ((c = *s++) == '\0') {
816 for (p=group_string ; *p ; p++) {
818 groups |= group_set[(int)(p-group_string)];
827 if (groups == 0) { /* The default is "all" */
828 groups |= S_ISUID | S_ISGID | S_ISVTX
829 | S_IRWXU | S_IRWXG | S_IRWXO;
833 if ((c < '0') || (c > '7') || (mode | groups)) {
836 *theMode = strtol(--s, NULL, 8);
842 if (((c = *s++) != '\0') && (c != ',')) {
843 for (p=mode_string ; *p ; p++) {
845 mode |= mode_set[(int)(p-mode_string)];
849 break; /* We're done so break out of loop.*/
853 andMode &= ~(groups); /* Now fall through. */
855 orMode |= mode & groups;
858 andMode &= ~(mode & groups);
859 orMode &= ~(mode & groups);
871 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
877 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
878 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
879 || defined BB_LOGNAME || defined BB_WHOAMI || defined BB_SH
880 /* returns a uid given a username */
881 long my_getpwnam(char *name)
883 struct passwd *myuser;
885 myuser = getpwnam(name);
889 return myuser->pw_uid;
892 /* returns a gid given a group name */
893 long my_getgrnam(char *name)
895 struct group *mygroup;
897 mygroup = getgrnam(name);
901 return (mygroup->gr_gid);
904 /* gets a username given a uid */
905 void my_getpwuid(char *name, long uid)
907 struct passwd *myuser;
909 myuser = getpwuid(uid);
911 sprintf(name, "%-8ld ", (long)uid);
913 strcpy(name, myuser->pw_name);
916 /* gets a groupname given a gid */
917 void my_getgrgid(char *group, long gid)
919 struct group *mygroup;
921 mygroup = getgrgid(gid);
923 sprintf(group, "%-8ld ", (long)gid);
925 strcpy(group, mygroup->gr_name);
929 /* gets a gid given a user name */
930 long my_getpwnamegid(char *name)
932 struct group *mygroup;
933 struct passwd *myuser;
935 myuser=getpwnam(name);
937 error_msg_and_die( "unknown user name: %s", name);
939 mygroup = getgrgid(myuser->pw_gid);
941 error_msg_and_die( "unknown gid %ld", (long)myuser->pw_gid);
943 return mygroup->gr_gid;
947 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
948 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
951 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
953 /* From <linux/kd.h> */
954 static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
955 static const int KB_84 = 0x01;
956 static const int KB_101 = 0x02; /* this is what we always answer */
958 int is_a_console(int fd)
963 return (ioctl(fd, KDGKBTYPE, &arg) == 0
964 && ((arg == KB_101) || (arg == KB_84)));
967 static int open_a_console(char *fnam)
972 fd = open(fnam, O_RDWR);
974 /* if failed, try read-only */
975 if (fd < 0 && errno == EACCES)
976 fd = open(fnam, O_RDONLY);
978 /* if failed, try write-only */
979 if (fd < 0 && errno == EACCES)
980 fd = open(fnam, O_WRONLY);
982 /* if failed, fail */
986 /* if not a console, fail */
987 if (!is_a_console(fd)) {
997 * Get an fd for use with kbd/console ioctls.
998 * We try several things because opening /dev/console will fail
999 * if someone else used X (which does a chown on /dev/console).
1001 * if tty_name is non-NULL, try this one instead.
1004 int get_console_fd(char *tty_name)
1009 if (-1 == (fd = open_a_console(tty_name)))
1015 fd = open_a_console("/dev/tty");
1019 fd = open_a_console("/dev/tty0");
1023 fd = open_a_console("/dev/console");
1027 for (fd = 0; fd < 3; fd++)
1028 if (is_a_console(fd))
1031 error_msg("Couldnt get a file descriptor referring to the console");
1032 return -1; /* total failure */
1036 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1039 #if defined BB_FIND || defined BB_INSMOD
1041 * Routine to see if a text string is matched by a wildcard pattern.
1042 * Returns TRUE if the text is matched, or FALSE if it is not matched
1043 * or if the pattern is invalid.
1044 * * matches zero or more characters
1045 * ? matches a single character
1046 * [abc] matches 'a', 'b' or 'c'
1047 * \c quotes character c
1048 * Adapted from code written by Ingo Wilken, and
1049 * then taken from sash, Copyright (c) 1999 by David I. Bell
1050 * Permission is granted to use, distribute, or modify this source,
1051 * provided that this copyright notice remains intact.
1052 * Permission to distribute this code under the GPL has been granted.
1054 extern int check_wildcard_match(const char *text, const char *pattern)
1056 const char *retryPat;
1057 const char *retryText;
1065 while (*text || *pattern) {
1077 while ((ch = *pattern++) != ']') {
1088 if (found == FALSE && len!=0) {
1091 if (found == TRUE) {
1092 if (strlen(pattern)==0 && len==1) {
1101 /* fall into next case */
1104 if (*text++ == '\0')
1115 /* fall into next case */
1133 if (pattern == NULL)
1139 #endif /* BB_FIND || BB_INSMOD */
1144 #if defined BB_DF || defined BB_MTAB
1147 * Given a block device, find the mount table entry if that block device
1150 * Given any other file (or directory), find the mount table entry for its
1153 extern struct mntent *find_mount_point(const char *name, const char *table)
1158 struct mntent *mountEntry;
1160 if (stat(name, &s) != 0)
1163 if ((s.st_mode & S_IFMT) == S_IFBLK)
1164 mountDevice = s.st_rdev;
1166 mountDevice = s.st_dev;
1169 if ((mountTable = setmntent(table, "r")) == 0)
1172 while ((mountEntry = getmntent(mountTable)) != 0) {
1173 if (strcmp(name, mountEntry->mnt_dir) == 0
1174 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1176 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1178 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1181 endmntent(mountTable);
1184 #endif /* BB_DF || BB_MTAB */
1186 #if defined BB_INIT || defined BB_SYSLOGD
1187 /* try to open up the specified device */
1188 extern int device_open(char *device, int mode)
1192 m = mode | O_NONBLOCK;
1194 /* Retry up to 5 times */
1195 for (f = 0; f < 5; f++)
1196 if ((fd = open(device, m, 0600)) >= 0)
1200 /* Reset original flags. */
1202 fcntl(fd, F_SETFL, mode);
1205 #endif /* BB_INIT BB_SYSLOGD */
1208 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1209 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1210 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1213 #if defined BB_FEATURE_USE_DEVPS_PATCH
1214 /* find_pid_by_name()
1216 * This finds the pid of the specified process,
1217 * by using the /dev/ps device driver.
1219 * Returns a list of all matching PIDs
1221 extern pid_t* find_pid_by_name( char* pidName)
1224 char device[] = "/dev/ps";
1226 pid_t* pid_array = NULL;
1227 pid_t* pidList=NULL;
1230 fd = open(device, O_RDONLY);
1232 perror_msg_and_die("open failed for `%s'", device);
1234 /* Find out how many processes there are */
1235 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1236 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1238 /* Allocate some memory -- grab a few extras just in case
1239 * some new processes start up while we wait. The kernel will
1240 * just ignore any extras if we give it too many, and will trunc.
1241 * the list if we give it too few. */
1242 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1243 pid_array[0] = num_pids+10;
1245 /* Now grab the pid list */
1246 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1247 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1249 /* Now search for a match */
1250 for (i=1, j=0; i<pid_array[0] ; i++) {
1252 struct pid_info info;
1254 info.pid = pid_array[i];
1255 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1256 perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1258 /* Make sure we only match on the process name */
1259 p=info.command_line+1;
1260 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1266 if ((strstr(info.command_line, pidName) != NULL)
1267 && (strlen(pidName) == strlen(info.command_line))) {
1268 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1269 pidList[j++]=info.pid;
1279 if (close (fd) != 0)
1280 perror_msg_and_die("close failed for `%s'", device);
1284 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1286 /* find_pid_by_name()
1288 * This finds the pid of the specified process.
1289 * Currently, it's implemented by rummaging through
1290 * the proc filesystem.
1292 * Returns a list of all matching PIDs
1294 extern pid_t* find_pid_by_name( char* pidName)
1297 struct dirent *next;
1298 pid_t* pidList=NULL;
1301 dir = opendir("/proc");
1303 perror_msg_and_die("Cannot open /proc");
1305 while ((next = readdir(dir)) != NULL) {
1310 /* If it isn't a number, we don't want it */
1311 if (!isdigit(*next->d_name))
1314 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1315 status = fopen(filename, "r");
1319 fgets(buffer, 256, status);
1322 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1323 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1324 pidList[i++]=strtol(next->d_name, NULL, 0);
1332 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1333 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1336 /* this should really be farmed out to libbusybox.a */
1337 extern void *xmalloc(size_t size)
1339 void *ptr = malloc(size);
1342 error_msg_and_die(memory_exhausted);
1346 extern void *xrealloc(void *old, size_t size)
1348 void *ptr = realloc(old, size);
1350 error_msg_and_die(memory_exhausted);
1354 extern void *xcalloc(size_t nmemb, size_t size)
1356 void *ptr = calloc(nmemb, size);
1358 error_msg_and_die(memory_exhausted);
1363 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || \
1364 defined BB_WGET || defined BB_DPKG_DEB || defined BB_TAR || \
1367 extern char * xstrdup (const char *s) {
1376 error_msg_and_die(memory_exhausted);
1383 #if defined BB_NFSMOUNT
1384 extern char * xstrndup (const char *s, int n) {
1388 error_msg_and_die("xstrndup bug");
1392 return safe_strncpy(t,s,n);
1396 #if defined BB_IFCONFIG || defined BB_ROUTE || defined BB_NFSMOUNT || \
1397 defined BB_FEATURE_MOUNT_LOOP
1398 /* Like strncpy but make sure the resulting string is always 0 terminated. */
1399 extern char * safe_strncpy(char *dst, const char *src, size_t size)
1402 return strncpy(dst, src, size-1);
1406 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1407 extern int vdprintf(int d, const char *format, va_list ap)
1412 len = vsprintf(buf, format, ap);
1413 return write(d, buf, len);
1415 #endif /* BB_SYSLOGD */
1418 #if defined BB_FEATURE_MOUNT_LOOP
1420 #include "loop.h" /* Pull in loop device support */
1422 extern int del_loop(const char *device)
1426 if ((fd = open(device, O_RDONLY)) < 0) {
1427 perror_msg("%s", device);
1430 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1431 perror_msg("ioctl: LOOP_CLR_FD");
1438 extern int set_loop(const char *device, const char *file, int offset,
1441 struct loop_info loopinfo;
1444 mode = *loopro ? O_RDONLY : O_RDWR;
1445 if ((ffd = open(file, mode)) < 0 && !*loopro
1446 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1447 perror_msg("%s", file);
1450 if ((fd = open(device, mode)) < 0) {
1452 perror_msg("%s", device);
1455 *loopro = (mode == O_RDONLY);
1457 memset(&loopinfo, 0, sizeof(loopinfo));
1458 safe_strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1460 loopinfo.lo_offset = offset;
1462 loopinfo.lo_encrypt_key_size = 0;
1463 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1464 perror_msg("ioctl: LOOP_SET_FD");
1469 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1470 (void) ioctl(fd, LOOP_CLR_FD, 0);
1471 perror_msg("ioctl: LOOP_SET_STATUS");
1481 extern char *find_unused_loop_device(void)
1485 struct stat statbuf;
1486 struct loop_info loopinfo;
1488 for (i = 0; i <= 7; i++) {
1489 sprintf(dev, "/dev/loop%d", i);
1490 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1491 if ((fd = open(dev, O_RDONLY)) >= 0) {
1492 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1493 if (errno == ENXIO) { /* probably free */
1504 #endif /* BB_FEATURE_MOUNT_LOOP */
1506 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1507 extern int find_real_root_device_name(char* name)
1510 struct dirent *entry;
1511 struct stat statBuf, rootStat;
1512 char fileName[BUFSIZ];
1514 if (stat("/", &rootStat) != 0) {
1515 error_msg("could not stat '/'");
1519 dir = opendir("/dev");
1521 error_msg("could not open '/dev'");
1525 while((entry = readdir(dir)) != NULL) {
1527 /* Must skip ".." since that is "/", and so we
1528 * would get a false positive on ".." */
1529 if (strcmp(entry->d_name, "..") == 0)
1532 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1534 if (stat(fileName, &statBuf) != 0)
1536 /* Some char devices have the same dev_t as block
1537 * devices, so make sure this is a block device */
1538 if (! S_ISBLK(statBuf.st_mode))
1540 if (statBuf.st_rdev == rootStat.st_rdev) {
1541 strcpy(name, fileName);
1551 /* get_line_from_file() - This function reads an entire line from a text file
1552 * up to a newline. It returns a malloc'ed char * which must be stored and
1553 * free'ed by the caller. */
1554 extern char *get_line_from_file(FILE *file)
1556 static const int GROWBY = 80; /* how large we will grow strings by */
1560 char *linebuf = NULL;
1567 /* grow the line buffer as necessary */
1568 while (idx > linebufsz-2)
1569 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1570 linebuf[idx++] = (char)ch;
1571 if ((char)ch == '\n')
1583 extern void print_file(FILE *file)
1587 while ((c = getc(file)) != EOF)
1593 extern int print_file_by_name(char *filename)
1596 if ((file = wfopen(filename, "r")) == NULL)
1603 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1604 char process_escape_sequence(char **ptr)
1606 static const char charmap[] = {
1607 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', 0,
1608 '\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '\\' };
1618 for ( num_digits = 0 ; num_digits < 3 ; ++num_digits) {
1619 if ((*q < '0') || (*q > '7')) { /* not a digit? */
1622 n = n * 8 + (*q++ - '0');
1625 if (num_digits == 0) { /* mnemonic escape sequence? */
1626 for (p=charmap ; *p ; p++) {
1632 n = *(p+(sizeof(charmap)/2));
1635 /* doesn't hurt to fall through to here from mnemonic case */
1636 if (n > UCHAR_MAX) { /* is octal code too big for a char? */
1637 n /= 8; /* adjust value and */
1638 --q; /* back up one char */
1646 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1647 ! defined BB_FEATURE_USE_DEVPS_PATCH || defined BB_WGET
1648 char *get_last_path_component(char *path)
1650 char *s=path+strlen(path)-1;
1652 /* strip trailing slashes */
1653 while (s != path && *s == '/') {
1657 /* find last component */
1658 s = strrchr(path, '/');
1659 if (s == NULL || s[1] == '\0')
1666 #if defined BB_GREP || defined BB_SED
1668 void xregcomp(regex_t *preg, const char *regex, int cflags)
1671 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1672 int errmsgsz = regerror(ret, preg, NULL, 0);
1673 char *errmsg = xmalloc(errmsgsz);
1674 regerror(ret, preg, errmsg, errmsgsz);
1675 error_msg_and_die("xregcomp: %s", errmsg);
1680 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1681 FILE *wfopen(const char *path, const char *mode)
1684 if ((fp = fopen(path, mode)) == NULL) {
1685 perror_msg("%s", path);
1692 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1693 || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1694 || defined BB_WC || defined BB_CMP || defined BB_SORT || defined BB_WGET \
1695 || defined BB_MOUNT || defined BB_ROUTE
1696 FILE *xfopen(const char *path, const char *mode)
1699 if ((fp = fopen(path, mode)) == NULL)
1700 perror_msg_and_die("%s", path);
1705 static int applet_name_compare(const void *x, const void *y)
1707 const char *name = x;
1708 const struct BB_applet *applet = y;
1710 return strcmp(name, applet->name);
1713 extern size_t NUM_APPLETS;
1715 struct BB_applet *find_applet_by_name(const char *name)
1717 return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
1718 applet_name_compare);
1721 void run_applet_by_name(const char *name, int argc, char **argv)
1723 /* Do a binary search to find the applet entry given the name. */
1724 if ((applet_using = find_applet_by_name(name)) != NULL) {
1725 applet_name = applet_using->name;
1726 if (argv[1] && strcmp(argv[1], "--help") == 0)
1728 exit((*(applet_using->main)) (argc, argv));
1732 #if defined BB_DD || defined BB_TAIL || defined BB_STTY
1733 unsigned long parse_number(const char *numstr,
1734 const struct suffix_mult *suffixes)
1736 const struct suffix_mult *sm;
1737 unsigned long int ret;
1741 ret = strtoul(numstr, &end, 10);
1743 error_msg_and_die("invalid number `%s'", numstr);
1744 while (end[0] != '\0') {
1748 len = strlen(sm->suffix);
1749 if (strncmp(sm->suffix, end, len) == 0) {
1760 error_msg_and_die("invalid number `%s'", numstr);
1766 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1767 ssize_t safe_read(int fd, void *buf, size_t count)
1772 n = read(fd, buf, count);
1773 } while (n < 0 && errno == EINTR);
1779 #ifdef BB_FEATURE_HUMAN_READABLE
1780 const char *format(unsigned long val, unsigned long hr)
1782 static const char strings[] = { '0', 0, 'k', 0, 'M', 0, 'G', 0 };
1783 static const char fmt[] = "%lu";
1784 static const char fmt_u[] = "%lu.%lu%s";
1786 static char str[10];
1788 unsigned long frac __attribute__ ((unused)); /* 'may be uninitialized' warning is ok */
1793 if(val == 0) { /* This may be omitted to reduce size */
1794 return strings; /* at the cost of speed. */
1803 while ((val >= KILOBYTE) && (*u != 'G')) {
1806 frac = (((val % KILOBYTE) * 10) + (KILOBYTE/2)) / KILOBYTE;
1808 if (frac >= 10) { /* We need to round up here. */
1815 /* If f==fmt then 'frac' and 'u' are ignored and need not be set. */
1816 snprintf(str, sizeof(str), f, val, frac, u);
1822 #if defined(BB_GREP) || defined(BB_HOSTNAME) || defined(BB_SED) || defined(BB_TAR) || defined(BB_WGET) || defined(BB_XARGS)
1825 size_t len = strlen(s);
1830 if (s[len-1] == '\n')
1838 c-file-style: "linux"