4 * Copyright (C) tons of folks. Tracking down who wrote what
5 * isn't something I'm going to worry about... If you wrote something
6 * here, please feel free to acknowledge your work.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * Based in part on code from sash, Copyright (c) 1999 by David I. Bell
23 * Permission has been granted to redistribute this code under the GPL.
28 #if defined (BB_CHMOD_CHOWN_CHGRP) \
29 || defined (BB_CP_MV) \
30 || defined (BB_FIND) \
32 || defined (BB_INSMOD)
33 /* same conditions as recursiveAction */
34 #define bb_need_name_too_long
36 #define BB_DECLARE_EXTERN
49 #include <sys/param.h> /* for PATH_MAX */
51 #if defined BB_FEATURE_MOUNT_LOOP
53 #include <sys/ioctl.h>
54 #include <linux/loop.h>
58 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
59 # if defined BB_FEATURE_USE_PROCFS
60 const char mtab_file[] = "/proc/mounts";
63 const char mtab_file[] = "/etc/mtab";
65 # error With (BB_MOUNT||BB_UMOUNT||BB_DF) defined, you must define either BB_MTAB or BB_FEATURE_USE_PROCFS
71 extern void usage(const char *usage)
73 fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
75 fprintf(stderr, "Usage: %s\n", usage);
80 #if defined (BB_INIT) || defined (BB_PS)
82 #if ! defined BB_FEATURE_USE_PROCFS
83 #error Sorry, I depend on the /proc filesystem right now.
85 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
86 * so, for example, to check if the kernel is greater than 2.2.11:
87 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
93 int major=0, minor=0, patch=0;
95 file = fopen("/proc/sys/kernel/osrelease", "r");
97 /* bummer, /proc must not be mounted... */
100 fscanf(file,"%d.%d.%d",&major,&minor,&patch);
102 return major*65536 + minor*256 + patch;
104 #endif /* BB_INIT || BB_PS */
108 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
110 * Return TRUE if a fileName is a directory.
111 * Nonexistant files return FALSE.
113 int isDirectory(const char *fileName, const int followLinks)
118 if (followLinks == TRUE)
119 status = stat(fileName, &statBuf);
121 status = lstat(fileName, &statBuf);
125 if (S_ISDIR(statBuf.st_mode))
131 #if defined (BB_CP_MV)
133 * Copy one file to another, while possibly preserving its modes, times,
134 * and modes. Returns TRUE if successful, or FALSE on a failure with an
135 * error message output. (Failure is not indicted if the attributes cannot
140 copyFile( const char *srcName, const char *destName,
141 int setModes, int followLinks)
148 struct stat srcStatBuf;
149 struct stat dstStatBuf;
150 struct utimbuf times;
152 if (followLinks == TRUE)
153 status = stat(srcName, &srcStatBuf);
155 status = lstat(srcName, &srcStatBuf);
162 if (followLinks == TRUE)
163 status = stat(destName, &dstStatBuf);
165 status = lstat(destName, &dstStatBuf);
168 dstStatBuf.st_ino = -1;
169 dstStatBuf.st_dev = -1;
172 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
173 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
174 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
178 if (S_ISDIR(srcStatBuf.st_mode)) {
179 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
180 /* Make sure the directory is writable */
181 status = mkdir(destName, 0777777 ^ umask(0));
182 if (status < 0 && errno != EEXIST) {
186 } else if (S_ISLNK(srcStatBuf.st_mode)) {
187 char link_val[PATH_MAX + 1];
190 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
191 /* Warning: This could possibly truncate silently, to PATH_MAX chars */
192 link_size = readlink(srcName, &link_val[0], PATH_MAX);
197 link_val[link_size] = '\0';
198 status = symlink(link_val, destName);
203 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
204 if (setModes == TRUE) {
205 if (lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
212 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
213 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
214 if (mkfifo(destName, 0644) < 0) {
218 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
219 || S_ISSOCK (srcStatBuf.st_mode)) {
220 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
221 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
225 } else if (S_ISREG(srcStatBuf.st_mode)) {
226 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
227 rfd = open(srcName, O_RDONLY);
233 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC, srcStatBuf.st_mode);
240 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
241 if (fullWrite(wfd, buf, rcc) < 0)
249 if (close(wfd) < 0) {
254 if (setModes == TRUE) {
255 /* This is fine, since symlinks never get here */
256 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
260 if (chmod(destName, srcStatBuf.st_mode) < 0) {
264 times.actime = srcStatBuf.st_atime;
265 times.modtime = srcStatBuf.st_mtime;
266 if (utime(destName, ×) < 0) {
281 #endif /* BB_CP_MV */
285 #if defined BB_TAR || defined BB_LS
287 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
288 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
290 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
291 static const mode_t SBIT[] = {
297 /* The 9 mode bits to test */
298 static const mode_t MBIT[] = {
299 S_IRUSR, S_IWUSR, S_IXUSR,
300 S_IRGRP, S_IWGRP, S_IXGRP,
301 S_IROTH, S_IWOTH, S_IXOTH
304 #define MODE1 "rwxrwxrwx"
305 #define MODE0 "---------"
306 #define SMODE1 "..s..s..t"
307 #define SMODE0 "..S..S..T"
310 * Return the standard ls-like mode string from a file mode.
311 * This is static and so is overwritten on each call.
313 const char *modeString(int mode)
318 buf[0] = TYPECHAR(mode);
319 for (i=0; i<9; i++) {
321 buf[i+1] = (mode & MBIT[i])?
322 SMODE1[i] : SMODE0[i];
324 buf[i+1] = (mode & MBIT[i])?
329 #endif /* BB_TAR || BB_LS */
334 * Return the standard ls-like time string from a time_t
335 * This is static and so is overwritten on each call.
337 const char *timeString(time_t timeVal)
345 str = ctime(&timeVal);
347 strcpy(buf, &str[4]);
350 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
351 strcpy(&buf[7], &str[20]);
359 #if defined BB_TAR || defined BB_CP_MV
361 * Write all of the supplied buffer out to a file.
362 * This does multiple writes as necessary.
363 * Returns the amount written, or -1 on an error.
365 int fullWrite(int fd, const char *buf, int len)
373 cc = write(fd, buf, len);
385 #endif /* BB_TAR || BB_CP_MV */
388 #if defined BB_TAR || defined BB_TAIL
390 * Read all of the supplied buffer from a file.
391 * This does multiple reads as necessary.
392 * Returns the amount read, or -1 on an error.
393 * A short read is returned on an end of file.
395 int fullRead(int fd, char *buf, int len)
403 cc = read(fd, buf, len);
418 #endif /* BB_TAR || BB_TAIL */
421 #if defined (BB_CHMOD_CHOWN_CHGRP) \
422 || defined (BB_CP_MV) \
423 || defined (BB_FIND) \
425 || defined (BB_INSMOD)
427 * Walk down all the directories under the specified
428 * location, and do something (something specified
429 * by the fileAction and dirAction function pointers).
431 * Unfortunatly, while nftw(3) could replace this and reduce
432 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
433 * and so isn't sufficiently portable to take over since glibc2.1
434 * is so stinking huge.
436 int recursiveAction(const char *fileName,
437 int recurse, int followLinks, int depthFirst,
438 int (*fileAction) (const char *fileName,
439 struct stat* statbuf),
440 int (*dirAction) (const char *fileName,
441 struct stat* statbuf))
447 if (followLinks == TRUE)
448 status = stat(fileName, &statbuf);
450 status = lstat(fileName, &statbuf);
453 #ifdef BB_DEBUG_PRINT_SCAFFOLD
455 "status=%d followLinks=%d TRUE=%d\n",
456 status, followLinks, TRUE);
462 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode)) ) {
463 if (fileAction == NULL)
466 return fileAction(fileName, &statbuf);
469 if (recurse == FALSE) {
470 if (S_ISDIR(statbuf.st_mode)) {
471 if (dirAction != NULL)
472 return (dirAction(fileName, &statbuf));
478 if (S_ISDIR(statbuf.st_mode)) {
480 dir = opendir(fileName);
485 if (dirAction != NULL && depthFirst == FALSE) {
486 status = dirAction(fileName, &statbuf);
487 if (status == FALSE) {
492 while ((next = readdir(dir)) != NULL) {
493 char nextFile[PATH_MAX + 1];
494 if ((strcmp(next->d_name, "..") == 0)
495 || (strcmp(next->d_name, ".") == 0)) {
498 if (strlen(fileName) + strlen(next->d_name) + 1 > PATH_MAX) {
499 fprintf(stderr, name_too_long, "ftw");
502 sprintf(nextFile, "%s/%s", fileName, next->d_name);
504 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
505 fileAction, dirAction);
511 status = closedir(dir);
516 if (dirAction != NULL && depthFirst == TRUE) {
517 status = dirAction(fileName, &statbuf);
518 if (status == FALSE) {
524 if (fileAction == NULL)
527 return fileAction(fileName, &statbuf);
532 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
536 #if defined (BB_TAR) || defined (BB_MKDIR)
538 * Attempt to create the directories along the specified path, except for
539 * the final component. The mode is given for the final directory only,
540 * while all previous ones get default protections. Errors are not reported
541 * here, as failures to restore files can be reported later.
543 extern int createPath (const char *name, int mode)
547 char buf[PATH_MAX + 1];
551 cp = strchr(buf, '/');
554 cp = strchr(cp + 1, '/');
556 retVal = mkdir(buf, cp ? 0777 : mode);
557 if (retVal != 0 && errno != EEXIST) {
565 #endif /* BB_TAR || BB_MKDIR */
569 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
570 /* [ugoa]{+|-|=}[rwxst] */
575 parse_mode( const char* s, mode_t* theMode)
577 mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
586 switch ( c = *s++ ) {
590 groups |= S_ISUID|S_IRWXU;
593 groups |= S_ISGID|S_IRWXG;
599 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
605 if ( groups == 0 ) /* The default is "all" */
606 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
609 if ( isdigit(c) && c >= '0' && c <= '7' &&
610 mode == 0 && groups == 0 ) {
611 *theMode = strtol(--s, NULL, 8);
620 while ( (c = *s++) != '\0' ) {
625 mode |= S_IRUSR|S_IRGRP|S_IROTH;
628 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
631 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
634 mode |= S_IXGRP|S_ISUID|S_ISGID;
648 andMode &= ~(groups);
651 orMode |= mode & groups;
654 andMode &= ~(mode & groups);
658 } while ( c == ',' );
665 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
673 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
675 /* Use this to avoid needing the glibc NSS stuff
676 * This uses storage buf to hold things.
679 my_getid(const char *filename, char *name, uid_t id)
682 char *rname, *start, *end, buf[128];
685 file=fopen(filename,"r");
691 while (fgets (buf, 128, file) != NULL) {
696 end = strchr (start, ':');
703 end = strchr (start, ':');
708 rid = (uid_t) strtol (start, &end, 10);
713 if (0 == strcmp(rname, name)) {
718 if ( id != -1 && id == rid ) {
719 strncpy(name, rname, 8);
729 my_getpwnam(char *name)
731 return my_getid("/etc/passwd", name, -1);
735 my_getgrnam(char *name)
737 return my_getid("/etc/group", name, -1);
741 my_getpwuid(char* name, uid_t uid)
743 my_getid("/etc/passwd", name, uid);
747 my_getgrgid(char* group, gid_t gid)
749 my_getid("/etc/group", group, gid);
753 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS */
758 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
761 #include <linux/kd.h>
762 #include <sys/ioctl.h>
764 int is_a_console(int fd)
769 return (ioctl(fd, KDGKBTYPE, &arg) == 0
770 && ((arg == KB_101) || (arg == KB_84)));
773 static int open_a_console(char *fnam)
778 fd = open(fnam, O_RDWR);
780 /* if failed, try read-only */
781 if (fd < 0 && errno == EACCES)
782 fd = open(fnam, O_RDONLY);
784 /* if failed, try write-only */
785 if (fd < 0 && errno == EACCES)
786 fd = open(fnam, O_WRONLY);
788 /* if failed, fail */
792 /* if not a console, fail */
793 if (! is_a_console(fd))
804 * Get an fd for use with kbd/console ioctls.
805 * We try several things because opening /dev/console will fail
806 * if someone else used X (which does a chown on /dev/console).
808 * if tty_name is non-NULL, try this one instead.
811 int get_console_fd(char* tty_name)
817 if (-1 == (fd = open_a_console(tty_name)))
823 fd = open_a_console("/dev/tty");
827 fd = open_a_console("/dev/tty0");
831 fd = open_a_console("/dev/console");
835 for (fd = 0; fd < 3; fd++)
836 if (is_a_console(fd))
840 "Couldnt get a file descriptor referring to the console\n");
841 return -1; /* total failure */
845 #endif /* BB_CHVT || BB_DEALLOCVT */
848 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
850 /* Do a case insensitive strstr() */
851 char* stristr(char *haystack, const char *needle)
853 int len = strlen( needle );
855 if( !strncasecmp( haystack, needle, len ) )
866 /* This tries to find a needle in a haystack, but does so by
867 * only trying to match literal strings (look 'ma, no regexps!)
868 * This is short, sweet, and carries _very_ little baggage,
869 * unlike its beefier cousin in regexp.c
872 extern int find_match(char *haystack, char *needle, int ignoreCase)
875 if (ignoreCase == FALSE)
876 haystack = strstr (haystack, needle);
878 haystack = stristr (haystack, needle);
879 if (haystack == NULL)
885 /* This performs substitutions after a string match has been found. */
886 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
889 char *where, *slider, *slider1, *oldhayStack;
891 if (ignoreCase == FALSE)
892 where = strstr (haystack, needle);
894 where = stristr (haystack, needle);
896 if (strcmp(needle, newNeedle)==0)
899 oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
902 strcpy(oldhayStack, haystack);
904 if ( strlen(newNeedle) > strlen(needle)) {
905 haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) -
906 strlen(needle) + strlen(newNeedle)));
909 for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
911 haystack=strcat(haystack, newNeedle);
912 slider1+=strlen(needle);
913 haystack = strcat(haystack, slider1);
914 where = strstr (slider, needle);
924 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
929 * Routine to see if a text string is matched by a wildcard pattern.
930 * Returns TRUE if the text is matched, or FALSE if it is not matched
931 * or if the pattern is invalid.
932 * * matches zero or more characters
933 * ? matches a single character
934 * [abc] matches 'a', 'b' or 'c'
935 * \c quotes character c
936 * Adapted from code written by Ingo Wilken, and
937 * then taken from sash, Copyright (c) 1999 by David I. Bell
938 * Permission is granted to use, distribute, or modify this source,
939 * provided that this copyright notice remains intact.
940 * Permission to distribute this code under the GPL has been granted.
943 check_wildcard_match(const char* text, const char* pattern)
945 const char* retryPat;
946 const char* retryText;
953 while (*text || *pattern)
967 while ((ch = *pattern++) != ']')
986 /* fall into next case */
1000 /* fall into next case */
1020 if (pattern == NULL)
1026 #endif /* BB_FIND */
1031 #if defined BB_DF || defined BB_MTAB
1033 * Given a block device, find the mount table entry if that block device
1036 * Given any other file (or directory), find the mount table entry for its
1039 extern struct mntent *findMountPoint(const char *name, const char *table)
1044 struct mntent *mountEntry;
1046 if (stat(name, &s) != 0)
1049 if ((s.st_mode & S_IFMT) == S_IFBLK)
1050 mountDevice = s.st_rdev;
1052 mountDevice = s.st_dev;
1055 if ((mountTable = setmntent(table, "r")) == 0)
1058 while ((mountEntry = getmntent(mountTable)) != 0) {
1059 if (strcmp(name, mountEntry->mnt_dir) == 0
1060 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1062 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1064 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1067 endmntent(mountTable);
1070 #endif /* BB_DF || BB_MTAB */
1074 #if defined BB_DD || defined BB_TAIL
1076 * Read a number with a possible multiplier.
1077 * Returns -1 if the number format is illegal.
1079 extern long getNum (const char *cp)
1083 if (!isDecimal (*cp))
1088 while (isDecimal (*cp))
1089 value = value * 10 + *cp++ - '0';
1093 case 'm': /* `tail' uses it traditionally */
1121 #endif /* BB_DD || BB_TAIL */
1124 #if defined BB_INIT || defined BB_SYSLOGD
1125 /* try to open up the specified device */
1126 extern int device_open(char *device, int mode)
1130 m = mode | O_NONBLOCK;
1132 /* Retry up to 5 times */
1133 for (f = 0; f < 5; f++)
1134 if ((fd = open(device, m, 0600)) >= 0)
1138 /* Reset original flags. */
1140 fcntl(fd, F_SETFL, mode);
1143 #endif /* BB_INIT BB_SYSLOGD */
1146 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT
1148 #if ! defined BB_FEATURE_USE_PROCFS
1149 #error Sorry, I depend on the /proc filesystem right now.
1153 * This finds the pid of init (which is not always 1).
1154 * Currently, it's implemented by rummaging through the proc filesystem.
1158 * pid when init's pid is found.
1167 /* no need to opendir ;) */
1168 for (init_pid = 1; init_pid < 65536; init_pid++) {
1171 sprintf(filename, "/proc/%d/status", init_pid);
1172 status = fopen(filename, "r");
1173 if (!status) { continue; }
1174 fgets(buffer, 256, status);
1177 if ( (strstr(buffer, "init\n") != NULL )) {
1183 #endif /* BB_INIT || BB_HALT || BB_REBOOT */
1185 #if defined BB_GUNZIP \
1186 || defined BB_GZIP \
1187 || defined BB_PRINTF \
1189 extern void *xmalloc (size_t size)
1191 void *cp = malloc (size);
1194 error("out of memory");
1199 extern void error(char *msg)
1201 fprintf(stderr, "\n%s\n", msg);
1204 #endif /* BB_GUNZIP || BB_GZIP || BB_PRINTF || BB_TAIL */
1206 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1207 extern int vdprintf(int d, const char *format, va_list ap)
1212 len = vsprintf(buf, format, ap);
1213 return write(d, buf, len);
1215 #endif /* BB_SYSLOGD */
1217 #if defined BB_FEATURE_MOUNT_LOOP
1218 extern int del_loop(const char *device)
1222 if ((fd = open(device, O_RDONLY)) < 0) {
1226 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1227 perror("ioctl: LOOP_CLR_FD");
1234 extern int set_loop(const char *device, const char *file, int offset, int *loopro)
1236 struct loop_info loopinfo;
1239 mode = *loopro ? O_RDONLY : O_RDWR;
1240 if ((ffd = open (file, mode)) < 0 && !*loopro
1241 && (errno != EROFS || (ffd = open (file, mode = O_RDONLY)) < 0)) {
1245 if ((fd = open (device, mode)) < 0) {
1250 *loopro = (mode == O_RDONLY);
1252 memset(&loopinfo, 0, sizeof(loopinfo));
1253 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1254 loopinfo.lo_name[LO_NAME_SIZE-1] = 0;
1256 loopinfo.lo_offset = offset;
1258 loopinfo.lo_encrypt_key_size = 0;
1259 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1260 perror("ioctl: LOOP_SET_FD");
1265 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1266 (void) ioctl(fd, LOOP_CLR_FD, 0);
1267 perror("ioctl: LOOP_SET_STATUS");
1277 extern char *find_unused_loop_device (void)
1281 struct stat statbuf;
1282 struct loop_info loopinfo;
1284 for(i = 0; i <= 7; i++) {
1285 sprintf(dev, "/dev/loop%d", i);
1286 if (stat (dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1287 if ((fd = open (dev, O_RDONLY)) >= 0) {
1288 if(ioctl (fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1289 if (errno == ENXIO) { /* probably free */
1300 #endif /* BB_FEATURE_MOUNT_LOOP */