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_MOUNT || defined BB_UMOUNT || defined BB_DF
40 # if defined BB_FEATURE_USE_PROCFS
41 const char mtab_file[] = "/proc/mounts";
44 const char mtab_file[] = "/etc/mtab";
46 # error With (BB_MOUNT||BB_UMOUNT||BB_DF) defined, you must define either BB_MTAB or BB_FEATURE_USE_PROCFS
52 extern void usage(const char *usage)
54 fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n", BB_VER, BB_BT);
55 fprintf(stderr, "Usage: %s\n", usage);
60 #if defined (BB_INIT) || defined (BB_PS)
62 #if ! defined BB_FEATURE_USE_PROCFS
63 #error Sorry, I depend on the /proc filesystem right now.
65 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
66 * so, for example, to check if the kernel is greater than 2.2.11:
67 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
73 int major=0, minor=0, patch=0;
74 char* filename="/proc/sys/kernel/osrelease";
76 file = fopen(filename,"r");
78 /* bummer, /proc must not be mounted... */
81 fscanf(file,"%d.%d.%d",&major,&minor,&patch);
83 return major*65536 + minor*256 + patch;
90 #if defined (BB_CP) || defined (BB_MV)
92 * Return TRUE if a fileName is a directory.
93 * Nonexistant files return FALSE.
95 int isDirectory(const char *name)
99 if (stat(name, &statBuf) < 0)
101 if (S_ISDIR(statBuf.st_mode))
108 * Copy one file to another, while possibly preserving its modes, times,
109 * and modes. Returns TRUE if successful, or FALSE on a failure with an
110 * error message output. (Failure is not indicted if the attributes cannot
115 copyFile( const char *srcName, const char *destName,
116 int setModes, int followLinks)
123 struct stat srcStatBuf;
124 struct stat dstStatBuf;
125 struct utimbuf times;
127 if (followLinks == FALSE)
128 result = stat(srcName, &srcStatBuf);
130 result = lstat(srcName, &srcStatBuf);
136 if (followLinks == FALSE)
137 result = stat(destName, &dstStatBuf);
139 result = lstat(destName, &dstStatBuf);
141 dstStatBuf.st_ino = -1;
142 dstStatBuf.st_dev = -1;
145 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
146 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
147 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
151 if (S_ISDIR(srcStatBuf.st_mode)) {
152 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
153 /* Make sure the directory is writable */
154 result = mkdir(destName, 0777777 ^ umask(0));
155 if (result < 0 && errno != EEXIST) {
159 } else if (S_ISLNK(srcStatBuf.st_mode)) {
163 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
164 link_val = (char *) alloca(PATH_MAX + 2);
165 link_size = readlink(srcName, link_val, PATH_MAX + 1);
170 link_val[link_size] = '\0';
171 link_size = symlink(link_val, destName);
172 if (link_size != 0) {
176 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
177 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
178 if (mkfifo(destName, 644)) {
182 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
183 || S_ISSOCK (srcStatBuf.st_mode)) {
184 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
185 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev)) {
189 } else if (S_ISREG(srcStatBuf.st_mode)) {
190 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
191 rfd = open(srcName, O_RDONLY);
197 wfd = creat(destName, srcStatBuf.st_mode);
204 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
205 if (fullWrite(wfd, buf, rcc) < 0)
213 if (close(wfd) < 0) {
218 if (setModes == TRUE) {
219 //fprintf(stderr, "Setting permissions for %s\n", destName);
220 chmod(destName, srcStatBuf.st_mode);
221 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
222 if (followLinks == FALSE)
223 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
226 chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
228 times.actime = srcStatBuf.st_atime;
229 times.modtime = srcStatBuf.st_mtime;
231 utime(destName, ×);
248 #if defined BB_TAR || defined BB_LS
250 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
251 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
253 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
254 static const mode_t SBIT[] = {
260 /* The 9 mode bits to test */
261 static const mode_t MBIT[] = {
262 S_IRUSR, S_IWUSR, S_IXUSR,
263 S_IRGRP, S_IWGRP, S_IXGRP,
264 S_IROTH, S_IWOTH, S_IXOTH
267 #define MODE1 "rwxrwxrwx"
268 #define MODE0 "---------"
269 #define SMODE1 "..s..s..t"
270 #define SMODE0 "..S..S..T"
273 * Return the standard ls-like mode string from a file mode.
274 * This is static and so is overwritten on each call.
276 const char *modeString(int mode)
281 buf[0] = TYPECHAR(mode);
282 for (i=0; i<9; i++) {
284 buf[i+1] = (mode & MBIT[i])?
285 SMODE1[i] : SMODE0[i];
287 buf[i+1] = (mode & MBIT[i])?
297 * Return the standard ls-like time string from a time_t
298 * This is static and so is overwritten on each call.
300 const char *timeString(time_t timeVal)
308 str = ctime(&timeVal);
310 strcpy(buf, &str[4]);
313 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
314 strcpy(&buf[7], &str[20]);
322 * Write all of the supplied buffer out to a file.
323 * This does multiple writes as necessary.
324 * Returns the amount written, or -1 on an error.
326 int fullWrite(int fd, const char *buf, int len)
334 cc = write(fd, buf, len);
349 #if defined BB_TAR || defined BB_TAIL
351 * Read all of the supplied buffer from a file.
352 * This does multiple reads as necessary.
353 * Returns the amount read, or -1 on an error.
354 * A short read is returned on an end of file.
356 int fullRead(int fd, char *buf, int len)
364 cc = read(fd, buf, len);
382 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_CP) || defined (BB_FIND) || defined (BB_LS) || defined (BB_INSMOD)
384 * Walk down all the directories under the specified
385 * location, and do something (something specified
386 * by the fileAction and dirAction function pointers).
388 * Unfortunatly, while nftw(3) could replace this and reduce
389 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
390 * and so isn't sufficiently portable to take over since glibc2.1
391 * is so stinking huge.
394 recursiveAction(const char *fileName, int recurse, int followLinks, int depthFirst,
395 int (*fileAction) (const char *fileName, struct stat* statbuf),
396 int (*dirAction) (const char *fileName, struct stat* statbuf))
402 if (followLinks == TRUE)
403 status = stat(fileName, &statbuf);
405 status = lstat(fileName, &statbuf);
412 if ( (followLinks == FALSE) && (S_ISLNK(statbuf.st_mode)) ) {
413 if (fileAction == NULL)
416 return (fileAction(fileName, &statbuf));
419 if (recurse == FALSE) {
420 if (S_ISDIR(statbuf.st_mode)) {
421 if (dirAction != NULL)
422 return (dirAction(fileName, &statbuf));
428 if (S_ISDIR(statbuf.st_mode)) {
430 dir = opendir(fileName);
435 if (dirAction != NULL && depthFirst == FALSE) {
436 status = dirAction(fileName, &statbuf);
437 if (status == FALSE) {
442 while ((next = readdir(dir)) != NULL) {
443 char nextFile[NAME_MAX];
444 if ((strcmp(next->d_name, "..") == 0)
445 || (strcmp(next->d_name, ".") == 0)) {
448 sprintf(nextFile, "%s/%s", fileName, next->d_name);
450 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
451 fileAction, dirAction);
457 status = closedir(dir);
462 if (dirAction != NULL && depthFirst == TRUE) {
463 status = dirAction(fileName, &statbuf);
464 if (status == FALSE) {
470 if (fileAction == NULL)
473 return (fileAction(fileName, &statbuf));
482 #if defined (BB_TAR) || defined (BB_MKDIR)
484 * Attempt to create the directories along the specified path, except for
485 * the final component. The mode is given for the final directory only,
486 * while all previous ones get default protections. Errors are not reported
487 * here, as failures to restore files can be reported later.
489 extern void createPath (const char *name, int mode)
496 cp = strchr (buf, '/');
499 cp = strchr (cp + 1, '/');
501 mkdir (buf, cp ? 0777 : mode);
509 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
510 /* [ugoa]{+|-|=}[rwxst] */
515 parse_mode( const char* s, mode_t* theMode)
517 mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
526 switch ( c = *s++ ) {
530 groups |= S_ISUID|S_IRWXU;
533 groups |= S_ISGID|S_IRWXG;
539 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
545 if ( groups == 0 ) /* The default is "all" */
546 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
549 if ( isdigit(c) && c >= '0' && c <= '7' &&
550 mode == 0 && groups == 0 ) {
551 *theMode = strtol(--s, NULL, 8);
560 while ( (c = *s++) != '\0' ) {
565 mode |= S_IRUSR|S_IRGRP|S_IROTH;
568 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
571 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
574 mode |= S_IXGRP|S_ISUID|S_ISGID;
588 andMode &= ~(groups);
591 orMode |= mode & groups;
594 andMode &= ~(mode & groups);
598 } while ( c == ',' );
613 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
615 /* Use this to avoid needing the glibc NSS stuff
616 * This uses storage buf to hold things.
619 my_getid(const char *filename, char *name, uid_t id)
622 char *rname, *start, *end, buf[128];
625 file=fopen(filename,"r");
631 while (fgets (buf, 128, file) != NULL) {
636 end = strchr (start, ':');
643 end = strchr (start, ':');
648 rid = (uid_t) strtol (start, &end, 10);
653 if (0 == strcmp(rname, name)) {
658 if ( id != -1 && id == rid ) {
659 strncpy(name, rname, 8);
669 my_getpwnam(char *name)
671 return my_getid("/etc/passwd", name, -1);
675 my_getgrnam(char *name)
677 return my_getid("/etc/group", name, -1);
681 my_getpwuid(char* name, uid_t uid)
683 my_getid("/etc/passwd", name, uid);
687 my_getgrgid(char* group, gid_t gid)
689 my_getid("/etc/group", group, gid);
698 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
701 #include <linux/kd.h>
702 #include <sys/ioctl.h>
704 int is_a_console(int fd)
709 return (ioctl(fd, KDGKBTYPE, &arg) == 0
710 && ((arg == KB_101) || (arg == KB_84)));
713 static int open_a_console(char *fnam)
718 fd = open(fnam, O_RDWR);
720 /* if failed, try read-only */
721 if (fd < 0 && errno == EACCES)
722 fd = open(fnam, O_RDONLY);
724 /* if failed, try write-only */
725 if (fd < 0 && errno == EACCES)
726 fd = open(fnam, O_WRONLY);
728 /* if failed, fail */
732 /* if not a console, fail */
733 if (! is_a_console(fd))
744 * Get an fd for use with kbd/console ioctls.
745 * We try several things because opening /dev/console will fail
746 * if someone else used X (which does a chown on /dev/console).
748 * if tty_name is non-NULL, try this one instead.
751 int get_console_fd(char* tty_name)
757 if (-1 == (fd = open_a_console(tty_name)))
763 fd = open_a_console("/dev/tty");
767 fd = open_a_console("/dev/tty0");
771 fd = open_a_console("/dev/console");
775 for (fd = 0; fd < 3; fd++)
776 if (is_a_console(fd))
780 "Couldnt get a file descriptor referring to the console\n");
781 return -1; /* total failure */
788 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
790 /* Do a case insensitive strstr() */
791 char* stristr(char *haystack, const char *needle)
793 int len = strlen( needle );
795 if( !strncasecmp( haystack, needle, len ) )
806 /* This tries to find a needle in a haystack, but does so by
807 * only trying to match literal strings (look 'ma, no regexps!)
808 * This is short, sweet, and carries _very_ little baggage,
809 * unlike its beefier cousin in regexp.c
812 extern int find_match(char *haystack, char *needle, int ignoreCase)
815 if (ignoreCase == FALSE)
816 haystack = strstr (haystack, needle);
818 haystack = stristr (haystack, needle);
819 if (haystack == NULL)
825 /* This performs substitutions after a string match has been found. */
826 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
829 char *where, *slider, *slider1, *oldhayStack;
831 if (ignoreCase == FALSE)
832 where = strstr (haystack, needle);
834 where = stristr (haystack, needle);
836 if (strcmp(needle, newNeedle)==0)
839 oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
842 strcpy(oldhayStack, haystack);
844 if ( strlen(newNeedle) > strlen(needle)) {
845 haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) -
846 strlen(needle) + strlen(newNeedle)));
849 for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
851 haystack=strcat(haystack, newNeedle);
852 slider1+=strlen(needle);
853 haystack = strcat(haystack, slider1);
854 where = strstr (slider, needle);
870 * Routine to see if a text string is matched by a wildcard pattern.
871 * Returns TRUE if the text is matched, or FALSE if it is not matched
872 * or if the pattern is invalid.
873 * * matches zero or more characters
874 * ? matches a single character
875 * [abc] matches 'a', 'b' or 'c'
876 * \c quotes character c
877 * Adapted from code written by Ingo Wilken, and
878 * then taken from sash, Copyright (c) 1999 by David I. Bell
879 * Permission is granted to use, distribute, or modify this source,
880 * provided that this copyright notice remains intact.
881 * Permission to distribute this code under the GPL has been granted.
884 check_wildcard_match(const char* text, const char* pattern)
886 const char* retryPat;
887 const char* retryText;
894 while (*text || *pattern)
908 while ((ch = *pattern++) != ']')
927 /* fall into next case */
941 /* fall into next case */
972 #if defined BB_DF || defined BB_MTAB
974 * Given a block device, find the mount table entry if that block device
977 * Given any other file (or directory), find the mount table entry for its
980 extern struct mntent *findMountPoint(const char *name, const char *table)
985 struct mntent *mountEntry;
987 if (stat(name, &s) != 0)
990 if ((s.st_mode & S_IFMT) == S_IFBLK)
991 mountDevice = s.st_rdev;
993 mountDevice = s.st_dev;
996 if ((mountTable = setmntent(table, "r")) == 0)
999 while ((mountEntry = getmntent(mountTable)) != 0) {
1000 if (strcmp(name, mountEntry->mnt_dir) == 0
1001 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1003 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1005 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1008 endmntent(mountTable);
1015 #if defined BB_DD || defined BB_TAIL
1017 * Read a number with a possible multiplier.
1018 * Returns -1 if the number format is illegal.
1020 extern long getNum (const char *cp)
1024 if (!isDecimal (*cp))
1029 while (isDecimal (*cp))
1030 value = value * 10 + *cp++ - '0';
1064 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT
1066 #if ! defined BB_FEATURE_USE_PROCFS
1067 #error Sorry, I depend on the /proc filesystem right now.
1071 * This finds the pid of init (which is not always 1).
1072 * Currently, it's implemented by rummaging through the proc filesystem.
1076 * pid when init's pid is found.
1085 /* no need to opendir ;) */
1086 for (init_pid = 1; init_pid < 65536; init_pid++) {
1089 sprintf(filename, "/proc/%d/status", init_pid);
1090 status = fopen(filename, "r");
1091 if (!status) { continue; }
1092 fgets(buffer, 256, status);
1095 if ( (strstr(buffer, "init\n") != NULL )) {
1103 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1104 extern int vdprintf(int d, const char *format, va_list ap)
1109 len = vsprintf(buf, format, ap);
1110 return write(d, buf, len);