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/utsname.h> /* for uname(2) */
53 #if defined BB_FEATURE_MOUNT_LOOP
55 #include <sys/ioctl.h>
56 #include <linux/loop.h>
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)
84 extern void usage(const char *usage)
86 fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
88 fprintf(stderr, "Usage: %s\n", usage);
92 extern void errorMsg(const char *s, ...)
98 vfprintf(stderr, s, p);
103 extern void fatalError(const char *s, ...)
109 vfprintf(stderr, s, p);
116 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
117 * so, for example, to check if the kernel is greater than 2.2.11:
118 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
120 extern int get_kernel_revision(void)
123 int major = 0, minor = 0, patch = 0;
125 if (uname(&name) == -1) {
126 perror("cannot get system information");
129 sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
130 return major * 65536 + minor * 256 + patch;
136 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
137 #include <sys/syscall.h>
138 #include <linux/unistd.h>
139 _syscall1(int, sysinfo, struct sysinfo *, info);
144 #if defined (BB_CP_MV) || defined (BB_DU)
146 #define HASH_SIZE 311 /* Should be prime */
147 #define hash_inode(i) ((i) % HASH_SIZE)
149 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
152 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
153 * `ino_dev_hashtable', else return 0
155 * If NAME is a non-NULL pointer to a character pointer, and there is
156 * a match, then set *NAME to the value of the name slot in that
159 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
161 ino_dev_hashtable_bucket_t *bucket;
163 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
164 while (bucket != NULL) {
165 if ((bucket->ino == statbuf->st_ino) &&
166 (bucket->dev == statbuf->st_dev))
168 if (name) *name = bucket->name;
171 bucket = bucket->next;
176 /* Add statbuf to statbuf hash table */
177 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
181 ino_dev_hashtable_bucket_t *bucket;
183 i = hash_inode(statbuf->st_ino);
184 s = name ? strlen(name) : 0;
185 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
186 bucket->ino = statbuf->st_ino;
187 bucket->dev = statbuf->st_dev;
189 strcpy(bucket->name, name);
191 bucket->name[0] = '\0';
192 bucket->next = ino_dev_hashtable[i];
193 ino_dev_hashtable[i] = bucket;
196 /* Clear statbuf hash table */
197 void reset_ino_dev_hashtable(void)
200 ino_dev_hashtable_bucket_t *bucket;
202 for (i = 0; i < HASH_SIZE; i++) {
203 while (ino_dev_hashtable[i] != NULL) {
204 bucket = ino_dev_hashtable[i]->next;
205 free(ino_dev_hashtable[i]);
206 ino_dev_hashtable[i] = bucket;
211 #endif /* BB_CP_MV || BB_DU */
213 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
215 * Return TRUE if a fileName is a directory.
216 * Nonexistant files return FALSE.
218 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
223 if (statBuf == NULL) {
224 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
228 if (followLinks == TRUE)
229 status = stat(fileName, statBuf);
231 status = lstat(fileName, statBuf);
233 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
246 #if defined (BB_CP_MV)
248 * Copy one file to another, while possibly preserving its modes, times, and
249 * modes. Returns TRUE if successful, or FALSE on a failure with an error
250 * message output. (Failure is not indicated if attributes cannot be set.)
254 copyFile(const char *srcName, const char *destName,
255 int setModes, int followLinks, int forceFlag)
262 struct stat srcStatBuf;
263 struct stat dstStatBuf;
264 struct utimbuf times;
266 if (followLinks == TRUE)
267 status = stat(srcName, &srcStatBuf);
269 status = lstat(srcName, &srcStatBuf);
276 if (followLinks == TRUE)
277 status = stat(destName, &dstStatBuf);
279 status = lstat(destName, &dstStatBuf);
281 if (status < 0 || forceFlag==TRUE) {
283 dstStatBuf.st_ino = -1;
284 dstStatBuf.st_dev = -1;
287 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
288 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
289 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
293 if (S_ISDIR(srcStatBuf.st_mode)) {
294 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
295 /* Make sure the directory is writable */
296 status = mkdir(destName, 0777777 ^ umask(0));
297 if (status < 0 && errno != EEXIST) {
301 } else if (S_ISLNK(srcStatBuf.st_mode)) {
302 char link_val[BUFSIZ + 1];
305 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
306 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
307 link_size = readlink(srcName, &link_val[0], BUFSIZ);
312 link_val[link_size] = '\0';
313 status = symlink(link_val, destName);
318 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
319 if (setModes == TRUE) {
320 /* Try to set owner, but fail silently like GNU cp */
321 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
325 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
326 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
327 if (mkfifo(destName, 0644) < 0) {
331 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
332 || S_ISSOCK(srcStatBuf.st_mode)) {
333 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
334 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
338 } else if (S_ISREG(srcStatBuf.st_mode)) {
339 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
340 rfd = open(srcName, O_RDONLY);
347 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
355 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
356 if (fullWrite(wfd, buf, rcc) < 0)
364 if (close(wfd) < 0) {
369 if (setModes == TRUE) {
370 /* This is fine, since symlinks never get here */
371 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
375 if (chmod(destName, srcStatBuf.st_mode) < 0) {
379 times.actime = srcStatBuf.st_atime;
380 times.modtime = srcStatBuf.st_mtime;
381 if (utime(destName, ×) < 0) {
396 #endif /* BB_CP_MV */
400 #if defined BB_TAR || defined BB_LS
402 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
403 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
405 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
406 static const mode_t SBIT[] = {
412 /* The 9 mode bits to test */
413 static const mode_t MBIT[] = {
414 S_IRUSR, S_IWUSR, S_IXUSR,
415 S_IRGRP, S_IWGRP, S_IXGRP,
416 S_IROTH, S_IWOTH, S_IXOTH
419 #define MODE1 "rwxrwxrwx"
420 #define MODE0 "---------"
421 #define SMODE1 "..s..s..t"
422 #define SMODE0 "..S..S..T"
425 * Return the standard ls-like mode string from a file mode.
426 * This is static and so is overwritten on each call.
428 const char *modeString(int mode)
434 buf[0] = TYPECHAR(mode);
435 for (i = 0; i < 9; i++) {
437 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
439 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
443 #endif /* BB_TAR || BB_LS */
448 * Return the standard ls-like time string from a time_t
449 * This is static and so is overwritten on each call.
451 const char *timeString(time_t timeVal)
459 str = ctime(&timeVal);
461 strcpy(buf, &str[4]);
464 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
465 strcpy(&buf[7], &str[20]);
473 #if defined BB_TAR || defined BB_CP_MV
475 * Write all of the supplied buffer out to a file.
476 * This does multiple writes as necessary.
477 * Returns the amount written, or -1 on an error.
479 int fullWrite(int fd, const char *buf, int len)
487 cc = write(fd, buf, len);
499 #endif /* BB_TAR || BB_CP_MV */
502 #if defined BB_TAR || defined BB_TAIL
504 * Read all of the supplied buffer from a file.
505 * This does multiple reads as necessary.
506 * Returns the amount read, or -1 on an error.
507 * A short read is returned on an end of file.
509 int fullRead(int fd, char *buf, int len)
517 cc = read(fd, buf, len);
532 #endif /* BB_TAR || BB_TAIL */
535 #if defined (BB_CHMOD_CHOWN_CHGRP) \
536 || defined (BB_CP_MV) \
537 || defined (BB_FIND) \
538 || defined (BB_INSMOD) \
543 * Walk down all the directories under the specified
544 * location, and do something (something specified
545 * by the fileAction and dirAction function pointers).
547 * Unfortunatly, while nftw(3) could replace this and reduce
548 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
549 * and so isn't sufficiently portable to take over since glibc2.1
550 * is so stinking huge.
552 int recursiveAction(const char *fileName,
553 int recurse, int followLinks, int depthFirst,
554 int (*fileAction) (const char *fileName,
555 struct stat * statbuf,
557 int (*dirAction) (const char *fileName,
558 struct stat * statbuf,
566 if (followLinks == TRUE)
567 status = stat(fileName, &statbuf);
569 status = lstat(fileName, &statbuf);
572 #ifdef BB_DEBUG_PRINT_SCAFFOLD
574 "status=%d followLinks=%d TRUE=%d\n",
575 status, followLinks, TRUE);
581 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
582 if (fileAction == NULL)
585 return fileAction(fileName, &statbuf, userData);
588 if (recurse == FALSE) {
589 if (S_ISDIR(statbuf.st_mode)) {
590 if (dirAction != NULL)
591 return (dirAction(fileName, &statbuf, userData));
597 if (S_ISDIR(statbuf.st_mode)) {
600 dir = opendir(fileName);
605 if (dirAction != NULL && depthFirst == FALSE) {
606 status = dirAction(fileName, &statbuf, userData);
607 if (status == FALSE) {
612 while ((next = readdir(dir)) != NULL) {
613 char nextFile[BUFSIZ + 1];
615 if ((strcmp(next->d_name, "..") == 0)
616 || (strcmp(next->d_name, ".") == 0)) {
619 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
620 fprintf(stderr, name_too_long, "ftw");
623 memset(nextFile, 0, sizeof(nextFile));
624 sprintf(nextFile, "%s/%s", fileName, next->d_name);
626 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
627 fileAction, dirAction, userData);
633 status = closedir(dir);
638 if (dirAction != NULL && depthFirst == TRUE) {
639 status = dirAction(fileName, &statbuf, userData);
640 if (status == FALSE) {
646 if (fileAction == NULL)
649 return fileAction(fileName, &statbuf, userData);
654 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
658 #if defined (BB_TAR) || defined (BB_MKDIR)
660 * Attempt to create the directories along the specified path, except for
661 * the final component. The mode is given for the final directory only,
662 * while all previous ones get default protections. Errors are not reported
663 * here, as failures to restore files can be reported later.
665 extern int createPath(const char *name, int mode)
669 char buf[BUFSIZ + 1];
673 for (cp = buf; *cp == '/'; cp++);
674 cp = strchr(cp, '/');
677 cp = strchr(cp + 1, '/');
679 retVal = mkdir(buf, cp ? 0777 : mode);
680 if (retVal != 0 && errno != EEXIST) {
688 #endif /* BB_TAR || BB_MKDIR */
692 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
693 /* [ugoa]{+|-|=}[rwxst] */
697 extern int parse_mode(const char *s, mode_t * theMode)
701 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
714 groups |= S_ISUID | S_IRWXU;
717 groups |= S_ISGID | S_IRWXG;
723 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
729 if (groups == 0) /* The default is "all" */
731 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
734 if (isdigit(c) && c >= '0' && c <= '7' &&
735 mode == 0 && groups == 0) {
736 *theMode = strtol(--s, NULL, 8);
744 while ((c = *s++) != '\0') {
749 mode |= S_IRUSR | S_IRGRP | S_IROTH;
752 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
755 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
758 mode |= S_IXGRP | S_ISUID | S_ISGID;
772 andMode &= ~(groups);
775 orMode |= mode & groups;
778 andMode &= ~(mode & groups);
789 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
795 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS || defined BB_TAR || defined BB_ID
797 /* This parses entries in /etc/passwd and /etc/group. This is desirable
798 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
799 * increases target size and is often not needed or wanted for embedded
802 * /etc/passwd entries look like this:
803 * root:x:0:0:root:/root:/bin/bash
804 * and /etc/group entries look like this:
807 * This uses buf as storage to hold things.
810 unsigned long my_getid(const char *filename, char *name, unsigned long id, unsigned long *gid)
813 char *rname, *start, *end, buf[128];
815 unsigned long rgid = 0;
817 file = fopen(filename, "r");
819 /* Do not complain. It is ok for /etc/passwd and
820 * friends to be missing... */
824 while (fgets(buf, 128, file) != NULL) {
828 /* username/group name */
830 end = strchr(start, ':');
838 end = strchr(start, ':');
842 /* uid in passwd, gid in group */
844 rid = (unsigned long) strtol(start, &end, 10);
850 rgid = (unsigned long) strtol(start, &end, 10);
853 if (0 == strcmp(rname, name)) {
854 if (gid) *gid = rgid;
859 if (id != -1 && id == rid) {
860 strncpy(name, rname, 8);
861 if (gid) *gid = rgid;
870 /* returns a uid given a username */
871 unsigned long my_getpwnam(char *name)
873 return my_getid("/etc/passwd", name, -1, NULL);
876 /* returns a gid given a group name */
877 unsigned long my_getgrnam(char *name)
879 return my_getid("/etc/group", name, -1, NULL);
882 /* gets a username given a uid */
883 void my_getpwuid(char *name, unsigned long uid)
885 my_getid("/etc/passwd", name, uid, NULL);
888 /* gets a groupname given a gid */
889 void my_getgrgid(char *group, unsigned long gid)
891 my_getid("/etc/group", group, gid, NULL);
894 /* gets a gid given a user name */
895 unsigned long my_getpwnamegid(char *name)
898 my_getid("/etc/passwd", name, -1, &gid);
902 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR || BB_ID */
905 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
908 #include <linux/kd.h>
909 #include <sys/ioctl.h>
911 int is_a_console(int fd)
916 return (ioctl(fd, KDGKBTYPE, &arg) == 0
917 && ((arg == KB_101) || (arg == KB_84)));
920 static int open_a_console(char *fnam)
925 fd = open(fnam, O_RDWR);
927 /* if failed, try read-only */
928 if (fd < 0 && errno == EACCES)
929 fd = open(fnam, O_RDONLY);
931 /* if failed, try write-only */
932 if (fd < 0 && errno == EACCES)
933 fd = open(fnam, O_WRONLY);
935 /* if failed, fail */
939 /* if not a console, fail */
940 if (!is_a_console(fd)) {
950 * Get an fd for use with kbd/console ioctls.
951 * We try several things because opening /dev/console will fail
952 * if someone else used X (which does a chown on /dev/console).
954 * if tty_name is non-NULL, try this one instead.
957 int get_console_fd(char *tty_name)
962 if (-1 == (fd = open_a_console(tty_name)))
968 fd = open_a_console("/dev/tty");
972 fd = open_a_console("/dev/tty0");
976 fd = open_a_console("/dev/console");
980 for (fd = 0; fd < 3; fd++)
981 if (is_a_console(fd))
985 "Couldnt get a file descriptor referring to the console\n");
986 return -1; /* total failure */
990 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
993 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
995 /* Do a case insensitive strstr() */
996 char *stristr(char *haystack, const char *needle)
998 int len = strlen(needle);
1001 if (!strncasecmp(haystack, needle, len))
1012 /* This tries to find a needle in a haystack, but does so by
1013 * only trying to match literal strings (look 'ma, no regexps!)
1014 * This is short, sweet, and carries _very_ little baggage,
1015 * unlike its beefier cousin in regexp.c
1018 extern int find_match(char *haystack, char *needle, int ignoreCase)
1021 if (ignoreCase == FALSE)
1022 haystack = strstr(haystack, needle);
1024 haystack = stristr(haystack, needle);
1025 if (haystack == NULL)
1031 /* This performs substitutions after a string match has been found. */
1032 extern int replace_match(char *haystack, char *needle, char *newNeedle,
1036 char *where, *slider, *slider1, *oldhayStack;
1038 if (ignoreCase == FALSE)
1039 where = strstr(haystack, needle);
1041 where = stristr(haystack, needle);
1043 if (strcmp(needle, newNeedle) == 0)
1046 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1047 while (where != NULL) {
1049 strcpy(oldhayStack, haystack);
1050 for (slider = haystack, slider1 = oldhayStack; slider != where;
1051 slider++, slider1++);
1053 haystack = strcat(haystack, newNeedle);
1054 slider1 += strlen(needle);
1055 haystack = strcat(haystack, slider1);
1056 where = strstr(slider, needle);
1066 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1069 #if defined BB_FIND || defined BB_INSMOD
1071 * Routine to see if a text string is matched by a wildcard pattern.
1072 * Returns TRUE if the text is matched, or FALSE if it is not matched
1073 * or if the pattern is invalid.
1074 * * matches zero or more characters
1075 * ? matches a single character
1076 * [abc] matches 'a', 'b' or 'c'
1077 * \c quotes character c
1078 * Adapted from code written by Ingo Wilken, and
1079 * then taken from sash, Copyright (c) 1999 by David I. Bell
1080 * Permission is granted to use, distribute, or modify this source,
1081 * provided that this copyright notice remains intact.
1082 * Permission to distribute this code under the GPL has been granted.
1084 extern int check_wildcard_match(const char *text, const char *pattern)
1086 const char *retryPat;
1087 const char *retryText;
1095 while (*text || *pattern) {
1107 while ((ch = *pattern++) != ']') {
1118 if (found == FALSE && len!=0) {
1121 if (found == TRUE) {
1122 if (strlen(pattern)==0 && len==1) {
1131 /* fall into next case */
1134 if (*text++ == '\0')
1145 /* fall into next case */
1163 if (pattern == NULL)
1169 #endif /* BB_FIND || BB_INSMOD */
1174 #if defined BB_DF || defined BB_MTAB
1176 * Given a block device, find the mount table entry if that block device
1179 * Given any other file (or directory), find the mount table entry for its
1182 extern struct mntent *findMountPoint(const char *name, const char *table)
1187 struct mntent *mountEntry;
1189 if (stat(name, &s) != 0)
1192 if ((s.st_mode & S_IFMT) == S_IFBLK)
1193 mountDevice = s.st_rdev;
1195 mountDevice = s.st_dev;
1198 if ((mountTable = setmntent(table, "r")) == 0)
1201 while ((mountEntry = getmntent(mountTable)) != 0) {
1202 if (strcmp(name, mountEntry->mnt_dir) == 0
1203 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1205 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1207 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1210 endmntent(mountTable);
1213 #endif /* BB_DF || BB_MTAB */
1217 #if defined BB_DD || defined BB_TAIL
1219 * Read a number with a possible multiplier.
1220 * Returns -1 if the number format is illegal.
1222 extern long getNum(const char *cp)
1226 if (!isDecimal(*cp))
1231 while (isDecimal(*cp))
1232 value = value * 10 + *cp++ - '0';
1236 case 'm': /* `tail' uses it traditionally */
1264 #endif /* BB_DD || BB_TAIL */
1267 #if defined BB_INIT || defined BB_SYSLOGD
1268 /* try to open up the specified device */
1269 extern int device_open(char *device, int mode)
1273 m = mode | O_NONBLOCK;
1275 /* Retry up to 5 times */
1276 for (f = 0; f < 5; f++)
1277 if ((fd = open(device, m, 0600)) >= 0)
1281 /* Reset original flags. */
1283 fcntl(fd, F_SETFL, mode);
1286 #endif /* BB_INIT BB_SYSLOGD */
1289 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1290 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1291 #include <linux/devps.h>
1294 #if defined BB_FEATURE_USE_DEVPS_PATCH
1297 * This finds the pid of the specified process,
1298 * by using the /dev/ps device driver.
1300 * Returns a list of all matching PIDs
1302 extern pid_t* findPidByName( char* pidName)
1305 char device[] = "/dev/ps";
1307 pid_t* pid_array = NULL;
1308 pid_t* pidList=NULL;
1311 fd = open(device, O_RDONLY);
1313 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1315 /* Find out how many processes there are */
1316 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1317 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1319 /* Allocate some memory -- grab a few extras just in case
1320 * some new processes start up while we wait. The kernel will
1321 * just ignore any extras if we give it too many, and will trunc.
1322 * the list if we give it too few. */
1323 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1324 pid_array[0] = num_pids+10;
1326 /* Now grab the pid list */
1327 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1328 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1330 /* Now search for a match */
1331 for (i=1, j=0; i<pid_array[0] ; i++) {
1333 struct pid_info info;
1335 info.pid = pid_array[i];
1336 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1337 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1339 /* Make sure we only match on the process name */
1340 p=info.command_line+1;
1341 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1347 if ((strstr(info.command_line, pidName) != NULL)
1348 && (strlen(pidName) == strlen(info.command_line))) {
1349 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1351 fatalError(memory_exhausted, "");
1352 pidList[j++]=info.pid;
1362 if (close (fd) != 0)
1363 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1367 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1368 #if ! defined BB_FEATURE_USE_PROCFS
1369 #error Sorry, I depend on the /proc filesystem right now.
1374 * This finds the pid of the specified process.
1375 * Currently, it's implemented by rummaging through
1376 * the proc filesystem.
1378 * Returns a list of all matching PIDs
1380 extern pid_t* findPidByName( char* pidName)
1383 struct dirent *next;
1384 pid_t* pidList=NULL;
1387 dir = opendir("/proc");
1389 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1391 while ((next = readdir(dir)) != NULL) {
1397 /* If it isn't a number, we don't want it */
1398 if (!isdigit(*next->d_name))
1401 /* Now open the status file */
1402 sprintf(filename, "/proc/%s/status", next->d_name);
1403 status = fopen(filename, "r");
1407 fgets(buffer, 256, status);
1410 /* Make sure we only match on the process name */
1411 p=buffer+5; /* Skip the name */
1413 if (*p==0 || *p=='\n') {
1418 p=buffer+6; /* Skip the "Name:\t" */
1420 if ((strstr(p, pidName) != NULL)
1421 && (strlen(pidName) == strlen(p))) {
1422 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1424 fatalError(memory_exhausted, "");
1425 pidList[i++]=strtol(next->d_name, NULL, 0);
1432 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1433 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1435 /* this should really be farmed out to libbusybox.a */
1436 extern void *xmalloc(size_t size)
1438 void *cp = malloc(size);
1441 fatalError(memory_exhausted, "");
1445 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1446 extern int vdprintf(int d, const char *format, va_list ap)
1451 len = vsprintf(buf, format, ap);
1452 return write(d, buf, len);
1454 #endif /* BB_SYSLOGD */
1456 #if defined BB_FEATURE_MOUNT_LOOP
1457 extern int del_loop(const char *device)
1461 if ((fd = open(device, O_RDONLY)) < 0) {
1465 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1466 perror("ioctl: LOOP_CLR_FD");
1473 extern int set_loop(const char *device, const char *file, int offset,
1476 struct loop_info loopinfo;
1479 mode = *loopro ? O_RDONLY : O_RDWR;
1480 if ((ffd = open(file, mode)) < 0 && !*loopro
1481 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1485 if ((fd = open(device, mode)) < 0) {
1490 *loopro = (mode == O_RDONLY);
1492 memset(&loopinfo, 0, sizeof(loopinfo));
1493 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1494 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1496 loopinfo.lo_offset = offset;
1498 loopinfo.lo_encrypt_key_size = 0;
1499 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1500 perror("ioctl: LOOP_SET_FD");
1505 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1506 (void) ioctl(fd, LOOP_CLR_FD, 0);
1507 perror("ioctl: LOOP_SET_STATUS");
1517 extern char *find_unused_loop_device(void)
1521 struct stat statbuf;
1522 struct loop_info loopinfo;
1524 for (i = 0; i <= 7; i++) {
1525 sprintf(dev, "/dev/loop%d", i);
1526 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1527 if ((fd = open(dev, O_RDONLY)) >= 0) {
1528 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1529 if (errno == ENXIO) { /* probably free */
1540 #endif /* BB_FEATURE_MOUNT_LOOP */
1542 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1543 extern int find_real_root_device_name(char* name)
1546 struct dirent *entry;
1547 struct stat statBuf, rootStat;
1548 char fileName[BUFSIZ];
1550 if (stat("/", &rootStat) != 0) {
1551 errorMsg("could not stat '/'\n");
1555 dir = opendir("/dev");
1557 errorMsg("could not open '/dev'\n");
1561 while((entry = readdir(dir)) != NULL) {
1563 /* Must skip ".." since that is "/", and so we
1564 * would get a false positive on ".." */
1565 if (strcmp(entry->d_name, "..") == 0)
1568 sprintf( fileName, "/dev/%s", entry->d_name);
1570 if (stat(fileName, &statBuf) != 0)
1572 /* Some char devices have the same dev_t as block
1573 * devices, so make sure this is a block device */
1574 if (! S_ISBLK(statBuf.st_mode))
1576 if (statBuf.st_rdev == rootStat.st_rdev) {
1577 strcpy(name, fileName);
1586 static const int GROWBY = 80; /* how large we will grow strings by */
1588 /* get_line_from_file() - This function reads an entire line from a text file
1589 * up to a newline. It returns a malloc'ed char * which must be stored and
1590 * free'ed by the caller. */
1591 extern char *get_line_from_file(FILE *file)
1595 char *linebuf = NULL;
1602 /* grow the line buffer as necessary */
1603 if (idx > linebufsz-1)
1604 linebuf = realloc(linebuf, linebufsz += GROWBY);
1605 linebuf[idx++] = (char)ch;
1606 if ((char)ch == '\n')
1617 #if defined BB_ECHO || defined BB_TR
1618 char process_escape_sequence(char **ptr)
1622 switch (c = *(*ptr)++) {
1644 case '0': case '1': case '2': case '3':
1645 case '4': case '5': case '6': case '7':
1647 if ('0' <= **ptr && **ptr <= '7') {
1648 c = c * 8 + (*(*ptr)++ - '0');
1649 if ('0' <= **ptr && **ptr <= '7')
1650 c = c * 8 + (*(*ptr)++ - '0');
1665 c-file-style: "linux"