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 recursive_action */
37 #define bb_need_name_too_long
39 #define bb_need_memory_exhausted
40 #define bb_need_full_version
41 #define BB_DECLARE_EXTERN
55 #include <sys/ioctl.h>
56 #include <sys/utsname.h> /* for uname(2) */
58 #include "pwd_grp/pwd.h"
59 #include "pwd_grp/grp.h"
61 /* for the _syscall() macros */
62 #include <sys/syscall.h>
63 #include <linux/unistd.h>
65 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
66 * list of available filesystems used for the -t auto option */
67 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
69 const char mtab_file[] = "/etc/mtab";
71 # if defined BB_FEATURE_USE_DEVPS_PATCH
72 const char mtab_file[] = "/dev/mtab";
74 const char mtab_file[] = "/proc/mounts";
79 extern void usage(const char *usage)
81 fprintf(stderr, "%s\n\nUsage: %s\n\n", full_version, usage);
85 static void verror_msg(const char *s, va_list p)
88 fprintf(stderr, "%s: ", applet_name);
89 vfprintf(stderr, s, p);
92 extern void error_msg(const char *s, ...)
102 extern void error_msg_and_die(const char *s, ...)
113 static void vperror_msg(const char *s, va_list p)
119 fprintf(stderr, "%s%s\n", s, strerror(err));
122 extern void perror_msg(const char *s, ...)
131 extern void perror_msg_and_die(const char *s, ...)
141 #if defined BB_INIT || defined BB_MKSWAP || defined BB_MOUNT || defined BB_NFSMOUNT
142 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
143 * so, for example, to check if the kernel is greater than 2.2.11:
144 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
146 extern int get_kernel_revision(void)
152 if (uname(&name) == -1) {
153 perror_msg("cannot get system information");
159 for (i=0 ; i<3 ; i++) {
160 r = r * 256 + atoi(strtok(s, "."));
169 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
170 _syscall1(int, sysinfo, struct sysinfo *, info);
173 #if defined BB_MOUNT || defined BB_UMOUNT
176 static const int __NR_umount2 = 52;
179 /* Include our own version of <sys/mount.h>, since libc5 doesn't
180 * know about umount2 */
181 extern _syscall1(int, umount, const char *, special_file);
182 extern _syscall2(int, umount2, const char *, special_file, int, flags);
183 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
184 const char *, fstype, unsigned long int, rwflag, const void *, data);
187 #if defined BB_INSMOD || defined BB_LSMOD
188 #ifndef __NR_query_module
189 static const int __NR_query_module = 167;
191 _syscall5(int, query_module, const char *, name, int, which,
192 void *, buf, size_t, bufsize, size_t*, ret);
196 #if defined (BB_CP_MV) || defined (BB_DU)
198 #define HASH_SIZE 311 /* Should be prime */
199 #define hash_inode(i) ((i) % HASH_SIZE)
201 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
204 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
205 * `ino_dev_hashtable', else return 0
207 * If NAME is a non-NULL pointer to a character pointer, and there is
208 * a match, then set *NAME to the value of the name slot in that
211 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
213 ino_dev_hashtable_bucket_t *bucket;
215 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
216 while (bucket != NULL) {
217 if ((bucket->ino == statbuf->st_ino) &&
218 (bucket->dev == statbuf->st_dev))
220 if (name) *name = bucket->name;
223 bucket = bucket->next;
228 /* Add statbuf to statbuf hash table */
229 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
233 ino_dev_hashtable_bucket_t *bucket;
235 i = hash_inode(statbuf->st_ino);
236 s = name ? strlen(name) : 0;
237 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
238 bucket->ino = statbuf->st_ino;
239 bucket->dev = statbuf->st_dev;
241 strcpy(bucket->name, name);
243 bucket->name[0] = '\0';
244 bucket->next = ino_dev_hashtable[i];
245 ino_dev_hashtable[i] = bucket;
248 /* Clear statbuf hash table */
249 void reset_ino_dev_hashtable(void)
252 ino_dev_hashtable_bucket_t *bucket;
254 for (i = 0; i < HASH_SIZE; i++) {
255 while (ino_dev_hashtable[i] != NULL) {
256 bucket = ino_dev_hashtable[i]->next;
257 free(ino_dev_hashtable[i]);
258 ino_dev_hashtable[i] = bucket;
263 #endif /* BB_CP_MV || BB_DU */
265 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_DPKG_DEB)
267 * Return TRUE if a fileName is a directory.
268 * Nonexistant files return FALSE.
270 int is_directory(const char *fileName, const int followLinks, struct stat *statBuf)
275 if (statBuf == NULL) {
276 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
280 if (followLinks == TRUE)
281 status = stat(fileName, statBuf);
283 status = lstat(fileName, statBuf);
285 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
298 #if defined BB_AR || defined BB_CP_MV
300 * Copy chunksize bytes between two file descriptors
302 int copy_file_chunk(int srcfd, int dstfd, size_t chunksize)
305 char buffer[BUFSIZ]; /* BUFSIZ is declared in stdio.h */
307 while (chunksize > 0) {
308 if (chunksize > BUFSIZ)
312 if (full_write(dstfd, buffer, full_read(srcfd, buffer, size)) < size)
321 #if defined (BB_CP_MV) || defined BB_DPKG
323 * Copy one file to another, while possibly preserving its modes, times, and
324 * modes. Returns TRUE if successful, or FALSE on a failure with an error
325 * message output. (Failure is not indicated if attributes cannot be set.)
329 copy_file(const char *srcName, const char *destName,
330 int setModes, int followLinks, int forceFlag)
335 struct stat srcStatBuf;
336 struct stat dstStatBuf;
337 struct utimbuf times;
339 if (followLinks == TRUE)
340 status = stat(srcName, &srcStatBuf);
342 status = lstat(srcName, &srcStatBuf);
345 perror_msg("%s", srcName);
349 if (followLinks == TRUE)
350 status = stat(destName, &dstStatBuf);
352 status = lstat(destName, &dstStatBuf);
354 if (status < 0 || forceFlag==TRUE) {
356 dstStatBuf.st_ino = -1;
357 dstStatBuf.st_dev = -1;
360 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
361 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
362 error_msg("Copying file \"%s\" to itself", srcName);
366 if (S_ISDIR(srcStatBuf.st_mode)) {
367 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
368 /* Make sure the directory is writable */
369 status = mkdir(destName, 0777777 ^ umask(0));
370 if (status < 0 && errno != EEXIST) {
371 perror_msg("%s", destName);
374 } else if (S_ISLNK(srcStatBuf.st_mode)) {
375 char link_val[BUFSIZ + 1];
378 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
379 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
380 link_size = readlink(srcName, &link_val[0], BUFSIZ);
382 perror_msg("%s", srcName);
385 link_val[link_size] = '\0';
386 status = symlink(link_val, destName);
388 perror_msg("%s", destName);
391 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
392 if (setModes == TRUE) {
393 /* Try to set owner, but fail silently like GNU cp */
394 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
398 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
399 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
400 if (mkfifo(destName, 0644) < 0) {
401 perror_msg("%s", destName);
404 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
405 || S_ISSOCK(srcStatBuf.st_mode)) {
406 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
407 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
408 perror_msg("%s", destName);
411 } else if (S_ISREG(srcStatBuf.st_mode)) {
412 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
413 rfd = open(srcName, O_RDONLY);
415 perror_msg("%s", srcName);
419 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
422 perror_msg("%s", destName);
427 if (copy_file_chunk(rfd, wfd, srcStatBuf.st_size)==FALSE)
431 if (close(wfd) < 0) {
436 if (setModes == TRUE) {
437 /* This is fine, since symlinks never get here */
438 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0)
439 perror_msg_and_die("%s", destName);
440 if (chmod(destName, srcStatBuf.st_mode) < 0)
441 perror_msg_and_die("%s", destName);
442 times.actime = srcStatBuf.st_atime;
443 times.modtime = srcStatBuf.st_mtime;
444 if (utime(destName, ×) < 0)
445 perror_msg_and_die("%s", destName);
451 perror_msg("%s", destName);
457 #endif /* BB_CP_MV */
461 #if defined BB_TAR || defined BB_LS ||defined BB_AR
463 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
464 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
466 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
467 static const mode_t SBIT[] = {
473 /* The 9 mode bits to test */
474 static const mode_t MBIT[] = {
475 S_IRUSR, S_IWUSR, S_IXUSR,
476 S_IRGRP, S_IWGRP, S_IXGRP,
477 S_IROTH, S_IWOTH, S_IXOTH
480 static const char MODE1[] = "rwxrwxrwx";
481 static const char MODE0[] = "---------";
482 static const char SMODE1[] = "..s..s..t";
483 static const char SMODE0[] = "..S..S..T";
486 * Return the standard ls-like mode string from a file mode.
487 * This is static and so is overwritten on each call.
489 const char *mode_string(int mode)
495 buf[0] = TYPECHAR(mode);
496 for (i = 0; i < 9; i++) {
498 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
500 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
504 #endif /* BB_TAR || BB_LS */
507 #if defined BB_TAR || defined BB_AR
509 * Return the standard ls-like time string from a time_t
510 * This is static and so is overwritten on each call.
512 const char *time_string(time_t timeVal)
520 str = ctime(&timeVal);
522 strcpy(buf, &str[4]);
525 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
526 strcpy(&buf[7], &str[20]);
532 #endif /* BB_TAR || BB_AR */
534 #if defined BB_DD || defined BB_NC || defined BB_TAIL || defined BB_TAR || defined BB_AR || defined BB_CP_MV
536 * Write all of the supplied buffer out to a file.
537 * This does multiple writes as necessary.
538 * Returns the amount written, or -1 on an error.
540 int full_write(int fd, const char *buf, int len)
548 cc = write(fd, buf, len);
562 #if defined BB_AR || defined BB_CP_MV || defined BB_SH || defined BB_TAR
564 * Read all of the supplied buffer from a file.
565 * This does multiple reads as necessary.
566 * Returns the amount read, or -1 on an error.
567 * A short read is returned on an end of file.
569 int full_read(int fd, char *buf, int len)
577 cc = read(fd, buf, len);
592 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
595 #if defined (BB_CHMOD_CHOWN_CHGRP) \
596 || defined (BB_CP_MV) \
597 || defined (BB_FIND) \
598 || defined (BB_INSMOD) \
604 * Walk down all the directories under the specified
605 * location, and do something (something specified
606 * by the fileAction and dirAction function pointers).
608 * Unfortunately, while nftw(3) could replace this and reduce
609 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
610 * and so isn't sufficiently portable to take over since glibc2.1
611 * is so stinking huge.
613 int recursive_action(const char *fileName,
614 int recurse, int followLinks, int depthFirst,
615 int (*fileAction) (const char *fileName,
616 struct stat * statbuf,
618 int (*dirAction) (const char *fileName,
619 struct stat * statbuf,
627 if (followLinks == TRUE)
628 status = stat(fileName, &statbuf);
630 status = lstat(fileName, &statbuf);
633 #ifdef BB_DEBUG_PRINT_SCAFFOLD
635 "status=%d followLinks=%d TRUE=%d\n",
636 status, followLinks, TRUE);
638 perror_msg("%s", fileName);
642 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
643 if (fileAction == NULL)
646 return fileAction(fileName, &statbuf, userData);
649 if (recurse == FALSE) {
650 if (S_ISDIR(statbuf.st_mode)) {
651 if (dirAction != NULL)
652 return (dirAction(fileName, &statbuf, userData));
658 if (S_ISDIR(statbuf.st_mode)) {
661 if (dirAction != NULL && depthFirst == FALSE) {
662 status = dirAction(fileName, &statbuf, userData);
663 if (status == FALSE) {
664 perror_msg("%s", fileName);
666 } else if (status == SKIP)
669 dir = opendir(fileName);
671 perror_msg("%s", fileName);
674 while ((next = readdir(dir)) != NULL) {
675 char nextFile[BUFSIZ + 1];
677 if ((strcmp(next->d_name, "..") == 0)
678 || (strcmp(next->d_name, ".") == 0)) {
681 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
682 error_msg(name_too_long);
685 memset(nextFile, 0, sizeof(nextFile));
686 sprintf(nextFile, "%s/%s", fileName, next->d_name);
688 recursive_action(nextFile, TRUE, followLinks, depthFirst,
689 fileAction, dirAction, userData);
690 if (status == FALSE) {
695 status = closedir(dir);
697 perror_msg("%s", fileName);
700 if (dirAction != NULL && depthFirst == TRUE) {
701 status = dirAction(fileName, &statbuf, userData);
702 if (status == FALSE) {
703 perror_msg("%s", fileName);
708 if (fileAction == NULL)
711 return fileAction(fileName, &statbuf, userData);
716 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
720 #if defined (BB_TAR) || defined (BB_MKDIR)
722 * Attempt to create the directories along the specified path, except for
723 * the final component. The mode is given for the final directory only,
724 * while all previous ones get default protections. Errors are not reported
725 * here, as failures to restore files can be reported later.
727 extern int create_path(const char *name, int mode)
731 char buf[BUFSIZ + 1];
735 for (cp = buf; *cp == '/'; cp++);
736 cp = strchr(cp, '/');
739 cp = strchr(cp + 1, '/');
741 retVal = mkdir(buf, cp ? 0777 : mode);
742 if (retVal != 0 && errno != EEXIST) {
743 perror_msg("%s", buf);
750 #endif /* BB_TAR || BB_MKDIR */
754 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
755 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
756 /* [ugoa]{+|-|=}[rwxst] */
758 extern int parse_mode(const char *s, mode_t * theMode)
760 static const mode_t group_set[] = {
761 S_ISUID | S_IRWXU, /* u */
762 S_ISGID | S_IRWXG, /* g */
764 S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO /* a */
767 static const mode_t mode_set[] = {
768 S_IRUSR | S_IRGRP | S_IROTH, /* r */
769 S_IWUSR | S_IWGRP | S_IWOTH, /* w */
770 S_IXUSR | S_IXGRP | S_IXOTH, /* x */
771 S_ISUID | S_ISGID, /* s */
775 static const char group_string[] = "ugoa";
776 static const char mode_string[] = "rwxst";
781 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
796 if ((c = *s++) == '\0') {
799 for (p=group_string ; *p ; p++) {
801 groups |= group_set[(int)(p-group_string)];
810 if (groups == 0) { /* The default is "all" */
811 groups |= S_ISUID | S_ISGID | S_ISVTX
812 | S_IRWXU | S_IRWXG | S_IRWXO;
816 if ((c < '0') || (c > '7') || (mode | groups)) {
819 *theMode = strtol(--s, NULL, 8);
825 if (((c = *s++) != '\0') && (c != ',')) {
826 for (p=mode_string ; *p ; p++) {
828 mode |= mode_set[(int)(p-mode_string)];
832 break; /* We're done so break out of loop.*/
836 andMode &= ~(groups); /* Now fall through. */
838 orMode |= mode & groups;
841 andMode &= ~(mode & groups);
842 orMode &= ~(mode & groups);
854 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
860 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
861 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
862 || defined BB_LOGNAME || defined BB_WHOAMI || defined BB_SH
863 /* returns a uid given a username */
864 long my_getpwnam(char *name)
866 struct passwd *myuser;
868 myuser = getpwnam(name);
872 return myuser->pw_uid;
875 /* returns a gid given a group name */
876 long my_getgrnam(char *name)
878 struct group *mygroup;
880 mygroup = getgrnam(name);
884 return (mygroup->gr_gid);
887 /* gets a username given a uid */
888 void my_getpwuid(char *name, long uid)
890 struct passwd *myuser;
892 myuser = getpwuid(uid);
894 sprintf(name, "%-8ld ", (long)uid);
896 strcpy(name, myuser->pw_name);
899 /* gets a groupname given a gid */
900 void my_getgrgid(char *group, long gid)
902 struct group *mygroup;
904 mygroup = getgrgid(gid);
906 sprintf(group, "%-8ld ", (long)gid);
908 strcpy(group, mygroup->gr_name);
912 /* gets a gid given a user name */
913 long my_getpwnamegid(char *name)
915 struct group *mygroup;
916 struct passwd *myuser;
918 myuser=getpwnam(name);
920 error_msg_and_die( "unknown user name: %s", name);
922 mygroup = getgrgid(myuser->pw_gid);
924 error_msg_and_die( "unknown gid %ld", (long)myuser->pw_gid);
926 return mygroup->gr_gid;
930 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
931 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
934 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
936 /* From <linux/kd.h> */
937 static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
938 static const int KB_84 = 0x01;
939 static const int KB_101 = 0x02; /* this is what we always answer */
941 int is_a_console(int fd)
946 return (ioctl(fd, KDGKBTYPE, &arg) == 0
947 && ((arg == KB_101) || (arg == KB_84)));
950 static int open_a_console(char *fnam)
955 fd = open(fnam, O_RDWR);
957 /* if failed, try read-only */
958 if (fd < 0 && errno == EACCES)
959 fd = open(fnam, O_RDONLY);
961 /* if failed, try write-only */
962 if (fd < 0 && errno == EACCES)
963 fd = open(fnam, O_WRONLY);
965 /* if failed, fail */
969 /* if not a console, fail */
970 if (!is_a_console(fd)) {
980 * Get an fd for use with kbd/console ioctls.
981 * We try several things because opening /dev/console will fail
982 * if someone else used X (which does a chown on /dev/console).
984 * if tty_name is non-NULL, try this one instead.
987 int get_console_fd(char *tty_name)
992 if (-1 == (fd = open_a_console(tty_name)))
998 fd = open_a_console("/dev/tty");
1002 fd = open_a_console("/dev/tty0");
1006 fd = open_a_console("/dev/console");
1010 for (fd = 0; fd < 3; fd++)
1011 if (is_a_console(fd))
1014 error_msg("Couldnt get a file descriptor referring to the console");
1015 return -1; /* total failure */
1019 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1022 #if defined BB_FIND || defined BB_INSMOD
1024 * Routine to see if a text string is matched by a wildcard pattern.
1025 * Returns TRUE if the text is matched, or FALSE if it is not matched
1026 * or if the pattern is invalid.
1027 * * matches zero or more characters
1028 * ? matches a single character
1029 * [abc] matches 'a', 'b' or 'c'
1030 * \c quotes character c
1031 * Adapted from code written by Ingo Wilken, and
1032 * then taken from sash, Copyright (c) 1999 by David I. Bell
1033 * Permission is granted to use, distribute, or modify this source,
1034 * provided that this copyright notice remains intact.
1035 * Permission to distribute this code under the GPL has been granted.
1037 extern int check_wildcard_match(const char *text, const char *pattern)
1039 const char *retryPat;
1040 const char *retryText;
1048 while (*text || *pattern) {
1060 while ((ch = *pattern++) != ']') {
1071 if (found == FALSE && len!=0) {
1074 if (found == TRUE) {
1075 if (strlen(pattern)==0 && len==1) {
1084 /* fall into next case */
1087 if (*text++ == '\0')
1098 /* fall into next case */
1116 if (pattern == NULL)
1122 #endif /* BB_FIND || BB_INSMOD */
1127 #if defined BB_DF || defined BB_MTAB
1130 * Given a block device, find the mount table entry if that block device
1133 * Given any other file (or directory), find the mount table entry for its
1136 extern struct mntent *find_mount_point(const char *name, const char *table)
1141 struct mntent *mountEntry;
1143 if (stat(name, &s) != 0)
1146 if ((s.st_mode & S_IFMT) == S_IFBLK)
1147 mountDevice = s.st_rdev;
1149 mountDevice = s.st_dev;
1152 if ((mountTable = setmntent(table, "r")) == 0)
1155 while ((mountEntry = getmntent(mountTable)) != 0) {
1156 if (strcmp(name, mountEntry->mnt_dir) == 0
1157 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1159 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1161 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1164 endmntent(mountTable);
1167 #endif /* BB_DF || BB_MTAB */
1169 #if defined BB_INIT || defined BB_SYSLOGD
1170 /* try to open up the specified device */
1171 extern int device_open(char *device, int mode)
1175 m = mode | O_NONBLOCK;
1177 /* Retry up to 5 times */
1178 for (f = 0; f < 5; f++)
1179 if ((fd = open(device, m, 0600)) >= 0)
1183 /* Reset original flags. */
1185 fcntl(fd, F_SETFL, mode);
1188 #endif /* BB_INIT BB_SYSLOGD */
1191 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1192 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1193 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1196 #if defined BB_FEATURE_USE_DEVPS_PATCH
1197 /* find_pid_by_name()
1199 * This finds the pid of the specified process,
1200 * by using the /dev/ps device driver.
1202 * Returns a list of all matching PIDs
1204 extern pid_t* find_pid_by_name( char* pidName)
1207 char device[] = "/dev/ps";
1209 pid_t* pid_array = NULL;
1210 pid_t* pidList=NULL;
1213 fd = open(device, O_RDONLY);
1215 perror_msg_and_die("open failed for `%s'", device);
1217 /* Find out how many processes there are */
1218 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1219 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1221 /* Allocate some memory -- grab a few extras just in case
1222 * some new processes start up while we wait. The kernel will
1223 * just ignore any extras if we give it too many, and will trunc.
1224 * the list if we give it too few. */
1225 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1226 pid_array[0] = num_pids+10;
1228 /* Now grab the pid list */
1229 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1230 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1232 /* Now search for a match */
1233 for (i=1, j=0; i<pid_array[0] ; i++) {
1235 struct pid_info info;
1237 info.pid = pid_array[i];
1238 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1239 perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1241 /* Make sure we only match on the process name */
1242 p=info.command_line+1;
1243 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1249 if ((strstr(info.command_line, pidName) != NULL)
1250 && (strlen(pidName) == strlen(info.command_line))) {
1251 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1252 pidList[j++]=info.pid;
1262 if (close (fd) != 0)
1263 perror_msg_and_die("close failed for `%s'", device);
1267 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1269 /* find_pid_by_name()
1271 * This finds the pid of the specified process.
1272 * Currently, it's implemented by rummaging through
1273 * the proc filesystem.
1275 * Returns a list of all matching PIDs
1277 extern pid_t* find_pid_by_name( char* pidName)
1280 struct dirent *next;
1281 pid_t* pidList=NULL;
1284 dir = opendir("/proc");
1286 perror_msg_and_die("Cannot open /proc");
1288 while ((next = readdir(dir)) != NULL) {
1293 /* If it isn't a number, we don't want it */
1294 if (!isdigit(*next->d_name))
1297 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1298 status = fopen(filename, "r");
1302 fgets(buffer, 256, status);
1305 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1306 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1307 pidList[i++]=strtol(next->d_name, NULL, 0);
1315 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1316 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1319 /* this should really be farmed out to libbusybox.a */
1320 extern void *xmalloc(size_t size)
1322 void *ptr = malloc(size);
1325 error_msg_and_die(memory_exhausted);
1329 extern void *xrealloc(void *old, size_t size)
1331 void *ptr = realloc(old, size);
1333 error_msg_and_die(memory_exhausted);
1337 extern void *xcalloc(size_t nmemb, size_t size)
1339 void *ptr = calloc(nmemb, size);
1341 error_msg_and_die(memory_exhausted);
1346 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || defined BB_WGET || \
1347 defined BB_DPKG_DEB || defined BB_TAR
1349 extern char * xstrdup (const char *s) {
1358 error_msg_and_die(memory_exhausted);
1365 #if defined BB_NFSMOUNT
1366 extern char * xstrndup (const char *s, int n) {
1370 error_msg_and_die("xstrndup bug");
1380 #if defined BB_IFCONFIG || defined BB_ROUTE
1381 /* Like strncpy but make sure the resulting string is always 0 terminated. */
1382 extern char * safe_strncpy(char *dst, const char *src, size_t size)
1385 return strncpy(dst, src, size-1);
1389 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1390 extern int vdprintf(int d, const char *format, va_list ap)
1395 len = vsprintf(buf, format, ap);
1396 return write(d, buf, len);
1398 #endif /* BB_SYSLOGD */
1401 #if defined BB_FEATURE_MOUNT_LOOP
1403 #include "loop.h" /* Pull in loop device support */
1405 extern int del_loop(const char *device)
1409 if ((fd = open(device, O_RDONLY)) < 0) {
1410 perror_msg("%s", device);
1413 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1414 perror_msg("ioctl: LOOP_CLR_FD");
1421 extern int set_loop(const char *device, const char *file, int offset,
1424 struct loop_info loopinfo;
1427 mode = *loopro ? O_RDONLY : O_RDWR;
1428 if ((ffd = open(file, mode)) < 0 && !*loopro
1429 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1430 perror_msg("%s", file);
1433 if ((fd = open(device, mode)) < 0) {
1435 perror_msg("%s", device);
1438 *loopro = (mode == O_RDONLY);
1440 memset(&loopinfo, 0, sizeof(loopinfo));
1441 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1442 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1444 loopinfo.lo_offset = offset;
1446 loopinfo.lo_encrypt_key_size = 0;
1447 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1448 perror_msg("ioctl: LOOP_SET_FD");
1453 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1454 (void) ioctl(fd, LOOP_CLR_FD, 0);
1455 perror_msg("ioctl: LOOP_SET_STATUS");
1465 extern char *find_unused_loop_device(void)
1469 struct stat statbuf;
1470 struct loop_info loopinfo;
1472 for (i = 0; i <= 7; i++) {
1473 sprintf(dev, "/dev/loop%d", i);
1474 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1475 if ((fd = open(dev, O_RDONLY)) >= 0) {
1476 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1477 if (errno == ENXIO) { /* probably free */
1488 #endif /* BB_FEATURE_MOUNT_LOOP */
1490 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1491 extern int find_real_root_device_name(char* name)
1494 struct dirent *entry;
1495 struct stat statBuf, rootStat;
1496 char fileName[BUFSIZ];
1498 if (stat("/", &rootStat) != 0) {
1499 error_msg("could not stat '/'");
1503 dir = opendir("/dev");
1505 error_msg("could not open '/dev'");
1509 while((entry = readdir(dir)) != NULL) {
1511 /* Must skip ".." since that is "/", and so we
1512 * would get a false positive on ".." */
1513 if (strcmp(entry->d_name, "..") == 0)
1516 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1518 if (stat(fileName, &statBuf) != 0)
1520 /* Some char devices have the same dev_t as block
1521 * devices, so make sure this is a block device */
1522 if (! S_ISBLK(statBuf.st_mode))
1524 if (statBuf.st_rdev == rootStat.st_rdev) {
1525 strcpy(name, fileName);
1535 /* get_line_from_file() - This function reads an entire line from a text file
1536 * up to a newline. It returns a malloc'ed char * which must be stored and
1537 * free'ed by the caller. */
1538 extern char *get_line_from_file(FILE *file)
1540 static const int GROWBY = 80; /* how large we will grow strings by */
1544 char *linebuf = NULL;
1551 /* grow the line buffer as necessary */
1552 while (idx > linebufsz-2)
1553 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1554 linebuf[idx++] = (char)ch;
1555 if ((char)ch == '\n')
1567 extern void print_file(FILE *file)
1571 while ((c = getc(file)) != EOF)
1577 extern int print_file_by_name(char *filename)
1580 if ((file = wfopen(filename, "r")) == NULL)
1587 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1588 char process_escape_sequence(char **ptr)
1590 static const char charmap[] = {
1591 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', 0,
1592 '\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '\\' };
1602 for ( num_digits = 0 ; num_digits < 3 ; ++num_digits) {
1603 if ((*q < '0') || (*q > '7')) { /* not a digit? */
1606 n = n * 8 + (*q++ - '0');
1609 if (num_digits == 0) { /* mnemonic escape sequence? */
1610 for (p=charmap ; *p ; p++) {
1616 n = *(p+(sizeof(charmap)/2));
1619 /* doesn't hurt to fall through to here from mnemonic case */
1620 if (n > UCHAR_MAX) { /* is octal code too big for a char? */
1621 n /= 8; /* adjust value and */
1622 --q; /* back up one char */
1630 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1631 ! defined BB_FEATURE_USE_DEVPS_PATCH || defined BB_WGET
1632 char *get_last_path_component(char *path)
1634 char *s=path+strlen(path)-1;
1636 /* strip trailing slashes */
1637 while (s != path && *s == '/') {
1641 /* find last component */
1642 s = strrchr(path, '/');
1643 if (s == NULL || s[1] == '\0')
1650 #if defined BB_GREP || defined BB_SED
1652 void xregcomp(regex_t *preg, const char *regex, int cflags)
1655 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1656 int errmsgsz = regerror(ret, preg, NULL, 0);
1657 char *errmsg = xmalloc(errmsgsz);
1658 regerror(ret, preg, errmsg, errmsgsz);
1659 error_msg_and_die("xregcomp: %s", errmsg);
1664 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1665 FILE *wfopen(const char *path, const char *mode)
1668 if ((fp = fopen(path, mode)) == NULL) {
1669 perror_msg("%s", path);
1676 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1677 || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1678 || defined BB_WC || defined BB_CMP || defined BB_SORT || defined BB_WGET \
1680 FILE *xfopen(const char *path, const char *mode)
1683 if ((fp = fopen(path, mode)) == NULL)
1684 perror_msg_and_die("%s", path);
1689 static int applet_name_compare(const void *x, const void *y)
1691 const char *name = x;
1692 const struct BB_applet *applet = y;
1694 return strcmp(name, applet->name);
1697 extern size_t NUM_APPLETS;
1699 struct BB_applet *find_applet_by_name(const char *name)
1701 return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
1702 applet_name_compare);
1705 #if defined BB_DD || defined BB_TAIL
1706 unsigned long parse_number(const char *numstr,
1707 const struct suffix_mult *suffixes)
1709 const struct suffix_mult *sm;
1710 unsigned long int ret;
1714 ret = strtoul(numstr, &end, 10);
1716 error_msg_and_die("invalid number `%s'", numstr);
1717 while (end[0] != '\0') {
1718 for (sm = suffixes; sm->suffix != NULL; sm++) {
1719 len = strlen(sm->suffix);
1720 if (strncmp(sm->suffix, end, len) == 0) {
1726 if (sm->suffix == NULL)
1727 error_msg_and_die("invalid number `%s'", numstr);
1733 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1734 ssize_t safe_read(int fd, void *buf, size_t count)
1739 n = read(fd, buf, count);
1740 } while (n < 0 && errno == EINTR);
1746 #ifdef BB_FEATURE_HUMAN_READABLE
1747 const char *format(unsigned long val, unsigned long hr)
1749 static const char strings[] = { '0', 0, 'k', 0, 'M', 0, 'G', 0 };
1750 static const char fmt[] = "%lu";
1751 static const char fmt_u[] = "%lu.%lu%s";
1753 static char str[10];
1755 unsigned long frac __attribute__ ((unused)); /* 'may be uninitialized' warning is ok */
1760 if(val == 0) { /* This may be omitted to reduce size */
1761 return strings; /* at the cost of speed. */
1770 while ((val >= KILOBYTE) && (*u != 'G')) {
1773 frac = (((val % KILOBYTE) * 10) + (KILOBYTE/2)) / KILOBYTE;
1775 if (frac >= 10) { /* We need to round up here. */
1782 /* If f==fmt then 'frac' and 'u' are ignored and need not be set. */
1783 snprintf(str, sizeof(str), f, val, frac, u);
1789 #if defined(BB_GREP) || defined(BB_HOSTNAME) || defined(BB_SED) || defined(BB_TAR) || defined(BB_WGET) || defined(BB_XARGS)
1792 size_t len = strlen(s);
1797 if (s[len-1] == '\n')
1805 c-file-style: "linux"