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) \
33 || defined (BB_INSMOD)
34 /* same conditions as recursiveAction */
35 #define bb_need_name_too_long
37 #define bb_need_memory_exhausted
38 #define BB_DECLARE_EXTERN
51 #include <sys/ioctl.h>
52 #include <sys/utsname.h> /* for uname(2) */
54 #if defined BB_FEATURE_MOUNT_LOOP
56 #include <linux/loop.h> /* Pull in loop device support */
59 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
60 * list of available filesystems used for the -t auto option */
61 #if defined BB_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
62 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
63 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
67 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
68 # if defined BB_FEATURE_USE_PROCFS
69 const char mtab_file[] = "/proc/mounts";
72 const char mtab_file[] = "/etc/mtab";
74 # if defined BB_FEATURE_USE_DEVPS_PATCH
75 const char mtab_file[] = "/dev/mtab";
77 # 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)
83 extern void usage(const char *usage)
85 fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
87 fprintf(stderr, "Usage: %s\n", usage);
91 extern void errorMsg(const char *s, ...)
97 vfprintf(stderr, s, p);
102 extern void fatalError(const char *s, ...)
108 vfprintf(stderr, s, p);
115 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
116 * so, for example, to check if the kernel is greater than 2.2.11:
117 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
119 extern int get_kernel_revision(void)
122 int major = 0, minor = 0, patch = 0;
124 if (uname(&name) == -1) {
125 perror("cannot get system information");
128 sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
129 return major * 65536 + minor * 256 + patch;
135 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
136 _syscall1(int, sysinfo, struct sysinfo *, info);
139 #if defined BB_MOUNT || defined BB_UMOUNT
142 #define __NR_umount2 52
145 /* Include our own version of <sys/mount.h>, since libc5 doesn't
146 * know about umount2 */
147 extern _syscall1(int, umount, const char *, special_file);
148 extern _syscall2(int, umount2, const char *, special_file, int, flags);
149 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
150 const char *, fstype, unsigned long int, rwflag, const void *, data);
155 #if defined (BB_CP_MV) || defined (BB_DU)
157 #define HASH_SIZE 311 /* Should be prime */
158 #define hash_inode(i) ((i) % HASH_SIZE)
160 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
163 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
164 * `ino_dev_hashtable', else return 0
166 * If NAME is a non-NULL pointer to a character pointer, and there is
167 * a match, then set *NAME to the value of the name slot in that
170 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
172 ino_dev_hashtable_bucket_t *bucket;
174 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
175 while (bucket != NULL) {
176 if ((bucket->ino == statbuf->st_ino) &&
177 (bucket->dev == statbuf->st_dev))
179 if (name) *name = bucket->name;
182 bucket = bucket->next;
187 /* Add statbuf to statbuf hash table */
188 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
192 ino_dev_hashtable_bucket_t *bucket;
194 i = hash_inode(statbuf->st_ino);
195 s = name ? strlen(name) : 0;
196 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
197 bucket->ino = statbuf->st_ino;
198 bucket->dev = statbuf->st_dev;
200 strcpy(bucket->name, name);
202 bucket->name[0] = '\0';
203 bucket->next = ino_dev_hashtable[i];
204 ino_dev_hashtable[i] = bucket;
207 /* Clear statbuf hash table */
208 void reset_ino_dev_hashtable(void)
211 ino_dev_hashtable_bucket_t *bucket;
213 for (i = 0; i < HASH_SIZE; i++) {
214 while (ino_dev_hashtable[i] != NULL) {
215 bucket = ino_dev_hashtable[i]->next;
216 free(ino_dev_hashtable[i]);
217 ino_dev_hashtable[i] = bucket;
222 #endif /* BB_CP_MV || BB_DU */
224 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
226 * Return TRUE if a fileName is a directory.
227 * Nonexistant files return FALSE.
229 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
234 if (statBuf == NULL) {
235 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
239 if (followLinks == TRUE)
240 status = stat(fileName, statBuf);
242 status = lstat(fileName, statBuf);
244 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
257 #if defined (BB_CP_MV)
259 * Copy one file to another, while possibly preserving its modes, times, and
260 * modes. Returns TRUE if successful, or FALSE on a failure with an error
261 * message output. (Failure is not indicated if attributes cannot be set.)
265 copyFile(const char *srcName, const char *destName,
266 int setModes, int followLinks, int forceFlag)
273 struct stat srcStatBuf;
274 struct stat dstStatBuf;
275 struct utimbuf times;
277 if (followLinks == TRUE)
278 status = stat(srcName, &srcStatBuf);
280 status = lstat(srcName, &srcStatBuf);
287 if (followLinks == TRUE)
288 status = stat(destName, &dstStatBuf);
290 status = lstat(destName, &dstStatBuf);
292 if (status < 0 || forceFlag==TRUE) {
294 dstStatBuf.st_ino = -1;
295 dstStatBuf.st_dev = -1;
298 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
299 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
300 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
304 if (S_ISDIR(srcStatBuf.st_mode)) {
305 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
306 /* Make sure the directory is writable */
307 status = mkdir(destName, 0777777 ^ umask(0));
308 if (status < 0 && errno != EEXIST) {
312 } else if (S_ISLNK(srcStatBuf.st_mode)) {
313 char link_val[BUFSIZ + 1];
316 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
317 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
318 link_size = readlink(srcName, &link_val[0], BUFSIZ);
323 link_val[link_size] = '\0';
324 status = symlink(link_val, destName);
329 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
330 if (setModes == TRUE) {
331 /* Try to set owner, but fail silently like GNU cp */
332 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
336 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
337 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
338 if (mkfifo(destName, 0644) < 0) {
342 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
343 || S_ISSOCK(srcStatBuf.st_mode)) {
344 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
345 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
349 } else if (S_ISREG(srcStatBuf.st_mode)) {
350 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
351 rfd = open(srcName, O_RDONLY);
358 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
366 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
367 if (fullWrite(wfd, buf, rcc) < 0)
375 if (close(wfd) < 0) {
380 if (setModes == TRUE) {
381 /* This is fine, since symlinks never get here */
382 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
386 if (chmod(destName, srcStatBuf.st_mode) < 0) {
390 times.actime = srcStatBuf.st_atime;
391 times.modtime = srcStatBuf.st_mtime;
392 if (utime(destName, ×) < 0) {
407 #endif /* BB_CP_MV */
411 #if defined BB_TAR || defined BB_LS
413 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
414 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
416 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
417 static const mode_t SBIT[] = {
423 /* The 9 mode bits to test */
424 static const mode_t MBIT[] = {
425 S_IRUSR, S_IWUSR, S_IXUSR,
426 S_IRGRP, S_IWGRP, S_IXGRP,
427 S_IROTH, S_IWOTH, S_IXOTH
430 #define MODE1 "rwxrwxrwx"
431 #define MODE0 "---------"
432 #define SMODE1 "..s..s..t"
433 #define SMODE0 "..S..S..T"
436 * Return the standard ls-like mode string from a file mode.
437 * This is static and so is overwritten on each call.
439 const char *modeString(int mode)
445 buf[0] = TYPECHAR(mode);
446 for (i = 0; i < 9; i++) {
448 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
450 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
454 #endif /* BB_TAR || BB_LS */
459 * Return the standard ls-like time string from a time_t
460 * This is static and so is overwritten on each call.
462 const char *timeString(time_t timeVal)
470 str = ctime(&timeVal);
472 strcpy(buf, &str[4]);
475 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
476 strcpy(&buf[7], &str[20]);
484 #if defined BB_TAR || defined BB_CP_MV
486 * Write all of the supplied buffer out to a file.
487 * This does multiple writes as necessary.
488 * Returns the amount written, or -1 on an error.
490 int fullWrite(int fd, const char *buf, int len)
498 cc = write(fd, buf, len);
510 #endif /* BB_TAR || BB_CP_MV */
513 #if defined BB_TAR || defined BB_TAIL
515 * Read all of the supplied buffer from a file.
516 * This does multiple reads as necessary.
517 * Returns the amount read, or -1 on an error.
518 * A short read is returned on an end of file.
520 int fullRead(int fd, char *buf, int len)
528 cc = read(fd, buf, len);
543 #endif /* BB_TAR || BB_TAIL */
546 #if defined (BB_CHMOD_CHOWN_CHGRP) \
547 || defined (BB_CP_MV) \
548 || defined (BB_FIND) \
549 || defined (BB_INSMOD) \
554 * Walk down all the directories under the specified
555 * location, and do something (something specified
556 * by the fileAction and dirAction function pointers).
558 * Unfortunatly, while nftw(3) could replace this and reduce
559 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
560 * and so isn't sufficiently portable to take over since glibc2.1
561 * is so stinking huge.
563 int recursiveAction(const char *fileName,
564 int recurse, int followLinks, int depthFirst,
565 int (*fileAction) (const char *fileName,
566 struct stat * statbuf,
568 int (*dirAction) (const char *fileName,
569 struct stat * statbuf,
577 if (followLinks == TRUE)
578 status = stat(fileName, &statbuf);
580 status = lstat(fileName, &statbuf);
583 #ifdef BB_DEBUG_PRINT_SCAFFOLD
585 "status=%d followLinks=%d TRUE=%d\n",
586 status, followLinks, TRUE);
592 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
593 if (fileAction == NULL)
596 return fileAction(fileName, &statbuf, userData);
599 if (recurse == FALSE) {
600 if (S_ISDIR(statbuf.st_mode)) {
601 if (dirAction != NULL)
602 return (dirAction(fileName, &statbuf, userData));
608 if (S_ISDIR(statbuf.st_mode)) {
611 dir = opendir(fileName);
616 if (dirAction != NULL && depthFirst == FALSE) {
617 status = dirAction(fileName, &statbuf, userData);
618 if (status == FALSE) {
623 while ((next = readdir(dir)) != NULL) {
624 char nextFile[BUFSIZ + 1];
626 if ((strcmp(next->d_name, "..") == 0)
627 || (strcmp(next->d_name, ".") == 0)) {
630 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
631 fprintf(stderr, name_too_long, "ftw");
634 memset(nextFile, 0, sizeof(nextFile));
635 sprintf(nextFile, "%s/%s", fileName, next->d_name);
637 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
638 fileAction, dirAction, userData);
644 status = closedir(dir);
649 if (dirAction != NULL && depthFirst == TRUE) {
650 status = dirAction(fileName, &statbuf, userData);
651 if (status == FALSE) {
657 if (fileAction == NULL)
660 return fileAction(fileName, &statbuf, userData);
665 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
669 #if defined (BB_TAR) || defined (BB_MKDIR)
671 * Attempt to create the directories along the specified path, except for
672 * the final component. The mode is given for the final directory only,
673 * while all previous ones get default protections. Errors are not reported
674 * here, as failures to restore files can be reported later.
676 extern int createPath(const char *name, int mode)
680 char buf[BUFSIZ + 1];
684 for (cp = buf; *cp == '/'; cp++);
685 cp = strchr(cp, '/');
688 cp = strchr(cp + 1, '/');
690 retVal = mkdir(buf, cp ? 0777 : mode);
691 if (retVal != 0 && errno != EEXIST) {
699 #endif /* BB_TAR || BB_MKDIR */
703 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
704 /* [ugoa]{+|-|=}[rwxst] */
708 extern int parse_mode(const char *s, mode_t * theMode)
712 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
725 groups |= S_ISUID | S_IRWXU;
728 groups |= S_ISGID | S_IRWXG;
734 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
740 if (groups == 0) /* The default is "all" */
742 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
745 if (isdigit(c) && c >= '0' && c <= '7' &&
746 mode == 0 && groups == 0) {
747 *theMode = strtol(--s, NULL, 8);
755 while ((c = *s++) != '\0') {
760 mode |= S_IRUSR | S_IRGRP | S_IROTH;
763 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
766 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
769 mode |= S_IXGRP | S_ISUID | S_ISGID;
783 andMode &= ~(groups);
786 orMode |= mode & groups;
789 andMode &= ~(mode & groups);
800 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
806 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS || defined BB_TAR || defined BB_ID
808 /* This parses entries in /etc/passwd and /etc/group. This is desirable
809 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
810 * increases target size and is often not needed or wanted for embedded
813 * /etc/passwd entries look like this:
814 * root:x:0:0:root:/root:/bin/bash
815 * and /etc/group entries look like this:
818 * This uses buf as storage to hold things.
821 unsigned long my_getid(const char *filename, char *name, unsigned long id, unsigned long *gid)
824 char *rname, *start, *end, buf[128];
826 unsigned long rgid = 0;
828 file = fopen(filename, "r");
830 /* Do not complain. It is ok for /etc/passwd and
831 * friends to be missing... */
835 while (fgets(buf, 128, file) != NULL) {
839 /* username/group name */
841 end = strchr(start, ':');
849 end = strchr(start, ':');
853 /* uid in passwd, gid in group */
855 rid = (unsigned long) strtol(start, &end, 10);
861 rgid = (unsigned long) strtol(start, &end, 10);
864 if (0 == strcmp(rname, name)) {
865 if (gid) *gid = rgid;
870 if (id != -1 && id == rid) {
871 strncpy(name, rname, 8);
872 if (gid) *gid = rgid;
881 /* returns a uid given a username */
882 unsigned long my_getpwnam(char *name)
884 return my_getid("/etc/passwd", name, -1, NULL);
887 /* returns a gid given a group name */
888 unsigned long my_getgrnam(char *name)
890 return my_getid("/etc/group", name, -1, NULL);
893 /* gets a username given a uid */
894 void my_getpwuid(char *name, unsigned long uid)
896 my_getid("/etc/passwd", name, uid, NULL);
899 /* gets a groupname given a gid */
900 void my_getgrgid(char *group, unsigned long gid)
902 my_getid("/etc/group", group, gid, NULL);
905 /* gets a gid given a user name */
906 unsigned long my_getpwnamegid(char *name)
909 my_getid("/etc/passwd", name, -1, &gid);
913 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR || BB_ID */
916 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
918 /* From <linux/kd.h> */
919 #define KDGKBTYPE 0x4B33 /* get keyboard type */
921 #define KB_101 0x02 /* this is what we always answer */
923 int is_a_console(int fd)
928 return (ioctl(fd, KDGKBTYPE, &arg) == 0
929 && ((arg == KB_101) || (arg == KB_84)));
932 static int open_a_console(char *fnam)
937 fd = open(fnam, O_RDWR);
939 /* if failed, try read-only */
940 if (fd < 0 && errno == EACCES)
941 fd = open(fnam, O_RDONLY);
943 /* if failed, try write-only */
944 if (fd < 0 && errno == EACCES)
945 fd = open(fnam, O_WRONLY);
947 /* if failed, fail */
951 /* if not a console, fail */
952 if (!is_a_console(fd)) {
962 * Get an fd for use with kbd/console ioctls.
963 * We try several things because opening /dev/console will fail
964 * if someone else used X (which does a chown on /dev/console).
966 * if tty_name is non-NULL, try this one instead.
969 int get_console_fd(char *tty_name)
974 if (-1 == (fd = open_a_console(tty_name)))
980 fd = open_a_console("/dev/tty");
984 fd = open_a_console("/dev/tty0");
988 fd = open_a_console("/dev/console");
992 for (fd = 0; fd < 3; fd++)
993 if (is_a_console(fd))
997 "Couldnt get a file descriptor referring to the console\n");
998 return -1; /* total failure */
1002 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1005 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
1007 /* Do a case insensitive strstr() */
1008 char *stristr(char *haystack, const char *needle)
1010 int len = strlen(needle);
1013 if (!strncasecmp(haystack, needle, len))
1024 /* This tries to find a needle in a haystack, but does so by
1025 * only trying to match literal strings (look 'ma, no regexps!)
1026 * This is short, sweet, and carries _very_ little baggage,
1027 * unlike its beefier cousin in regexp.c
1030 extern int find_match(char *haystack, char *needle, int ignoreCase)
1033 if (ignoreCase == FALSE)
1034 haystack = strstr(haystack, needle);
1036 haystack = stristr(haystack, needle);
1037 if (haystack == NULL)
1043 /* This performs substitutions after a string match has been found. */
1044 extern int replace_match(char *haystack, char *needle, char *newNeedle,
1048 char *where, *slider, *slider1, *oldhayStack;
1050 if (ignoreCase == FALSE)
1051 where = strstr(haystack, needle);
1053 where = stristr(haystack, needle);
1055 if (strcmp(needle, newNeedle) == 0)
1058 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1059 while (where != NULL) {
1061 strcpy(oldhayStack, haystack);
1062 for (slider = haystack, slider1 = oldhayStack; slider != where;
1063 slider++, slider1++);
1065 haystack = strcat(haystack, newNeedle);
1066 slider1 += strlen(needle);
1067 haystack = strcat(haystack, slider1);
1068 where = strstr(slider, needle);
1078 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1081 #if defined BB_FIND || defined BB_INSMOD
1083 * Routine to see if a text string is matched by a wildcard pattern.
1084 * Returns TRUE if the text is matched, or FALSE if it is not matched
1085 * or if the pattern is invalid.
1086 * * matches zero or more characters
1087 * ? matches a single character
1088 * [abc] matches 'a', 'b' or 'c'
1089 * \c quotes character c
1090 * Adapted from code written by Ingo Wilken, and
1091 * then taken from sash, Copyright (c) 1999 by David I. Bell
1092 * Permission is granted to use, distribute, or modify this source,
1093 * provided that this copyright notice remains intact.
1094 * Permission to distribute this code under the GPL has been granted.
1096 extern int check_wildcard_match(const char *text, const char *pattern)
1098 const char *retryPat;
1099 const char *retryText;
1107 while (*text || *pattern) {
1119 while ((ch = *pattern++) != ']') {
1130 if (found == FALSE && len!=0) {
1133 if (found == TRUE) {
1134 if (strlen(pattern)==0 && len==1) {
1143 /* fall into next case */
1146 if (*text++ == '\0')
1157 /* fall into next case */
1175 if (pattern == NULL)
1181 #endif /* BB_FIND || BB_INSMOD */
1186 #if defined BB_DF || defined BB_MTAB
1188 * Given a block device, find the mount table entry if that block device
1191 * Given any other file (or directory), find the mount table entry for its
1194 extern struct mntent *findMountPoint(const char *name, const char *table)
1199 struct mntent *mountEntry;
1201 if (stat(name, &s) != 0)
1204 if ((s.st_mode & S_IFMT) == S_IFBLK)
1205 mountDevice = s.st_rdev;
1207 mountDevice = s.st_dev;
1210 if ((mountTable = setmntent(table, "r")) == 0)
1213 while ((mountEntry = getmntent(mountTable)) != 0) {
1214 if (strcmp(name, mountEntry->mnt_dir) == 0
1215 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1217 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1219 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1222 endmntent(mountTable);
1225 #endif /* BB_DF || BB_MTAB */
1229 #if defined BB_DD || defined BB_TAIL
1231 * Read a number with a possible multiplier.
1232 * Returns -1 if the number format is illegal.
1234 extern long getNum(const char *cp)
1238 if (!isDecimal(*cp))
1243 while (isDecimal(*cp))
1244 value = value * 10 + *cp++ - '0';
1248 case 'm': /* `tail' uses it traditionally */
1276 #endif /* BB_DD || BB_TAIL */
1279 #if defined BB_INIT || defined BB_SYSLOGD
1280 /* try to open up the specified device */
1281 extern int device_open(char *device, int mode)
1285 m = mode | O_NONBLOCK;
1287 /* Retry up to 5 times */
1288 for (f = 0; f < 5; f++)
1289 if ((fd = open(device, m, 0600)) >= 0)
1293 /* Reset original flags. */
1295 fcntl(fd, F_SETFL, mode);
1298 #endif /* BB_INIT BB_SYSLOGD */
1301 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1302 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1303 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1306 #if defined BB_FEATURE_USE_DEVPS_PATCH
1309 * This finds the pid of the specified process,
1310 * by using the /dev/ps device driver.
1312 * Returns a list of all matching PIDs
1314 extern pid_t* findPidByName( char* pidName)
1317 char device[] = "/dev/ps";
1319 pid_t* pid_array = NULL;
1320 pid_t* pidList=NULL;
1323 fd = open(device, O_RDONLY);
1325 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1327 /* Find out how many processes there are */
1328 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1329 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1331 /* Allocate some memory -- grab a few extras just in case
1332 * some new processes start up while we wait. The kernel will
1333 * just ignore any extras if we give it too many, and will trunc.
1334 * the list if we give it too few. */
1335 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1336 pid_array[0] = num_pids+10;
1338 /* Now grab the pid list */
1339 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1340 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1342 /* Now search for a match */
1343 for (i=1, j=0; i<pid_array[0] ; i++) {
1345 struct pid_info info;
1347 info.pid = pid_array[i];
1348 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1349 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1351 /* Make sure we only match on the process name */
1352 p=info.command_line+1;
1353 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1359 if ((strstr(info.command_line, pidName) != NULL)
1360 && (strlen(pidName) == strlen(info.command_line))) {
1361 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1363 fatalError(memory_exhausted, "");
1364 pidList[j++]=info.pid;
1374 if (close (fd) != 0)
1375 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1379 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1380 #if ! defined BB_FEATURE_USE_PROCFS
1381 #error Sorry, I depend on the /proc filesystem right now.
1386 * This finds the pid of the specified process.
1387 * Currently, it's implemented by rummaging through
1388 * the proc filesystem.
1390 * Returns a list of all matching PIDs
1392 extern pid_t* findPidByName( char* pidName)
1395 struct dirent *next;
1396 pid_t* pidList=NULL;
1399 dir = opendir("/proc");
1401 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1403 while ((next = readdir(dir)) != NULL) {
1409 /* If it isn't a number, we don't want it */
1410 if (!isdigit(*next->d_name))
1413 /* Now open the status file */
1414 sprintf(filename, "/proc/%s/status", next->d_name);
1415 status = fopen(filename, "r");
1419 fgets(buffer, 256, status);
1422 /* Make sure we only match on the process name */
1423 p=buffer+5; /* Skip the name */
1425 if (*p==0 || *p=='\n') {
1430 p=buffer+6; /* Skip the "Name:\t" */
1432 if ((strstr(p, pidName) != NULL)
1433 && (strlen(pidName) == strlen(p))) {
1434 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1436 fatalError(memory_exhausted, "");
1437 pidList[i++]=strtol(next->d_name, NULL, 0);
1444 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1445 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1447 /* this should really be farmed out to libbusybox.a */
1448 extern void *xmalloc(size_t size)
1450 void *cp = malloc(size);
1453 fatalError(memory_exhausted, "");
1457 #if defined BB_FEATURE_NFSMOUNT
1458 extern char * xstrdup (const char *s) {
1467 fatalError(memory_exhausted, "");
1472 extern char * xstrndup (const char *s, int n) {
1476 fatalError("xstrndup bug");
1487 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1488 extern int vdprintf(int d, const char *format, va_list ap)
1493 len = vsprintf(buf, format, ap);
1494 return write(d, buf, len);
1496 #endif /* BB_SYSLOGD */
1498 #if defined BB_FEATURE_MOUNT_LOOP
1499 extern int del_loop(const char *device)
1503 if ((fd = open(device, O_RDONLY)) < 0) {
1507 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1508 perror("ioctl: LOOP_CLR_FD");
1515 extern int set_loop(const char *device, const char *file, int offset,
1518 struct loop_info loopinfo;
1521 mode = *loopro ? O_RDONLY : O_RDWR;
1522 if ((ffd = open(file, mode)) < 0 && !*loopro
1523 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1527 if ((fd = open(device, mode)) < 0) {
1532 *loopro = (mode == O_RDONLY);
1534 memset(&loopinfo, 0, sizeof(loopinfo));
1535 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1536 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1538 loopinfo.lo_offset = offset;
1540 loopinfo.lo_encrypt_key_size = 0;
1541 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1542 perror("ioctl: LOOP_SET_FD");
1547 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1548 (void) ioctl(fd, LOOP_CLR_FD, 0);
1549 perror("ioctl: LOOP_SET_STATUS");
1559 extern char *find_unused_loop_device(void)
1563 struct stat statbuf;
1564 struct loop_info loopinfo;
1566 for (i = 0; i <= 7; i++) {
1567 sprintf(dev, "/dev/loop%d", i);
1568 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1569 if ((fd = open(dev, O_RDONLY)) >= 0) {
1570 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1571 if (errno == ENXIO) { /* probably free */
1582 #endif /* BB_FEATURE_MOUNT_LOOP */
1584 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1585 extern int find_real_root_device_name(char* name)
1588 struct dirent *entry;
1589 struct stat statBuf, rootStat;
1590 char fileName[BUFSIZ];
1592 if (stat("/", &rootStat) != 0) {
1593 errorMsg("could not stat '/'\n");
1597 dir = opendir("/dev");
1599 errorMsg("could not open '/dev'\n");
1603 while((entry = readdir(dir)) != NULL) {
1605 /* Must skip ".." since that is "/", and so we
1606 * would get a false positive on ".." */
1607 if (strcmp(entry->d_name, "..") == 0)
1610 sprintf( fileName, "/dev/%s", entry->d_name);
1612 if (stat(fileName, &statBuf) != 0)
1614 /* Some char devices have the same dev_t as block
1615 * devices, so make sure this is a block device */
1616 if (! S_ISBLK(statBuf.st_mode))
1618 if (statBuf.st_rdev == rootStat.st_rdev) {
1619 strcpy(name, fileName);
1629 /* get_line_from_file() - This function reads an entire line from a text file
1630 * up to a newline. It returns a malloc'ed char * which must be stored and
1631 * free'ed by the caller. */
1632 extern char *get_line_from_file(FILE *file)
1634 static const int GROWBY = 80; /* how large we will grow strings by */
1638 char *linebuf = NULL;
1645 /* grow the line buffer as necessary */
1646 if (idx > linebufsz-2)
1647 linebuf = realloc(linebuf, linebufsz += GROWBY);
1648 linebuf[idx++] = (char)ch;
1649 if ((char)ch == '\n')
1660 #if defined BB_ECHO || defined BB_TR
1661 char process_escape_sequence(char **ptr)
1665 switch (c = *(*ptr)++) {
1687 case '0': case '1': case '2': case '3':
1688 case '4': case '5': case '6': case '7':
1690 if ('0' <= **ptr && **ptr <= '7') {
1691 c = c * 8 + (*(*ptr)++ - '0');
1692 if ('0' <= **ptr && **ptr <= '7')
1693 c = c * 8 + (*(*ptr)++ - '0');
1705 #if defined BB_BASENAME || defined BB_LN
1706 char *get_last_path_component(char *path)
1708 char *s=path+strlen(path)-1;
1710 /* strip trailing slashes */
1711 while (s && *s == '/') {
1715 /* find last component */
1716 s = strrchr(path, '/');
1717 if (s==NULL) return path;
1722 #if defined BB_GREP || defined BB_SED
1723 int bb_regcomp(regex_t *preg, const char *regex, int cflags)
1726 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1727 int errmsgsz = regerror(ret, preg, NULL, 0);
1728 char *errmsg = xmalloc(errmsgsz);
1729 regerror(ret, preg, errmsg, errmsgsz);
1730 errorMsg("bb_regcomp: %s\n", errmsg);
1741 c-file-style: "linux"