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.
29 #if defined (BB_CHMOD_CHOWN_CHGRP) \
30 || defined (BB_CP_MV) \
31 || defined (BB_FIND) \
32 || defined (BB_INSMOD) \
36 /* same conditions as recursiveAction */
37 #define bb_need_name_too_long
39 #define bb_need_memory_exhausted
40 #define bb_need_full_version
41 #define BB_DECLARE_EXTERN
54 #include <sys/ioctl.h>
55 #include <sys/utsname.h> /* for uname(2) */
57 #if defined BB_FEATURE_MOUNT_LOOP
59 #include <linux/loop.h> /* Pull in loop device support */
62 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
63 * list of available filesystems used for the -t auto option */
64 #if defined BB_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
65 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
66 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
70 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
72 const char mtab_file[] = "/etc/mtab";
74 # if defined BB_FEATURE_USE_PROCFS
75 const char mtab_file[] = "/proc/mounts";
77 # if defined BB_FEATURE_USE_DEVPS_PATCH
78 const char mtab_file[] = "/dev/mtab";
80 # error With (BB_MOUNT||BB_UMOUNT||BB_DF) defined, you must define either BB_MTAB or ( BB_FEATURE_USE_PROCFS | BB_FEATURE_USE_DEVPS_PATCH)
86 extern void usage(const char *usage)
88 fprintf(stderr, "%s\n\n", full_version);
89 fprintf(stderr, "Usage: %s\n", usage);
93 extern void errorMsg(const char *s, ...)
99 fprintf(stderr, "%s: ", applet_name);
100 vfprintf(stderr, s, p);
105 extern void fatalError(const char *s, ...)
111 fprintf(stderr, "%s: ", applet_name);
112 vfprintf(stderr, s, p);
119 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
120 * so, for example, to check if the kernel is greater than 2.2.11:
121 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
123 extern int get_kernel_revision(void)
126 int major = 0, minor = 0, patch = 0;
128 if (uname(&name) == -1) {
129 perror("cannot get system information");
132 sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
133 return major * 65536 + minor * 256 + patch;
139 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
140 _syscall1(int, sysinfo, struct sysinfo *, info);
143 #if defined BB_MOUNT || defined BB_UMOUNT
146 #define __NR_umount2 52
149 /* Include our own version of <sys/mount.h>, since libc5 doesn't
150 * know about umount2 */
151 extern _syscall1(int, umount, const char *, special_file);
152 extern _syscall2(int, umount2, const char *, special_file, int, flags);
153 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
154 const char *, fstype, unsigned long int, rwflag, const void *, data);
159 #if defined (BB_CP_MV) || defined (BB_DU)
161 #define HASH_SIZE 311 /* Should be prime */
162 #define hash_inode(i) ((i) % HASH_SIZE)
164 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
167 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
168 * `ino_dev_hashtable', else return 0
170 * If NAME is a non-NULL pointer to a character pointer, and there is
171 * a match, then set *NAME to the value of the name slot in that
174 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
176 ino_dev_hashtable_bucket_t *bucket;
178 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
179 while (bucket != NULL) {
180 if ((bucket->ino == statbuf->st_ino) &&
181 (bucket->dev == statbuf->st_dev))
183 if (name) *name = bucket->name;
186 bucket = bucket->next;
191 /* Add statbuf to statbuf hash table */
192 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
196 ino_dev_hashtable_bucket_t *bucket;
198 i = hash_inode(statbuf->st_ino);
199 s = name ? strlen(name) : 0;
200 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
201 bucket->ino = statbuf->st_ino;
202 bucket->dev = statbuf->st_dev;
204 strcpy(bucket->name, name);
206 bucket->name[0] = '\0';
207 bucket->next = ino_dev_hashtable[i];
208 ino_dev_hashtable[i] = bucket;
211 /* Clear statbuf hash table */
212 void reset_ino_dev_hashtable(void)
215 ino_dev_hashtable_bucket_t *bucket;
217 for (i = 0; i < HASH_SIZE; i++) {
218 while (ino_dev_hashtable[i] != NULL) {
219 bucket = ino_dev_hashtable[i]->next;
220 free(ino_dev_hashtable[i]);
221 ino_dev_hashtable[i] = bucket;
226 #endif /* BB_CP_MV || BB_DU */
228 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_AR)
230 * Return TRUE if a fileName is a directory.
231 * Nonexistant files return FALSE.
233 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
238 if (statBuf == NULL) {
239 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
243 if (followLinks == TRUE)
244 status = stat(fileName, statBuf);
246 status = lstat(fileName, statBuf);
248 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
261 #if defined (BB_CP_MV)
263 * Copy one file to another, while possibly preserving its modes, times, and
264 * modes. Returns TRUE if successful, or FALSE on a failure with an error
265 * message output. (Failure is not indicated if attributes cannot be set.)
269 copyFile(const char *srcName, const char *destName,
270 int setModes, int followLinks, int forceFlag)
277 struct stat srcStatBuf;
278 struct stat dstStatBuf;
279 struct utimbuf times;
281 if (followLinks == TRUE)
282 status = stat(srcName, &srcStatBuf);
284 status = lstat(srcName, &srcStatBuf);
291 if (followLinks == TRUE)
292 status = stat(destName, &dstStatBuf);
294 status = lstat(destName, &dstStatBuf);
296 if (status < 0 || forceFlag==TRUE) {
298 dstStatBuf.st_ino = -1;
299 dstStatBuf.st_dev = -1;
302 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
303 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
304 errorMsg("Copying file \"%s\" to itself\n", srcName);
308 if (S_ISDIR(srcStatBuf.st_mode)) {
309 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
310 /* Make sure the directory is writable */
311 status = mkdir(destName, 0777777 ^ umask(0));
312 if (status < 0 && errno != EEXIST) {
316 } else if (S_ISLNK(srcStatBuf.st_mode)) {
317 char link_val[BUFSIZ + 1];
320 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
321 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
322 link_size = readlink(srcName, &link_val[0], BUFSIZ);
327 link_val[link_size] = '\0';
328 status = symlink(link_val, destName);
333 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
334 if (setModes == TRUE) {
335 /* Try to set owner, but fail silently like GNU cp */
336 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
340 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
341 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
342 if (mkfifo(destName, 0644) < 0) {
346 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
347 || S_ISSOCK(srcStatBuf.st_mode)) {
348 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
349 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
353 } else if (S_ISREG(srcStatBuf.st_mode)) {
354 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
355 rfd = open(srcName, O_RDONLY);
362 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
370 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
371 if (fullWrite(wfd, buf, rcc) < 0)
379 if (close(wfd) < 0) {
384 if (setModes == TRUE) {
385 /* This is fine, since symlinks never get here */
386 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
390 if (chmod(destName, srcStatBuf.st_mode) < 0) {
394 times.actime = srcStatBuf.st_atime;
395 times.modtime = srcStatBuf.st_mtime;
396 if (utime(destName, ×) < 0) {
411 #endif /* BB_CP_MV */
415 #if defined BB_TAR || defined BB_LS
417 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
418 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
420 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
421 static const mode_t SBIT[] = {
427 /* The 9 mode bits to test */
428 static const mode_t MBIT[] = {
429 S_IRUSR, S_IWUSR, S_IXUSR,
430 S_IRGRP, S_IWGRP, S_IXGRP,
431 S_IROTH, S_IWOTH, S_IXOTH
434 #define MODE1 "rwxrwxrwx"
435 #define MODE0 "---------"
436 #define SMODE1 "..s..s..t"
437 #define SMODE0 "..S..S..T"
440 * Return the standard ls-like mode string from a file mode.
441 * This is static and so is overwritten on each call.
443 const char *modeString(int mode)
449 buf[0] = TYPECHAR(mode);
450 for (i = 0; i < 9; i++) {
452 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
454 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
458 #endif /* BB_TAR || BB_LS */
461 #if defined BB_TAR || defined BB_AR
463 * Return the standard ls-like time string from a time_t
464 * This is static and so is overwritten on each call.
466 const char *timeString(time_t timeVal)
474 str = ctime(&timeVal);
476 strcpy(buf, &str[4]);
479 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
480 strcpy(&buf[7], &str[20]);
486 #endif /* BB_TAR || BB_AR */
488 #if defined BB_TAR || defined BB_CP_MV || defined BB_AR
490 * Write all of the supplied buffer out to a file.
491 * This does multiple writes as necessary.
492 * Returns the amount written, or -1 on an error.
494 int fullWrite(int fd, const char *buf, int len)
502 cc = write(fd, buf, len);
514 #endif /* BB_TAR || BB_CP_MV || BB_AR */
517 #if defined BB_TAR || defined BB_TAIL || defined BB_AR || defined BB_SH
519 * Read all of the supplied buffer from a file.
520 * This does multiple reads as necessary.
521 * Returns the amount read, or -1 on an error.
522 * A short read is returned on an end of file.
524 int fullRead(int fd, char *buf, int len)
532 cc = read(fd, buf, len);
547 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
550 #if defined (BB_CHMOD_CHOWN_CHGRP) \
551 || defined (BB_CP_MV) \
552 || defined (BB_FIND) \
553 || defined (BB_INSMOD) \
559 * Walk down all the directories under the specified
560 * location, and do something (something specified
561 * by the fileAction and dirAction function pointers).
563 * Unfortunatly, while nftw(3) could replace this and reduce
564 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
565 * and so isn't sufficiently portable to take over since glibc2.1
566 * is so stinking huge.
568 int recursiveAction(const char *fileName,
569 int recurse, int followLinks, int depthFirst,
570 int (*fileAction) (const char *fileName,
571 struct stat * statbuf,
573 int (*dirAction) (const char *fileName,
574 struct stat * statbuf,
582 if (followLinks == TRUE)
583 status = stat(fileName, &statbuf);
585 status = lstat(fileName, &statbuf);
588 #ifdef BB_DEBUG_PRINT_SCAFFOLD
590 "status=%d followLinks=%d TRUE=%d\n",
591 status, followLinks, TRUE);
597 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
598 if (fileAction == NULL)
601 return fileAction(fileName, &statbuf, userData);
604 if (recurse == FALSE) {
605 if (S_ISDIR(statbuf.st_mode)) {
606 if (dirAction != NULL)
607 return (dirAction(fileName, &statbuf, userData));
613 if (S_ISDIR(statbuf.st_mode)) {
616 dir = opendir(fileName);
621 if (dirAction != NULL && depthFirst == FALSE) {
622 status = dirAction(fileName, &statbuf, userData);
623 if (status == FALSE) {
628 while ((next = readdir(dir)) != NULL) {
629 char nextFile[BUFSIZ + 1];
631 if ((strcmp(next->d_name, "..") == 0)
632 || (strcmp(next->d_name, ".") == 0)) {
635 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
636 errorMsg(name_too_long);
639 memset(nextFile, 0, sizeof(nextFile));
640 sprintf(nextFile, "%s/%s", fileName, next->d_name);
642 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
643 fileAction, dirAction, userData);
644 if (status == FALSE) {
649 status = closedir(dir);
654 if (dirAction != NULL && depthFirst == TRUE) {
655 status = dirAction(fileName, &statbuf, userData);
656 if (status == FALSE) {
662 if (fileAction == NULL)
665 return fileAction(fileName, &statbuf, userData);
670 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
674 #if defined (BB_TAR) || defined (BB_MKDIR) || defined (BB_AR)
676 * Attempt to create the directories along the specified path, except for
677 * the final component. The mode is given for the final directory only,
678 * while all previous ones get default protections. Errors are not reported
679 * here, as failures to restore files can be reported later.
681 extern int createPath(const char *name, int mode)
685 char buf[BUFSIZ + 1];
689 for (cp = buf; *cp == '/'; cp++);
690 cp = strchr(cp, '/');
693 cp = strchr(cp + 1, '/');
695 retVal = mkdir(buf, cp ? 0777 : mode);
696 if (retVal != 0 && errno != EEXIST) {
704 #endif /* BB_TAR || BB_MKDIR */
708 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
709 || defined (BB_MKFIFO) || defined (BB_MKNOD)
710 /* [ugoa]{+|-|=}[rwxst] */
714 extern int parse_mode(const char *s, mode_t * theMode)
718 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
731 groups |= S_ISUID | S_IRWXU;
734 groups |= S_ISGID | S_IRWXG;
740 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
746 if (groups == 0) /* The default is "all" */
748 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
751 if (isdigit(c) && c >= '0' && c <= '7' &&
752 mode == 0 && groups == 0) {
753 *theMode = strtol(--s, NULL, 8);
761 while ((c = *s++) != '\0') {
766 mode |= S_IRUSR | S_IRGRP | S_IROTH;
769 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
772 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
775 mode |= S_IXGRP | S_ISUID | S_ISGID;
789 andMode &= ~(groups);
792 orMode |= mode & groups;
795 andMode &= ~(mode & groups);
807 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
813 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
814 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
815 || defined BB_LOGNAME || defined BB_WHOAMI
817 /* This parses entries in /etc/passwd and /etc/group. This is desirable
818 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
819 * increases target size and is often not needed or wanted for embedded
822 * /etc/passwd entries look like this:
823 * root:x:0:0:root:/root:/bin/bash
824 * and /etc/group entries look like this:
827 * This uses buf as storage to hold things.
830 unsigned long my_getid(const char *filename, char *name, long id, long *gid)
833 char *rname, *start, *end, buf[128];
837 file = fopen(filename, "r");
839 /* Do not complain. It is ok for /etc/passwd and
840 * friends to be missing... */
844 while (fgets(buf, 128, file) != NULL) {
848 /* username/group name */
850 end = strchr(start, ':');
858 end = strchr(start, ':');
862 /* uid in passwd, gid in group */
864 rid = (unsigned long) strtol(start, &end, 10);
870 rgid = (unsigned long) strtol(start, &end, 10);
873 if (0 == strcmp(rname, name)) {
874 if (gid) *gid = rgid;
879 if (id != -1 && id == rid) {
880 strncpy(name, rname, 8);
881 if (gid) *gid = rgid;
890 /* returns a uid given a username */
891 long my_getpwnam(char *name)
893 return my_getid("/etc/passwd", name, -1, NULL);
896 /* returns a gid given a group name */
897 long my_getgrnam(char *name)
899 return my_getid("/etc/group", name, -1, NULL);
902 /* gets a username given a uid */
903 void my_getpwuid(char *name, long uid)
905 my_getid("/etc/passwd", name, uid, NULL);
908 /* gets a groupname given a gid */
909 void my_getgrgid(char *group, long gid)
911 my_getid("/etc/group", group, gid, NULL);
914 /* gets a gid given a user name */
915 long my_getpwnamegid(char *name)
918 my_getid("/etc/passwd", name, -1, &gid);
923 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
924 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
927 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
929 /* From <linux/kd.h> */
930 #define KDGKBTYPE 0x4B33 /* get keyboard type */
932 #define KB_101 0x02 /* this is what we always answer */
934 int is_a_console(int fd)
939 return (ioctl(fd, KDGKBTYPE, &arg) == 0
940 && ((arg == KB_101) || (arg == KB_84)));
943 static int open_a_console(char *fnam)
948 fd = open(fnam, O_RDWR);
950 /* if failed, try read-only */
951 if (fd < 0 && errno == EACCES)
952 fd = open(fnam, O_RDONLY);
954 /* if failed, try write-only */
955 if (fd < 0 && errno == EACCES)
956 fd = open(fnam, O_WRONLY);
958 /* if failed, fail */
962 /* if not a console, fail */
963 if (!is_a_console(fd)) {
973 * Get an fd for use with kbd/console ioctls.
974 * We try several things because opening /dev/console will fail
975 * if someone else used X (which does a chown on /dev/console).
977 * if tty_name is non-NULL, try this one instead.
980 int get_console_fd(char *tty_name)
985 if (-1 == (fd = open_a_console(tty_name)))
991 fd = open_a_console("/dev/tty");
995 fd = open_a_console("/dev/tty0");
999 fd = open_a_console("/dev/console");
1003 for (fd = 0; fd < 3; fd++)
1004 if (is_a_console(fd))
1007 errorMsg("Couldnt get a file descriptor referring to the console\n");
1008 return -1; /* total failure */
1012 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1015 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
1017 /* Do a case insensitive strstr() */
1018 char *stristr(char *haystack, const char *needle)
1020 int len = strlen(needle);
1023 if (!strncasecmp(haystack, needle, len))
1034 /* This tries to find a needle in a haystack, but does so by
1035 * only trying to match literal strings (look 'ma, no regexps!)
1036 * This is short, sweet, and carries _very_ little baggage,
1037 * unlike its beefier cousin in regexp.c
1040 extern int find_match(char *haystack, char *needle, int ignoreCase)
1043 if (ignoreCase == FALSE)
1044 haystack = strstr(haystack, needle);
1046 haystack = stristr(haystack, needle);
1047 if (haystack == NULL)
1053 /* This performs substitutions after a string match has been found. */
1054 extern int replace_match(char *haystack, char *needle, char *newNeedle,
1058 char *where, *slider, *slider1, *oldhayStack;
1060 if (ignoreCase == FALSE)
1061 where = strstr(haystack, needle);
1063 where = stristr(haystack, needle);
1065 if (strcmp(needle, newNeedle) == 0)
1068 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1069 while (where != NULL) {
1071 strcpy(oldhayStack, haystack);
1072 for (slider = haystack, slider1 = oldhayStack; slider != where;
1073 slider++, slider1++);
1075 haystack = strcat(haystack, newNeedle);
1076 slider1 += strlen(needle);
1077 haystack = strcat(haystack, slider1);
1078 where = strstr(slider, needle);
1088 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1091 #if defined BB_FIND || defined BB_INSMOD
1093 * Routine to see if a text string is matched by a wildcard pattern.
1094 * Returns TRUE if the text is matched, or FALSE if it is not matched
1095 * or if the pattern is invalid.
1096 * * matches zero or more characters
1097 * ? matches a single character
1098 * [abc] matches 'a', 'b' or 'c'
1099 * \c quotes character c
1100 * Adapted from code written by Ingo Wilken, and
1101 * then taken from sash, Copyright (c) 1999 by David I. Bell
1102 * Permission is granted to use, distribute, or modify this source,
1103 * provided that this copyright notice remains intact.
1104 * Permission to distribute this code under the GPL has been granted.
1106 extern int check_wildcard_match(const char *text, const char *pattern)
1108 const char *retryPat;
1109 const char *retryText;
1117 while (*text || *pattern) {
1129 while ((ch = *pattern++) != ']') {
1140 if (found == FALSE && len!=0) {
1143 if (found == TRUE) {
1144 if (strlen(pattern)==0 && len==1) {
1153 /* fall into next case */
1156 if (*text++ == '\0')
1167 /* fall into next case */
1185 if (pattern == NULL)
1191 #endif /* BB_FIND || BB_INSMOD */
1196 #if defined BB_DF || defined BB_MTAB
1198 * Given a block device, find the mount table entry if that block device
1201 * Given any other file (or directory), find the mount table entry for its
1204 extern struct mntent *findMountPoint(const char *name, const char *table)
1209 struct mntent *mountEntry;
1211 if (stat(name, &s) != 0)
1214 if ((s.st_mode & S_IFMT) == S_IFBLK)
1215 mountDevice = s.st_rdev;
1217 mountDevice = s.st_dev;
1220 if ((mountTable = setmntent(table, "r")) == 0)
1223 while ((mountEntry = getmntent(mountTable)) != 0) {
1224 if (strcmp(name, mountEntry->mnt_dir) == 0
1225 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1227 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1229 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1232 endmntent(mountTable);
1235 #endif /* BB_DF || BB_MTAB */
1239 #if defined BB_DD || defined BB_TAIL
1241 * Read a number with a possible multiplier.
1242 * Returns -1 if the number format is illegal.
1244 extern long getNum(const char *cp)
1248 if (!isDecimal(*cp))
1253 while (isDecimal(*cp))
1254 value = value * 10 + *cp++ - '0';
1258 case 'm': /* `tail' uses it traditionally */
1286 #endif /* BB_DD || BB_TAIL */
1289 #if defined BB_INIT || defined BB_SYSLOGD || defined BB_AR
1290 /* try to open up the specified device */
1291 extern int device_open(char *device, int mode)
1295 m = mode | O_NONBLOCK;
1297 /* Retry up to 5 times */
1298 for (f = 0; f < 5; f++)
1299 if ((fd = open(device, m, 0600)) >= 0)
1303 /* Reset original flags. */
1305 fcntl(fd, F_SETFL, mode);
1308 #endif /* BB_INIT BB_SYSLOGD */
1311 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1312 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1313 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1316 #if defined BB_FEATURE_USE_DEVPS_PATCH
1319 * This finds the pid of the specified process,
1320 * by using the /dev/ps device driver.
1322 * Returns a list of all matching PIDs
1324 extern pid_t* findPidByName( char* pidName)
1327 char device[] = "/dev/ps";
1329 pid_t* pid_array = NULL;
1330 pid_t* pidList=NULL;
1333 fd = open(device, O_RDONLY);
1335 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1337 /* Find out how many processes there are */
1338 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1339 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1341 /* Allocate some memory -- grab a few extras just in case
1342 * some new processes start up while we wait. The kernel will
1343 * just ignore any extras if we give it too many, and will trunc.
1344 * the list if we give it too few. */
1345 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1346 pid_array[0] = num_pids+10;
1348 /* Now grab the pid list */
1349 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1350 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1352 /* Now search for a match */
1353 for (i=1, j=0; i<pid_array[0] ; i++) {
1355 struct pid_info info;
1357 info.pid = pid_array[i];
1358 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1359 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1361 /* Make sure we only match on the process name */
1362 p=info.command_line+1;
1363 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1369 if ((strstr(info.command_line, pidName) != NULL)
1370 && (strlen(pidName) == strlen(info.command_line))) {
1371 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1373 fatalError(memory_exhausted);
1374 pidList[j++]=info.pid;
1384 if (close (fd) != 0)
1385 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1389 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1390 #if ! defined BB_FEATURE_USE_PROCFS
1391 #error Sorry, I depend on the /proc filesystem right now.
1396 * This finds the pid of the specified process.
1397 * Currently, it's implemented by rummaging through
1398 * the proc filesystem.
1400 * Returns a list of all matching PIDs
1402 extern pid_t* findPidByName( char* pidName)
1405 struct dirent *next;
1406 pid_t* pidList=NULL;
1409 dir = opendir("/proc");
1411 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1413 while ((next = readdir(dir)) != NULL) {
1419 /* If it isn't a number, we don't want it */
1420 if (!isdigit(*next->d_name))
1423 /* Now open the status file */
1424 sprintf(filename, "/proc/%s/status", next->d_name);
1425 status = fopen(filename, "r");
1429 fgets(buffer, 256, status);
1432 /* Make sure we only match on the process name */
1433 p=buffer+5; /* Skip the name */
1435 if (*p==0 || *p=='\n') {
1440 p=buffer+6; /* Skip the "Name:\t" */
1442 if ((strstr(p, pidName) != NULL)
1443 && (strlen(pidName) == strlen(p))) {
1444 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1446 fatalError(memory_exhausted);
1447 pidList[i++]=strtol(next->d_name, NULL, 0);
1454 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1455 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1458 /* this should really be farmed out to libbusybox.a */
1459 extern void *xmalloc(size_t size)
1461 void *ptr = malloc(size);
1464 fatalError(memory_exhausted);
1468 extern void *xrealloc(void *old, size_t size)
1470 void *ptr = realloc(old, size);
1472 fatalError(memory_exhausted);
1476 extern void *xcalloc(size_t nmemb, size_t size)
1478 void *ptr = calloc(nmemb, size);
1480 fatalError(memory_exhausted);
1485 #if defined BB_FEATURE_NFSMOUNT
1487 extern char * xstrdup (const char *s) {
1496 fatalError(memory_exhausted);
1502 extern char * xstrndup (const char *s, int n) {
1506 fatalError("xstrndup bug");
1517 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1518 extern int vdprintf(int d, const char *format, va_list ap)
1523 len = vsprintf(buf, format, ap);
1524 return write(d, buf, len);
1526 #endif /* BB_SYSLOGD */
1528 #if defined BB_FEATURE_MOUNT_LOOP
1529 extern int del_loop(const char *device)
1533 if ((fd = open(device, O_RDONLY)) < 0) {
1537 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1538 perror("ioctl: LOOP_CLR_FD");
1545 extern int set_loop(const char *device, const char *file, int offset,
1548 struct loop_info loopinfo;
1551 mode = *loopro ? O_RDONLY : O_RDWR;
1552 if ((ffd = open(file, mode)) < 0 && !*loopro
1553 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1557 if ((fd = open(device, mode)) < 0) {
1562 *loopro = (mode == O_RDONLY);
1564 memset(&loopinfo, 0, sizeof(loopinfo));
1565 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1566 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1568 loopinfo.lo_offset = offset;
1570 loopinfo.lo_encrypt_key_size = 0;
1571 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1572 perror("ioctl: LOOP_SET_FD");
1577 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1578 (void) ioctl(fd, LOOP_CLR_FD, 0);
1579 perror("ioctl: LOOP_SET_STATUS");
1589 extern char *find_unused_loop_device(void)
1593 struct stat statbuf;
1594 struct loop_info loopinfo;
1596 for (i = 0; i <= 7; i++) {
1597 sprintf(dev, "/dev/loop%d", i);
1598 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1599 if ((fd = open(dev, O_RDONLY)) >= 0) {
1600 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1601 if (errno == ENXIO) { /* probably free */
1612 #endif /* BB_FEATURE_MOUNT_LOOP */
1614 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1615 extern int find_real_root_device_name(char* name)
1618 struct dirent *entry;
1619 struct stat statBuf, rootStat;
1620 char fileName[BUFSIZ];
1622 if (stat("/", &rootStat) != 0) {
1623 errorMsg("could not stat '/'\n");
1627 dir = opendir("/dev");
1629 errorMsg("could not open '/dev'\n");
1633 while((entry = readdir(dir)) != NULL) {
1635 /* Must skip ".." since that is "/", and so we
1636 * would get a false positive on ".." */
1637 if (strcmp(entry->d_name, "..") == 0)
1640 sprintf( fileName, "/dev/%s", entry->d_name);
1642 if (stat(fileName, &statBuf) != 0)
1644 /* Some char devices have the same dev_t as block
1645 * devices, so make sure this is a block device */
1646 if (! S_ISBLK(statBuf.st_mode))
1648 if (statBuf.st_rdev == rootStat.st_rdev) {
1649 strcpy(name, fileName);
1659 /* get_line_from_file() - This function reads an entire line from a text file
1660 * up to a newline. It returns a malloc'ed char * which must be stored and
1661 * free'ed by the caller. */
1662 extern char *get_line_from_file(FILE *file)
1664 static const int GROWBY = 80; /* how large we will grow strings by */
1668 char *linebuf = NULL;
1675 /* grow the line buffer as necessary */
1676 if (idx > linebufsz-2)
1677 linebuf = realloc(linebuf, linebufsz += GROWBY);
1678 linebuf[idx++] = (char)ch;
1679 if ((char)ch == '\n')
1690 #if defined BB_CAT || defined BB_LSMOD
1691 extern void print_file(FILE *file)
1695 while ((c = getc(file)) != EOF)
1701 extern int print_file_by_name(char *filename)
1704 file = fopen(filename, "r");
1711 #endif /* BB_CAT || BB_LSMOD */
1713 #if defined BB_ECHO || defined BB_TR
1714 char process_escape_sequence(char **ptr)
1718 switch (c = *(*ptr)++) {
1740 case '0': case '1': case '2': case '3':
1741 case '4': case '5': case '6': case '7':
1743 if ('0' <= **ptr && **ptr <= '7') {
1744 c = c * 8 + (*(*ptr)++ - '0');
1745 if ('0' <= **ptr && **ptr <= '7')
1746 c = c * 8 + (*(*ptr)++ - '0');
1758 #if defined BB_BASENAME || defined BB_LN
1759 char *get_last_path_component(char *path)
1761 char *s=path+strlen(path)-1;
1763 /* strip trailing slashes */
1764 while (s && *s == '/') {
1768 /* find last component */
1769 s = strrchr(path, '/');
1770 if (s==NULL) return path;
1775 #if defined BB_GREP || defined BB_SED
1776 void xregcomp(regex_t *preg, const char *regex, int cflags)
1779 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1780 int errmsgsz = regerror(ret, preg, NULL, 0);
1781 char *errmsg = xmalloc(errmsgsz);
1782 regerror(ret, preg, errmsg, errmsgsz);
1783 fatalError("bb_regcomp: %s\n", errmsg);
1791 c-file-style: "linux"