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
54 #include <sys/ioctl.h>
55 #include <sys/utsname.h> /* for uname(2) */
57 #include "pwd_grp/pwd.h"
58 #include "pwd_grp/grp.h"
60 /* for the _syscall() macros */
61 #include <sys/syscall.h>
62 #include <linux/unistd.h>
64 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
65 * list of available filesystems used for the -t auto option */
66 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
68 const char mtab_file[] = "/etc/mtab";
70 # if defined BB_FEATURE_USE_DEVPS_PATCH
71 const char mtab_file[] = "/dev/mtab";
73 const char mtab_file[] = "/proc/mounts";
78 extern void usage(const char *usage)
80 fprintf(stderr, "%s\n\nUsage: %s\n", full_version, usage);
84 static void verror_msg(const char *s, va_list p)
87 fprintf(stderr, "%s: ", applet_name);
88 vfprintf(stderr, s, p);
91 extern void error_msg(const char *s, ...)
101 extern void error_msg_and_die(const char *s, ...)
112 static void vperror_msg(const char *s, va_list p)
118 fprintf(stderr, "%s%s\n", s, strerror(err));
121 extern void perror_msg(const char *s, ...)
130 extern void perror_msg_and_die(const char *s, ...)
140 #if defined BB_INIT || defined BB_MKSWAP || defined BB_MOUNT || defined BB_NFSMOUNT
141 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
142 * so, for example, to check if the kernel is greater than 2.2.11:
143 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
145 extern int get_kernel_revision(void)
148 int major = 0, minor = 0, patch = 0;
150 if (uname(&name) == -1) {
151 perror_msg("cannot get system information");
154 major = atoi(strtok(name.release, "."));
155 minor = atoi(strtok(NULL, "."));
156 patch = atoi(strtok(NULL, "."));
157 return major * 65536 + minor * 256 + patch;
163 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
164 _syscall1(int, sysinfo, struct sysinfo *, info);
167 #if defined BB_MOUNT || defined BB_UMOUNT
170 static const int __NR_umount2 = 52;
173 /* Include our own version of <sys/mount.h>, since libc5 doesn't
174 * know about umount2 */
175 extern _syscall1(int, umount, const char *, special_file);
176 extern _syscall2(int, umount2, const char *, special_file, int, flags);
177 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
178 const char *, fstype, unsigned long int, rwflag, const void *, data);
181 #if defined BB_INSMOD || defined BB_LSMOD
182 #ifndef __NR_query_module
183 static const int __NR_query_module = 167;
185 _syscall5(int, query_module, const char *, name, int, which,
186 void *, buf, size_t, bufsize, size_t*, ret);
190 #if defined (BB_CP_MV) || defined (BB_DU)
192 #define HASH_SIZE 311 /* Should be prime */
193 #define hash_inode(i) ((i) % HASH_SIZE)
195 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
198 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
199 * `ino_dev_hashtable', else return 0
201 * If NAME is a non-NULL pointer to a character pointer, and there is
202 * a match, then set *NAME to the value of the name slot in that
205 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
207 ino_dev_hashtable_bucket_t *bucket;
209 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
210 while (bucket != NULL) {
211 if ((bucket->ino == statbuf->st_ino) &&
212 (bucket->dev == statbuf->st_dev))
214 if (name) *name = bucket->name;
217 bucket = bucket->next;
222 /* Add statbuf to statbuf hash table */
223 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
227 ino_dev_hashtable_bucket_t *bucket;
229 i = hash_inode(statbuf->st_ino);
230 s = name ? strlen(name) : 0;
231 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
232 bucket->ino = statbuf->st_ino;
233 bucket->dev = statbuf->st_dev;
235 strcpy(bucket->name, name);
237 bucket->name[0] = '\0';
238 bucket->next = ino_dev_hashtable[i];
239 ino_dev_hashtable[i] = bucket;
242 /* Clear statbuf hash table */
243 void reset_ino_dev_hashtable(void)
246 ino_dev_hashtable_bucket_t *bucket;
248 for (i = 0; i < HASH_SIZE; i++) {
249 while (ino_dev_hashtable[i] != NULL) {
250 bucket = ino_dev_hashtable[i]->next;
251 free(ino_dev_hashtable[i]);
252 ino_dev_hashtable[i] = bucket;
257 #endif /* BB_CP_MV || BB_DU */
259 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_DPKG_DEB)
261 * Return TRUE if a fileName is a directory.
262 * Nonexistant files return FALSE.
264 int is_directory(const char *fileName, const int followLinks, struct stat *statBuf)
269 if (statBuf == NULL) {
270 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
274 if (followLinks == TRUE)
275 status = stat(fileName, statBuf);
277 status = lstat(fileName, statBuf);
279 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
292 #if defined BB_AR || defined BB_CP_MV
294 * Copy chunksize bytes between two file descriptors
296 int copy_file_chunk(int srcfd, int dstfd, size_t chunksize)
299 char buffer[BUFSIZ]; /* BUFSIZ is declared in stdio.h */
301 while (chunksize > 0) {
302 if (chunksize > BUFSIZ)
306 if (full_write(dstfd, buffer, full_read(srcfd, buffer, size)) < size)
315 #if defined (BB_CP_MV) || defined BB_DPKG
317 * Copy one file to another, while possibly preserving its modes, times, and
318 * modes. Returns TRUE if successful, or FALSE on a failure with an error
319 * message output. (Failure is not indicated if attributes cannot be set.)
323 copy_file(const char *srcName, const char *destName,
324 int setModes, int followLinks, int forceFlag)
329 struct stat srcStatBuf;
330 struct stat dstStatBuf;
331 struct utimbuf times;
333 if (followLinks == TRUE)
334 status = stat(srcName, &srcStatBuf);
336 status = lstat(srcName, &srcStatBuf);
339 perror_msg("%s", srcName);
343 if (followLinks == TRUE)
344 status = stat(destName, &dstStatBuf);
346 status = lstat(destName, &dstStatBuf);
348 if (status < 0 || forceFlag==TRUE) {
350 dstStatBuf.st_ino = -1;
351 dstStatBuf.st_dev = -1;
354 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
355 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
356 error_msg("Copying file \"%s\" to itself", srcName);
360 if (S_ISDIR(srcStatBuf.st_mode)) {
361 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
362 /* Make sure the directory is writable */
363 status = mkdir(destName, 0777777 ^ umask(0));
364 if (status < 0 && errno != EEXIST) {
365 perror_msg("%s", destName);
368 } else if (S_ISLNK(srcStatBuf.st_mode)) {
369 char link_val[BUFSIZ + 1];
372 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
373 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
374 link_size = readlink(srcName, &link_val[0], BUFSIZ);
376 perror_msg("%s", srcName);
379 link_val[link_size] = '\0';
380 status = symlink(link_val, destName);
382 perror_msg("%s", destName);
385 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
386 if (setModes == TRUE) {
387 /* Try to set owner, but fail silently like GNU cp */
388 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
392 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
393 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
394 if (mkfifo(destName, 0644) < 0) {
395 perror_msg("%s", destName);
398 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
399 || S_ISSOCK(srcStatBuf.st_mode)) {
400 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
401 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
402 perror_msg("%s", destName);
405 } else if (S_ISREG(srcStatBuf.st_mode)) {
406 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
407 rfd = open(srcName, O_RDONLY);
409 perror_msg("%s", srcName);
413 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
416 perror_msg("%s", destName);
421 if (copy_file_chunk(rfd, wfd, srcStatBuf.st_size)==FALSE)
425 if (close(wfd) < 0) {
430 if (setModes == TRUE) {
431 /* This is fine, since symlinks never get here */
432 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0)
433 perror_msg_and_die("%s", destName);
434 if (chmod(destName, srcStatBuf.st_mode) < 0)
435 perror_msg_and_die("%s", destName);
436 times.actime = srcStatBuf.st_atime;
437 times.modtime = srcStatBuf.st_mtime;
438 if (utime(destName, ×) < 0)
439 perror_msg_and_die("%s", destName);
445 perror_msg("%s", destName);
451 #endif /* BB_CP_MV */
455 #if defined BB_TAR || defined BB_LS ||defined BB_AR
457 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
458 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
460 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
461 static const mode_t SBIT[] = {
467 /* The 9 mode bits to test */
468 static const mode_t MBIT[] = {
469 S_IRUSR, S_IWUSR, S_IXUSR,
470 S_IRGRP, S_IWGRP, S_IXGRP,
471 S_IROTH, S_IWOTH, S_IXOTH
474 static const char MODE1[] = "rwxrwxrwx";
475 static const char MODE0[] = "---------";
476 static const char SMODE1[] = "..s..s..t";
477 static const char SMODE0[] = "..S..S..T";
480 * Return the standard ls-like mode string from a file mode.
481 * This is static and so is overwritten on each call.
483 const char *mode_string(int mode)
489 buf[0] = TYPECHAR(mode);
490 for (i = 0; i < 9; i++) {
492 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
494 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
498 #endif /* BB_TAR || BB_LS */
501 #if defined BB_TAR || defined BB_AR
503 * Return the standard ls-like time string from a time_t
504 * This is static and so is overwritten on each call.
506 const char *time_string(time_t timeVal)
514 str = ctime(&timeVal);
516 strcpy(buf, &str[4]);
519 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
520 strcpy(&buf[7], &str[20]);
526 #endif /* BB_TAR || BB_AR */
528 #if defined BB_DD || defined BB_NC || defined BB_TAIL || defined BB_TAR || defined BB_AR || defined BB_CP_MV
530 * Write all of the supplied buffer out to a file.
531 * This does multiple writes as necessary.
532 * Returns the amount written, or -1 on an error.
534 int full_write(int fd, const char *buf, int len)
542 cc = write(fd, buf, len);
556 #if defined BB_AR || defined BB_CP_MV || defined BB_SH || defined BB_TAR
558 * Read all of the supplied buffer from a file.
559 * This does multiple reads as necessary.
560 * Returns the amount read, or -1 on an error.
561 * A short read is returned on an end of file.
563 int full_read(int fd, char *buf, int len)
571 cc = read(fd, buf, len);
586 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
589 #if defined (BB_CHMOD_CHOWN_CHGRP) \
590 || defined (BB_CP_MV) \
591 || defined (BB_FIND) \
592 || defined (BB_INSMOD) \
598 * Walk down all the directories under the specified
599 * location, and do something (something specified
600 * by the fileAction and dirAction function pointers).
602 * Unfortunately, while nftw(3) could replace this and reduce
603 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
604 * and so isn't sufficiently portable to take over since glibc2.1
605 * is so stinking huge.
607 int recursive_action(const char *fileName,
608 int recurse, int followLinks, int depthFirst,
609 int (*fileAction) (const char *fileName,
610 struct stat * statbuf,
612 int (*dirAction) (const char *fileName,
613 struct stat * statbuf,
621 if (followLinks == TRUE)
622 status = stat(fileName, &statbuf);
624 status = lstat(fileName, &statbuf);
627 #ifdef BB_DEBUG_PRINT_SCAFFOLD
629 "status=%d followLinks=%d TRUE=%d\n",
630 status, followLinks, TRUE);
632 perror_msg("%s", fileName);
636 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
637 if (fileAction == NULL)
640 return fileAction(fileName, &statbuf, userData);
643 if (recurse == FALSE) {
644 if (S_ISDIR(statbuf.st_mode)) {
645 if (dirAction != NULL)
646 return (dirAction(fileName, &statbuf, userData));
652 if (S_ISDIR(statbuf.st_mode)) {
655 if (dirAction != NULL && depthFirst == FALSE) {
656 status = dirAction(fileName, &statbuf, userData);
657 if (status == FALSE) {
658 perror_msg("%s", fileName);
660 } else if (status == SKIP)
663 dir = opendir(fileName);
665 perror_msg("%s", fileName);
668 while ((next = readdir(dir)) != NULL) {
669 char nextFile[BUFSIZ + 1];
671 if ((strcmp(next->d_name, "..") == 0)
672 || (strcmp(next->d_name, ".") == 0)) {
675 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
676 error_msg(name_too_long);
679 memset(nextFile, 0, sizeof(nextFile));
680 sprintf(nextFile, "%s/%s", fileName, next->d_name);
682 recursive_action(nextFile, TRUE, followLinks, depthFirst,
683 fileAction, dirAction, userData);
684 if (status == FALSE) {
689 status = closedir(dir);
691 perror_msg("%s", fileName);
694 if (dirAction != NULL && depthFirst == TRUE) {
695 status = dirAction(fileName, &statbuf, userData);
696 if (status == FALSE) {
697 perror_msg("%s", fileName);
702 if (fileAction == NULL)
705 return fileAction(fileName, &statbuf, userData);
710 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
714 #if defined (BB_TAR) || defined (BB_MKDIR)
716 * Attempt to create the directories along the specified path, except for
717 * the final component. The mode is given for the final directory only,
718 * while all previous ones get default protections. Errors are not reported
719 * here, as failures to restore files can be reported later.
721 extern int create_path(const char *name, int mode)
725 char buf[BUFSIZ + 1];
729 for (cp = buf; *cp == '/'; cp++);
730 cp = strchr(cp, '/');
733 cp = strchr(cp + 1, '/');
735 retVal = mkdir(buf, cp ? 0777 : mode);
736 if (retVal != 0 && errno != EEXIST) {
737 perror_msg("%s", buf);
744 #endif /* BB_TAR || BB_MKDIR */
748 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
749 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
750 /* [ugoa]{+|-|=}[rwxst] */
754 extern int parse_mode(const char *s, mode_t * theMode)
758 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
774 groups |= S_ISUID | S_IRWXU;
777 groups |= S_ISGID | S_IRWXG;
783 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
789 if (groups == 0) /* The default is "all" */
791 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
794 if (isdigit(c) && c >= '0' && c <= '7' &&
795 mode == 0 && groups == 0) {
796 *theMode = strtol(--s, NULL, 8);
804 while ((c = *s++) != '\0') {
809 mode |= S_IRUSR | S_IRGRP | S_IROTH;
812 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
815 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
818 mode |= S_IXGRP | S_ISUID | S_ISGID;
832 andMode &= ~(groups);
835 orMode |= mode & groups;
838 andMode &= ~(mode & groups);
850 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
856 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
857 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
858 || defined BB_LOGNAME || defined BB_WHOAMI || defined BB_SH
859 /* returns a uid given a username */
860 long my_getpwnam(char *name)
862 struct passwd *myuser;
864 myuser = getpwnam(name);
868 return myuser->pw_uid;
871 /* returns a gid given a group name */
872 long my_getgrnam(char *name)
874 struct group *mygroup;
876 mygroup = getgrnam(name);
880 return (mygroup->gr_gid);
883 /* gets a username given a uid */
884 void my_getpwuid(char *name, long uid)
886 struct passwd *myuser;
888 myuser = getpwuid(uid);
890 sprintf(name, "%-8ld ", (long)uid);
892 strcpy(name, myuser->pw_name);
895 /* gets a groupname given a gid */
896 void my_getgrgid(char *group, long gid)
898 struct group *mygroup;
900 mygroup = getgrgid(gid);
902 sprintf(group, "%-8ld ", (long)gid);
904 strcpy(group, mygroup->gr_name);
908 /* gets a gid given a user name */
909 long my_getpwnamegid(char *name)
911 struct group *mygroup;
912 struct passwd *myuser;
914 myuser=getpwnam(name);
916 error_msg_and_die( "unknown user name: %s", name);
918 mygroup = getgrgid(myuser->pw_gid);
920 error_msg_and_die( "unknown gid %ld", (long)myuser->pw_gid);
922 return mygroup->gr_gid;
926 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
927 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
930 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
932 /* From <linux/kd.h> */
933 static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
934 static const int KB_84 = 0x01;
935 static const int KB_101 = 0x02; /* this is what we always answer */
937 int is_a_console(int fd)
942 return (ioctl(fd, KDGKBTYPE, &arg) == 0
943 && ((arg == KB_101) || (arg == KB_84)));
946 static int open_a_console(char *fnam)
951 fd = open(fnam, O_RDWR);
953 /* if failed, try read-only */
954 if (fd < 0 && errno == EACCES)
955 fd = open(fnam, O_RDONLY);
957 /* if failed, try write-only */
958 if (fd < 0 && errno == EACCES)
959 fd = open(fnam, O_WRONLY);
961 /* if failed, fail */
965 /* if not a console, fail */
966 if (!is_a_console(fd)) {
976 * Get an fd for use with kbd/console ioctls.
977 * We try several things because opening /dev/console will fail
978 * if someone else used X (which does a chown on /dev/console).
980 * if tty_name is non-NULL, try this one instead.
983 int get_console_fd(char *tty_name)
988 if (-1 == (fd = open_a_console(tty_name)))
994 fd = open_a_console("/dev/tty");
998 fd = open_a_console("/dev/tty0");
1002 fd = open_a_console("/dev/console");
1006 for (fd = 0; fd < 3; fd++)
1007 if (is_a_console(fd))
1010 error_msg("Couldnt get a file descriptor referring to the console");
1011 return -1; /* total failure */
1015 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1018 #if defined BB_FIND || defined BB_INSMOD
1020 * Routine to see if a text string is matched by a wildcard pattern.
1021 * Returns TRUE if the text is matched, or FALSE if it is not matched
1022 * or if the pattern is invalid.
1023 * * matches zero or more characters
1024 * ? matches a single character
1025 * [abc] matches 'a', 'b' or 'c'
1026 * \c quotes character c
1027 * Adapted from code written by Ingo Wilken, and
1028 * then taken from sash, Copyright (c) 1999 by David I. Bell
1029 * Permission is granted to use, distribute, or modify this source,
1030 * provided that this copyright notice remains intact.
1031 * Permission to distribute this code under the GPL has been granted.
1033 extern int check_wildcard_match(const char *text, const char *pattern)
1035 const char *retryPat;
1036 const char *retryText;
1044 while (*text || *pattern) {
1056 while ((ch = *pattern++) != ']') {
1067 if (found == FALSE && len!=0) {
1070 if (found == TRUE) {
1071 if (strlen(pattern)==0 && len==1) {
1080 /* fall into next case */
1083 if (*text++ == '\0')
1094 /* fall into next case */
1112 if (pattern == NULL)
1118 #endif /* BB_FIND || BB_INSMOD */
1123 #if defined BB_DF || defined BB_MTAB
1126 * Given a block device, find the mount table entry if that block device
1129 * Given any other file (or directory), find the mount table entry for its
1132 extern struct mntent *find_mount_point(const char *name, const char *table)
1137 struct mntent *mountEntry;
1139 if (stat(name, &s) != 0)
1142 if ((s.st_mode & S_IFMT) == S_IFBLK)
1143 mountDevice = s.st_rdev;
1145 mountDevice = s.st_dev;
1148 if ((mountTable = setmntent(table, "r")) == 0)
1151 while ((mountEntry = getmntent(mountTable)) != 0) {
1152 if (strcmp(name, mountEntry->mnt_dir) == 0
1153 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1155 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1157 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1160 endmntent(mountTable);
1163 #endif /* BB_DF || BB_MTAB */
1165 #if defined BB_INIT || defined BB_SYSLOGD
1166 /* try to open up the specified device */
1167 extern int device_open(char *device, int mode)
1171 m = mode | O_NONBLOCK;
1173 /* Retry up to 5 times */
1174 for (f = 0; f < 5; f++)
1175 if ((fd = open(device, m, 0600)) >= 0)
1179 /* Reset original flags. */
1181 fcntl(fd, F_SETFL, mode);
1184 #endif /* BB_INIT BB_SYSLOGD */
1187 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1188 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1189 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1192 #if defined BB_FEATURE_USE_DEVPS_PATCH
1193 /* find_pid_by_name()
1195 * This finds the pid of the specified process,
1196 * by using the /dev/ps device driver.
1198 * Returns a list of all matching PIDs
1200 extern pid_t* find_pid_by_name( char* pidName)
1203 char device[] = "/dev/ps";
1205 pid_t* pid_array = NULL;
1206 pid_t* pidList=NULL;
1209 fd = open(device, O_RDONLY);
1211 perror_msg_and_die("open failed for `%s'", device);
1213 /* Find out how many processes there are */
1214 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1215 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1217 /* Allocate some memory -- grab a few extras just in case
1218 * some new processes start up while we wait. The kernel will
1219 * just ignore any extras if we give it too many, and will trunc.
1220 * the list if we give it too few. */
1221 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1222 pid_array[0] = num_pids+10;
1224 /* Now grab the pid list */
1225 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1226 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1228 /* Now search for a match */
1229 for (i=1, j=0; i<pid_array[0] ; i++) {
1231 struct pid_info info;
1233 info.pid = pid_array[i];
1234 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1235 perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1237 /* Make sure we only match on the process name */
1238 p=info.command_line+1;
1239 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1245 if ((strstr(info.command_line, pidName) != NULL)
1246 && (strlen(pidName) == strlen(info.command_line))) {
1247 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1248 pidList[j++]=info.pid;
1258 if (close (fd) != 0)
1259 perror_msg_and_die("close failed for `%s'", device);
1263 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1265 /* find_pid_by_name()
1267 * This finds the pid of the specified process.
1268 * Currently, it's implemented by rummaging through
1269 * the proc filesystem.
1271 * Returns a list of all matching PIDs
1273 extern pid_t* find_pid_by_name( char* pidName)
1276 struct dirent *next;
1277 pid_t* pidList=NULL;
1280 dir = opendir("/proc");
1282 perror_msg_and_die("Cannot open /proc");
1284 while ((next = readdir(dir)) != NULL) {
1289 /* If it isn't a number, we don't want it */
1290 if (!isdigit(*next->d_name))
1293 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1294 status = fopen(filename, "r");
1298 fgets(buffer, 256, status);
1301 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1302 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1303 pidList[i++]=strtol(next->d_name, NULL, 0);
1311 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1312 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1315 /* this should really be farmed out to libbusybox.a */
1316 extern void *xmalloc(size_t size)
1318 void *ptr = malloc(size);
1321 error_msg_and_die(memory_exhausted);
1325 extern void *xrealloc(void *old, size_t size)
1327 void *ptr = realloc(old, size);
1329 error_msg_and_die(memory_exhausted);
1333 extern void *xcalloc(size_t nmemb, size_t size)
1335 void *ptr = calloc(nmemb, size);
1337 error_msg_and_die(memory_exhausted);
1342 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || defined BB_WGET || \
1343 defined BB_DPKG_DEB || defined BB_TAR
1345 extern char * xstrdup (const char *s) {
1354 error_msg_and_die(memory_exhausted);
1361 #if defined BB_NFSMOUNT
1362 extern char * xstrndup (const char *s, int n) {
1366 error_msg_and_die("xstrndup bug");
1377 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1378 extern int vdprintf(int d, const char *format, va_list ap)
1383 len = vsprintf(buf, format, ap);
1384 return write(d, buf, len);
1386 #endif /* BB_SYSLOGD */
1389 #if defined BB_FEATURE_MOUNT_LOOP
1391 #include "loop.h" /* Pull in loop device support */
1393 extern int del_loop(const char *device)
1397 if ((fd = open(device, O_RDONLY)) < 0) {
1398 perror_msg("%s", device);
1401 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1402 perror_msg("ioctl: LOOP_CLR_FD");
1409 extern int set_loop(const char *device, const char *file, int offset,
1412 struct loop_info loopinfo;
1415 mode = *loopro ? O_RDONLY : O_RDWR;
1416 if ((ffd = open(file, mode)) < 0 && !*loopro
1417 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1418 perror_msg("%s", file);
1421 if ((fd = open(device, mode)) < 0) {
1423 perror_msg("%s", device);
1426 *loopro = (mode == O_RDONLY);
1428 memset(&loopinfo, 0, sizeof(loopinfo));
1429 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1430 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1432 loopinfo.lo_offset = offset;
1434 loopinfo.lo_encrypt_key_size = 0;
1435 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1436 perror_msg("ioctl: LOOP_SET_FD");
1441 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1442 (void) ioctl(fd, LOOP_CLR_FD, 0);
1443 perror_msg("ioctl: LOOP_SET_STATUS");
1453 extern char *find_unused_loop_device(void)
1457 struct stat statbuf;
1458 struct loop_info loopinfo;
1460 for (i = 0; i <= 7; i++) {
1461 sprintf(dev, "/dev/loop%d", i);
1462 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1463 if ((fd = open(dev, O_RDONLY)) >= 0) {
1464 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1465 if (errno == ENXIO) { /* probably free */
1476 #endif /* BB_FEATURE_MOUNT_LOOP */
1478 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1479 extern int find_real_root_device_name(char* name)
1482 struct dirent *entry;
1483 struct stat statBuf, rootStat;
1484 char fileName[BUFSIZ];
1486 if (stat("/", &rootStat) != 0) {
1487 error_msg("could not stat '/'");
1491 dir = opendir("/dev");
1493 error_msg("could not open '/dev'");
1497 while((entry = readdir(dir)) != NULL) {
1499 /* Must skip ".." since that is "/", and so we
1500 * would get a false positive on ".." */
1501 if (strcmp(entry->d_name, "..") == 0)
1504 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1506 if (stat(fileName, &statBuf) != 0)
1508 /* Some char devices have the same dev_t as block
1509 * devices, so make sure this is a block device */
1510 if (! S_ISBLK(statBuf.st_mode))
1512 if (statBuf.st_rdev == rootStat.st_rdev) {
1513 strcpy(name, fileName);
1523 /* get_line_from_file() - This function reads an entire line from a text file
1524 * up to a newline. It returns a malloc'ed char * which must be stored and
1525 * free'ed by the caller. */
1526 extern char *get_line_from_file(FILE *file)
1528 static const int GROWBY = 80; /* how large we will grow strings by */
1532 char *linebuf = NULL;
1539 /* grow the line buffer as necessary */
1540 while (idx > linebufsz-2)
1541 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1542 linebuf[idx++] = (char)ch;
1543 if ((char)ch == '\n')
1555 extern void print_file(FILE *file)
1559 while ((c = getc(file)) != EOF)
1565 extern int print_file_by_name(char *filename)
1568 if ((file = wfopen(filename, "r")) == NULL)
1575 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1576 char process_escape_sequence(char **ptr)
1580 switch (c = *(*ptr)++) {
1605 case '0': case '1': case '2': case '3':
1606 case '4': case '5': case '6': case '7':
1608 if ('0' <= **ptr && **ptr <= '7') {
1609 c = c * 8 + (*(*ptr)++ - '0');
1610 if ('0' <= **ptr && **ptr <= '7')
1611 c = c * 8 + (*(*ptr)++ - '0');
1623 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1624 ! defined BB_FEATURE_USE_DEVPS_PATCH || defined BB_WGET
1625 char *get_last_path_component(char *path)
1627 char *s=path+strlen(path)-1;
1629 /* strip trailing slashes */
1630 while (s != path && *s == '/') {
1634 /* find last component */
1635 s = strrchr(path, '/');
1636 if (s == NULL || s[1] == '\0')
1643 #if defined BB_GREP || defined BB_SED
1645 void xregcomp(regex_t *preg, const char *regex, int cflags)
1648 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1649 int errmsgsz = regerror(ret, preg, NULL, 0);
1650 char *errmsg = xmalloc(errmsgsz);
1651 regerror(ret, preg, errmsg, errmsgsz);
1652 error_msg_and_die("xregcomp: %s", errmsg);
1657 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1658 FILE *wfopen(const char *path, const char *mode)
1661 if ((fp = fopen(path, mode)) == NULL) {
1662 perror_msg("%s", path);
1669 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1670 || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1671 || defined BB_WC || defined BB_CMP || defined BB_SORT || defined BB_WGET \
1673 FILE *xfopen(const char *path, const char *mode)
1676 if ((fp = fopen(path, mode)) == NULL)
1677 perror_msg_and_die("%s", path);
1682 static int applet_name_compare(const void *x, const void *y)
1684 const char *name = x;
1685 const struct BB_applet *applet = y;
1687 return strcmp(name, applet->name);
1690 extern size_t NUM_APPLETS;
1692 struct BB_applet *find_applet_by_name(const char *name)
1694 return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
1695 applet_name_compare);
1698 #if defined BB_DD || defined BB_TAIL
1699 unsigned long parse_number(const char *numstr,
1700 const struct suffix_mult *suffixes)
1702 const struct suffix_mult *sm;
1703 unsigned long int ret;
1707 ret = strtoul(numstr, &end, 10);
1709 error_msg_and_die("invalid number `%s'", numstr);
1710 while (end[0] != '\0') {
1711 for (sm = suffixes; sm->suffix != NULL; sm++) {
1712 len = strlen(sm->suffix);
1713 if (strncmp(sm->suffix, end, len) == 0) {
1719 if (sm->suffix == NULL)
1720 error_msg_and_die("invalid number `%s'", numstr);
1726 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1727 ssize_t safe_read(int fd, void *buf, size_t count)
1732 n = read(fd, buf, count);
1733 } while (n < 0 && errno == EINTR);
1739 #ifdef BB_FEATURE_HUMAN_READABLE
1740 char *format(unsigned long val, unsigned long hr)
1742 static char str[10] = "\0";
1747 snprintf(str, 9, "%ld", val/hr);
1748 else if(val >= GIGABYTE)
1749 snprintf(str, 9, "%.1LfG", ((long double)(val)/GIGABYTE));
1750 else if(val >= MEGABYTE)
1751 snprintf(str, 9, "%.1LfM", ((long double)(val)/MEGABYTE));
1752 else if(val >= KILOBYTE)
1753 snprintf(str, 9, "%.1Lfk", ((long double)(val)/KILOBYTE));
1755 snprintf(str, 9, "%ld", (val));
1760 #if defined(BB_GREP) || defined(BB_HOSTNAME) || defined(BB_SED) || defined(BB_TAR) || defined(BB_WGET) || defined(BB_XARGS)
1763 size_t len = strlen(s);
1768 if (s[len-1] == '\n')
1776 c-file-style: "linux"