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_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
67 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
68 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
72 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
74 const char mtab_file[] = "/etc/mtab";
76 # if defined BB_FEATURE_USE_PROCFS
77 const char mtab_file[] = "/proc/mounts";
79 # if defined BB_FEATURE_USE_DEVPS_PATCH
80 const char mtab_file[] = "/dev/mtab";
82 # 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)
88 extern void usage(const char *usage)
90 fprintf(stderr, "%s\n\nUsage: %s\n", full_version, usage);
94 static void verror_msg(const char *s, va_list p)
97 fprintf(stderr, "%s: ", applet_name);
98 vfprintf(stderr, s, p);
101 extern void error_msg(const char *s, ...)
110 extern void error_msg_and_die(const char *s, ...)
120 static void vperror_msg(const char *s, va_list p)
126 fprintf(stderr, "%s%s\n", s, strerror(err));
129 extern void perror_msg(const char *s, ...)
138 extern void perror_msg_and_die(const char *s, ...)
148 #if defined BB_INIT || defined BB_MKSWAP || defined BB_MOUNT || defined BB_NFSMOUNT
149 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
150 * so, for example, to check if the kernel is greater than 2.2.11:
151 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
153 extern int get_kernel_revision(void)
156 int major = 0, minor = 0, patch = 0;
158 if (uname(&name) == -1) {
159 perror_msg("cannot get system information");
162 major = atoi(strtok(name.release, "."));
163 minor = atoi(strtok(NULL, "."));
164 patch = atoi(strtok(NULL, "."));
165 return major * 65536 + minor * 256 + patch;
171 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
172 _syscall1(int, sysinfo, struct sysinfo *, info);
175 #if defined BB_MOUNT || defined BB_UMOUNT
178 static const int __NR_umount2 = 52;
181 /* Include our own version of <sys/mount.h>, since libc5 doesn't
182 * know about umount2 */
183 extern _syscall1(int, umount, const char *, special_file);
184 extern _syscall2(int, umount2, const char *, special_file, int, flags);
185 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
186 const char *, fstype, unsigned long int, rwflag, const void *, data);
189 #if defined BB_INSMOD || defined BB_LSMOD
190 #ifndef __NR_query_module
191 static const int __NR_query_module = 167;
193 _syscall5(int, query_module, const char *, name, int, which,
194 void *, buf, size_t, bufsize, size_t*, ret);
198 #if defined (BB_CP_MV) || defined (BB_DU)
200 #define HASH_SIZE 311 /* Should be prime */
201 #define hash_inode(i) ((i) % HASH_SIZE)
203 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
206 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
207 * `ino_dev_hashtable', else return 0
209 * If NAME is a non-NULL pointer to a character pointer, and there is
210 * a match, then set *NAME to the value of the name slot in that
213 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
215 ino_dev_hashtable_bucket_t *bucket;
217 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
218 while (bucket != NULL) {
219 if ((bucket->ino == statbuf->st_ino) &&
220 (bucket->dev == statbuf->st_dev))
222 if (name) *name = bucket->name;
225 bucket = bucket->next;
230 /* Add statbuf to statbuf hash table */
231 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
235 ino_dev_hashtable_bucket_t *bucket;
237 i = hash_inode(statbuf->st_ino);
238 s = name ? strlen(name) : 0;
239 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
240 bucket->ino = statbuf->st_ino;
241 bucket->dev = statbuf->st_dev;
243 strcpy(bucket->name, name);
245 bucket->name[0] = '\0';
246 bucket->next = ino_dev_hashtable[i];
247 ino_dev_hashtable[i] = bucket;
250 /* Clear statbuf hash table */
251 void reset_ino_dev_hashtable(void)
254 ino_dev_hashtable_bucket_t *bucket;
256 for (i = 0; i < HASH_SIZE; i++) {
257 while (ino_dev_hashtable[i] != NULL) {
258 bucket = ino_dev_hashtable[i]->next;
259 free(ino_dev_hashtable[i]);
260 ino_dev_hashtable[i] = bucket;
265 #endif /* BB_CP_MV || BB_DU */
267 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_DPKG_DEB)
269 * Return TRUE if a fileName is a directory.
270 * Nonexistant files return FALSE.
272 int is_directory(const char *fileName, const int followLinks, struct stat *statBuf)
277 if (statBuf == NULL) {
278 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
282 if (followLinks == TRUE)
283 status = stat(fileName, statBuf);
285 status = lstat(fileName, statBuf);
287 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
300 #if defined BB_AR || defined BB_CP_MV
302 * Copy chunksize bytes between two file descriptors
304 int copy_file_chunk(int srcfd, int dstfd, size_t chunksize)
307 char buffer[BUFSIZ]; /* BUFSIZ is declared in stdio.h */
309 while (chunksize > 0) {
310 if (chunksize > BUFSIZ)
314 if (full_write(dstfd, buffer, full_read(srcfd, buffer, size)) < size)
323 #if defined (BB_CP_MV)
325 * Copy one file to another, while possibly preserving its modes, times, and
326 * modes. Returns TRUE if successful, or FALSE on a failure with an error
327 * message output. (Failure is not indicated if attributes cannot be set.)
331 copy_file(const char *srcName, const char *destName,
332 int setModes, int followLinks, int forceFlag)
337 struct stat srcStatBuf;
338 struct stat dstStatBuf;
339 struct utimbuf times;
341 if (followLinks == TRUE)
342 status = stat(srcName, &srcStatBuf);
344 status = lstat(srcName, &srcStatBuf);
347 perror_msg("%s", srcName);
351 if (followLinks == TRUE)
352 status = stat(destName, &dstStatBuf);
354 status = lstat(destName, &dstStatBuf);
356 if (status < 0 || forceFlag==TRUE) {
358 dstStatBuf.st_ino = -1;
359 dstStatBuf.st_dev = -1;
362 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
363 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
364 error_msg("Copying file \"%s\" to itself\n", srcName);
368 if (S_ISDIR(srcStatBuf.st_mode)) {
369 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
370 /* Make sure the directory is writable */
371 status = mkdir(destName, 0777777 ^ umask(0));
372 if (status < 0 && errno != EEXIST) {
373 perror_msg("%s", destName);
376 } else if (S_ISLNK(srcStatBuf.st_mode)) {
377 char link_val[BUFSIZ + 1];
380 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
381 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
382 link_size = readlink(srcName, &link_val[0], BUFSIZ);
384 perror_msg("%s", srcName);
387 link_val[link_size] = '\0';
388 status = symlink(link_val, destName);
390 perror_msg("%s", destName);
393 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
394 if (setModes == TRUE) {
395 /* Try to set owner, but fail silently like GNU cp */
396 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
400 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
401 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
402 if (mkfifo(destName, 0644) < 0) {
403 perror_msg("%s", destName);
406 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
407 || S_ISSOCK(srcStatBuf.st_mode)) {
408 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
409 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
410 perror_msg("%s", destName);
413 } else if (S_ISREG(srcStatBuf.st_mode)) {
414 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
415 rfd = open(srcName, O_RDONLY);
417 perror_msg("%s", srcName);
421 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
424 perror_msg("%s", destName);
429 if (copy_file_chunk(rfd, wfd, srcStatBuf.st_size)==FALSE)
433 if (close(wfd) < 0) {
438 if (setModes == TRUE) {
439 /* This is fine, since symlinks never get here */
440 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0)
441 perror_msg_and_die("%s", destName);
442 if (chmod(destName, srcStatBuf.st_mode) < 0)
443 perror_msg_and_die("%s", destName);
444 times.actime = srcStatBuf.st_atime;
445 times.modtime = srcStatBuf.st_mtime;
446 if (utime(destName, ×) < 0)
447 perror_msg_and_die("%s", destName);
453 perror_msg("%s", destName);
459 #endif /* BB_CP_MV */
463 #if defined BB_TAR || defined BB_LS ||defined BB_AR
465 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
466 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
468 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
469 static const mode_t SBIT[] = {
475 /* The 9 mode bits to test */
476 static const mode_t MBIT[] = {
477 S_IRUSR, S_IWUSR, S_IXUSR,
478 S_IRGRP, S_IWGRP, S_IXGRP,
479 S_IROTH, S_IWOTH, S_IXOTH
482 static const char MODE1[] = "rwxrwxrwx";
483 static const char MODE0[] = "---------";
484 static const char SMODE1[] = "..s..s..t";
485 static const char SMODE0[] = "..S..S..T";
488 * Return the standard ls-like mode string from a file mode.
489 * This is static and so is overwritten on each call.
491 const char *mode_string(int mode)
497 buf[0] = TYPECHAR(mode);
498 for (i = 0; i < 9; i++) {
500 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
502 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
506 #endif /* BB_TAR || BB_LS */
509 #if defined BB_TAR || defined BB_AR
511 * Return the standard ls-like time string from a time_t
512 * This is static and so is overwritten on each call.
514 const char *time_string(time_t timeVal)
522 str = ctime(&timeVal);
524 strcpy(buf, &str[4]);
527 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
528 strcpy(&buf[7], &str[20]);
534 #endif /* BB_TAR || BB_AR */
536 #if defined BB_DD || defined BB_NC || defined BB_TAIL || defined BB_TAR || defined BB_AR || defined BB_CP_MV
538 * Write all of the supplied buffer out to a file.
539 * This does multiple writes as necessary.
540 * Returns the amount written, or -1 on an error.
542 int full_write(int fd, const char *buf, int len)
550 cc = write(fd, buf, len);
564 #if defined BB_AR || defined BB_CP_MV || defined BB_SH || defined BB_TAR
566 * Read all of the supplied buffer from a file.
567 * This does multiple reads as necessary.
568 * Returns the amount read, or -1 on an error.
569 * A short read is returned on an end of file.
571 int full_read(int fd, char *buf, int len)
579 cc = read(fd, buf, len);
594 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
597 #if defined (BB_CHMOD_CHOWN_CHGRP) \
598 || defined (BB_CP_MV) \
599 || defined (BB_FIND) \
600 || defined (BB_INSMOD) \
606 * Walk down all the directories under the specified
607 * location, and do something (something specified
608 * by the fileAction and dirAction function pointers).
610 * Unfortunately, while nftw(3) could replace this and reduce
611 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
612 * and so isn't sufficiently portable to take over since glibc2.1
613 * is so stinking huge.
615 int recursive_action(const char *fileName,
616 int recurse, int followLinks, int depthFirst,
617 int (*fileAction) (const char *fileName,
618 struct stat * statbuf,
620 int (*dirAction) (const char *fileName,
621 struct stat * statbuf,
629 if (followLinks == TRUE)
630 status = stat(fileName, &statbuf);
632 status = lstat(fileName, &statbuf);
635 #ifdef BB_DEBUG_PRINT_SCAFFOLD
637 "status=%d followLinks=%d TRUE=%d\n",
638 status, followLinks, TRUE);
640 perror_msg("%s", fileName);
644 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
645 if (fileAction == NULL)
648 return fileAction(fileName, &statbuf, userData);
651 if (recurse == FALSE) {
652 if (S_ISDIR(statbuf.st_mode)) {
653 if (dirAction != NULL)
654 return (dirAction(fileName, &statbuf, userData));
660 if (S_ISDIR(statbuf.st_mode)) {
663 if (dirAction != NULL && depthFirst == FALSE) {
664 status = dirAction(fileName, &statbuf, userData);
665 if (status == FALSE) {
666 perror_msg("%s", fileName);
668 } else if (status == SKIP)
671 dir = opendir(fileName);
673 perror_msg("%s", fileName);
676 while ((next = readdir(dir)) != NULL) {
677 char nextFile[BUFSIZ + 1];
679 if ((strcmp(next->d_name, "..") == 0)
680 || (strcmp(next->d_name, ".") == 0)) {
683 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
684 error_msg(name_too_long);
687 memset(nextFile, 0, sizeof(nextFile));
688 sprintf(nextFile, "%s/%s", fileName, next->d_name);
690 recursive_action(nextFile, TRUE, followLinks, depthFirst,
691 fileAction, dirAction, userData);
692 if (status == FALSE) {
697 status = closedir(dir);
699 perror_msg("%s", fileName);
702 if (dirAction != NULL && depthFirst == TRUE) {
703 status = dirAction(fileName, &statbuf, userData);
704 if (status == FALSE) {
705 perror_msg("%s", fileName);
710 if (fileAction == NULL)
713 return fileAction(fileName, &statbuf, userData);
718 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
722 #if defined (BB_TAR) || defined (BB_MKDIR)
724 * Attempt to create the directories along the specified path, except for
725 * the final component. The mode is given for the final directory only,
726 * while all previous ones get default protections. Errors are not reported
727 * here, as failures to restore files can be reported later.
729 extern int create_path(const char *name, int mode)
733 char buf[BUFSIZ + 1];
737 for (cp = buf; *cp == '/'; cp++);
738 cp = strchr(cp, '/');
741 cp = strchr(cp + 1, '/');
743 retVal = mkdir(buf, cp ? 0777 : mode);
744 if (retVal != 0 && errno != EEXIST) {
745 perror_msg("%s", buf);
752 #endif /* BB_TAR || BB_MKDIR */
756 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
757 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
758 /* [ugoa]{+|-|=}[rwxst] */
762 extern int parse_mode(const char *s, mode_t * theMode)
766 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
782 groups |= S_ISUID | S_IRWXU;
785 groups |= S_ISGID | S_IRWXG;
791 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
797 if (groups == 0) /* The default is "all" */
799 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
802 if (isdigit(c) && c >= '0' && c <= '7' &&
803 mode == 0 && groups == 0) {
804 *theMode = strtol(--s, NULL, 8);
812 while ((c = *s++) != '\0') {
817 mode |= S_IRUSR | S_IRGRP | S_IROTH;
820 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
823 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
826 mode |= S_IXGRP | S_ISUID | S_ISGID;
840 andMode &= ~(groups);
843 orMode |= mode & groups;
846 andMode &= ~(mode & groups);
858 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
864 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
865 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
866 || defined BB_LOGNAME || defined BB_WHOAMI || defined BB_SH
867 /* returns a uid given a username */
868 long my_getpwnam(char *name)
870 struct passwd *myuser;
872 myuser = getpwnam(name);
876 return myuser->pw_uid;
879 /* returns a gid given a group name */
880 long my_getgrnam(char *name)
882 struct group *mygroup;
884 mygroup = getgrnam(name);
888 return (mygroup->gr_gid);
891 /* gets a username given a uid */
892 void my_getpwuid(char *name, long uid)
894 struct passwd *myuser;
896 myuser = getpwuid(uid);
898 sprintf(name, "%-8ld ", (long)uid);
900 strcpy(name, myuser->pw_name);
903 /* gets a groupname given a gid */
904 void my_getgrgid(char *group, long gid)
906 struct group *mygroup;
908 mygroup = getgrgid(gid);
910 sprintf(group, "%-8ld ", (long)gid);
912 strcpy(group, mygroup->gr_name);
916 /* gets a gid given a user name */
917 long my_getpwnamegid(char *name)
919 struct group *mygroup;
920 struct passwd *myuser;
922 myuser=getpwnam(name);
924 error_msg_and_die( "unknown user name: %s\n", name);
926 mygroup = getgrgid(myuser->pw_gid);
928 error_msg_and_die( "unknown gid %ld\n", (long)myuser->pw_gid);
930 return mygroup->gr_gid;
934 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
935 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
938 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
940 /* From <linux/kd.h> */
941 static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
942 static const int KB_84 = 0x01;
943 static const int KB_101 = 0x02; /* this is what we always answer */
945 int is_a_console(int fd)
950 return (ioctl(fd, KDGKBTYPE, &arg) == 0
951 && ((arg == KB_101) || (arg == KB_84)));
954 static int open_a_console(char *fnam)
959 fd = open(fnam, O_RDWR);
961 /* if failed, try read-only */
962 if (fd < 0 && errno == EACCES)
963 fd = open(fnam, O_RDONLY);
965 /* if failed, try write-only */
966 if (fd < 0 && errno == EACCES)
967 fd = open(fnam, O_WRONLY);
969 /* if failed, fail */
973 /* if not a console, fail */
974 if (!is_a_console(fd)) {
984 * Get an fd for use with kbd/console ioctls.
985 * We try several things because opening /dev/console will fail
986 * if someone else used X (which does a chown on /dev/console).
988 * if tty_name is non-NULL, try this one instead.
991 int get_console_fd(char *tty_name)
996 if (-1 == (fd = open_a_console(tty_name)))
1002 fd = open_a_console("/dev/tty");
1006 fd = open_a_console("/dev/tty0");
1010 fd = open_a_console("/dev/console");
1014 for (fd = 0; fd < 3; fd++)
1015 if (is_a_console(fd))
1018 error_msg("Couldnt get a file descriptor referring to the console\n");
1019 return -1; /* total failure */
1023 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1026 #if defined BB_FIND || defined BB_INSMOD
1028 * Routine to see if a text string is matched by a wildcard pattern.
1029 * Returns TRUE if the text is matched, or FALSE if it is not matched
1030 * or if the pattern is invalid.
1031 * * matches zero or more characters
1032 * ? matches a single character
1033 * [abc] matches 'a', 'b' or 'c'
1034 * \c quotes character c
1035 * Adapted from code written by Ingo Wilken, and
1036 * then taken from sash, Copyright (c) 1999 by David I. Bell
1037 * Permission is granted to use, distribute, or modify this source,
1038 * provided that this copyright notice remains intact.
1039 * Permission to distribute this code under the GPL has been granted.
1041 extern int check_wildcard_match(const char *text, const char *pattern)
1043 const char *retryPat;
1044 const char *retryText;
1052 while (*text || *pattern) {
1064 while ((ch = *pattern++) != ']') {
1075 if (found == FALSE && len!=0) {
1078 if (found == TRUE) {
1079 if (strlen(pattern)==0 && len==1) {
1088 /* fall into next case */
1091 if (*text++ == '\0')
1102 /* fall into next case */
1120 if (pattern == NULL)
1126 #endif /* BB_FIND || BB_INSMOD */
1131 #if defined BB_DF || defined BB_MTAB
1134 * Given a block device, find the mount table entry if that block device
1137 * Given any other file (or directory), find the mount table entry for its
1140 extern struct mntent *find_mount_point(const char *name, const char *table)
1145 struct mntent *mountEntry;
1147 if (stat(name, &s) != 0)
1150 if ((s.st_mode & S_IFMT) == S_IFBLK)
1151 mountDevice = s.st_rdev;
1153 mountDevice = s.st_dev;
1156 if ((mountTable = setmntent(table, "r")) == 0)
1159 while ((mountEntry = getmntent(mountTable)) != 0) {
1160 if (strcmp(name, mountEntry->mnt_dir) == 0
1161 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1163 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1165 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1168 endmntent(mountTable);
1171 #endif /* BB_DF || BB_MTAB */
1173 #if defined BB_INIT || defined BB_SYSLOGD
1174 /* try to open up the specified device */
1175 extern int device_open(char *device, int mode)
1179 m = mode | O_NONBLOCK;
1181 /* Retry up to 5 times */
1182 for (f = 0; f < 5; f++)
1183 if ((fd = open(device, m, 0600)) >= 0)
1187 /* Reset original flags. */
1189 fcntl(fd, F_SETFL, mode);
1192 #endif /* BB_INIT BB_SYSLOGD */
1195 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1196 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1197 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1200 #if defined BB_FEATURE_USE_DEVPS_PATCH
1201 /* find_pid_by_name()
1203 * This finds the pid of the specified process,
1204 * by using the /dev/ps device driver.
1206 * Returns a list of all matching PIDs
1208 extern pid_t* find_pid_by_name( char* pidName)
1211 char device[] = "/dev/ps";
1213 pid_t* pid_array = NULL;
1214 pid_t* pidList=NULL;
1217 fd = open(device, O_RDONLY);
1219 perror_msg_and_die("open failed for `%s'", device);
1221 /* Find out how many processes there are */
1222 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1223 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1225 /* Allocate some memory -- grab a few extras just in case
1226 * some new processes start up while we wait. The kernel will
1227 * just ignore any extras if we give it too many, and will trunc.
1228 * the list if we give it too few. */
1229 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1230 pid_array[0] = num_pids+10;
1232 /* Now grab the pid list */
1233 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1234 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1236 /* Now search for a match */
1237 for (i=1, j=0; i<pid_array[0] ; i++) {
1239 struct pid_info info;
1241 info.pid = pid_array[i];
1242 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1243 perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1245 /* Make sure we only match on the process name */
1246 p=info.command_line+1;
1247 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1253 if ((strstr(info.command_line, pidName) != NULL)
1254 && (strlen(pidName) == strlen(info.command_line))) {
1255 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1256 pidList[j++]=info.pid;
1266 if (close (fd) != 0)
1267 perror_msg_and_die("close failed for `%s'", device);
1271 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1272 #if ! defined BB_FEATURE_USE_PROCFS
1273 #error Sorry, I depend on the /proc filesystem right now.
1276 /* find_pid_by_name()
1278 * This finds the pid of the specified process.
1279 * Currently, it's implemented by rummaging through
1280 * the proc filesystem.
1282 * Returns a list of all matching PIDs
1284 extern pid_t* find_pid_by_name( char* pidName)
1287 struct dirent *next;
1288 pid_t* pidList=NULL;
1291 dir = opendir("/proc");
1293 perror_msg_and_die("Cannot open /proc");
1295 while ((next = readdir(dir)) != NULL) {
1300 /* If it isn't a number, we don't want it */
1301 if (!isdigit(*next->d_name))
1304 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1305 status = fopen(filename, "r");
1309 fgets(buffer, 256, status);
1312 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1313 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1314 pidList[i++]=strtol(next->d_name, NULL, 0);
1322 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1323 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1326 /* this should really be farmed out to libbusybox.a */
1327 extern void *xmalloc(size_t size)
1329 void *ptr = malloc(size);
1332 error_msg_and_die(memory_exhausted);
1336 extern void *xrealloc(void *old, size_t size)
1338 void *ptr = realloc(old, size);
1340 error_msg_and_die(memory_exhausted);
1344 extern void *xcalloc(size_t nmemb, size_t size)
1346 void *ptr = calloc(nmemb, size);
1348 error_msg_and_die(memory_exhausted);
1353 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || defined BB_WGET || \
1354 defined BB_DPKG_DEB || defined BB_TAR
1356 extern char * xstrdup (const char *s) {
1365 error_msg_and_die(memory_exhausted);
1372 #if defined BB_NFSMOUNT
1373 extern char * xstrndup (const char *s, int n) {
1377 error_msg_and_die("xstrndup bug\n");
1388 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1389 extern int vdprintf(int d, const char *format, va_list ap)
1394 len = vsprintf(buf, format, ap);
1395 return write(d, buf, len);
1397 #endif /* BB_SYSLOGD */
1400 #if defined BB_FEATURE_MOUNT_LOOP
1402 #include "loop.h" /* Pull in loop device support */
1404 extern int del_loop(const char *device)
1408 if ((fd = open(device, O_RDONLY)) < 0) {
1409 perror_msg("%s", device);
1412 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1413 perror_msg("ioctl: LOOP_CLR_FD");
1420 extern int set_loop(const char *device, const char *file, int offset,
1423 struct loop_info loopinfo;
1426 mode = *loopro ? O_RDONLY : O_RDWR;
1427 if ((ffd = open(file, mode)) < 0 && !*loopro
1428 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1429 perror_msg("%s", file);
1432 if ((fd = open(device, mode)) < 0) {
1434 perror_msg("%s", device);
1437 *loopro = (mode == O_RDONLY);
1439 memset(&loopinfo, 0, sizeof(loopinfo));
1440 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1441 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1443 loopinfo.lo_offset = offset;
1445 loopinfo.lo_encrypt_key_size = 0;
1446 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1447 perror_msg("ioctl: LOOP_SET_FD");
1452 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1453 (void) ioctl(fd, LOOP_CLR_FD, 0);
1454 perror_msg("ioctl: LOOP_SET_STATUS");
1464 extern char *find_unused_loop_device(void)
1468 struct stat statbuf;
1469 struct loop_info loopinfo;
1471 for (i = 0; i <= 7; i++) {
1472 sprintf(dev, "/dev/loop%d", i);
1473 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1474 if ((fd = open(dev, O_RDONLY)) >= 0) {
1475 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1476 if (errno == ENXIO) { /* probably free */
1487 #endif /* BB_FEATURE_MOUNT_LOOP */
1489 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1490 extern int find_real_root_device_name(char* name)
1493 struct dirent *entry;
1494 struct stat statBuf, rootStat;
1495 char fileName[BUFSIZ];
1497 if (stat("/", &rootStat) != 0) {
1498 error_msg("could not stat '/'\n");
1502 dir = opendir("/dev");
1504 error_msg("could not open '/dev'\n");
1508 while((entry = readdir(dir)) != NULL) {
1510 /* Must skip ".." since that is "/", and so we
1511 * would get a false positive on ".." */
1512 if (strcmp(entry->d_name, "..") == 0)
1515 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1517 if (stat(fileName, &statBuf) != 0)
1519 /* Some char devices have the same dev_t as block
1520 * devices, so make sure this is a block device */
1521 if (! S_ISBLK(statBuf.st_mode))
1523 if (statBuf.st_rdev == rootStat.st_rdev) {
1524 strcpy(name, fileName);
1534 /* get_line_from_file() - This function reads an entire line from a text file
1535 * up to a newline. It returns a malloc'ed char * which must be stored and
1536 * free'ed by the caller. */
1537 extern char *get_line_from_file(FILE *file)
1539 static const int GROWBY = 80; /* how large we will grow strings by */
1543 char *linebuf = NULL;
1550 /* grow the line buffer as necessary */
1551 while (idx > linebufsz-2)
1552 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1553 linebuf[idx++] = (char)ch;
1554 if ((char)ch == '\n')
1566 extern void print_file(FILE *file)
1570 while ((c = getc(file)) != EOF)
1576 extern int print_file_by_name(char *filename)
1579 if ((file = wfopen(filename, "r")) == NULL)
1586 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1587 char process_escape_sequence(char **ptr)
1591 switch (c = *(*ptr)++) {
1616 case '0': case '1': case '2': case '3':
1617 case '4': case '5': case '6': case '7':
1619 if ('0' <= **ptr && **ptr <= '7') {
1620 c = c * 8 + (*(*ptr)++ - '0');
1621 if ('0' <= **ptr && **ptr <= '7')
1622 c = c * 8 + (*(*ptr)++ - '0');
1634 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1635 defined BB_FEATURE_USE_PROCFS || defined BB_WGET
1636 char *get_last_path_component(char *path)
1638 char *s=path+strlen(path)-1;
1640 /* strip trailing slashes */
1641 while (s != path && *s == '/') {
1645 /* find last component */
1646 s = strrchr(path, '/');
1647 if (s == NULL || s[1] == '\0')
1654 #if defined BB_GREP || defined BB_SED
1656 void xregcomp(regex_t *preg, const char *regex, int cflags)
1659 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1660 int errmsgsz = regerror(ret, preg, NULL, 0);
1661 char *errmsg = xmalloc(errmsgsz);
1662 regerror(ret, preg, errmsg, errmsgsz);
1663 error_msg_and_die("xregcomp: %s\n", errmsg);
1668 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1669 FILE *wfopen(const char *path, const char *mode)
1672 if ((fp = fopen(path, mode)) == NULL) {
1673 perror_msg("%s", path);
1680 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1681 || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1682 || defined BB_WC || defined BB_CMP || defined BB_SORT || defined BB_WGET
1683 FILE *xfopen(const char *path, const char *mode)
1686 if ((fp = fopen(path, mode)) == NULL)
1687 perror_msg_and_die("%s", path);
1692 int applet_name_compare(const void *x, const void *y)
1694 const struct BB_applet *applet1 = x;
1695 const struct BB_applet *applet2 = y;
1697 return strcmp(applet1->name, applet2->name);
1700 #if defined BB_DD || defined BB_TAIL
1701 unsigned long parse_number(const char *numstr, struct suffix_mult *suffixes)
1703 struct suffix_mult *sm;
1704 unsigned long int ret;
1708 ret = strtoul(numstr, &end, 10);
1710 error_msg_and_die("invalid number `%s'\n", numstr);
1711 while (end[0] != '\0') {
1712 for (sm = suffixes; sm->suffix != NULL; sm++) {
1713 len = strlen(sm->suffix);
1714 if (strncmp(sm->suffix, end, len) == 0) {
1720 if (sm->suffix == NULL)
1721 error_msg_and_die("invalid number `%s'\n", numstr);
1727 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1728 ssize_t safe_read(int fd, void *buf, size_t count)
1733 n = read(fd, buf, count);
1734 } while (n < 0 && errno == EINTR);
1740 #ifdef BB_FEATURE_HUMAN_READABLE
1741 char *format(unsigned long val, unsigned long hr)
1743 static char str[10] = "\0";
1748 snprintf(str, 9, "%ld", val/hr);
1749 else if(val >= GIGABYTE)
1750 snprintf(str, 9, "%.1LfG", ((long double)(val)/GIGABYTE));
1751 else if(val >= MEGABYTE)
1752 snprintf(str, 9, "%.1LfM", ((long double)(val)/MEGABYTE));
1753 else if(val >= KILOBYTE)
1754 snprintf(str, 9, "%.1Lfk", ((long double)(val)/KILOBYTE));
1756 snprintf(str, 9, "%ld", (val));
1764 c-file-style: "linux"