1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) tons of folks. Tracking down who wrote what
6 * isn't something I'm going to worry about... If you wrote something
7 * here, please feel free to acknowledge your work.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * Based in part on code from sash, Copyright (c) 1999 by David I. Bell
24 * Permission has been granted to redistribute this code under the GPL.
29 #if defined (BB_CHMOD_CHOWN_CHGRP) \
30 || defined (BB_CP_MV) \
31 || defined (BB_FIND) \
32 || defined (BB_INSMOD) \
36 /* same conditions as recursiveAction */
37 #define bb_need_name_too_long
39 #define bb_need_memory_exhausted
40 #define bb_need_full_version
41 #define BB_DECLARE_EXTERN
53 #include <sys/ioctl.h>
54 #include <sys/utsname.h> /* for uname(2) */
56 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
57 * list of available filesystems used for the -t auto option */
58 #if defined BB_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
59 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
60 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
64 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
66 const char mtab_file[] = "/etc/mtab";
68 # if defined BB_FEATURE_USE_PROCFS
69 const char mtab_file[] = "/proc/mounts";
71 # if defined BB_FEATURE_USE_DEVPS_PATCH
72 const char mtab_file[] = "/dev/mtab";
74 # 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)
80 extern void usage(const char *usage)
82 fprintf(stderr, "%s\n\n", full_version);
83 fprintf(stderr, "Usage: %s\n", usage);
87 extern void errorMsg(const char *s, ...)
93 fprintf(stderr, "%s: ", applet_name);
94 vfprintf(stderr, s, p);
99 extern void fatalError(const char *s, ...)
105 fprintf(stderr, "%s: ", applet_name);
106 vfprintf(stderr, s, p);
113 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
114 * so, for example, to check if the kernel is greater than 2.2.11:
115 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
117 extern int get_kernel_revision(void)
120 int major = 0, minor = 0, patch = 0;
122 if (uname(&name) == -1) {
123 perror("cannot get system information");
126 sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
127 return major * 65536 + minor * 256 + patch;
133 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
134 _syscall1(int, sysinfo, struct sysinfo *, info);
137 #if defined BB_MOUNT || defined BB_UMOUNT
140 #define __NR_umount2 52
143 /* Include our own version of <sys/mount.h>, since libc5 doesn't
144 * know about umount2 */
145 extern _syscall1(int, umount, const char *, special_file);
146 extern _syscall2(int, umount2, const char *, special_file, int, flags);
147 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
148 const char *, fstype, unsigned long int, rwflag, const void *, data);
151 #if defined BB_INSMOD || defined BB_LSMOD
152 #ifndef __NR_query_module
153 #define __NR_query_module 167
155 _syscall5(int, query_module, const char *, name, int, which,
156 void *, buf, size_t, bufsize, size_t*, ret);
160 #if defined (BB_CP_MV) || defined (BB_DU)
162 #define HASH_SIZE 311 /* Should be prime */
163 #define hash_inode(i) ((i) % HASH_SIZE)
165 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
168 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
169 * `ino_dev_hashtable', else return 0
171 * If NAME is a non-NULL pointer to a character pointer, and there is
172 * a match, then set *NAME to the value of the name slot in that
175 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
177 ino_dev_hashtable_bucket_t *bucket;
179 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
180 while (bucket != NULL) {
181 if ((bucket->ino == statbuf->st_ino) &&
182 (bucket->dev == statbuf->st_dev))
184 if (name) *name = bucket->name;
187 bucket = bucket->next;
192 /* Add statbuf to statbuf hash table */
193 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
197 ino_dev_hashtable_bucket_t *bucket;
199 i = hash_inode(statbuf->st_ino);
200 s = name ? strlen(name) : 0;
201 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
202 bucket->ino = statbuf->st_ino;
203 bucket->dev = statbuf->st_dev;
205 strcpy(bucket->name, name);
207 bucket->name[0] = '\0';
208 bucket->next = ino_dev_hashtable[i];
209 ino_dev_hashtable[i] = bucket;
212 /* Clear statbuf hash table */
213 void reset_ino_dev_hashtable(void)
216 ino_dev_hashtable_bucket_t *bucket;
218 for (i = 0; i < HASH_SIZE; i++) {
219 while (ino_dev_hashtable[i] != NULL) {
220 bucket = ino_dev_hashtable[i]->next;
221 free(ino_dev_hashtable[i]);
222 ino_dev_hashtable[i] = bucket;
227 #endif /* BB_CP_MV || BB_DU */
229 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_AR)
231 * Return TRUE if a fileName is a directory.
232 * Nonexistant files return FALSE.
234 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
239 if (statBuf == NULL) {
240 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
244 if (followLinks == TRUE)
245 status = stat(fileName, statBuf);
247 status = lstat(fileName, statBuf);
249 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
262 #if defined (BB_AR) || defined BB_CP_MV
264 * Copy readSize bytes between two file descriptors
266 int copySubFile(int srcFd, int dstFd, size_t remaining)
271 while (remaining > 0) {
272 if (remaining > BUFSIZ)
276 if (fullWrite(dstFd, buffer, fullRead(srcFd, buffer, size)) < size)
285 #if defined (BB_CP_MV)
287 * Copy one file to another, while possibly preserving its modes, times, and
288 * modes. Returns TRUE if successful, or FALSE on a failure with an error
289 * message output. (Failure is not indicated if attributes cannot be set.)
293 copyFile(const char *srcName, const char *destName,
294 int setModes, int followLinks, int forceFlag)
299 struct stat srcStatBuf;
300 struct stat dstStatBuf;
301 struct utimbuf times;
303 if (followLinks == TRUE)
304 status = stat(srcName, &srcStatBuf);
306 status = lstat(srcName, &srcStatBuf);
313 if (followLinks == TRUE)
314 status = stat(destName, &dstStatBuf);
316 status = lstat(destName, &dstStatBuf);
318 if (status < 0 || forceFlag==TRUE) {
320 dstStatBuf.st_ino = -1;
321 dstStatBuf.st_dev = -1;
324 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
325 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
326 errorMsg("Copying file \"%s\" to itself\n", srcName);
330 if (S_ISDIR(srcStatBuf.st_mode)) {
331 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
332 /* Make sure the directory is writable */
333 status = mkdir(destName, 0777777 ^ umask(0));
334 if (status < 0 && errno != EEXIST) {
338 } else if (S_ISLNK(srcStatBuf.st_mode)) {
339 char link_val[BUFSIZ + 1];
342 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
343 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
344 link_size = readlink(srcName, &link_val[0], BUFSIZ);
349 link_val[link_size] = '\0';
350 status = symlink(link_val, destName);
355 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
356 if (setModes == TRUE) {
357 /* Try to set owner, but fail silently like GNU cp */
358 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
362 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
363 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
364 if (mkfifo(destName, 0644) < 0) {
368 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
369 || S_ISSOCK(srcStatBuf.st_mode)) {
370 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
371 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
375 } else if (S_ISREG(srcStatBuf.st_mode)) {
376 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
377 rfd = open(srcName, O_RDONLY);
383 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
391 if (copySubFile(rfd, wfd, srcStatBuf.st_size)==FALSE)
395 if (close(wfd) < 0) {
400 if (setModes == TRUE) {
401 /* This is fine, since symlinks never get here */
402 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
406 if (chmod(destName, srcStatBuf.st_mode) < 0) {
410 times.actime = srcStatBuf.st_atime;
411 times.modtime = srcStatBuf.st_mtime;
412 if (utime(destName, ×) < 0) {
427 #endif /* BB_CP_MV */
431 #if defined BB_TAR || defined BB_LS ||defined BB_AR
433 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
434 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
436 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
437 static const mode_t SBIT[] = {
443 /* The 9 mode bits to test */
444 static const mode_t MBIT[] = {
445 S_IRUSR, S_IWUSR, S_IXUSR,
446 S_IRGRP, S_IWGRP, S_IXGRP,
447 S_IROTH, S_IWOTH, S_IXOTH
450 #define MODE1 "rwxrwxrwx"
451 #define MODE0 "---------"
452 #define SMODE1 "..s..s..t"
453 #define SMODE0 "..S..S..T"
456 * Return the standard ls-like mode string from a file mode.
457 * This is static and so is overwritten on each call.
459 const char *modeString(int mode)
465 buf[0] = TYPECHAR(mode);
466 for (i = 0; i < 9; i++) {
468 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
470 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
474 #endif /* BB_TAR || BB_LS */
477 #if defined BB_TAR || defined BB_AR
479 * Return the standard ls-like time string from a time_t
480 * This is static and so is overwritten on each call.
482 const char *timeString(time_t timeVal)
490 str = ctime(&timeVal);
492 strcpy(buf, &str[4]);
495 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
496 strcpy(&buf[7], &str[20]);
502 #endif /* BB_TAR || BB_AR */
504 #if defined BB_TAR || defined BB_CP_MV || defined BB_AR
506 * Write all of the supplied buffer out to a file.
507 * This does multiple writes as necessary.
508 * Returns the amount written, or -1 on an error.
510 int fullWrite(int fd, const char *buf, int len)
518 cc = write(fd, buf, len);
530 #endif /* BB_TAR || BB_CP_MV || BB_AR */
533 #if defined BB_TAR || defined BB_TAIL || defined BB_AR || defined BB_SH || defined BB_CP_MV
535 * Read all of the supplied buffer from a file.
536 * This does multiple reads as necessary.
537 * Returns the amount read, or -1 on an error.
538 * A short read is returned on an end of file.
540 int fullRead(int fd, char *buf, int len)
548 cc = read(fd, buf, len);
563 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
566 #if defined (BB_CHMOD_CHOWN_CHGRP) \
567 || defined (BB_CP_MV) \
568 || defined (BB_FIND) \
569 || defined (BB_INSMOD) \
575 * Walk down all the directories under the specified
576 * location, and do something (something specified
577 * by the fileAction and dirAction function pointers).
579 * Unfortunatly, while nftw(3) could replace this and reduce
580 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
581 * and so isn't sufficiently portable to take over since glibc2.1
582 * is so stinking huge.
584 int recursiveAction(const char *fileName,
585 int recurse, int followLinks, int depthFirst,
586 int (*fileAction) (const char *fileName,
587 struct stat * statbuf,
589 int (*dirAction) (const char *fileName,
590 struct stat * statbuf,
598 if (followLinks == TRUE)
599 status = stat(fileName, &statbuf);
601 status = lstat(fileName, &statbuf);
604 #ifdef BB_DEBUG_PRINT_SCAFFOLD
606 "status=%d followLinks=%d TRUE=%d\n",
607 status, followLinks, TRUE);
613 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
614 if (fileAction == NULL)
617 return fileAction(fileName, &statbuf, userData);
620 if (recurse == FALSE) {
621 if (S_ISDIR(statbuf.st_mode)) {
622 if (dirAction != NULL)
623 return (dirAction(fileName, &statbuf, userData));
629 if (S_ISDIR(statbuf.st_mode)) {
632 dir = opendir(fileName);
637 if (dirAction != NULL && depthFirst == FALSE) {
638 status = dirAction(fileName, &statbuf, userData);
639 if (status == FALSE) {
644 while ((next = readdir(dir)) != NULL) {
645 char nextFile[BUFSIZ + 1];
647 if ((strcmp(next->d_name, "..") == 0)
648 || (strcmp(next->d_name, ".") == 0)) {
651 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
652 errorMsg(name_too_long);
655 memset(nextFile, 0, sizeof(nextFile));
656 sprintf(nextFile, "%s/%s", fileName, next->d_name);
658 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
659 fileAction, dirAction, userData);
660 if (status == FALSE) {
665 status = closedir(dir);
670 if (dirAction != NULL && depthFirst == TRUE) {
671 status = dirAction(fileName, &statbuf, userData);
672 if (status == FALSE) {
678 if (fileAction == NULL)
681 return fileAction(fileName, &statbuf, userData);
686 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
690 #if defined (BB_TAR) || defined (BB_MKDIR) || defined (BB_AR)
692 * Attempt to create the directories along the specified path, except for
693 * the final component. The mode is given for the final directory only,
694 * while all previous ones get default protections. Errors are not reported
695 * here, as failures to restore files can be reported later.
697 extern int createPath(const char *name, int mode)
701 char buf[BUFSIZ + 1];
705 for (cp = buf; *cp == '/'; cp++);
706 cp = strchr(cp, '/');
709 cp = strchr(cp + 1, '/');
711 retVal = mkdir(buf, cp ? 0777 : mode);
712 if (retVal != 0 && errno != EEXIST) {
720 #endif /* BB_TAR || BB_MKDIR */
724 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
725 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
726 /* [ugoa]{+|-|=}[rwxst] */
730 extern int parse_mode(const char *s, mode_t * theMode)
734 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
750 groups |= S_ISUID | S_IRWXU;
753 groups |= S_ISGID | S_IRWXG;
759 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
765 if (groups == 0) /* The default is "all" */
767 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
770 if (isdigit(c) && c >= '0' && c <= '7' &&
771 mode == 0 && groups == 0) {
772 *theMode = strtol(--s, NULL, 8);
780 while ((c = *s++) != '\0') {
785 mode |= S_IRUSR | S_IRGRP | S_IROTH;
788 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
791 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
794 mode |= S_IXGRP | S_ISUID | S_ISGID;
808 andMode &= ~(groups);
811 orMode |= mode & groups;
814 andMode &= ~(mode & groups);
826 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
832 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
833 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
834 || defined BB_LOGNAME || defined BB_WHOAMI
836 /* This parses entries in /etc/passwd and /etc/group. This is desirable
837 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
838 * increases target size and is often not needed or wanted for embedded
841 * /etc/passwd entries look like this:
842 * root:x:0:0:root:/root:/bin/bash
843 * and /etc/group entries look like this:
846 * This uses buf as storage to hold things.
849 unsigned long my_getid(const char *filename, char *name, long id, long *gid)
852 char *rname, *start, *end, buf[128];
856 file = fopen(filename, "r");
858 /* Do not complain. It is ok for /etc/passwd and
859 * friends to be missing... */
863 while (fgets(buf, 128, file) != NULL) {
867 /* username/group name */
869 end = strchr(start, ':');
877 end = strchr(start, ':');
881 /* uid in passwd, gid in group */
883 rid = (unsigned long) strtol(start, &end, 10);
889 rgid = (unsigned long) strtol(start, &end, 10);
892 if (0 == strcmp(rname, name)) {
893 if (gid) *gid = rgid;
898 if (id != -1 && id == rid) {
899 strncpy(name, rname, 8);
900 if (gid) *gid = rgid;
909 /* returns a uid given a username */
910 long my_getpwnam(char *name)
912 return my_getid("/etc/passwd", name, -1, NULL);
915 /* returns a gid given a group name */
916 long my_getgrnam(char *name)
918 return my_getid("/etc/group", name, -1, NULL);
921 /* gets a username given a uid */
922 void my_getpwuid(char *name, long uid)
924 my_getid("/etc/passwd", name, uid, NULL);
927 /* gets a groupname given a gid */
928 void my_getgrgid(char *group, long gid)
930 my_getid("/etc/group", group, gid, NULL);
933 /* gets a gid given a user name */
934 long my_getpwnamegid(char *name)
937 my_getid("/etc/passwd", name, -1, &gid);
942 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
943 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
946 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
948 /* From <linux/kd.h> */
949 #define KDGKBTYPE 0x4B33 /* get keyboard type */
951 #define KB_101 0x02 /* this is what we always answer */
953 int is_a_console(int fd)
958 return (ioctl(fd, KDGKBTYPE, &arg) == 0
959 && ((arg == KB_101) || (arg == KB_84)));
962 static int open_a_console(char *fnam)
967 fd = open(fnam, O_RDWR);
969 /* if failed, try read-only */
970 if (fd < 0 && errno == EACCES)
971 fd = open(fnam, O_RDONLY);
973 /* if failed, try write-only */
974 if (fd < 0 && errno == EACCES)
975 fd = open(fnam, O_WRONLY);
977 /* if failed, fail */
981 /* if not a console, fail */
982 if (!is_a_console(fd)) {
992 * Get an fd for use with kbd/console ioctls.
993 * We try several things because opening /dev/console will fail
994 * if someone else used X (which does a chown on /dev/console).
996 * if tty_name is non-NULL, try this one instead.
999 int get_console_fd(char *tty_name)
1004 if (-1 == (fd = open_a_console(tty_name)))
1010 fd = open_a_console("/dev/tty");
1014 fd = open_a_console("/dev/tty0");
1018 fd = open_a_console("/dev/console");
1022 for (fd = 0; fd < 3; fd++)
1023 if (is_a_console(fd))
1026 errorMsg("Couldnt get a file descriptor referring to the console\n");
1027 return -1; /* total failure */
1031 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1034 #if defined BB_FIND || defined BB_INSMOD
1036 * Routine to see if a text string is matched by a wildcard pattern.
1037 * Returns TRUE if the text is matched, or FALSE if it is not matched
1038 * or if the pattern is invalid.
1039 * * matches zero or more characters
1040 * ? matches a single character
1041 * [abc] matches 'a', 'b' or 'c'
1042 * \c quotes character c
1043 * Adapted from code written by Ingo Wilken, and
1044 * then taken from sash, Copyright (c) 1999 by David I. Bell
1045 * Permission is granted to use, distribute, or modify this source,
1046 * provided that this copyright notice remains intact.
1047 * Permission to distribute this code under the GPL has been granted.
1049 extern int check_wildcard_match(const char *text, const char *pattern)
1051 const char *retryPat;
1052 const char *retryText;
1060 while (*text || *pattern) {
1072 while ((ch = *pattern++) != ']') {
1083 if (found == FALSE && len!=0) {
1086 if (found == TRUE) {
1087 if (strlen(pattern)==0 && len==1) {
1096 /* fall into next case */
1099 if (*text++ == '\0')
1110 /* fall into next case */
1128 if (pattern == NULL)
1134 #endif /* BB_FIND || BB_INSMOD */
1139 #if defined BB_DF || defined BB_MTAB
1141 * Given a block device, find the mount table entry if that block device
1144 * Given any other file (or directory), find the mount table entry for its
1147 extern struct mntent *findMountPoint(const char *name, const char *table)
1152 struct mntent *mountEntry;
1154 if (stat(name, &s) != 0)
1157 if ((s.st_mode & S_IFMT) == S_IFBLK)
1158 mountDevice = s.st_rdev;
1160 mountDevice = s.st_dev;
1163 if ((mountTable = setmntent(table, "r")) == 0)
1166 while ((mountEntry = getmntent(mountTable)) != 0) {
1167 if (strcmp(name, mountEntry->mnt_dir) == 0
1168 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1170 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1172 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1175 endmntent(mountTable);
1178 #endif /* BB_DF || BB_MTAB */
1182 #if defined BB_DD || defined BB_TAIL
1184 * Read a number with a possible multiplier.
1185 * Returns -1 if the number format is illegal.
1187 extern long getNum(const char *cp)
1191 if (!isDecimal(*cp))
1196 while (isDecimal(*cp))
1197 value = value * 10 + *cp++ - '0';
1201 case 'm': /* `tail' uses it traditionally */
1229 #endif /* BB_DD || BB_TAIL */
1232 #if defined BB_INIT || defined BB_SYSLOGD
1233 /* try to open up the specified device */
1234 extern int device_open(char *device, int mode)
1238 m = mode | O_NONBLOCK;
1240 /* Retry up to 5 times */
1241 for (f = 0; f < 5; f++)
1242 if ((fd = open(device, m, 0600)) >= 0)
1246 /* Reset original flags. */
1248 fcntl(fd, F_SETFL, mode);
1251 #endif /* BB_INIT BB_SYSLOGD */
1254 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1255 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1256 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1259 #if defined BB_FEATURE_USE_DEVPS_PATCH
1262 * This finds the pid of the specified process,
1263 * by using the /dev/ps device driver.
1265 * Returns a list of all matching PIDs
1267 extern pid_t* findPidByName( char* pidName)
1270 char device[] = "/dev/ps";
1272 pid_t* pid_array = NULL;
1273 pid_t* pidList=NULL;
1276 fd = open(device, O_RDONLY);
1278 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1280 /* Find out how many processes there are */
1281 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1282 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1284 /* Allocate some memory -- grab a few extras just in case
1285 * some new processes start up while we wait. The kernel will
1286 * just ignore any extras if we give it too many, and will trunc.
1287 * the list if we give it too few. */
1288 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1289 pid_array[0] = num_pids+10;
1291 /* Now grab the pid list */
1292 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1293 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1295 /* Now search for a match */
1296 for (i=1, j=0; i<pid_array[0] ; i++) {
1298 struct pid_info info;
1300 info.pid = pid_array[i];
1301 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1302 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1304 /* Make sure we only match on the process name */
1305 p=info.command_line+1;
1306 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1312 if ((strstr(info.command_line, pidName) != NULL)
1313 && (strlen(pidName) == strlen(info.command_line))) {
1314 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1315 pidList[j++]=info.pid;
1325 if (close (fd) != 0)
1326 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1330 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1331 #if ! defined BB_FEATURE_USE_PROCFS
1332 #error Sorry, I depend on the /proc filesystem right now.
1337 * This finds the pid of the specified process.
1338 * Currently, it's implemented by rummaging through
1339 * the proc filesystem.
1341 * Returns a list of all matching PIDs
1343 extern pid_t* findPidByName( char* pidName)
1346 struct dirent *next;
1347 pid_t* pidList=NULL;
1350 dir = opendir("/proc");
1352 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1354 while ((next = readdir(dir)) != NULL) {
1359 /* If it isn't a number, we don't want it */
1360 if (!isdigit(*next->d_name))
1363 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1364 status = fopen(filename, "r");
1368 fgets(buffer, 256, status);
1371 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1372 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1373 pidList[i++]=strtol(next->d_name, NULL, 0);
1381 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1382 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1385 /* this should really be farmed out to libbusybox.a */
1386 extern void *xmalloc(size_t size)
1388 void *ptr = malloc(size);
1391 fatalError(memory_exhausted);
1395 extern void *xrealloc(void *old, size_t size)
1397 void *ptr = realloc(old, size);
1399 fatalError(memory_exhausted);
1403 extern void *xcalloc(size_t nmemb, size_t size)
1405 void *ptr = calloc(nmemb, size);
1407 fatalError(memory_exhausted);
1412 #if defined BB_FEATURE_NFSMOUNT || defined BB_SH || defined BB_LS
1414 extern char * xstrdup (const char *s) {
1423 fatalError(memory_exhausted);
1430 #if defined BB_FEATURE_NFSMOUNT
1431 extern char * xstrndup (const char *s, int n) {
1435 fatalError("xstrndup bug");
1446 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1447 extern int vdprintf(int d, const char *format, va_list ap)
1452 len = vsprintf(buf, format, ap);
1453 return write(d, buf, len);
1455 #endif /* BB_SYSLOGD */
1458 #if defined BB_FEATURE_MOUNT_LOOP
1460 #include "loop.h" /* Pull in loop device support */
1462 extern int del_loop(const char *device)
1466 if ((fd = open(device, O_RDONLY)) < 0) {
1470 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1471 perror("ioctl: LOOP_CLR_FD");
1478 extern int set_loop(const char *device, const char *file, int offset,
1481 struct loop_info loopinfo;
1484 mode = *loopro ? O_RDONLY : O_RDWR;
1485 if ((ffd = open(file, mode)) < 0 && !*loopro
1486 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1490 if ((fd = open(device, mode)) < 0) {
1495 *loopro = (mode == O_RDONLY);
1497 memset(&loopinfo, 0, sizeof(loopinfo));
1498 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1499 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1501 loopinfo.lo_offset = offset;
1503 loopinfo.lo_encrypt_key_size = 0;
1504 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1505 perror("ioctl: LOOP_SET_FD");
1510 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1511 (void) ioctl(fd, LOOP_CLR_FD, 0);
1512 perror("ioctl: LOOP_SET_STATUS");
1522 extern char *find_unused_loop_device(void)
1526 struct stat statbuf;
1527 struct loop_info loopinfo;
1529 for (i = 0; i <= 7; i++) {
1530 sprintf(dev, "/dev/loop%d", i);
1531 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1532 if ((fd = open(dev, O_RDONLY)) >= 0) {
1533 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1534 if (errno == ENXIO) { /* probably free */
1545 #endif /* BB_FEATURE_MOUNT_LOOP */
1547 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1548 extern int find_real_root_device_name(char* name)
1551 struct dirent *entry;
1552 struct stat statBuf, rootStat;
1553 char fileName[BUFSIZ];
1555 if (stat("/", &rootStat) != 0) {
1556 errorMsg("could not stat '/'\n");
1560 dir = opendir("/dev");
1562 errorMsg("could not open '/dev'\n");
1566 while((entry = readdir(dir)) != NULL) {
1568 /* Must skip ".." since that is "/", and so we
1569 * would get a false positive on ".." */
1570 if (strcmp(entry->d_name, "..") == 0)
1573 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1575 if (stat(fileName, &statBuf) != 0)
1577 /* Some char devices have the same dev_t as block
1578 * devices, so make sure this is a block device */
1579 if (! S_ISBLK(statBuf.st_mode))
1581 if (statBuf.st_rdev == rootStat.st_rdev) {
1582 strcpy(name, fileName);
1592 /* get_line_from_file() - This function reads an entire line from a text file
1593 * up to a newline. It returns a malloc'ed char * which must be stored and
1594 * free'ed by the caller. */
1595 extern char *get_line_from_file(FILE *file)
1597 static const int GROWBY = 80; /* how large we will grow strings by */
1601 char *linebuf = NULL;
1608 /* grow the line buffer as necessary */
1609 while (idx > linebufsz-2)
1610 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1611 linebuf[idx++] = (char)ch;
1612 if ((char)ch == '\n')
1624 extern void print_file(FILE *file)
1628 while ((c = getc(file)) != EOF)
1634 extern int print_file_by_name(char *filename)
1637 file = fopen(filename, "r");
1644 #endif /* BB_CAT || BB_LSMOD */
1646 #if defined BB_ECHO || defined BB_TR
1647 char process_escape_sequence(char **ptr)
1651 switch (c = *(*ptr)++) {
1673 case '0': case '1': case '2': case '3':
1674 case '4': case '5': case '6': case '7':
1676 if ('0' <= **ptr && **ptr <= '7') {
1677 c = c * 8 + (*(*ptr)++ - '0');
1678 if ('0' <= **ptr && **ptr <= '7')
1679 c = c * 8 + (*(*ptr)++ - '0');
1691 #if defined BB_BASENAME || defined BB_LN || defined BB_SH
1692 char *get_last_path_component(char *path)
1694 char *s=path+strlen(path)-1;
1696 /* strip trailing slashes */
1697 while (s && *s == '/') {
1701 /* find last component */
1702 s = strrchr(path, '/');
1703 if (s==NULL) return path;
1708 #if defined BB_GREP || defined BB_SED
1709 void xregcomp(regex_t *preg, const char *regex, int cflags)
1712 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1713 int errmsgsz = regerror(ret, preg, NULL, 0);
1714 char *errmsg = xmalloc(errmsgsz);
1715 regerror(ret, preg, errmsg, errmsgsz);
1716 fatalError("xregcomp: %s\n", errmsg);
1721 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE || defined BB_SED || defined BB_SH || defined BB_UNIQ || defined BB_WC
1722 FILE *xfopen(const char *path, const char *mode)
1725 if ((fp = fopen(path, mode)) == NULL)
1726 fatalError("%s: %s\n", path, strerror(errno));
1734 c-file-style: "linux"