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.
39 #if defined BB_FEATURE_MOUNT_LOOP
41 #include <sys/ioctl.h>
42 #include <linux/loop.h>
46 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
47 # if defined BB_FEATURE_USE_PROCFS
48 const char mtab_file[] = "/proc/mounts";
51 const char mtab_file[] = "/etc/mtab";
53 # error With (BB_MOUNT||BB_UMOUNT||BB_DF) defined, you must define either BB_MTAB or BB_FEATURE_USE_PROCFS
59 extern void usage(const char *usage)
61 fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n", BB_VER, BB_BT);
62 fprintf(stderr, "Usage: %s\n", usage);
67 #if defined (BB_INIT) || defined (BB_PS)
69 #if ! defined BB_FEATURE_USE_PROCFS
70 #error Sorry, I depend on the /proc filesystem right now.
72 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
73 * so, for example, to check if the kernel is greater than 2.2.11:
74 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
80 int major=0, minor=0, patch=0;
81 char* filename="/proc/sys/kernel/osrelease";
83 file = fopen(filename,"r");
85 /* bummer, /proc must not be mounted... */
88 fscanf(file,"%d.%d.%d",&major,&minor,&patch);
90 return major*65536 + minor*256 + patch;
97 #if defined (BB_CP) || defined (BB_MV)
99 * Return TRUE if a fileName is a directory.
100 * Nonexistant files return FALSE.
102 int isDirectory(const char *name)
106 if (stat(name, &statBuf) < 0)
108 if (S_ISDIR(statBuf.st_mode))
115 * Copy one file to another, while possibly preserving its modes, times,
116 * and modes. Returns TRUE if successful, or FALSE on a failure with an
117 * error message output. (Failure is not indicted if the attributes cannot
122 copyFile( const char *srcName, const char *destName,
123 int setModes, int followLinks)
130 struct stat srcStatBuf;
131 struct stat dstStatBuf;
132 struct utimbuf times;
134 /* Grab the source file's stats */
135 if (followLinks == FALSE)
136 result = stat(srcName, &srcStatBuf);
138 result = lstat(srcName, &srcStatBuf);
144 /* Grab the dest file's stats */
145 if (followLinks == FALSE)
146 result = stat(destName, &dstStatBuf);
148 result = lstat(destName, &dstStatBuf);
150 dstStatBuf.st_ino = -1;
151 dstStatBuf.st_dev = -1;
154 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
155 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
156 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
160 if (S_ISDIR(srcStatBuf.st_mode)) {
161 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
162 /* Make sure the directory is writable */
163 result = mkdir(destName, 0777777 ^ umask(0));
164 if (result < 0 && errno != EEXIST) {
168 } else if (S_ISLNK(srcStatBuf.st_mode)) {
172 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
173 link_val = (char *) alloca(PATH_MAX + 2);
174 link_size = readlink(srcName, link_val, PATH_MAX + 1);
179 link_val[link_size] = '\0';
180 link_size = symlink(link_val, destName);
181 if (link_size != 0) {
185 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
186 if (setModes == TRUE) {
187 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
190 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
191 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
192 if (mkfifo(destName, 0644)) {
196 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
197 || S_ISSOCK (srcStatBuf.st_mode)) {
198 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
199 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev)) {
203 } else if (S_ISREG(srcStatBuf.st_mode)) {
204 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
205 rfd = open(srcName, O_RDONLY);
211 wfd = creat(destName, srcStatBuf.st_mode);
218 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
219 if (fullWrite(wfd, buf, rcc) < 0)
227 if (close(wfd) < 0) {
232 if (setModes == TRUE) {
233 /* This is fine, since symlinks never get here */
234 chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
235 chmod(destName, srcStatBuf.st_mode);
236 times.actime = srcStatBuf.st_atime;
237 times.modtime = srcStatBuf.st_mtime;
238 utime(destName, ×);
255 #if defined BB_TAR || defined BB_LS
257 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
258 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
260 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
261 static const mode_t SBIT[] = {
267 /* The 9 mode bits to test */
268 static const mode_t MBIT[] = {
269 S_IRUSR, S_IWUSR, S_IXUSR,
270 S_IRGRP, S_IWGRP, S_IXGRP,
271 S_IROTH, S_IWOTH, S_IXOTH
274 #define MODE1 "rwxrwxrwx"
275 #define MODE0 "---------"
276 #define SMODE1 "..s..s..t"
277 #define SMODE0 "..S..S..T"
280 * Return the standard ls-like mode string from a file mode.
281 * This is static and so is overwritten on each call.
283 const char *modeString(int mode)
288 buf[0] = TYPECHAR(mode);
289 for (i=0; i<9; i++) {
291 buf[i+1] = (mode & MBIT[i])?
292 SMODE1[i] : SMODE0[i];
294 buf[i+1] = (mode & MBIT[i])?
304 * Return the standard ls-like time string from a time_t
305 * This is static and so is overwritten on each call.
307 const char *timeString(time_t timeVal)
315 str = ctime(&timeVal);
317 strcpy(buf, &str[4]);
320 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
321 strcpy(&buf[7], &str[20]);
329 #if defined BB_TAR || defined BB_CP || defined BB_MV
331 * Write all of the supplied buffer out to a file.
332 * This does multiple writes as necessary.
333 * Returns the amount written, or -1 on an error.
335 int fullWrite(int fd, const char *buf, int len)
343 cc = write(fd, buf, len);
358 #if defined BB_TAR || defined BB_TAIL
360 * Read all of the supplied buffer from a file.
361 * This does multiple reads as necessary.
362 * Returns the amount read, or -1 on an error.
363 * A short read is returned on an end of file.
365 int fullRead(int fd, char *buf, int len)
373 cc = read(fd, buf, len);
391 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_CP) || defined (BB_FIND) || defined (BB_LS) || defined (BB_INSMOD)
393 * Walk down all the directories under the specified
394 * location, and do something (something specified
395 * by the fileAction and dirAction function pointers).
397 * Unfortunatly, while nftw(3) could replace this and reduce
398 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
399 * and so isn't sufficiently portable to take over since glibc2.1
400 * is so stinking huge.
403 recursiveAction(const char *fileName, int recurse, int followLinks, int depthFirst,
404 int (*fileAction) (const char *fileName, struct stat* statbuf),
405 int (*dirAction) (const char *fileName, struct stat* statbuf))
408 struct stat statbuf, statbuf1;
411 if (followLinks == TRUE)
412 status = stat(fileName, &statbuf);
414 status = lstat(fileName, &statbuf);
417 //fprintf(stderr, "status=%d followLinks=%d TRUE=%d\n", status, followLinks, TRUE);
422 if ( (followLinks == FALSE) && (S_ISLNK(statbuf.st_mode)) ) {
423 if (fileAction == NULL)
426 return (fileAction(fileName, &statbuf));
429 if (recurse == FALSE) {
430 if (S_ISDIR(statbuf.st_mode)) {
431 if (dirAction != NULL)
432 return (dirAction(fileName, &statbuf));
438 status = lstat(fileName, &statbuf1);
444 if (S_ISDIR(statbuf.st_mode) && S_ISDIR(statbuf1.st_mode)) {
446 dir = opendir(fileName);
451 if (dirAction != NULL && depthFirst == FALSE) {
452 status = dirAction(fileName, &statbuf);
453 if (status == FALSE) {
458 while ((next = readdir(dir)) != NULL) {
459 char nextFile[NAME_MAX];
460 if ((strcmp(next->d_name, "..") == 0)
461 || (strcmp(next->d_name, ".") == 0)) {
464 sprintf(nextFile, "%s/%s", fileName, next->d_name);
466 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
467 fileAction, dirAction);
473 status = closedir(dir);
478 if (dirAction != NULL && depthFirst == TRUE) {
479 status = dirAction(fileName, &statbuf);
480 if (status == FALSE) {
486 if (fileAction == NULL)
489 return (fileAction(fileName, &statbuf));
498 #if defined (BB_TAR) || defined (BB_MKDIR)
500 * Attempt to create the directories along the specified path, except for
501 * the final component. The mode is given for the final directory only,
502 * while all previous ones get default protections. Errors are not reported
503 * here, as failures to restore files can be reported later.
505 extern int createPath (const char *name, int mode)
513 cp = strchr (buf, '/');
516 cp = strchr (cp + 1, '/');
518 retVal = mkdir (buf, cp ? 0777 : mode);
519 if (retVal != 0 && errno != EEXIST) {
531 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
532 /* [ugoa]{+|-|=}[rwxst] */
537 parse_mode( const char* s, mode_t* theMode)
539 mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
548 switch ( c = *s++ ) {
552 groups |= S_ISUID|S_IRWXU;
555 groups |= S_ISGID|S_IRWXG;
561 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
567 if ( groups == 0 ) /* The default is "all" */
568 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
571 if ( isdigit(c) && c >= '0' && c <= '7' &&
572 mode == 0 && groups == 0 ) {
573 *theMode = strtol(--s, NULL, 8);
582 while ( (c = *s++) != '\0' ) {
587 mode |= S_IRUSR|S_IRGRP|S_IROTH;
590 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
593 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
596 mode |= S_IXGRP|S_ISUID|S_ISGID;
610 andMode &= ~(groups);
613 orMode |= mode & groups;
616 andMode &= ~(mode & groups);
620 } while ( c == ',' );
635 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
637 /* Use this to avoid needing the glibc NSS stuff
638 * This uses storage buf to hold things.
641 my_getid(const char *filename, char *name, uid_t id)
644 char *rname, *start, *end, buf[128];
647 file=fopen(filename,"r");
653 while (fgets (buf, 128, file) != NULL) {
658 end = strchr (start, ':');
665 end = strchr (start, ':');
670 rid = (uid_t) strtol (start, &end, 10);
675 if (0 == strcmp(rname, name)) {
680 if ( id != -1 && id == rid ) {
681 strncpy(name, rname, 8);
691 my_getpwnam(char *name)
693 return my_getid("/etc/passwd", name, -1);
697 my_getgrnam(char *name)
699 return my_getid("/etc/group", name, -1);
703 my_getpwuid(char* name, uid_t uid)
705 my_getid("/etc/passwd", name, uid);
709 my_getgrgid(char* group, gid_t gid)
711 my_getid("/etc/group", group, gid);
720 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
723 #include <linux/kd.h>
724 #include <sys/ioctl.h>
726 int is_a_console(int fd)
731 return (ioctl(fd, KDGKBTYPE, &arg) == 0
732 && ((arg == KB_101) || (arg == KB_84)));
735 static int open_a_console(char *fnam)
740 fd = open(fnam, O_RDWR);
742 /* if failed, try read-only */
743 if (fd < 0 && errno == EACCES)
744 fd = open(fnam, O_RDONLY);
746 /* if failed, try write-only */
747 if (fd < 0 && errno == EACCES)
748 fd = open(fnam, O_WRONLY);
750 /* if failed, fail */
754 /* if not a console, fail */
755 if (! is_a_console(fd))
766 * Get an fd for use with kbd/console ioctls.
767 * We try several things because opening /dev/console will fail
768 * if someone else used X (which does a chown on /dev/console).
770 * if tty_name is non-NULL, try this one instead.
773 int get_console_fd(char* tty_name)
779 if (-1 == (fd = open_a_console(tty_name)))
785 fd = open_a_console("/dev/tty");
789 fd = open_a_console("/dev/tty0");
793 fd = open_a_console("/dev/console");
797 for (fd = 0; fd < 3; fd++)
798 if (is_a_console(fd))
802 "Couldnt get a file descriptor referring to the console\n");
803 return -1; /* total failure */
810 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
812 /* Do a case insensitive strstr() */
813 char* stristr(char *haystack, const char *needle)
815 int len = strlen( needle );
817 if( !strncasecmp( haystack, needle, len ) )
828 /* This tries to find a needle in a haystack, but does so by
829 * only trying to match literal strings (look 'ma, no regexps!)
830 * This is short, sweet, and carries _very_ little baggage,
831 * unlike its beefier cousin in regexp.c
834 extern int find_match(char *haystack, char *needle, int ignoreCase)
837 if (ignoreCase == FALSE)
838 haystack = strstr (haystack, needle);
840 haystack = stristr (haystack, needle);
841 if (haystack == NULL)
847 /* This performs substitutions after a string match has been found. */
848 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
851 char *where, *slider, *slider1, *oldhayStack;
853 if (ignoreCase == FALSE)
854 where = strstr (haystack, needle);
856 where = stristr (haystack, needle);
858 if (strcmp(needle, newNeedle)==0)
861 oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
864 strcpy(oldhayStack, haystack);
866 if ( strlen(newNeedle) > strlen(needle)) {
867 haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) -
868 strlen(needle) + strlen(newNeedle)));
871 for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
873 haystack=strcat(haystack, newNeedle);
874 slider1+=strlen(needle);
875 haystack = strcat(haystack, slider1);
876 where = strstr (slider, needle);
892 * Routine to see if a text string is matched by a wildcard pattern.
893 * Returns TRUE if the text is matched, or FALSE if it is not matched
894 * or if the pattern is invalid.
895 * * matches zero or more characters
896 * ? matches a single character
897 * [abc] matches 'a', 'b' or 'c'
898 * \c quotes character c
899 * Adapted from code written by Ingo Wilken, and
900 * then taken from sash, Copyright (c) 1999 by David I. Bell
901 * Permission is granted to use, distribute, or modify this source,
902 * provided that this copyright notice remains intact.
903 * Permission to distribute this code under the GPL has been granted.
906 check_wildcard_match(const char* text, const char* pattern)
908 const char* retryPat;
909 const char* retryText;
916 while (*text || *pattern)
930 while ((ch = *pattern++) != ']')
949 /* fall into next case */
963 /* fall into next case */
994 #if defined BB_DF || defined BB_MTAB
996 * Given a block device, find the mount table entry if that block device
999 * Given any other file (or directory), find the mount table entry for its
1002 extern struct mntent *findMountPoint(const char *name, const char *table)
1007 struct mntent *mountEntry;
1009 if (stat(name, &s) != 0)
1012 if ((s.st_mode & S_IFMT) == S_IFBLK)
1013 mountDevice = s.st_rdev;
1015 mountDevice = s.st_dev;
1018 if ((mountTable = setmntent(table, "r")) == 0)
1021 while ((mountEntry = getmntent(mountTable)) != 0) {
1022 if (strcmp(name, mountEntry->mnt_dir) == 0
1023 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1025 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1027 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1030 endmntent(mountTable);
1037 #if defined BB_DD || defined BB_TAIL
1039 * Read a number with a possible multiplier.
1040 * Returns -1 if the number format is illegal.
1042 extern long getNum (const char *cp)
1046 if (!isDecimal (*cp))
1051 while (isDecimal (*cp))
1052 value = value * 10 + *cp++ - '0';
1086 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT
1088 #if ! defined BB_FEATURE_USE_PROCFS
1089 #error Sorry, I depend on the /proc filesystem right now.
1093 * This finds the pid of init (which is not always 1).
1094 * Currently, it's implemented by rummaging through the proc filesystem.
1098 * pid when init's pid is found.
1107 /* no need to opendir ;) */
1108 for (init_pid = 1; init_pid < 65536; init_pid++) {
1111 sprintf(filename, "/proc/%d/status", init_pid);
1112 status = fopen(filename, "r");
1113 if (!status) { continue; }
1114 fgets(buffer, 256, status);
1117 if ( (strstr(buffer, "init\n") != NULL )) {
1125 #if defined BB_GUNZIP || defined BB_GZIP || defined BB_PRINTF || defined BB_TAIL
1126 extern void *xmalloc (size_t size)
1128 void *cp = malloc (size);
1131 error("out of memory");
1136 extern void error(char *msg)
1138 fprintf(stderr, "\n%s\n", msg);
1143 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1144 extern int vdprintf(int d, const char *format, va_list ap)
1149 len = vsprintf(buf, format, ap);
1150 return write(d, buf, len);
1154 #if defined BB_FEATURE_MOUNT_LOOP
1155 extern int del_loop(const char *device)
1159 if ((fd = open(device, O_RDONLY)) < 0) {
1163 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1164 perror("ioctl: LOOP_CLR_FD");
1171 extern int set_loop(const char *device, const char *file, int offset, int *loopro)
1173 struct loop_info loopinfo;
1176 mode = *loopro ? O_RDONLY : O_RDWR;
1177 if ((ffd = open (file, mode)) < 0 && !*loopro
1178 && (errno != EROFS || (ffd = open (file, mode = O_RDONLY)) < 0)) {
1182 if ((fd = open (device, mode)) < 0) {
1187 *loopro = (mode == O_RDONLY);
1189 memset(&loopinfo, 0, sizeof(loopinfo));
1190 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1191 loopinfo.lo_name[LO_NAME_SIZE-1] = 0;
1193 loopinfo.lo_offset = offset;
1195 loopinfo.lo_encrypt_key_size = 0;
1196 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1197 perror("ioctl: LOOP_SET_FD");
1202 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1203 (void) ioctl(fd, LOOP_CLR_FD, 0);
1204 perror("ioctl: LOOP_SET_STATUS");
1214 extern char *find_unused_loop_device (void)
1218 struct stat statbuf;
1219 struct loop_info loopinfo;
1221 for(i = 0; i <= 7; i++) {
1222 sprintf(dev, "/dev/loop%d", i);
1223 if (stat (dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1224 if ((fd = open (dev, O_RDONLY)) >= 0) {
1225 if(ioctl (fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1226 if (errno == ENXIO) { /* probably free */
1237 #endif /* BB_FEATURE_MOUNT_LOOP */