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 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
186 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
187 if (mkfifo(destName, 0644)) {
191 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
192 || S_ISSOCK (srcStatBuf.st_mode)) {
193 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
194 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev)) {
198 } else if (S_ISREG(srcStatBuf.st_mode)) {
199 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
200 rfd = open(srcName, O_RDONLY);
206 wfd = creat(destName, srcStatBuf.st_mode);
213 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
214 if (fullWrite(wfd, buf, rcc) < 0)
222 if (close(wfd) < 0) {
227 if (setModes == TRUE) {
228 if (! S_ISLNK(srcStatBuf.st_mode)) {
229 chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
230 /* Never chmod a symlink; it follows the link */
231 chmod(destName, srcStatBuf.st_mode);
233 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
235 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
238 times.actime = srcStatBuf.st_atime;
239 times.modtime = srcStatBuf.st_mtime;
240 utime(destName, ×);
257 #if defined BB_TAR || defined BB_LS
259 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
260 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
262 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
263 static const mode_t SBIT[] = {
269 /* The 9 mode bits to test */
270 static const mode_t MBIT[] = {
271 S_IRUSR, S_IWUSR, S_IXUSR,
272 S_IRGRP, S_IWGRP, S_IXGRP,
273 S_IROTH, S_IWOTH, S_IXOTH
276 #define MODE1 "rwxrwxrwx"
277 #define MODE0 "---------"
278 #define SMODE1 "..s..s..t"
279 #define SMODE0 "..S..S..T"
282 * Return the standard ls-like mode string from a file mode.
283 * This is static and so is overwritten on each call.
285 const char *modeString(int mode)
290 buf[0] = TYPECHAR(mode);
291 for (i=0; i<9; i++) {
293 buf[i+1] = (mode & MBIT[i])?
294 SMODE1[i] : SMODE0[i];
296 buf[i+1] = (mode & MBIT[i])?
306 * Return the standard ls-like time string from a time_t
307 * This is static and so is overwritten on each call.
309 const char *timeString(time_t timeVal)
317 str = ctime(&timeVal);
319 strcpy(buf, &str[4]);
322 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
323 strcpy(&buf[7], &str[20]);
331 #if defined BB_TAR || defined BB_CP || defined BB_MV
333 * Write all of the supplied buffer out to a file.
334 * This does multiple writes as necessary.
335 * Returns the amount written, or -1 on an error.
337 int fullWrite(int fd, const char *buf, int len)
345 cc = write(fd, buf, len);
360 #if defined BB_TAR || defined BB_TAIL
362 * Read all of the supplied buffer from a file.
363 * This does multiple reads as necessary.
364 * Returns the amount read, or -1 on an error.
365 * A short read is returned on an end of file.
367 int fullRead(int fd, char *buf, int len)
375 cc = read(fd, buf, len);
393 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_CP) || defined (BB_FIND) || defined (BB_LS) || defined (BB_INSMOD)
395 * Walk down all the directories under the specified
396 * location, and do something (something specified
397 * by the fileAction and dirAction function pointers).
399 * Unfortunatly, while nftw(3) could replace this and reduce
400 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
401 * and so isn't sufficiently portable to take over since glibc2.1
402 * is so stinking huge.
405 recursiveAction(const char *fileName, int recurse, int followLinks, int depthFirst,
406 int (*fileAction) (const char *fileName, struct stat* statbuf),
407 int (*dirAction) (const char *fileName, struct stat* statbuf))
410 struct stat statbuf, statbuf1;
413 if (followLinks == TRUE)
414 status = stat(fileName, &statbuf);
416 status = lstat(fileName, &statbuf);
419 fprintf(stderr, "status=%d followLinks=%d TRUE=%d\n", status, followLinks, TRUE);
424 if ( (followLinks == FALSE) && (S_ISLNK(statbuf.st_mode)) ) {
425 if (fileAction == NULL)
428 return (fileAction(fileName, &statbuf));
431 if (recurse == FALSE) {
432 if (S_ISDIR(statbuf.st_mode)) {
433 if (dirAction != NULL)
434 return (dirAction(fileName, &statbuf));
440 status = lstat(fileName, &statbuf1);
446 if (S_ISDIR(statbuf.st_mode) && S_ISDIR(statbuf1.st_mode)) {
448 dir = opendir(fileName);
453 if (dirAction != NULL && depthFirst == FALSE) {
454 status = dirAction(fileName, &statbuf);
455 if (status == FALSE) {
460 while ((next = readdir(dir)) != NULL) {
461 char nextFile[NAME_MAX];
462 if ((strcmp(next->d_name, "..") == 0)
463 || (strcmp(next->d_name, ".") == 0)) {
466 sprintf(nextFile, "%s/%s", fileName, next->d_name);
468 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
469 fileAction, dirAction);
475 status = closedir(dir);
480 if (dirAction != NULL && depthFirst == TRUE) {
481 status = dirAction(fileName, &statbuf);
482 if (status == FALSE) {
488 if (fileAction == NULL)
491 return (fileAction(fileName, &statbuf));
500 #if defined (BB_TAR) || defined (BB_MKDIR)
502 * Attempt to create the directories along the specified path, except for
503 * the final component. The mode is given for the final directory only,
504 * while all previous ones get default protections. Errors are not reported
505 * here, as failures to restore files can be reported later.
507 extern int createPath (const char *name, int mode)
515 cp = strchr (buf, '/');
518 cp = strchr (cp + 1, '/');
520 retVal = mkdir (buf, cp ? 0777 : mode);
521 if (retVal != 0 && errno != EEXIST) {
533 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
534 /* [ugoa]{+|-|=}[rwxst] */
539 parse_mode( const char* s, mode_t* theMode)
541 mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
550 switch ( c = *s++ ) {
554 groups |= S_ISUID|S_IRWXU;
557 groups |= S_ISGID|S_IRWXG;
563 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
569 if ( groups == 0 ) /* The default is "all" */
570 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
573 if ( isdigit(c) && c >= '0' && c <= '7' &&
574 mode == 0 && groups == 0 ) {
575 *theMode = strtol(--s, NULL, 8);
584 while ( (c = *s++) != '\0' ) {
589 mode |= S_IRUSR|S_IRGRP|S_IROTH;
592 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
595 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
598 mode |= S_IXGRP|S_ISUID|S_ISGID;
612 andMode &= ~(groups);
615 orMode |= mode & groups;
618 andMode &= ~(mode & groups);
622 } while ( c == ',' );
637 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
639 /* Use this to avoid needing the glibc NSS stuff
640 * This uses storage buf to hold things.
643 my_getid(const char *filename, char *name, uid_t id)
646 char *rname, *start, *end, buf[128];
649 file=fopen(filename,"r");
655 while (fgets (buf, 128, file) != NULL) {
660 end = strchr (start, ':');
667 end = strchr (start, ':');
672 rid = (uid_t) strtol (start, &end, 10);
677 if (0 == strcmp(rname, name)) {
682 if ( id != -1 && id == rid ) {
683 strncpy(name, rname, 8);
693 my_getpwnam(char *name)
695 return my_getid("/etc/passwd", name, -1);
699 my_getgrnam(char *name)
701 return my_getid("/etc/group", name, -1);
705 my_getpwuid(char* name, uid_t uid)
707 my_getid("/etc/passwd", name, uid);
711 my_getgrgid(char* group, gid_t gid)
713 my_getid("/etc/group", group, gid);
722 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
725 #include <linux/kd.h>
726 #include <sys/ioctl.h>
728 int is_a_console(int fd)
733 return (ioctl(fd, KDGKBTYPE, &arg) == 0
734 && ((arg == KB_101) || (arg == KB_84)));
737 static int open_a_console(char *fnam)
742 fd = open(fnam, O_RDWR);
744 /* if failed, try read-only */
745 if (fd < 0 && errno == EACCES)
746 fd = open(fnam, O_RDONLY);
748 /* if failed, try write-only */
749 if (fd < 0 && errno == EACCES)
750 fd = open(fnam, O_WRONLY);
752 /* if failed, fail */
756 /* if not a console, fail */
757 if (! is_a_console(fd))
768 * Get an fd for use with kbd/console ioctls.
769 * We try several things because opening /dev/console will fail
770 * if someone else used X (which does a chown on /dev/console).
772 * if tty_name is non-NULL, try this one instead.
775 int get_console_fd(char* tty_name)
781 if (-1 == (fd = open_a_console(tty_name)))
787 fd = open_a_console("/dev/tty");
791 fd = open_a_console("/dev/tty0");
795 fd = open_a_console("/dev/console");
799 for (fd = 0; fd < 3; fd++)
800 if (is_a_console(fd))
804 "Couldnt get a file descriptor referring to the console\n");
805 return -1; /* total failure */
812 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
814 /* Do a case insensitive strstr() */
815 char* stristr(char *haystack, const char *needle)
817 int len = strlen( needle );
819 if( !strncasecmp( haystack, needle, len ) )
830 /* This tries to find a needle in a haystack, but does so by
831 * only trying to match literal strings (look 'ma, no regexps!)
832 * This is short, sweet, and carries _very_ little baggage,
833 * unlike its beefier cousin in regexp.c
836 extern int find_match(char *haystack, char *needle, int ignoreCase)
839 if (ignoreCase == FALSE)
840 haystack = strstr (haystack, needle);
842 haystack = stristr (haystack, needle);
843 if (haystack == NULL)
849 /* This performs substitutions after a string match has been found. */
850 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
853 char *where, *slider, *slider1, *oldhayStack;
855 if (ignoreCase == FALSE)
856 where = strstr (haystack, needle);
858 where = stristr (haystack, needle);
860 if (strcmp(needle, newNeedle)==0)
863 oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
866 strcpy(oldhayStack, haystack);
868 if ( strlen(newNeedle) > strlen(needle)) {
869 haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) -
870 strlen(needle) + strlen(newNeedle)));
873 for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
875 haystack=strcat(haystack, newNeedle);
876 slider1+=strlen(needle);
877 haystack = strcat(haystack, slider1);
878 where = strstr (slider, needle);
894 * Routine to see if a text string is matched by a wildcard pattern.
895 * Returns TRUE if the text is matched, or FALSE if it is not matched
896 * or if the pattern is invalid.
897 * * matches zero or more characters
898 * ? matches a single character
899 * [abc] matches 'a', 'b' or 'c'
900 * \c quotes character c
901 * Adapted from code written by Ingo Wilken, and
902 * then taken from sash, Copyright (c) 1999 by David I. Bell
903 * Permission is granted to use, distribute, or modify this source,
904 * provided that this copyright notice remains intact.
905 * Permission to distribute this code under the GPL has been granted.
908 check_wildcard_match(const char* text, const char* pattern)
910 const char* retryPat;
911 const char* retryText;
918 while (*text || *pattern)
932 while ((ch = *pattern++) != ']')
951 /* fall into next case */
965 /* fall into next case */
996 #if defined BB_DF || defined BB_MTAB
998 * Given a block device, find the mount table entry if that block device
1001 * Given any other file (or directory), find the mount table entry for its
1004 extern struct mntent *findMountPoint(const char *name, const char *table)
1009 struct mntent *mountEntry;
1011 if (stat(name, &s) != 0)
1014 if ((s.st_mode & S_IFMT) == S_IFBLK)
1015 mountDevice = s.st_rdev;
1017 mountDevice = s.st_dev;
1020 if ((mountTable = setmntent(table, "r")) == 0)
1023 while ((mountEntry = getmntent(mountTable)) != 0) {
1024 if (strcmp(name, mountEntry->mnt_dir) == 0
1025 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1027 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1029 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1032 endmntent(mountTable);
1039 #if defined BB_DD || defined BB_TAIL
1041 * Read a number with a possible multiplier.
1042 * Returns -1 if the number format is illegal.
1044 extern long getNum (const char *cp)
1048 if (!isDecimal (*cp))
1053 while (isDecimal (*cp))
1054 value = value * 10 + *cp++ - '0';
1088 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT
1090 #if ! defined BB_FEATURE_USE_PROCFS
1091 #error Sorry, I depend on the /proc filesystem right now.
1095 * This finds the pid of init (which is not always 1).
1096 * Currently, it's implemented by rummaging through the proc filesystem.
1100 * pid when init's pid is found.
1109 /* no need to opendir ;) */
1110 for (init_pid = 1; init_pid < 65536; init_pid++) {
1113 sprintf(filename, "/proc/%d/status", init_pid);
1114 status = fopen(filename, "r");
1115 if (!status) { continue; }
1116 fgets(buffer, 256, status);
1119 if ( (strstr(buffer, "init\n") != NULL )) {
1127 #if defined BB_GUNZIP || defined BB_GZIP || defined BB_PRINTF || defined BB_TAIL
1128 extern void *xmalloc (size_t size)
1130 void *cp = malloc (size);
1133 error("out of memory");
1138 extern void error(char *msg)
1140 fprintf(stderr, "\n%s\n", msg);
1145 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1146 extern int vdprintf(int d, const char *format, va_list ap)
1151 len = vsprintf(buf, format, ap);
1152 return write(d, buf, len);
1156 #if defined BB_FEATURE_MOUNT_LOOP
1157 extern int del_loop(const char *device)
1161 if ((fd = open(device, O_RDONLY)) < 0) {
1165 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1166 perror("ioctl: LOOP_CLR_FD");
1173 extern int set_loop(const char *device, const char *file, int offset, int *loopro)
1175 struct loop_info loopinfo;
1178 mode = *loopro ? O_RDONLY : O_RDWR;
1179 if ((ffd = open (file, mode)) < 0 && !*loopro
1180 && (errno != EROFS || (ffd = open (file, mode = O_RDONLY)) < 0)) {
1184 if ((fd = open (device, mode)) < 0) {
1189 *loopro = (mode == O_RDONLY);
1191 memset(&loopinfo, 0, sizeof(loopinfo));
1192 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1193 loopinfo.lo_name[LO_NAME_SIZE-1] = 0;
1195 loopinfo.lo_offset = offset;
1197 loopinfo.lo_encrypt_key_size = 0;
1198 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1199 perror("ioctl: LOOP_SET_FD");
1204 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1205 (void) ioctl(fd, LOOP_CLR_FD, 0);
1206 perror("ioctl: LOOP_SET_STATUS");
1216 extern char *find_unused_loop_device (void)
1220 struct stat statbuf;
1221 struct loop_info loopinfo;
1223 for(i = 0; i <= 7; i++) {
1224 sprintf(dev, "/dev/loop%d", i);
1225 if (stat (dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1226 if ((fd = open (dev, O_RDONLY)) >= 0) {
1227 if(ioctl (fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1228 if (errno == ENXIO) { /* probably free */
1239 #endif /* BB_FEATURE_MOUNT_LOOP */