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.
39 #include <sys/ioctl.h>
40 #include <sys/utsname.h> /* for uname(2) */
43 #if defined (BB_CHMOD_CHOWN_CHGRP) \
44 || defined (BB_CP_MV) \
45 || defined (BB_FIND) \
46 || defined (BB_INSMOD) \
50 /* same conditions as recursive_action */
51 #define bb_need_name_too_long
53 #define bb_need_memory_exhausted
54 #define bb_need_full_version
55 #define BB_DECLARE_EXTERN
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 static struct BB_applet *applet_using;
81 extern void show_usage(void)
83 const char *format_string;
84 const char *usage_string = usage_messages;
87 for (i = applet_using - applets; i > 0; ) {
88 if (!*usage_string++) {
92 format_string = "%s\n\nUsage: %s %s\n\n";
93 if(*usage_string == 0)
94 format_string = "%s\n\nNo help available.\n\n";
95 fprintf(stderr, format_string,
96 full_version, applet_using->name, usage_string);
101 static void verror_msg(const char *s, va_list p)
104 fprintf(stderr, "%s: ", applet_name);
105 vfprintf(stderr, s, p);
108 extern void error_msg(const char *s, ...)
118 extern void error_msg_and_die(const char *s, ...)
129 static void vperror_msg(const char *s, va_list p)
135 fprintf(stderr, "%s%s\n", s, strerror(err));
138 extern void perror_msg(const char *s, ...)
147 extern void perror_msg_and_die(const char *s, ...)
157 #if defined BB_INIT || defined BB_MKSWAP || defined BB_MOUNT || defined BB_NFSMOUNT
158 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
159 * so, for example, to check if the kernel is greater than 2.2.11:
160 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
162 extern int get_kernel_revision(void)
168 if (uname(&name) == -1) {
169 perror_msg("cannot get system information");
175 for (i=0 ; i<3 ; i++) {
176 r = r * 256 + atoi(strtok(s, "."));
185 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
186 _syscall1(int, sysinfo, struct sysinfo *, info);
189 #if defined BB_MOUNT || defined BB_UMOUNT
192 static const int __NR_umount2 = 52;
195 /* Include our own version of <sys/mount.h>, since libc5 doesn't
196 * know about umount2 */
197 extern _syscall1(int, umount, const char *, special_file);
198 extern _syscall2(int, umount2, const char *, special_file, int, flags);
199 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
200 const char *, fstype, unsigned long int, rwflag, const void *, data);
203 #if defined BB_INSMOD || defined BB_LSMOD
204 #ifndef __NR_query_module
205 static const int __NR_query_module = 167;
207 _syscall5(int, query_module, const char *, name, int, which,
208 void *, buf, size_t, bufsize, size_t*, ret);
212 #if defined (BB_CP_MV) || defined (BB_DU)
214 #define HASH_SIZE 311 /* Should be prime */
215 #define hash_inode(i) ((i) % HASH_SIZE)
217 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
220 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
221 * `ino_dev_hashtable', else return 0
223 * If NAME is a non-NULL pointer to a character pointer, and there is
224 * a match, then set *NAME to the value of the name slot in that
227 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
229 ino_dev_hashtable_bucket_t *bucket;
231 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
232 while (bucket != NULL) {
233 if ((bucket->ino == statbuf->st_ino) &&
234 (bucket->dev == statbuf->st_dev))
236 if (name) *name = bucket->name;
239 bucket = bucket->next;
244 /* Add statbuf to statbuf hash table */
245 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
249 ino_dev_hashtable_bucket_t *bucket;
251 i = hash_inode(statbuf->st_ino);
252 s = name ? strlen(name) : 0;
253 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
254 bucket->ino = statbuf->st_ino;
255 bucket->dev = statbuf->st_dev;
257 strcpy(bucket->name, name);
259 bucket->name[0] = '\0';
260 bucket->next = ino_dev_hashtable[i];
261 ino_dev_hashtable[i] = bucket;
264 /* Clear statbuf hash table */
265 void reset_ino_dev_hashtable(void)
268 ino_dev_hashtable_bucket_t *bucket;
270 for (i = 0; i < HASH_SIZE; i++) {
271 while (ino_dev_hashtable[i] != NULL) {
272 bucket = ino_dev_hashtable[i]->next;
273 free(ino_dev_hashtable[i]);
274 ino_dev_hashtable[i] = bucket;
279 #endif /* BB_CP_MV || BB_DU */
281 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN) || defined (BB_DPKG_DEB)
283 * Return TRUE if a fileName is a directory.
284 * Nonexistant files return FALSE.
286 int is_directory(const char *fileName, const int followLinks, struct stat *statBuf)
291 if (statBuf == NULL) {
292 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
296 if (followLinks == TRUE)
297 status = stat(fileName, statBuf);
299 status = lstat(fileName, statBuf);
301 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
314 #if defined BB_AR || defined BB_CP_MV
316 * Copy chunksize bytes between two file descriptors
318 int copy_file_chunk(int srcfd, int dstfd, size_t chunksize)
321 char buffer[BUFSIZ]; /* BUFSIZ is declared in stdio.h */
323 while (chunksize > 0) {
324 if (chunksize > BUFSIZ)
328 if (full_write(dstfd, buffer, full_read(srcfd, buffer, size)) < size)
337 #if defined (BB_CP_MV) || defined BB_DPKG
339 * Copy one file to another, while possibly preserving its modes, times, and
340 * modes. Returns TRUE if successful, or FALSE on a failure with an error
341 * message output. (Failure is not indicated if attributes cannot be set.)
345 copy_file(const char *srcName, const char *destName,
346 int setModes, int followLinks, int forceFlag)
351 struct stat srcStatBuf;
352 struct stat dstStatBuf;
353 struct utimbuf times;
355 if (followLinks == TRUE)
356 status = stat(srcName, &srcStatBuf);
358 status = lstat(srcName, &srcStatBuf);
361 perror_msg("%s", srcName);
365 if (followLinks == TRUE)
366 status = stat(destName, &dstStatBuf);
368 status = lstat(destName, &dstStatBuf);
370 if (status < 0 || forceFlag==TRUE) {
372 dstStatBuf.st_ino = -1;
373 dstStatBuf.st_dev = -1;
376 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
377 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
378 error_msg("Copying file \"%s\" to itself", srcName);
382 if (S_ISDIR(srcStatBuf.st_mode)) {
383 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
384 /* Make sure the directory is writable */
385 status = mkdir(destName, 0777777 ^ umask(0));
386 if (status < 0 && errno != EEXIST) {
387 perror_msg("%s", destName);
390 } else if (S_ISLNK(srcStatBuf.st_mode)) {
391 char link_val[BUFSIZ + 1];
394 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
395 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
396 link_size = readlink(srcName, &link_val[0], BUFSIZ);
398 perror_msg("%s", srcName);
401 link_val[link_size] = '\0';
402 status = symlink(link_val, destName);
404 perror_msg("%s", destName);
407 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
408 if (setModes == TRUE) {
409 /* Try to set owner, but fail silently like GNU cp */
410 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
414 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
415 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
416 if (mkfifo(destName, 0644) < 0) {
417 perror_msg("%s", destName);
420 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
421 || S_ISSOCK(srcStatBuf.st_mode)) {
422 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
423 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
424 perror_msg("%s", destName);
427 } else if (S_ISREG(srcStatBuf.st_mode)) {
428 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
429 rfd = open(srcName, O_RDONLY);
431 perror_msg("%s", srcName);
435 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
438 perror_msg("%s", destName);
443 if (copy_file_chunk(rfd, wfd, srcStatBuf.st_size)==FALSE)
447 if (close(wfd) < 0) {
452 if (setModes == TRUE) {
453 /* This is fine, since symlinks never get here */
454 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0)
455 perror_msg_and_die("%s", destName);
456 if (chmod(destName, srcStatBuf.st_mode) < 0)
457 perror_msg_and_die("%s", destName);
458 times.actime = srcStatBuf.st_atime;
459 times.modtime = srcStatBuf.st_mtime;
460 if (utime(destName, ×) < 0)
461 perror_msg_and_die("%s", destName);
467 perror_msg("%s", destName);
473 #endif /* BB_CP_MV */
477 #if defined BB_TAR || defined BB_LS ||defined BB_AR
479 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
480 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
482 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
483 static const mode_t SBIT[] = {
489 /* The 9 mode bits to test */
490 static const mode_t MBIT[] = {
491 S_IRUSR, S_IWUSR, S_IXUSR,
492 S_IRGRP, S_IWGRP, S_IXGRP,
493 S_IROTH, S_IWOTH, S_IXOTH
496 static const char MODE1[] = "rwxrwxrwx";
497 static const char MODE0[] = "---------";
498 static const char SMODE1[] = "..s..s..t";
499 static const char SMODE0[] = "..S..S..T";
502 * Return the standard ls-like mode string from a file mode.
503 * This is static and so is overwritten on each call.
505 const char *mode_string(int mode)
511 buf[0] = TYPECHAR(mode);
512 for (i = 0; i < 9; i++) {
514 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
516 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
520 #endif /* BB_TAR || BB_LS */
523 #if defined BB_TAR || defined BB_AR
525 * Return the standard ls-like time string from a time_t
526 * This is static and so is overwritten on each call.
528 const char *time_string(time_t timeVal)
536 str = ctime(&timeVal);
538 strcpy(buf, &str[4]);
541 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
542 strcpy(&buf[7], &str[20]);
548 #endif /* BB_TAR || BB_AR */
550 #if defined BB_DD || defined BB_NC || defined BB_TAIL || defined BB_TAR || defined BB_AR || defined BB_CP_MV
552 * Write all of the supplied buffer out to a file.
553 * This does multiple writes as necessary.
554 * Returns the amount written, or -1 on an error.
556 int full_write(int fd, const char *buf, int len)
564 cc = write(fd, buf, len);
578 #if defined BB_AR || defined BB_CP_MV || defined BB_SH || defined BB_TAR
580 * Read all of the supplied buffer from a file.
581 * This does multiple reads as necessary.
582 * Returns the amount read, or -1 on an error.
583 * A short read is returned on an end of file.
585 int full_read(int fd, char *buf, int len)
593 cc = read(fd, buf, len);
608 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
611 #if defined (BB_CHMOD_CHOWN_CHGRP) \
612 || defined (BB_CP_MV) \
613 || defined (BB_FIND) \
614 || defined (BB_INSMOD) \
620 * Walk down all the directories under the specified
621 * location, and do something (something specified
622 * by the fileAction and dirAction function pointers).
624 * Unfortunately, while nftw(3) could replace this and reduce
625 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
626 * and so isn't sufficiently portable to take over since glibc2.1
627 * is so stinking huge.
629 int recursive_action(const char *fileName,
630 int recurse, int followLinks, int depthFirst,
631 int (*fileAction) (const char *fileName,
632 struct stat * statbuf,
634 int (*dirAction) (const char *fileName,
635 struct stat * statbuf,
643 if (followLinks == TRUE)
644 status = stat(fileName, &statbuf);
646 status = lstat(fileName, &statbuf);
649 #ifdef BB_DEBUG_PRINT_SCAFFOLD
651 "status=%d followLinks=%d TRUE=%d\n",
652 status, followLinks, TRUE);
654 perror_msg("%s", fileName);
658 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
659 if (fileAction == NULL)
662 return fileAction(fileName, &statbuf, userData);
665 if (recurse == FALSE) {
666 if (S_ISDIR(statbuf.st_mode)) {
667 if (dirAction != NULL)
668 return (dirAction(fileName, &statbuf, userData));
674 if (S_ISDIR(statbuf.st_mode)) {
677 if (dirAction != NULL && depthFirst == FALSE) {
678 status = dirAction(fileName, &statbuf, userData);
679 if (status == FALSE) {
680 perror_msg("%s", fileName);
682 } else if (status == SKIP)
685 dir = opendir(fileName);
687 perror_msg("%s", fileName);
690 while ((next = readdir(dir)) != NULL) {
691 char nextFile[BUFSIZ + 1];
693 if ((strcmp(next->d_name, "..") == 0)
694 || (strcmp(next->d_name, ".") == 0)) {
697 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
698 error_msg(name_too_long);
701 memset(nextFile, 0, sizeof(nextFile));
702 sprintf(nextFile, "%s/%s", fileName, next->d_name);
704 recursive_action(nextFile, TRUE, followLinks, depthFirst,
705 fileAction, dirAction, userData);
706 if (status == FALSE) {
711 status = closedir(dir);
713 perror_msg("%s", fileName);
716 if (dirAction != NULL && depthFirst == TRUE) {
717 status = dirAction(fileName, &statbuf, userData);
718 if (status == FALSE) {
719 perror_msg("%s", fileName);
724 if (fileAction == NULL)
727 return fileAction(fileName, &statbuf, userData);
732 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
736 #if defined (BB_TAR) || defined (BB_MKDIR)
738 * Attempt to create the directories along the specified path, except for
739 * the final component. The mode is given for the final directory only,
740 * while all previous ones get default protections. Errors are not reported
741 * here, as failures to restore files can be reported later.
743 extern int create_path(const char *name, int mode)
747 char buf[BUFSIZ + 1];
751 for (cp = buf; *cp == '/'; cp++);
752 cp = strchr(cp, '/');
755 cp = strchr(cp + 1, '/');
757 retVal = mkdir(buf, cp ? 0777 : mode);
758 if (retVal != 0 && errno != EEXIST) {
759 perror_msg("%s", buf);
766 #endif /* BB_TAR || BB_MKDIR */
770 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
771 || defined (BB_MKFIFO) || defined (BB_MKNOD) || defined (BB_AR)
772 /* [ugoa]{+|-|=}[rwxst] */
774 extern int parse_mode(const char *s, mode_t * theMode)
776 static const mode_t group_set[] = {
777 S_ISUID | S_IRWXU, /* u */
778 S_ISGID | S_IRWXG, /* g */
780 S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO /* a */
783 static const mode_t mode_set[] = {
784 S_IRUSR | S_IRGRP | S_IROTH, /* r */
785 S_IWUSR | S_IWGRP | S_IWOTH, /* w */
786 S_IXUSR | S_IXGRP | S_IXOTH, /* x */
787 S_ISUID | S_ISGID, /* s */
791 static const char group_string[] = "ugoa";
792 static const char mode_string[] = "rwxst";
797 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
812 if ((c = *s++) == '\0') {
815 for (p=group_string ; *p ; p++) {
817 groups |= group_set[(int)(p-group_string)];
826 if (groups == 0) { /* The default is "all" */
827 groups |= S_ISUID | S_ISGID | S_ISVTX
828 | S_IRWXU | S_IRWXG | S_IRWXO;
832 if ((c < '0') || (c > '7') || (mode | groups)) {
835 *theMode = strtol(--s, NULL, 8);
841 if (((c = *s++) != '\0') && (c != ',')) {
842 for (p=mode_string ; *p ; p++) {
844 mode |= mode_set[(int)(p-mode_string)];
848 break; /* We're done so break out of loop.*/
852 andMode &= ~(groups); /* Now fall through. */
854 orMode |= mode & groups;
857 andMode &= ~(mode & groups);
858 orMode &= ~(mode & groups);
870 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
876 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
877 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
878 || defined BB_LOGNAME || defined BB_WHOAMI || defined BB_SH
879 /* returns a uid given a username */
880 long my_getpwnam(char *name)
882 struct passwd *myuser;
884 myuser = getpwnam(name);
888 return myuser->pw_uid;
891 /* returns a gid given a group name */
892 long my_getgrnam(char *name)
894 struct group *mygroup;
896 mygroup = getgrnam(name);
900 return (mygroup->gr_gid);
903 /* gets a username given a uid */
904 void my_getpwuid(char *name, long uid)
906 struct passwd *myuser;
908 myuser = getpwuid(uid);
910 sprintf(name, "%-8ld ", (long)uid);
912 strcpy(name, myuser->pw_name);
915 /* gets a groupname given a gid */
916 void my_getgrgid(char *group, long gid)
918 struct group *mygroup;
920 mygroup = getgrgid(gid);
922 sprintf(group, "%-8ld ", (long)gid);
924 strcpy(group, mygroup->gr_name);
928 /* gets a gid given a user name */
929 long my_getpwnamegid(char *name)
931 struct group *mygroup;
932 struct passwd *myuser;
934 myuser=getpwnam(name);
936 error_msg_and_die( "unknown user name: %s", name);
938 mygroup = getgrgid(myuser->pw_gid);
940 error_msg_and_die( "unknown gid %ld", (long)myuser->pw_gid);
942 return mygroup->gr_gid;
946 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
947 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
950 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
952 /* From <linux/kd.h> */
953 static const int KDGKBTYPE = 0x4B33; /* get keyboard type */
954 static const int KB_84 = 0x01;
955 static const int KB_101 = 0x02; /* this is what we always answer */
957 int is_a_console(int fd)
962 return (ioctl(fd, KDGKBTYPE, &arg) == 0
963 && ((arg == KB_101) || (arg == KB_84)));
966 static int open_a_console(char *fnam)
971 fd = open(fnam, O_RDWR);
973 /* if failed, try read-only */
974 if (fd < 0 && errno == EACCES)
975 fd = open(fnam, O_RDONLY);
977 /* if failed, try write-only */
978 if (fd < 0 && errno == EACCES)
979 fd = open(fnam, O_WRONLY);
981 /* if failed, fail */
985 /* if not a console, fail */
986 if (!is_a_console(fd)) {
996 * Get an fd for use with kbd/console ioctls.
997 * We try several things because opening /dev/console will fail
998 * if someone else used X (which does a chown on /dev/console).
1000 * if tty_name is non-NULL, try this one instead.
1003 int get_console_fd(char *tty_name)
1008 if (-1 == (fd = open_a_console(tty_name)))
1014 fd = open_a_console("/dev/tty");
1018 fd = open_a_console("/dev/tty0");
1022 fd = open_a_console("/dev/console");
1026 for (fd = 0; fd < 3; fd++)
1027 if (is_a_console(fd))
1030 error_msg("Couldnt get a file descriptor referring to the console");
1031 return -1; /* total failure */
1035 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1038 #if defined BB_FIND || defined BB_INSMOD
1040 * Routine to see if a text string is matched by a wildcard pattern.
1041 * Returns TRUE if the text is matched, or FALSE if it is not matched
1042 * or if the pattern is invalid.
1043 * * matches zero or more characters
1044 * ? matches a single character
1045 * [abc] matches 'a', 'b' or 'c'
1046 * \c quotes character c
1047 * Adapted from code written by Ingo Wilken, and
1048 * then taken from sash, Copyright (c) 1999 by David I. Bell
1049 * Permission is granted to use, distribute, or modify this source,
1050 * provided that this copyright notice remains intact.
1051 * Permission to distribute this code under the GPL has been granted.
1053 extern int check_wildcard_match(const char *text, const char *pattern)
1055 const char *retryPat;
1056 const char *retryText;
1064 while (*text || *pattern) {
1076 while ((ch = *pattern++) != ']') {
1087 if (found == FALSE && len!=0) {
1090 if (found == TRUE) {
1091 if (strlen(pattern)==0 && len==1) {
1100 /* fall into next case */
1103 if (*text++ == '\0')
1114 /* fall into next case */
1132 if (pattern == NULL)
1138 #endif /* BB_FIND || BB_INSMOD */
1143 #if defined BB_DF || defined BB_MTAB
1146 * Given a block device, find the mount table entry if that block device
1149 * Given any other file (or directory), find the mount table entry for its
1152 extern struct mntent *find_mount_point(const char *name, const char *table)
1157 struct mntent *mountEntry;
1159 if (stat(name, &s) != 0)
1162 if ((s.st_mode & S_IFMT) == S_IFBLK)
1163 mountDevice = s.st_rdev;
1165 mountDevice = s.st_dev;
1168 if ((mountTable = setmntent(table, "r")) == 0)
1171 while ((mountEntry = getmntent(mountTable)) != 0) {
1172 if (strcmp(name, mountEntry->mnt_dir) == 0
1173 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1175 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1177 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1180 endmntent(mountTable);
1183 #endif /* BB_DF || BB_MTAB */
1185 #if defined BB_INIT || defined BB_SYSLOGD
1186 /* try to open up the specified device */
1187 extern int device_open(char *device, int mode)
1191 m = mode | O_NONBLOCK;
1193 /* Retry up to 5 times */
1194 for (f = 0; f < 5; f++)
1195 if ((fd = open(device, m, 0600)) >= 0)
1199 /* Reset original flags. */
1201 fcntl(fd, F_SETFL, mode);
1204 #endif /* BB_INIT BB_SYSLOGD */
1207 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1208 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1209 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1212 #if defined BB_FEATURE_USE_DEVPS_PATCH
1213 /* find_pid_by_name()
1215 * This finds the pid of the specified process,
1216 * by using the /dev/ps device driver.
1218 * Returns a list of all matching PIDs
1220 extern pid_t* find_pid_by_name( char* pidName)
1223 char device[] = "/dev/ps";
1225 pid_t* pid_array = NULL;
1226 pid_t* pidList=NULL;
1229 fd = open(device, O_RDONLY);
1231 perror_msg_and_die("open failed for `%s'", device);
1233 /* Find out how many processes there are */
1234 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1235 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1237 /* Allocate some memory -- grab a few extras just in case
1238 * some new processes start up while we wait. The kernel will
1239 * just ignore any extras if we give it too many, and will trunc.
1240 * the list if we give it too few. */
1241 pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1242 pid_array[0] = num_pids+10;
1244 /* Now grab the pid list */
1245 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1246 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1248 /* Now search for a match */
1249 for (i=1, j=0; i<pid_array[0] ; i++) {
1251 struct pid_info info;
1253 info.pid = pid_array[i];
1254 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1255 perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1257 /* Make sure we only match on the process name */
1258 p=info.command_line+1;
1259 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1265 if ((strstr(info.command_line, pidName) != NULL)
1266 && (strlen(pidName) == strlen(info.command_line))) {
1267 pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1268 pidList[j++]=info.pid;
1278 if (close (fd) != 0)
1279 perror_msg_and_die("close failed for `%s'", device);
1283 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1285 /* find_pid_by_name()
1287 * This finds the pid of the specified process.
1288 * Currently, it's implemented by rummaging through
1289 * the proc filesystem.
1291 * Returns a list of all matching PIDs
1293 extern pid_t* find_pid_by_name( char* pidName)
1296 struct dirent *next;
1297 pid_t* pidList=NULL;
1300 dir = opendir("/proc");
1302 perror_msg_and_die("Cannot open /proc");
1304 while ((next = readdir(dir)) != NULL) {
1309 /* If it isn't a number, we don't want it */
1310 if (!isdigit(*next->d_name))
1313 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1314 status = fopen(filename, "r");
1318 fgets(buffer, 256, status);
1321 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1322 pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1323 pidList[i++]=strtol(next->d_name, NULL, 0);
1331 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1332 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1335 /* this should really be farmed out to libbusybox.a */
1336 extern void *xmalloc(size_t size)
1338 void *ptr = malloc(size);
1341 error_msg_and_die(memory_exhausted);
1345 extern void *xrealloc(void *old, size_t size)
1347 void *ptr = realloc(old, size);
1349 error_msg_and_die(memory_exhausted);
1353 extern void *xcalloc(size_t nmemb, size_t size)
1355 void *ptr = calloc(nmemb, size);
1357 error_msg_and_die(memory_exhausted);
1362 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || \
1363 defined BB_WGET || defined BB_DPKG_DEB || defined BB_TAR || \
1366 extern char * xstrdup (const char *s) {
1375 error_msg_and_die(memory_exhausted);
1382 #if defined BB_NFSMOUNT
1383 extern char * xstrndup (const char *s, int n) {
1387 error_msg_and_die("xstrndup bug");
1391 return safe_strncpy(t,s,n);
1395 #if defined BB_IFCONFIG || defined BB_ROUTE || defined BB_NFSMOUNT || \
1396 defined BB_FEATURE_MOUNT_LOOP
1397 /* Like strncpy but make sure the resulting string is always 0 terminated. */
1398 extern char * safe_strncpy(char *dst, const char *src, size_t size)
1401 return strncpy(dst, src, size-1);
1405 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1406 extern int vdprintf(int d, const char *format, va_list ap)
1411 len = vsprintf(buf, format, ap);
1412 return write(d, buf, len);
1414 #endif /* BB_SYSLOGD */
1417 #if defined BB_FEATURE_MOUNT_LOOP
1419 #include "loop.h" /* Pull in loop device support */
1421 extern int del_loop(const char *device)
1425 if ((fd = open(device, O_RDONLY)) < 0) {
1426 perror_msg("%s", device);
1429 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1430 perror_msg("ioctl: LOOP_CLR_FD");
1437 extern int set_loop(const char *device, const char *file, int offset,
1440 struct loop_info loopinfo;
1443 mode = *loopro ? O_RDONLY : O_RDWR;
1444 if ((ffd = open(file, mode)) < 0 && !*loopro
1445 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1446 perror_msg("%s", file);
1449 if ((fd = open(device, mode)) < 0) {
1451 perror_msg("%s", device);
1454 *loopro = (mode == O_RDONLY);
1456 memset(&loopinfo, 0, sizeof(loopinfo));
1457 safe_strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1459 loopinfo.lo_offset = offset;
1461 loopinfo.lo_encrypt_key_size = 0;
1462 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1463 perror_msg("ioctl: LOOP_SET_FD");
1468 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1469 (void) ioctl(fd, LOOP_CLR_FD, 0);
1470 perror_msg("ioctl: LOOP_SET_STATUS");
1480 extern char *find_unused_loop_device(void)
1484 struct stat statbuf;
1485 struct loop_info loopinfo;
1487 for (i = 0; i <= 7; i++) {
1488 sprintf(dev, "/dev/loop%d", i);
1489 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1490 if ((fd = open(dev, O_RDONLY)) >= 0) {
1491 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1492 if (errno == ENXIO) { /* probably free */
1503 #endif /* BB_FEATURE_MOUNT_LOOP */
1505 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1506 extern int find_real_root_device_name(char* name)
1509 struct dirent *entry;
1510 struct stat statBuf, rootStat;
1511 char fileName[BUFSIZ];
1513 if (stat("/", &rootStat) != 0) {
1514 error_msg("could not stat '/'");
1518 dir = opendir("/dev");
1520 error_msg("could not open '/dev'");
1524 while((entry = readdir(dir)) != NULL) {
1526 /* Must skip ".." since that is "/", and so we
1527 * would get a false positive on ".." */
1528 if (strcmp(entry->d_name, "..") == 0)
1531 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1533 if (stat(fileName, &statBuf) != 0)
1535 /* Some char devices have the same dev_t as block
1536 * devices, so make sure this is a block device */
1537 if (! S_ISBLK(statBuf.st_mode))
1539 if (statBuf.st_rdev == rootStat.st_rdev) {
1540 strcpy(name, fileName);
1550 /* get_line_from_file() - This function reads an entire line from a text file
1551 * up to a newline. It returns a malloc'ed char * which must be stored and
1552 * free'ed by the caller. */
1553 extern char *get_line_from_file(FILE *file)
1555 static const int GROWBY = 80; /* how large we will grow strings by */
1559 char *linebuf = NULL;
1566 /* grow the line buffer as necessary */
1567 while (idx > linebufsz-2)
1568 linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1569 linebuf[idx++] = (char)ch;
1570 if ((char)ch == '\n')
1582 extern void print_file(FILE *file)
1586 while ((c = getc(file)) != EOF)
1592 extern int print_file_by_name(char *filename)
1595 if ((file = wfopen(filename, "r")) == NULL)
1602 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1603 char process_escape_sequence(char **ptr)
1605 static const char charmap[] = {
1606 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', 0,
1607 '\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '\\' };
1617 for ( num_digits = 0 ; num_digits < 3 ; ++num_digits) {
1618 if ((*q < '0') || (*q > '7')) { /* not a digit? */
1621 n = n * 8 + (*q++ - '0');
1624 if (num_digits == 0) { /* mnemonic escape sequence? */
1625 for (p=charmap ; *p ; p++) {
1631 n = *(p+(sizeof(charmap)/2));
1634 /* doesn't hurt to fall through to here from mnemonic case */
1635 if (n > UCHAR_MAX) { /* is octal code too big for a char? */
1636 n /= 8; /* adjust value and */
1637 --q; /* back up one char */
1645 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1646 ! defined BB_FEATURE_USE_DEVPS_PATCH || defined BB_WGET
1647 char *get_last_path_component(char *path)
1649 char *s=path+strlen(path)-1;
1651 /* strip trailing slashes */
1652 while (s != path && *s == '/') {
1656 /* find last component */
1657 s = strrchr(path, '/');
1658 if (s == NULL || s[1] == '\0')
1665 #if defined BB_GREP || defined BB_SED
1667 void xregcomp(regex_t *preg, const char *regex, int cflags)
1670 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1671 int errmsgsz = regerror(ret, preg, NULL, 0);
1672 char *errmsg = xmalloc(errmsgsz);
1673 regerror(ret, preg, errmsg, errmsgsz);
1674 error_msg_and_die("xregcomp: %s", errmsg);
1679 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1680 FILE *wfopen(const char *path, const char *mode)
1683 if ((fp = fopen(path, mode)) == NULL) {
1684 perror_msg("%s", path);
1691 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1692 || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1693 || defined BB_WC || defined BB_CMP || defined BB_SORT || defined BB_WGET \
1694 || defined BB_MOUNT || defined BB_ROUTE
1695 FILE *xfopen(const char *path, const char *mode)
1698 if ((fp = fopen(path, mode)) == NULL)
1699 perror_msg_and_die("%s", path);
1704 static int applet_name_compare(const void *x, const void *y)
1706 const char *name = x;
1707 const struct BB_applet *applet = y;
1709 return strcmp(name, applet->name);
1712 extern size_t NUM_APPLETS;
1714 struct BB_applet *find_applet_by_name(const char *name)
1716 return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
1717 applet_name_compare);
1720 void run_applet_by_name(const char *name, int argc, char **argv)
1722 /* Do a binary search to find the applet entry given the name. */
1723 if ((applet_using = find_applet_by_name(name)) != NULL) {
1724 applet_name = applet_using->name;
1725 if (argv[1] && strcmp(argv[1], "--help") == 0)
1727 exit((*(applet_using->main)) (argc, argv));
1731 #if defined BB_DD || defined BB_TAIL || defined BB_STTY
1732 unsigned long parse_number(const char *numstr,
1733 const struct suffix_mult *suffixes)
1735 const struct suffix_mult *sm;
1736 unsigned long int ret;
1740 ret = strtoul(numstr, &end, 10);
1742 error_msg_and_die("invalid number `%s'", numstr);
1743 while (end[0] != '\0') {
1747 len = strlen(sm->suffix);
1748 if (strncmp(sm->suffix, end, len) == 0) {
1759 error_msg_and_die("invalid number `%s'", numstr);
1765 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1766 ssize_t safe_read(int fd, void *buf, size_t count)
1771 n = read(fd, buf, count);
1772 } while (n < 0 && errno == EINTR);
1778 #ifdef BB_FEATURE_HUMAN_READABLE
1779 const char *format(unsigned long val, unsigned long hr)
1781 static const char strings[] = { '0', 0, 'k', 0, 'M', 0, 'G', 0 };
1782 static const char fmt[] = "%lu";
1783 static const char fmt_u[] = "%lu.%lu%s";
1785 static char str[10];
1787 unsigned long frac __attribute__ ((unused)); /* 'may be uninitialized' warning is ok */
1792 if(val == 0) { /* This may be omitted to reduce size */
1793 return strings; /* at the cost of speed. */
1802 while ((val >= KILOBYTE) && (*u != 'G')) {
1805 frac = (((val % KILOBYTE) * 10) + (KILOBYTE/2)) / KILOBYTE;
1807 if (frac >= 10) { /* We need to round up here. */
1814 /* If f==fmt then 'frac' and 'u' are ignored and need not be set. */
1815 snprintf(str, sizeof(str), f, val, frac, u);
1821 #if defined(BB_GREP) || defined(BB_HOSTNAME) || defined(BB_SED) || defined(BB_TAR) || defined(BB_WGET) || defined(BB_XARGS)
1824 size_t len = strlen(s);
1829 if (s[len-1] == '\n')
1837 c-file-style: "linux"