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>
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 #include <sys/syscall.h>
137 _syscall1(int, sysinfo, struct sysinfo *, info);
140 #if defined BB_MOUNT || defined BB_UMOUNT
141 #include <sys/syscall.h>
144 #define __NR_umount2 52
147 /* Include our own version of <sys/mount.h>, since libc5 doesn't
148 * know about umount2 */
149 extern _syscall1(int, umount, const char *, special_file);
150 extern _syscall2(int, umount2, const char *, special_file, int, flags);
151 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
152 const char *, fstype, unsigned long int, rwflag, const void *, data);
157 #if defined (BB_CP_MV) || defined (BB_DU)
159 #define HASH_SIZE 311 /* Should be prime */
160 #define hash_inode(i) ((i) % HASH_SIZE)
162 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
165 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
166 * `ino_dev_hashtable', else return 0
168 * If NAME is a non-NULL pointer to a character pointer, and there is
169 * a match, then set *NAME to the value of the name slot in that
172 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
174 ino_dev_hashtable_bucket_t *bucket;
176 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
177 while (bucket != NULL) {
178 if ((bucket->ino == statbuf->st_ino) &&
179 (bucket->dev == statbuf->st_dev))
181 if (name) *name = bucket->name;
184 bucket = bucket->next;
189 /* Add statbuf to statbuf hash table */
190 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
194 ino_dev_hashtable_bucket_t *bucket;
196 i = hash_inode(statbuf->st_ino);
197 s = name ? strlen(name) : 0;
198 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
199 bucket->ino = statbuf->st_ino;
200 bucket->dev = statbuf->st_dev;
202 strcpy(bucket->name, name);
204 bucket->name[0] = '\0';
205 bucket->next = ino_dev_hashtable[i];
206 ino_dev_hashtable[i] = bucket;
209 /* Clear statbuf hash table */
210 void reset_ino_dev_hashtable(void)
213 ino_dev_hashtable_bucket_t *bucket;
215 for (i = 0; i < HASH_SIZE; i++) {
216 while (ino_dev_hashtable[i] != NULL) {
217 bucket = ino_dev_hashtable[i]->next;
218 free(ino_dev_hashtable[i]);
219 ino_dev_hashtable[i] = bucket;
224 #endif /* BB_CP_MV || BB_DU */
226 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
228 * Return TRUE if a fileName is a directory.
229 * Nonexistant files return FALSE.
231 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
236 if (statBuf == NULL) {
237 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
241 if (followLinks == TRUE)
242 status = stat(fileName, statBuf);
244 status = lstat(fileName, statBuf);
246 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
259 #if defined (BB_CP_MV)
261 * Copy one file to another, while possibly preserving its modes, times, and
262 * modes. Returns TRUE if successful, or FALSE on a failure with an error
263 * message output. (Failure is not indicated if attributes cannot be set.)
267 copyFile(const char *srcName, const char *destName,
268 int setModes, int followLinks, int forceFlag)
275 struct stat srcStatBuf;
276 struct stat dstStatBuf;
277 struct utimbuf times;
279 if (followLinks == TRUE)
280 status = stat(srcName, &srcStatBuf);
282 status = lstat(srcName, &srcStatBuf);
289 if (followLinks == TRUE)
290 status = stat(destName, &dstStatBuf);
292 status = lstat(destName, &dstStatBuf);
294 if (status < 0 || forceFlag==TRUE) {
296 dstStatBuf.st_ino = -1;
297 dstStatBuf.st_dev = -1;
300 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
301 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
302 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
306 if (S_ISDIR(srcStatBuf.st_mode)) {
307 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
308 /* Make sure the directory is writable */
309 status = mkdir(destName, 0777777 ^ umask(0));
310 if (status < 0 && errno != EEXIST) {
314 } else if (S_ISLNK(srcStatBuf.st_mode)) {
315 char link_val[BUFSIZ + 1];
318 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
319 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
320 link_size = readlink(srcName, &link_val[0], BUFSIZ);
325 link_val[link_size] = '\0';
326 status = symlink(link_val, destName);
331 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
332 if (setModes == TRUE) {
333 /* Try to set owner, but fail silently like GNU cp */
334 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
338 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
339 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
340 if (mkfifo(destName, 0644) < 0) {
344 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
345 || S_ISSOCK(srcStatBuf.st_mode)) {
346 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
347 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
351 } else if (S_ISREG(srcStatBuf.st_mode)) {
352 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
353 rfd = open(srcName, O_RDONLY);
360 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
368 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
369 if (fullWrite(wfd, buf, rcc) < 0)
377 if (close(wfd) < 0) {
382 if (setModes == TRUE) {
383 /* This is fine, since symlinks never get here */
384 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
388 if (chmod(destName, srcStatBuf.st_mode) < 0) {
392 times.actime = srcStatBuf.st_atime;
393 times.modtime = srcStatBuf.st_mtime;
394 if (utime(destName, ×) < 0) {
409 #endif /* BB_CP_MV */
413 #if defined BB_TAR || defined BB_LS
415 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
416 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
418 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
419 static const mode_t SBIT[] = {
425 /* The 9 mode bits to test */
426 static const mode_t MBIT[] = {
427 S_IRUSR, S_IWUSR, S_IXUSR,
428 S_IRGRP, S_IWGRP, S_IXGRP,
429 S_IROTH, S_IWOTH, S_IXOTH
432 #define MODE1 "rwxrwxrwx"
433 #define MODE0 "---------"
434 #define SMODE1 "..s..s..t"
435 #define SMODE0 "..S..S..T"
438 * Return the standard ls-like mode string from a file mode.
439 * This is static and so is overwritten on each call.
441 const char *modeString(int mode)
447 buf[0] = TYPECHAR(mode);
448 for (i = 0; i < 9; i++) {
450 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
452 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
456 #endif /* BB_TAR || BB_LS */
461 * Return the standard ls-like time string from a time_t
462 * This is static and so is overwritten on each call.
464 const char *timeString(time_t timeVal)
472 str = ctime(&timeVal);
474 strcpy(buf, &str[4]);
477 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
478 strcpy(&buf[7], &str[20]);
486 #if defined BB_TAR || defined BB_CP_MV
488 * Write all of the supplied buffer out to a file.
489 * This does multiple writes as necessary.
490 * Returns the amount written, or -1 on an error.
492 int fullWrite(int fd, const char *buf, int len)
500 cc = write(fd, buf, len);
512 #endif /* BB_TAR || BB_CP_MV */
515 #if defined BB_TAR || defined BB_TAIL
517 * Read all of the supplied buffer from a file.
518 * This does multiple reads as necessary.
519 * Returns the amount read, or -1 on an error.
520 * A short read is returned on an end of file.
522 int fullRead(int fd, char *buf, int len)
530 cc = read(fd, buf, len);
545 #endif /* BB_TAR || BB_TAIL */
548 #if defined (BB_CHMOD_CHOWN_CHGRP) \
549 || defined (BB_CP_MV) \
550 || defined (BB_FIND) \
551 || defined (BB_INSMOD) \
556 * Walk down all the directories under the specified
557 * location, and do something (something specified
558 * by the fileAction and dirAction function pointers).
560 * Unfortunatly, while nftw(3) could replace this and reduce
561 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
562 * and so isn't sufficiently portable to take over since glibc2.1
563 * is so stinking huge.
565 int recursiveAction(const char *fileName,
566 int recurse, int followLinks, int depthFirst,
567 int (*fileAction) (const char *fileName,
568 struct stat * statbuf,
570 int (*dirAction) (const char *fileName,
571 struct stat * statbuf,
579 if (followLinks == TRUE)
580 status = stat(fileName, &statbuf);
582 status = lstat(fileName, &statbuf);
585 #ifdef BB_DEBUG_PRINT_SCAFFOLD
587 "status=%d followLinks=%d TRUE=%d\n",
588 status, followLinks, TRUE);
594 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
595 if (fileAction == NULL)
598 return fileAction(fileName, &statbuf, userData);
601 if (recurse == FALSE) {
602 if (S_ISDIR(statbuf.st_mode)) {
603 if (dirAction != NULL)
604 return (dirAction(fileName, &statbuf, userData));
610 if (S_ISDIR(statbuf.st_mode)) {
613 dir = opendir(fileName);
618 if (dirAction != NULL && depthFirst == FALSE) {
619 status = dirAction(fileName, &statbuf, userData);
620 if (status == FALSE) {
625 while ((next = readdir(dir)) != NULL) {
626 char nextFile[BUFSIZ + 1];
628 if ((strcmp(next->d_name, "..") == 0)
629 || (strcmp(next->d_name, ".") == 0)) {
632 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
633 fprintf(stderr, name_too_long, "ftw");
636 memset(nextFile, 0, sizeof(nextFile));
637 sprintf(nextFile, "%s/%s", fileName, next->d_name);
639 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
640 fileAction, dirAction, userData);
646 status = closedir(dir);
651 if (dirAction != NULL && depthFirst == TRUE) {
652 status = dirAction(fileName, &statbuf, userData);
653 if (status == FALSE) {
659 if (fileAction == NULL)
662 return fileAction(fileName, &statbuf, userData);
667 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
671 #if defined (BB_TAR) || defined (BB_MKDIR)
673 * Attempt to create the directories along the specified path, except for
674 * the final component. The mode is given for the final directory only,
675 * while all previous ones get default protections. Errors are not reported
676 * here, as failures to restore files can be reported later.
678 extern int createPath(const char *name, int mode)
682 char buf[BUFSIZ + 1];
686 for (cp = buf; *cp == '/'; cp++);
687 cp = strchr(cp, '/');
690 cp = strchr(cp + 1, '/');
692 retVal = mkdir(buf, cp ? 0777 : mode);
693 if (retVal != 0 && errno != EEXIST) {
701 #endif /* BB_TAR || BB_MKDIR */
705 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
706 /* [ugoa]{+|-|=}[rwxst] */
710 extern int parse_mode(const char *s, mode_t * theMode)
714 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
727 groups |= S_ISUID | S_IRWXU;
730 groups |= S_ISGID | S_IRWXG;
736 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
742 if (groups == 0) /* The default is "all" */
744 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
747 if (isdigit(c) && c >= '0' && c <= '7' &&
748 mode == 0 && groups == 0) {
749 *theMode = strtol(--s, NULL, 8);
757 while ((c = *s++) != '\0') {
762 mode |= S_IRUSR | S_IRGRP | S_IROTH;
765 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
768 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
771 mode |= S_IXGRP | S_ISUID | S_ISGID;
785 andMode &= ~(groups);
788 orMode |= mode & groups;
791 andMode &= ~(mode & groups);
802 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
808 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS || defined BB_TAR || defined BB_ID
810 /* This parses entries in /etc/passwd and /etc/group. This is desirable
811 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
812 * increases target size and is often not needed or wanted for embedded
815 * /etc/passwd entries look like this:
816 * root:x:0:0:root:/root:/bin/bash
817 * and /etc/group entries look like this:
820 * This uses buf as storage to hold things.
823 unsigned long my_getid(const char *filename, char *name, unsigned long id, unsigned long *gid)
826 char *rname, *start, *end, buf[128];
828 unsigned long rgid = 0;
830 file = fopen(filename, "r");
832 /* Do not complain. It is ok for /etc/passwd and
833 * friends to be missing... */
837 while (fgets(buf, 128, file) != NULL) {
841 /* username/group name */
843 end = strchr(start, ':');
851 end = strchr(start, ':');
855 /* uid in passwd, gid in group */
857 rid = (unsigned long) strtol(start, &end, 10);
863 rgid = (unsigned long) strtol(start, &end, 10);
866 if (0 == strcmp(rname, name)) {
867 if (gid) *gid = rgid;
872 if (id != -1 && id == rid) {
873 strncpy(name, rname, 8);
874 if (gid) *gid = rgid;
883 /* returns a uid given a username */
884 unsigned long my_getpwnam(char *name)
886 return my_getid("/etc/passwd", name, -1, NULL);
889 /* returns a gid given a group name */
890 unsigned long my_getgrnam(char *name)
892 return my_getid("/etc/group", name, -1, NULL);
895 /* gets a username given a uid */
896 void my_getpwuid(char *name, unsigned long uid)
898 my_getid("/etc/passwd", name, uid, NULL);
901 /* gets a groupname given a gid */
902 void my_getgrgid(char *group, unsigned long gid)
904 my_getid("/etc/group", group, gid, NULL);
907 /* gets a gid given a user name */
908 unsigned long my_getpwnamegid(char *name)
911 my_getid("/etc/passwd", name, -1, &gid);
915 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR || BB_ID */
918 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
920 /* From <linux/kd.h> */
921 #define KDGKBTYPE 0x4B33 /* get keyboard type */
923 #define KB_101 0x02 /* this is what we always answer */
925 int is_a_console(int fd)
930 return (ioctl(fd, KDGKBTYPE, &arg) == 0
931 && ((arg == KB_101) || (arg == KB_84)));
934 static int open_a_console(char *fnam)
939 fd = open(fnam, O_RDWR);
941 /* if failed, try read-only */
942 if (fd < 0 && errno == EACCES)
943 fd = open(fnam, O_RDONLY);
945 /* if failed, try write-only */
946 if (fd < 0 && errno == EACCES)
947 fd = open(fnam, O_WRONLY);
949 /* if failed, fail */
953 /* if not a console, fail */
954 if (!is_a_console(fd)) {
964 * Get an fd for use with kbd/console ioctls.
965 * We try several things because opening /dev/console will fail
966 * if someone else used X (which does a chown on /dev/console).
968 * if tty_name is non-NULL, try this one instead.
971 int get_console_fd(char *tty_name)
976 if (-1 == (fd = open_a_console(tty_name)))
982 fd = open_a_console("/dev/tty");
986 fd = open_a_console("/dev/tty0");
990 fd = open_a_console("/dev/console");
994 for (fd = 0; fd < 3; fd++)
995 if (is_a_console(fd))
999 "Couldnt get a file descriptor referring to the console\n");
1000 return -1; /* total failure */
1004 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1007 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
1009 /* Do a case insensitive strstr() */
1010 char *stristr(char *haystack, const char *needle)
1012 int len = strlen(needle);
1015 if (!strncasecmp(haystack, needle, len))
1026 /* This tries to find a needle in a haystack, but does so by
1027 * only trying to match literal strings (look 'ma, no regexps!)
1028 * This is short, sweet, and carries _very_ little baggage,
1029 * unlike its beefier cousin in regexp.c
1032 extern int find_match(char *haystack, char *needle, int ignoreCase)
1035 if (ignoreCase == FALSE)
1036 haystack = strstr(haystack, needle);
1038 haystack = stristr(haystack, needle);
1039 if (haystack == NULL)
1045 /* This performs substitutions after a string match has been found. */
1046 extern int replace_match(char *haystack, char *needle, char *newNeedle,
1050 char *where, *slider, *slider1, *oldhayStack;
1052 if (ignoreCase == FALSE)
1053 where = strstr(haystack, needle);
1055 where = stristr(haystack, needle);
1057 if (strcmp(needle, newNeedle) == 0)
1060 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1061 while (where != NULL) {
1063 strcpy(oldhayStack, haystack);
1064 for (slider = haystack, slider1 = oldhayStack; slider != where;
1065 slider++, slider1++);
1067 haystack = strcat(haystack, newNeedle);
1068 slider1 += strlen(needle);
1069 haystack = strcat(haystack, slider1);
1070 where = strstr(slider, needle);
1080 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1083 #if defined BB_FIND || defined BB_INSMOD
1085 * Routine to see if a text string is matched by a wildcard pattern.
1086 * Returns TRUE if the text is matched, or FALSE if it is not matched
1087 * or if the pattern is invalid.
1088 * * matches zero or more characters
1089 * ? matches a single character
1090 * [abc] matches 'a', 'b' or 'c'
1091 * \c quotes character c
1092 * Adapted from code written by Ingo Wilken, and
1093 * then taken from sash, Copyright (c) 1999 by David I. Bell
1094 * Permission is granted to use, distribute, or modify this source,
1095 * provided that this copyright notice remains intact.
1096 * Permission to distribute this code under the GPL has been granted.
1098 extern int check_wildcard_match(const char *text, const char *pattern)
1100 const char *retryPat;
1101 const char *retryText;
1109 while (*text || *pattern) {
1121 while ((ch = *pattern++) != ']') {
1132 if (found == FALSE && len!=0) {
1135 if (found == TRUE) {
1136 if (strlen(pattern)==0 && len==1) {
1145 /* fall into next case */
1148 if (*text++ == '\0')
1159 /* fall into next case */
1177 if (pattern == NULL)
1183 #endif /* BB_FIND || BB_INSMOD */
1188 #if defined BB_DF || defined BB_MTAB
1190 * Given a block device, find the mount table entry if that block device
1193 * Given any other file (or directory), find the mount table entry for its
1196 extern struct mntent *findMountPoint(const char *name, const char *table)
1201 struct mntent *mountEntry;
1203 if (stat(name, &s) != 0)
1206 if ((s.st_mode & S_IFMT) == S_IFBLK)
1207 mountDevice = s.st_rdev;
1209 mountDevice = s.st_dev;
1212 if ((mountTable = setmntent(table, "r")) == 0)
1215 while ((mountEntry = getmntent(mountTable)) != 0) {
1216 if (strcmp(name, mountEntry->mnt_dir) == 0
1217 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1219 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1221 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1224 endmntent(mountTable);
1227 #endif /* BB_DF || BB_MTAB */
1231 #if defined BB_DD || defined BB_TAIL
1233 * Read a number with a possible multiplier.
1234 * Returns -1 if the number format is illegal.
1236 extern long getNum(const char *cp)
1240 if (!isDecimal(*cp))
1245 while (isDecimal(*cp))
1246 value = value * 10 + *cp++ - '0';
1250 case 'm': /* `tail' uses it traditionally */
1278 #endif /* BB_DD || BB_TAIL */
1281 #if defined BB_INIT || defined BB_SYSLOGD
1282 /* try to open up the specified device */
1283 extern int device_open(char *device, int mode)
1287 m = mode | O_NONBLOCK;
1289 /* Retry up to 5 times */
1290 for (f = 0; f < 5; f++)
1291 if ((fd = open(device, m, 0600)) >= 0)
1295 /* Reset original flags. */
1297 fcntl(fd, F_SETFL, mode);
1300 #endif /* BB_INIT BB_SYSLOGD */
1303 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1304 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1305 #include <linux/devps.h>
1308 #if defined BB_FEATURE_USE_DEVPS_PATCH
1311 * This finds the pid of the specified process,
1312 * by using the /dev/ps device driver.
1314 * Returns a list of all matching PIDs
1316 extern pid_t* findPidByName( char* pidName)
1319 char device[] = "/dev/ps";
1321 pid_t* pid_array = NULL;
1322 pid_t* pidList=NULL;
1325 fd = open(device, O_RDONLY);
1327 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1329 /* Find out how many processes there are */
1330 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1331 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1333 /* Allocate some memory -- grab a few extras just in case
1334 * some new processes start up while we wait. The kernel will
1335 * just ignore any extras if we give it too many, and will trunc.
1336 * the list if we give it too few. */
1337 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1338 pid_array[0] = num_pids+10;
1340 /* Now grab the pid list */
1341 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1342 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1344 /* Now search for a match */
1345 for (i=1, j=0; i<pid_array[0] ; i++) {
1347 struct pid_info info;
1349 info.pid = pid_array[i];
1350 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1351 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1353 /* Make sure we only match on the process name */
1354 p=info.command_line+1;
1355 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1361 if ((strstr(info.command_line, pidName) != NULL)
1362 && (strlen(pidName) == strlen(info.command_line))) {
1363 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1365 fatalError(memory_exhausted, "");
1366 pidList[j++]=info.pid;
1376 if (close (fd) != 0)
1377 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1381 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1382 #if ! defined BB_FEATURE_USE_PROCFS
1383 #error Sorry, I depend on the /proc filesystem right now.
1388 * This finds the pid of the specified process.
1389 * Currently, it's implemented by rummaging through
1390 * the proc filesystem.
1392 * Returns a list of all matching PIDs
1394 extern pid_t* findPidByName( char* pidName)
1397 struct dirent *next;
1398 pid_t* pidList=NULL;
1401 dir = opendir("/proc");
1403 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1405 while ((next = readdir(dir)) != NULL) {
1411 /* If it isn't a number, we don't want it */
1412 if (!isdigit(*next->d_name))
1415 /* Now open the status file */
1416 sprintf(filename, "/proc/%s/status", next->d_name);
1417 status = fopen(filename, "r");
1421 fgets(buffer, 256, status);
1424 /* Make sure we only match on the process name */
1425 p=buffer+5; /* Skip the name */
1427 if (*p==0 || *p=='\n') {
1432 p=buffer+6; /* Skip the "Name:\t" */
1434 if ((strstr(p, pidName) != NULL)
1435 && (strlen(pidName) == strlen(p))) {
1436 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1438 fatalError(memory_exhausted, "");
1439 pidList[i++]=strtol(next->d_name, NULL, 0);
1446 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1447 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1449 /* this should really be farmed out to libbusybox.a */
1450 extern void *xmalloc(size_t size)
1452 void *cp = malloc(size);
1455 fatalError(memory_exhausted, "");
1459 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1460 extern int vdprintf(int d, const char *format, va_list ap)
1465 len = vsprintf(buf, format, ap);
1466 return write(d, buf, len);
1468 #endif /* BB_SYSLOGD */
1470 #if defined BB_FEATURE_MOUNT_LOOP
1471 extern int del_loop(const char *device)
1475 if ((fd = open(device, O_RDONLY)) < 0) {
1479 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1480 perror("ioctl: LOOP_CLR_FD");
1487 extern int set_loop(const char *device, const char *file, int offset,
1490 struct loop_info loopinfo;
1493 mode = *loopro ? O_RDONLY : O_RDWR;
1494 if ((ffd = open(file, mode)) < 0 && !*loopro
1495 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1499 if ((fd = open(device, mode)) < 0) {
1504 *loopro = (mode == O_RDONLY);
1506 memset(&loopinfo, 0, sizeof(loopinfo));
1507 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1508 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1510 loopinfo.lo_offset = offset;
1512 loopinfo.lo_encrypt_key_size = 0;
1513 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1514 perror("ioctl: LOOP_SET_FD");
1519 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1520 (void) ioctl(fd, LOOP_CLR_FD, 0);
1521 perror("ioctl: LOOP_SET_STATUS");
1531 extern char *find_unused_loop_device(void)
1535 struct stat statbuf;
1536 struct loop_info loopinfo;
1538 for (i = 0; i <= 7; i++) {
1539 sprintf(dev, "/dev/loop%d", i);
1540 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1541 if ((fd = open(dev, O_RDONLY)) >= 0) {
1542 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1543 if (errno == ENXIO) { /* probably free */
1554 #endif /* BB_FEATURE_MOUNT_LOOP */
1556 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1557 extern int find_real_root_device_name(char* name)
1560 struct dirent *entry;
1561 struct stat statBuf, rootStat;
1562 char fileName[BUFSIZ];
1564 if (stat("/", &rootStat) != 0) {
1565 errorMsg("could not stat '/'\n");
1569 dir = opendir("/dev");
1571 errorMsg("could not open '/dev'\n");
1575 while((entry = readdir(dir)) != NULL) {
1577 /* Must skip ".." since that is "/", and so we
1578 * would get a false positive on ".." */
1579 if (strcmp(entry->d_name, "..") == 0)
1582 sprintf( fileName, "/dev/%s", entry->d_name);
1584 if (stat(fileName, &statBuf) != 0)
1586 /* Some char devices have the same dev_t as block
1587 * devices, so make sure this is a block device */
1588 if (! S_ISBLK(statBuf.st_mode))
1590 if (statBuf.st_rdev == rootStat.st_rdev) {
1591 strcpy(name, fileName);
1601 /* get_line_from_file() - This function reads an entire line from a text file
1602 * up to a newline. It returns a malloc'ed char * which must be stored and
1603 * free'ed by the caller. */
1604 extern char *get_line_from_file(FILE *file)
1606 static const int GROWBY = 80; /* how large we will grow strings by */
1610 char *linebuf = NULL;
1617 /* grow the line buffer as necessary */
1618 if (idx > linebufsz-2)
1619 linebuf = realloc(linebuf, linebufsz += GROWBY);
1620 linebuf[idx++] = (char)ch;
1621 if ((char)ch == '\n')
1632 #if defined BB_ECHO || defined BB_TR
1633 char process_escape_sequence(char **ptr)
1637 switch (c = *(*ptr)++) {
1659 case '0': case '1': case '2': case '3':
1660 case '4': case '5': case '6': case '7':
1662 if ('0' <= **ptr && **ptr <= '7') {
1663 c = c * 8 + (*(*ptr)++ - '0');
1664 if ('0' <= **ptr && **ptr <= '7')
1665 c = c * 8 + (*(*ptr)++ - '0');
1677 #if defined BB_BASENAME || defined BB_LN
1678 char *get_last_path_component(char *path)
1680 char *s=path+strlen(path)-1;
1682 /* strip trailing slashes */
1683 while (s && *s == '/') {
1687 /* find last component */
1688 s = strrchr(path, '/');
1689 if (s==NULL) return path;
1697 c-file-style: "linux"