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 _syscall1(int, sysinfo, struct sysinfo *, info);
143 #if defined (BB_CP_MV) || defined (BB_DU)
145 #define HASH_SIZE 311 /* Should be prime */
146 #define hash_inode(i) ((i) % HASH_SIZE)
148 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
151 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
152 * `ino_dev_hashtable', else return 0
154 * If NAME is a non-NULL pointer to a character pointer, and there is
155 * a match, then set *NAME to the value of the name slot in that
158 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
160 ino_dev_hashtable_bucket_t *bucket;
162 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
163 while (bucket != NULL) {
164 if ((bucket->ino == statbuf->st_ino) &&
165 (bucket->dev == statbuf->st_dev))
167 if (name) *name = bucket->name;
170 bucket = bucket->next;
175 /* Add statbuf to statbuf hash table */
176 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
180 ino_dev_hashtable_bucket_t *bucket;
182 i = hash_inode(statbuf->st_ino);
183 s = name ? strlen(name) : 0;
184 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
185 bucket->ino = statbuf->st_ino;
186 bucket->dev = statbuf->st_dev;
188 strcpy(bucket->name, name);
190 bucket->name[0] = '\0';
191 bucket->next = ino_dev_hashtable[i];
192 ino_dev_hashtable[i] = bucket;
195 /* Clear statbuf hash table */
196 void reset_ino_dev_hashtable(void)
199 ino_dev_hashtable_bucket_t *bucket;
201 for (i = 0; i < HASH_SIZE; i++) {
202 while (ino_dev_hashtable[i] != NULL) {
203 bucket = ino_dev_hashtable[i]->next;
204 free(ino_dev_hashtable[i]);
205 ino_dev_hashtable[i] = bucket;
210 #endif /* BB_CP_MV || BB_DU */
212 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
214 * Return TRUE if a fileName is a directory.
215 * Nonexistant files return FALSE.
217 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
222 if (statBuf == NULL) {
223 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
227 if (followLinks == TRUE)
228 status = stat(fileName, statBuf);
230 status = lstat(fileName, statBuf);
232 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
245 #if defined (BB_CP_MV)
247 * Copy one file to another, while possibly preserving its modes, times, and
248 * modes. Returns TRUE if successful, or FALSE on a failure with an error
249 * message output. (Failure is not indicated if attributes cannot be set.)
253 copyFile(const char *srcName, const char *destName,
254 int setModes, int followLinks, int forceFlag)
261 struct stat srcStatBuf;
262 struct stat dstStatBuf;
263 struct utimbuf times;
265 if (followLinks == TRUE)
266 status = stat(srcName, &srcStatBuf);
268 status = lstat(srcName, &srcStatBuf);
275 if (followLinks == TRUE)
276 status = stat(destName, &dstStatBuf);
278 status = lstat(destName, &dstStatBuf);
280 if (status < 0 || forceFlag==TRUE) {
282 dstStatBuf.st_ino = -1;
283 dstStatBuf.st_dev = -1;
286 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
287 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
288 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
292 if (S_ISDIR(srcStatBuf.st_mode)) {
293 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
294 /* Make sure the directory is writable */
295 status = mkdir(destName, 0777777 ^ umask(0));
296 if (status < 0 && errno != EEXIST) {
300 } else if (S_ISLNK(srcStatBuf.st_mode)) {
301 char link_val[BUFSIZ + 1];
304 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
305 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
306 link_size = readlink(srcName, &link_val[0], BUFSIZ);
311 link_val[link_size] = '\0';
312 status = symlink(link_val, destName);
317 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
318 if (setModes == TRUE) {
319 /* Try to set owner, but fail silently like GNU cp */
320 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
324 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
325 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
326 if (mkfifo(destName, 0644) < 0) {
330 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
331 || S_ISSOCK(srcStatBuf.st_mode)) {
332 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
333 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
337 } else if (S_ISREG(srcStatBuf.st_mode)) {
338 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
339 rfd = open(srcName, O_RDONLY);
346 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
354 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
355 if (fullWrite(wfd, buf, rcc) < 0)
363 if (close(wfd) < 0) {
368 if (setModes == TRUE) {
369 /* This is fine, since symlinks never get here */
370 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
374 if (chmod(destName, srcStatBuf.st_mode) < 0) {
378 times.actime = srcStatBuf.st_atime;
379 times.modtime = srcStatBuf.st_mtime;
380 if (utime(destName, ×) < 0) {
395 #endif /* BB_CP_MV */
399 #if defined BB_TAR || defined BB_LS
401 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
402 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
404 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
405 static const mode_t SBIT[] = {
411 /* The 9 mode bits to test */
412 static const mode_t MBIT[] = {
413 S_IRUSR, S_IWUSR, S_IXUSR,
414 S_IRGRP, S_IWGRP, S_IXGRP,
415 S_IROTH, S_IWOTH, S_IXOTH
418 #define MODE1 "rwxrwxrwx"
419 #define MODE0 "---------"
420 #define SMODE1 "..s..s..t"
421 #define SMODE0 "..S..S..T"
424 * Return the standard ls-like mode string from a file mode.
425 * This is static and so is overwritten on each call.
427 const char *modeString(int mode)
433 buf[0] = TYPECHAR(mode);
434 for (i = 0; i < 9; i++) {
436 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
438 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
442 #endif /* BB_TAR || BB_LS */
447 * Return the standard ls-like time string from a time_t
448 * This is static and so is overwritten on each call.
450 const char *timeString(time_t timeVal)
458 str = ctime(&timeVal);
460 strcpy(buf, &str[4]);
463 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
464 strcpy(&buf[7], &str[20]);
472 #if defined BB_TAR || defined BB_CP_MV
474 * Write all of the supplied buffer out to a file.
475 * This does multiple writes as necessary.
476 * Returns the amount written, or -1 on an error.
478 int fullWrite(int fd, const char *buf, int len)
486 cc = write(fd, buf, len);
498 #endif /* BB_TAR || BB_CP_MV */
501 #if defined BB_TAR || defined BB_TAIL
503 * Read all of the supplied buffer from a file.
504 * This does multiple reads as necessary.
505 * Returns the amount read, or -1 on an error.
506 * A short read is returned on an end of file.
508 int fullRead(int fd, char *buf, int len)
516 cc = read(fd, buf, len);
531 #endif /* BB_TAR || BB_TAIL */
534 #if defined (BB_CHMOD_CHOWN_CHGRP) \
535 || defined (BB_CP_MV) \
536 || defined (BB_FIND) \
537 || defined (BB_INSMOD) \
542 * Walk down all the directories under the specified
543 * location, and do something (something specified
544 * by the fileAction and dirAction function pointers).
546 * Unfortunatly, while nftw(3) could replace this and reduce
547 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
548 * and so isn't sufficiently portable to take over since glibc2.1
549 * is so stinking huge.
551 int recursiveAction(const char *fileName,
552 int recurse, int followLinks, int depthFirst,
553 int (*fileAction) (const char *fileName,
554 struct stat * statbuf,
556 int (*dirAction) (const char *fileName,
557 struct stat * statbuf,
565 if (followLinks == TRUE)
566 status = stat(fileName, &statbuf);
568 status = lstat(fileName, &statbuf);
571 #ifdef BB_DEBUG_PRINT_SCAFFOLD
573 "status=%d followLinks=%d TRUE=%d\n",
574 status, followLinks, TRUE);
580 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
581 if (fileAction == NULL)
584 return fileAction(fileName, &statbuf, userData);
587 if (recurse == FALSE) {
588 if (S_ISDIR(statbuf.st_mode)) {
589 if (dirAction != NULL)
590 return (dirAction(fileName, &statbuf, userData));
596 if (S_ISDIR(statbuf.st_mode)) {
599 dir = opendir(fileName);
604 if (dirAction != NULL && depthFirst == FALSE) {
605 status = dirAction(fileName, &statbuf, userData);
606 if (status == FALSE) {
611 while ((next = readdir(dir)) != NULL) {
612 char nextFile[BUFSIZ + 1];
614 if ((strcmp(next->d_name, "..") == 0)
615 || (strcmp(next->d_name, ".") == 0)) {
618 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
619 fprintf(stderr, name_too_long, "ftw");
622 memset(nextFile, 0, sizeof(nextFile));
623 sprintf(nextFile, "%s/%s", fileName, next->d_name);
625 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
626 fileAction, dirAction, userData);
632 status = closedir(dir);
637 if (dirAction != NULL && depthFirst == TRUE) {
638 status = dirAction(fileName, &statbuf, userData);
639 if (status == FALSE) {
645 if (fileAction == NULL)
648 return fileAction(fileName, &statbuf, userData);
653 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
657 #if defined (BB_TAR) || defined (BB_MKDIR)
659 * Attempt to create the directories along the specified path, except for
660 * the final component. The mode is given for the final directory only,
661 * while all previous ones get default protections. Errors are not reported
662 * here, as failures to restore files can be reported later.
664 extern int createPath(const char *name, int mode)
668 char buf[BUFSIZ + 1];
672 for (cp = buf; *cp == '/'; cp++);
673 cp = strchr(cp, '/');
676 cp = strchr(cp + 1, '/');
678 retVal = mkdir(buf, cp ? 0777 : mode);
679 if (retVal != 0 && errno != EEXIST) {
687 #endif /* BB_TAR || BB_MKDIR */
691 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
692 /* [ugoa]{+|-|=}[rwxst] */
696 extern int parse_mode(const char *s, mode_t * theMode)
700 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
713 groups |= S_ISUID | S_IRWXU;
716 groups |= S_ISGID | S_IRWXG;
722 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
728 if (groups == 0) /* The default is "all" */
730 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
733 if (isdigit(c) && c >= '0' && c <= '7' &&
734 mode == 0 && groups == 0) {
735 *theMode = strtol(--s, NULL, 8);
743 while ((c = *s++) != '\0') {
748 mode |= S_IRUSR | S_IRGRP | S_IROTH;
751 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
754 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
757 mode |= S_IXGRP | S_ISUID | S_ISGID;
771 andMode &= ~(groups);
774 orMode |= mode & groups;
777 andMode &= ~(mode & groups);
788 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
794 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS || defined BB_TAR || defined BB_ID
796 /* This parses entries in /etc/passwd and /etc/group. This is desirable
797 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
798 * increases target size and is often not needed or wanted for embedded
801 * /etc/passwd entries look like this:
802 * root:x:0:0:root:/root:/bin/bash
803 * and /etc/group entries look like this:
806 * This uses buf as storage to hold things.
809 unsigned long my_getid(const char *filename, char *name, unsigned long id, unsigned long *gid)
812 char *rname, *start, *end, buf[128];
814 unsigned long rgid = 0;
816 file = fopen(filename, "r");
818 /* Do not complain. It is ok for /etc/passwd and
819 * friends to be missing... */
823 while (fgets(buf, 128, file) != NULL) {
827 /* username/group name */
829 end = strchr(start, ':');
837 end = strchr(start, ':');
841 /* uid in passwd, gid in group */
843 rid = (unsigned long) strtol(start, &end, 10);
849 rgid = (unsigned long) strtol(start, &end, 10);
852 if (0 == strcmp(rname, name)) {
853 if (gid) *gid = rgid;
858 if (id != -1 && id == rid) {
859 strncpy(name, rname, 8);
860 if (gid) *gid = rgid;
869 /* returns a uid given a username */
870 unsigned long my_getpwnam(char *name)
872 return my_getid("/etc/passwd", name, -1, NULL);
875 /* returns a gid given a group name */
876 unsigned long my_getgrnam(char *name)
878 return my_getid("/etc/group", name, -1, NULL);
881 /* gets a username given a uid */
882 void my_getpwuid(char *name, unsigned long uid)
884 my_getid("/etc/passwd", name, uid, NULL);
887 /* gets a groupname given a gid */
888 void my_getgrgid(char *group, unsigned long gid)
890 my_getid("/etc/group", group, gid, NULL);
893 /* gets a gid given a user name */
894 unsigned long my_getpwnamegid(char *name)
897 my_getid("/etc/passwd", name, -1, &gid);
901 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR || BB_ID */
904 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
907 #include <linux/kd.h>
908 #include <sys/ioctl.h>
910 int is_a_console(int fd)
915 return (ioctl(fd, KDGKBTYPE, &arg) == 0
916 && ((arg == KB_101) || (arg == KB_84)));
919 static int open_a_console(char *fnam)
924 fd = open(fnam, O_RDWR);
926 /* if failed, try read-only */
927 if (fd < 0 && errno == EACCES)
928 fd = open(fnam, O_RDONLY);
930 /* if failed, try write-only */
931 if (fd < 0 && errno == EACCES)
932 fd = open(fnam, O_WRONLY);
934 /* if failed, fail */
938 /* if not a console, fail */
939 if (!is_a_console(fd)) {
949 * Get an fd for use with kbd/console ioctls.
950 * We try several things because opening /dev/console will fail
951 * if someone else used X (which does a chown on /dev/console).
953 * if tty_name is non-NULL, try this one instead.
956 int get_console_fd(char *tty_name)
961 if (-1 == (fd = open_a_console(tty_name)))
967 fd = open_a_console("/dev/tty");
971 fd = open_a_console("/dev/tty0");
975 fd = open_a_console("/dev/console");
979 for (fd = 0; fd < 3; fd++)
980 if (is_a_console(fd))
984 "Couldnt get a file descriptor referring to the console\n");
985 return -1; /* total failure */
989 #endif /* BB_CHVT || BB_DEALLOCVT */
992 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
994 /* Do a case insensitive strstr() */
995 char *stristr(char *haystack, const char *needle)
997 int len = strlen(needle);
1000 if (!strncasecmp(haystack, needle, len))
1011 /* This tries to find a needle in a haystack, but does so by
1012 * only trying to match literal strings (look 'ma, no regexps!)
1013 * This is short, sweet, and carries _very_ little baggage,
1014 * unlike its beefier cousin in regexp.c
1017 extern int find_match(char *haystack, char *needle, int ignoreCase)
1020 if (ignoreCase == FALSE)
1021 haystack = strstr(haystack, needle);
1023 haystack = stristr(haystack, needle);
1024 if (haystack == NULL)
1030 /* This performs substitutions after a string match has been found. */
1031 extern int replace_match(char *haystack, char *needle, char *newNeedle,
1035 char *where, *slider, *slider1, *oldhayStack;
1037 if (ignoreCase == FALSE)
1038 where = strstr(haystack, needle);
1040 where = stristr(haystack, needle);
1042 if (strcmp(needle, newNeedle) == 0)
1045 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1046 while (where != NULL) {
1048 strcpy(oldhayStack, haystack);
1049 for (slider = haystack, slider1 = oldhayStack; slider != where;
1050 slider++, slider1++);
1052 haystack = strcat(haystack, newNeedle);
1053 slider1 += strlen(needle);
1054 haystack = strcat(haystack, slider1);
1055 where = strstr(slider, needle);
1065 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1068 #if defined BB_FIND || defined BB_INSMOD
1070 * Routine to see if a text string is matched by a wildcard pattern.
1071 * Returns TRUE if the text is matched, or FALSE if it is not matched
1072 * or if the pattern is invalid.
1073 * * matches zero or more characters
1074 * ? matches a single character
1075 * [abc] matches 'a', 'b' or 'c'
1076 * \c quotes character c
1077 * Adapted from code written by Ingo Wilken, and
1078 * then taken from sash, Copyright (c) 1999 by David I. Bell
1079 * Permission is granted to use, distribute, or modify this source,
1080 * provided that this copyright notice remains intact.
1081 * Permission to distribute this code under the GPL has been granted.
1083 extern int check_wildcard_match(const char *text, const char *pattern)
1085 const char *retryPat;
1086 const char *retryText;
1094 while (*text || *pattern) {
1106 while ((ch = *pattern++) != ']') {
1117 if (found == FALSE && len!=0) {
1120 if (found == TRUE) {
1121 if (strlen(pattern)==0 && len==1) {
1130 /* fall into next case */
1133 if (*text++ == '\0')
1144 /* fall into next case */
1162 if (pattern == NULL)
1168 #endif /* BB_FIND || BB_INSMOD */
1173 #if defined BB_DF || defined BB_MTAB
1175 * Given a block device, find the mount table entry if that block device
1178 * Given any other file (or directory), find the mount table entry for its
1181 extern struct mntent *findMountPoint(const char *name, const char *table)
1186 struct mntent *mountEntry;
1188 if (stat(name, &s) != 0)
1191 if ((s.st_mode & S_IFMT) == S_IFBLK)
1192 mountDevice = s.st_rdev;
1194 mountDevice = s.st_dev;
1197 if ((mountTable = setmntent(table, "r")) == 0)
1200 while ((mountEntry = getmntent(mountTable)) != 0) {
1201 if (strcmp(mountEntry->mnt_fsname, "none") == 0) {
1204 if (strcmp(name, mountEntry->mnt_dir) == 0
1205 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1207 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1209 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1212 endmntent(mountTable);
1215 #endif /* BB_DF || BB_MTAB */
1219 #if defined BB_DD || defined BB_TAIL
1221 * Read a number with a possible multiplier.
1222 * Returns -1 if the number format is illegal.
1224 extern long getNum(const char *cp)
1228 if (!isDecimal(*cp))
1233 while (isDecimal(*cp))
1234 value = value * 10 + *cp++ - '0';
1238 case 'm': /* `tail' uses it traditionally */
1266 #endif /* BB_DD || BB_TAIL */
1269 #if defined BB_INIT || defined BB_SYSLOGD
1270 /* try to open up the specified device */
1271 extern int device_open(char *device, int mode)
1275 m = mode | O_NONBLOCK;
1277 /* Retry up to 5 times */
1278 for (f = 0; f < 5; f++)
1279 if ((fd = open(device, m, 0600)) >= 0)
1283 /* Reset original flags. */
1285 fcntl(fd, F_SETFL, mode);
1288 #endif /* BB_INIT BB_SYSLOGD */
1291 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1292 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1293 #include <linux/devps.h>
1296 #if defined BB_FEATURE_USE_DEVPS_PATCH
1299 * This finds the pid of the specified process,
1300 * by using the /dev/ps device driver.
1302 * Returns a list of all matching PIDs
1304 extern pid_t* findPidByName( char* pidName)
1307 char device[] = "/dev/ps";
1309 pid_t* pid_array = NULL;
1310 pid_t* pidList=NULL;
1313 fd = open(device, O_RDONLY);
1315 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1317 /* Find out how many processes there are */
1318 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1319 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1321 /* Allocate some memory -- grab a few extras just in case
1322 * some new processes start up while we wait. The kernel will
1323 * just ignore any extras if we give it too many, and will trunc.
1324 * the list if we give it too few. */
1325 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1326 pid_array[0] = num_pids+10;
1328 /* Now grab the pid list */
1329 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1330 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1332 /* Now search for a match */
1333 for (i=1; i<pid_array[0] ; i++) {
1335 struct pid_info info;
1337 info.pid = pid_array[i];
1338 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1339 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1341 /* Make sure we only match on the process name */
1342 p=info.command_line+1;
1343 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1349 if ((strstr(info.command_line, pidName) != NULL)
1350 && (strlen(pidName) == strlen(info.command_line))) {
1351 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1353 fatalError(memory_exhausted, "");
1354 pidList[j++]=info.pid;
1364 if (close (fd) != 0)
1365 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1369 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1370 #if ! defined BB_FEATURE_USE_PROCFS
1371 #error Sorry, I depend on the /proc filesystem right now.
1376 * This finds the pid of the specified process.
1377 * Currently, it's implemented by rummaging through
1378 * the proc filesystem.
1380 * Returns a list of all matching PIDs
1382 extern pid_t* findPidByName( char* pidName)
1385 struct dirent *next;
1386 pid_t* pidList=NULL;
1389 dir = opendir("/proc");
1391 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1393 while ((next = readdir(dir)) != NULL) {
1399 /* If it isn't a number, we don't want it */
1400 if (!isdigit(*next->d_name))
1403 /* Now open the status file */
1404 sprintf(filename, "/proc/%s/status", next->d_name);
1405 status = fopen(filename, "r");
1409 fgets(buffer, 256, status);
1412 /* Make sure we only match on the process name */
1413 p=buffer+5; /* Skip the name */
1415 if (*p==0 || *p=='\n') {
1420 p=buffer+6; /* Skip the "Name:\t" */
1422 if ((strstr(p, pidName) != NULL)
1423 && (strlen(pidName) == strlen(p))) {
1424 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1426 fatalError(memory_exhausted, "");
1427 pidList[i++]=strtol(next->d_name, NULL, 0);
1434 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1435 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1437 /* this should really be farmed out to libbusybox.a */
1438 extern void *xmalloc(size_t size)
1440 void *cp = malloc(size);
1443 fatalError(memory_exhausted, "");
1447 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1448 extern int vdprintf(int d, const char *format, va_list ap)
1453 len = vsprintf(buf, format, ap);
1454 return write(d, buf, len);
1456 #endif /* BB_SYSLOGD */
1458 #if defined BB_FEATURE_MOUNT_LOOP
1459 extern int del_loop(const char *device)
1463 if ((fd = open(device, O_RDONLY)) < 0) {
1467 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1468 perror("ioctl: LOOP_CLR_FD");
1475 extern int set_loop(const char *device, const char *file, int offset,
1478 struct loop_info loopinfo;
1481 mode = *loopro ? O_RDONLY : O_RDWR;
1482 if ((ffd = open(file, mode)) < 0 && !*loopro
1483 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1487 if ((fd = open(device, mode)) < 0) {
1492 *loopro = (mode == O_RDONLY);
1494 memset(&loopinfo, 0, sizeof(loopinfo));
1495 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1496 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1498 loopinfo.lo_offset = offset;
1500 loopinfo.lo_encrypt_key_size = 0;
1501 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1502 perror("ioctl: LOOP_SET_FD");
1507 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1508 (void) ioctl(fd, LOOP_CLR_FD, 0);
1509 perror("ioctl: LOOP_SET_STATUS");
1519 extern char *find_unused_loop_device(void)
1523 struct stat statbuf;
1524 struct loop_info loopinfo;
1526 for (i = 0; i <= 7; i++) {
1527 sprintf(dev, "/dev/loop%d", i);
1528 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1529 if ((fd = open(dev, O_RDONLY)) >= 0) {
1530 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1531 if (errno == ENXIO) { /* probably free */
1542 #endif /* BB_FEATURE_MOUNT_LOOP */
1544 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1545 extern int find_real_root_device_name(char* name)
1548 struct dirent *entry;
1549 struct stat statBuf, rootStat;
1550 char fileName[BUFSIZ];
1552 if (stat("/", &rootStat) != 0) {
1553 errorMsg("could not stat '/'\n");
1557 dir = opendir("/dev");
1559 errorMsg("could not open '/dev'\n");
1563 while((entry = readdir(dir)) != NULL) {
1565 /* Must skip ".." since that is "/", and so we
1566 * would get a false positive on ".." */
1567 if (strcmp(entry->d_name, "..") == 0)
1570 sprintf( fileName, "/dev/%s", entry->d_name);
1572 if (stat(fileName, &statBuf) != 0)
1574 /* Some char devices have the same dev_t as block
1575 * devices, so make sure this is a block device */
1576 if (! S_ISBLK(statBuf.st_mode))
1578 if (statBuf.st_rdev == rootStat.st_rdev) {
1579 strcpy(name, fileName);
1588 const unsigned int CSTRING_BUFFER_LENGTH = 1024;
1589 /* recursive parser that returns cstrings of arbitrary length
1593 cstring_alloc(FILE* f, int depth)
1596 char buffer[CSTRING_BUFFER_LENGTH];
1597 int target = CSTRING_BUFFER_LENGTH * depth;
1598 int c, i, len, size;
1602 while ((c = fgetc(f)) != EOF) {
1603 buffer[i] = (char) c;
1604 if (buffer[i++] == 0x0a) { break; }
1605 if (i == CSTRING_BUFFER_LENGTH) { break; }
1609 /* recurse or malloc? */
1610 if (len == CSTRING_BUFFER_LENGTH) {
1611 cstring = cstring_alloc(f, (depth + 1));
1613 /* [special case] EOF */
1614 if ((depth | len) == 0) { return NULL; }
1617 size = target + len + 1;
1618 cstring = malloc(size);
1619 if (!cstring) { return NULL; }
1620 cstring[size - 1] = 0;
1625 memcpy(&cstring[target], buffer, len);
1631 * wrapper around recursive cstring_alloc
1632 * it's the caller's responsibility to free the cstring
1635 cstring_lineFromFile(FILE *f)
1637 return cstring_alloc(f, 0);
1643 c-file-style: "linux"