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.
29 #if defined (BB_CHMOD_CHOWN_CHGRP) \
30 || defined (BB_CP_MV) \
31 || defined (BB_FIND) \
32 || defined (BB_INSMOD) \
36 /* same conditions as recursiveAction */
37 #define bb_need_name_too_long
39 #define bb_need_memory_exhausted
40 #define bb_need_full_version
41 #define BB_DECLARE_EXTERN
53 #include <sys/ioctl.h>
54 #include <sys/utsname.h> /* for uname(2) */
56 #if defined BB_FEATURE_MOUNT_LOOP
58 #include <linux/loop.h> /* Pull in loop device support */
61 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
62 * list of available filesystems used for the -t auto option */
63 #if defined BB_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
64 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
65 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
69 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
71 const char mtab_file[] = "/etc/mtab";
73 # if defined BB_FEATURE_USE_PROCFS
74 const char mtab_file[] = "/proc/mounts";
76 # if defined BB_FEATURE_USE_DEVPS_PATCH
77 const char mtab_file[] = "/dev/mtab";
79 # error With (BB_MOUNT||BB_UMOUNT||BB_DF) defined, you must define either BB_MTAB or ( BB_FEATURE_USE_PROCFS | BB_FEATURE_USE_DEVPS_PATCH)
85 extern void usage(const char *usage)
87 fprintf(stderr, "%s\n\n", full_version);
88 fprintf(stderr, "Usage: %s\n", usage);
92 extern void errorMsg(const char *s, ...)
98 fprintf(stderr, "%s: ", applet_name);
99 vfprintf(stderr, s, p);
104 extern void fatalError(const char *s, ...)
110 fprintf(stderr, "%s: ", applet_name);
111 vfprintf(stderr, s, p);
118 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
119 * so, for example, to check if the kernel is greater than 2.2.11:
120 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
122 extern int get_kernel_revision(void)
125 int major = 0, minor = 0, patch = 0;
127 if (uname(&name) == -1) {
128 perror("cannot get system information");
131 sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
132 return major * 65536 + minor * 256 + patch;
138 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
139 _syscall1(int, sysinfo, struct sysinfo *, info);
142 #if defined BB_MOUNT || defined BB_UMOUNT
145 #define __NR_umount2 52
148 /* Include our own version of <sys/mount.h>, since libc5 doesn't
149 * know about umount2 */
150 extern _syscall1(int, umount, const char *, special_file);
151 extern _syscall2(int, umount2, const char *, special_file, int, flags);
152 extern _syscall5(int, mount, const char *, special_file, const char *, dir,
153 const char *, fstype, unsigned long int, rwflag, const void *, data);
156 #if defined BB_INSMOD || defined BB_LSMOD
157 #ifndef __NR_query_module
158 #define __NR_query_module 167
160 _syscall5(int, query_module, const char *, name, int, which,
161 void *, buf, size_t, bufsize, size_t*, ret);
165 #if defined (BB_CP_MV) || defined (BB_DU)
167 #define HASH_SIZE 311 /* Should be prime */
168 #define hash_inode(i) ((i) % HASH_SIZE)
170 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
173 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
174 * `ino_dev_hashtable', else return 0
176 * If NAME is a non-NULL pointer to a character pointer, and there is
177 * a match, then set *NAME to the value of the name slot in that
180 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
182 ino_dev_hashtable_bucket_t *bucket;
184 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
185 while (bucket != NULL) {
186 if ((bucket->ino == statbuf->st_ino) &&
187 (bucket->dev == statbuf->st_dev))
189 if (name) *name = bucket->name;
192 bucket = bucket->next;
197 /* Add statbuf to statbuf hash table */
198 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
202 ino_dev_hashtable_bucket_t *bucket;
204 i = hash_inode(statbuf->st_ino);
205 s = name ? strlen(name) : 0;
206 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
207 bucket->ino = statbuf->st_ino;
208 bucket->dev = statbuf->st_dev;
210 strcpy(bucket->name, name);
212 bucket->name[0] = '\0';
213 bucket->next = ino_dev_hashtable[i];
214 ino_dev_hashtable[i] = bucket;
217 /* Clear statbuf hash table */
218 void reset_ino_dev_hashtable(void)
221 ino_dev_hashtable_bucket_t *bucket;
223 for (i = 0; i < HASH_SIZE; i++) {
224 while (ino_dev_hashtable[i] != NULL) {
225 bucket = ino_dev_hashtable[i]->next;
226 free(ino_dev_hashtable[i]);
227 ino_dev_hashtable[i] = bucket;
232 #endif /* BB_CP_MV || BB_DU */
234 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
236 * Return TRUE if a fileName is a directory.
237 * Nonexistant files return FALSE.
239 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
244 if (statBuf == NULL) {
245 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
249 if (followLinks == TRUE)
250 status = stat(fileName, statBuf);
252 status = lstat(fileName, statBuf);
254 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
269 * Copy readSize bytes between two file descriptors
271 int copySubFile(int srcFd, int dstFd, size_t remaining)
276 while (remaining > 0) {
277 if (remaining > BUFSIZ)
281 if (fullWrite(dstFd, buffer, fullRead(srcFd, buffer, size)) < size)
290 #if defined (BB_CP_MV)
292 * Copy one file to another, while possibly preserving its modes, times, and
293 * modes. Returns TRUE if successful, or FALSE on a failure with an error
294 * message output. (Failure is not indicated if attributes cannot be set.)
298 copyFile(const char *srcName, const char *destName,
299 int setModes, int followLinks, int forceFlag)
304 struct stat srcStatBuf;
305 struct stat dstStatBuf;
306 struct utimbuf times;
308 if (followLinks == TRUE)
309 status = stat(srcName, &srcStatBuf);
311 status = lstat(srcName, &srcStatBuf);
318 if (followLinks == TRUE)
319 status = stat(destName, &dstStatBuf);
321 status = lstat(destName, &dstStatBuf);
323 if (status < 0 || forceFlag==TRUE) {
325 dstStatBuf.st_ino = -1;
326 dstStatBuf.st_dev = -1;
329 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
330 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
331 errorMsg("Copying file \"%s\" to itself\n", srcName);
335 if (S_ISDIR(srcStatBuf.st_mode)) {
336 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
337 /* Make sure the directory is writable */
338 status = mkdir(destName, 0777777 ^ umask(0));
339 if (status < 0 && errno != EEXIST) {
343 } else if (S_ISLNK(srcStatBuf.st_mode)) {
344 char link_val[BUFSIZ + 1];
347 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
348 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
349 link_size = readlink(srcName, &link_val[0], BUFSIZ);
354 link_val[link_size] = '\0';
355 status = symlink(link_val, destName);
360 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
361 if (setModes == TRUE) {
362 /* Try to set owner, but fail silently like GNU cp */
363 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
367 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
368 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
369 if (mkfifo(destName, 0644) < 0) {
373 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
374 || S_ISSOCK(srcStatBuf.st_mode)) {
375 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
376 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
380 } else if (S_ISREG(srcStatBuf.st_mode)) {
381 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
382 rfd = open(srcName, O_RDONLY);
388 wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC,
396 if (copySubFile(rfd, wfd, srcStatBuf.st_size)==FALSE)
400 if (close(wfd) < 0) {
405 if (setModes == TRUE) {
406 /* This is fine, since symlinks never get here */
407 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
411 if (chmod(destName, srcStatBuf.st_mode) < 0) {
415 times.actime = srcStatBuf.st_atime;
416 times.modtime = srcStatBuf.st_mtime;
417 if (utime(destName, ×) < 0) {
432 #endif /* BB_CP_MV */
436 #if defined BB_TAR || defined BB_LS
438 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
439 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
441 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
442 static const mode_t SBIT[] = {
448 /* The 9 mode bits to test */
449 static const mode_t MBIT[] = {
450 S_IRUSR, S_IWUSR, S_IXUSR,
451 S_IRGRP, S_IWGRP, S_IXGRP,
452 S_IROTH, S_IWOTH, S_IXOTH
455 #define MODE1 "rwxrwxrwx"
456 #define MODE0 "---------"
457 #define SMODE1 "..s..s..t"
458 #define SMODE0 "..S..S..T"
461 * Return the standard ls-like mode string from a file mode.
462 * This is static and so is overwritten on each call.
464 const char *modeString(int mode)
470 buf[0] = TYPECHAR(mode);
471 for (i = 0; i < 9; i++) {
473 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
475 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
479 #endif /* BB_TAR || BB_LS */
482 #if defined BB_TAR || defined BB_AR
484 * Return the standard ls-like time string from a time_t
485 * This is static and so is overwritten on each call.
487 const char *timeString(time_t timeVal)
495 str = ctime(&timeVal);
497 strcpy(buf, &str[4]);
500 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
501 strcpy(&buf[7], &str[20]);
507 #endif /* BB_TAR || BB_AR */
509 #if defined BB_TAR || defined BB_CP_MV || defined BB_AR
511 * Write all of the supplied buffer out to a file.
512 * This does multiple writes as necessary.
513 * Returns the amount written, or -1 on an error.
515 int fullWrite(int fd, const char *buf, int len)
523 cc = write(fd, buf, len);
535 #endif /* BB_TAR || BB_CP_MV || BB_AR */
538 #if defined BB_TAR || defined BB_TAIL || defined BB_AR || defined BB_SH
540 * Read all of the supplied buffer from a file.
541 * This does multiple reads as necessary.
542 * Returns the amount read, or -1 on an error.
543 * A short read is returned on an end of file.
545 int fullRead(int fd, char *buf, int len)
553 cc = read(fd, buf, len);
568 #endif /* BB_TAR || BB_TAIL || BB_AR || BB_SH */
571 #if defined (BB_CHMOD_CHOWN_CHGRP) \
572 || defined (BB_CP_MV) \
573 || defined (BB_FIND) \
574 || defined (BB_INSMOD) \
580 * Walk down all the directories under the specified
581 * location, and do something (something specified
582 * by the fileAction and dirAction function pointers).
584 * Unfortunatly, while nftw(3) could replace this and reduce
585 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
586 * and so isn't sufficiently portable to take over since glibc2.1
587 * is so stinking huge.
589 int recursiveAction(const char *fileName,
590 int recurse, int followLinks, int depthFirst,
591 int (*fileAction) (const char *fileName,
592 struct stat * statbuf,
594 int (*dirAction) (const char *fileName,
595 struct stat * statbuf,
603 if (followLinks == TRUE)
604 status = stat(fileName, &statbuf);
606 status = lstat(fileName, &statbuf);
609 #ifdef BB_DEBUG_PRINT_SCAFFOLD
611 "status=%d followLinks=%d TRUE=%d\n",
612 status, followLinks, TRUE);
618 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
619 if (fileAction == NULL)
622 return fileAction(fileName, &statbuf, userData);
625 if (recurse == FALSE) {
626 if (S_ISDIR(statbuf.st_mode)) {
627 if (dirAction != NULL)
628 return (dirAction(fileName, &statbuf, userData));
634 if (S_ISDIR(statbuf.st_mode)) {
637 dir = opendir(fileName);
642 if (dirAction != NULL && depthFirst == FALSE) {
643 status = dirAction(fileName, &statbuf, userData);
644 if (status == FALSE) {
649 while ((next = readdir(dir)) != NULL) {
650 char nextFile[BUFSIZ + 1];
652 if ((strcmp(next->d_name, "..") == 0)
653 || (strcmp(next->d_name, ".") == 0)) {
656 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
657 errorMsg(name_too_long);
660 memset(nextFile, 0, sizeof(nextFile));
661 sprintf(nextFile, "%s/%s", fileName, next->d_name);
663 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
664 fileAction, dirAction, userData);
665 if (status == FALSE) {
670 status = closedir(dir);
675 if (dirAction != NULL && depthFirst == TRUE) {
676 status = dirAction(fileName, &statbuf, userData);
677 if (status == FALSE) {
683 if (fileAction == NULL)
686 return fileAction(fileName, &statbuf, userData);
691 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
695 #if defined (BB_TAR) || defined (BB_MKDIR)
697 * Attempt to create the directories along the specified path, except for
698 * the final component. The mode is given for the final directory only,
699 * while all previous ones get default protections. Errors are not reported
700 * here, as failures to restore files can be reported later.
702 extern int createPath(const char *name, int mode)
706 char buf[BUFSIZ + 1];
710 for (cp = buf; *cp == '/'; cp++);
711 cp = strchr(cp, '/');
714 cp = strchr(cp + 1, '/');
716 retVal = mkdir(buf, cp ? 0777 : mode);
717 if (retVal != 0 && errno != EEXIST) {
725 #endif /* BB_TAR || BB_MKDIR */
729 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR) \
730 || defined (BB_MKFIFO) || defined (BB_MKNOD)
731 /* [ugoa]{+|-|=}[rwxst] */
735 extern int parse_mode(const char *s, mode_t * theMode)
739 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
752 groups |= S_ISUID | S_IRWXU;
755 groups |= S_ISGID | S_IRWXG;
761 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
767 if (groups == 0) /* The default is "all" */
769 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
772 if (isdigit(c) && c >= '0' && c <= '7' &&
773 mode == 0 && groups == 0) {
774 *theMode = strtol(--s, NULL, 8);
782 while ((c = *s++) != '\0') {
787 mode |= S_IRUSR | S_IRGRP | S_IROTH;
790 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
793 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
796 mode |= S_IXGRP | S_ISUID | S_ISGID;
810 andMode &= ~(groups);
813 orMode |= mode & groups;
816 andMode &= ~(mode & groups);
828 /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR || BB_MKFIFO || BB_MKNOD */
834 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS \
835 || defined BB_TAR || defined BB_ID || defined BB_LOGGER \
836 || defined BB_LOGNAME || defined BB_WHOAMI
838 /* This parses entries in /etc/passwd and /etc/group. This is desirable
839 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
840 * increases target size and is often not needed or wanted for embedded
843 * /etc/passwd entries look like this:
844 * root:x:0:0:root:/root:/bin/bash
845 * and /etc/group entries look like this:
848 * This uses buf as storage to hold things.
851 unsigned long my_getid(const char *filename, char *name, long id, long *gid)
854 char *rname, *start, *end, buf[128];
858 file = fopen(filename, "r");
860 /* Do not complain. It is ok for /etc/passwd and
861 * friends to be missing... */
865 while (fgets(buf, 128, file) != NULL) {
869 /* username/group name */
871 end = strchr(start, ':');
879 end = strchr(start, ':');
883 /* uid in passwd, gid in group */
885 rid = (unsigned long) strtol(start, &end, 10);
891 rgid = (unsigned long) strtol(start, &end, 10);
894 if (0 == strcmp(rname, name)) {
895 if (gid) *gid = rgid;
900 if (id != -1 && id == rid) {
901 strncpy(name, rname, 8);
902 if (gid) *gid = rgid;
911 /* returns a uid given a username */
912 long my_getpwnam(char *name)
914 return my_getid("/etc/passwd", name, -1, NULL);
917 /* returns a gid given a group name */
918 long my_getgrnam(char *name)
920 return my_getid("/etc/group", name, -1, NULL);
923 /* gets a username given a uid */
924 void my_getpwuid(char *name, long uid)
926 my_getid("/etc/passwd", name, uid, NULL);
929 /* gets a groupname given a gid */
930 void my_getgrgid(char *group, long gid)
932 my_getid("/etc/group", group, gid, NULL);
935 /* gets a gid given a user name */
936 long my_getpwnamegid(char *name)
939 my_getid("/etc/passwd", name, -1, &gid);
944 /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
945 || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
948 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
950 /* From <linux/kd.h> */
951 #define KDGKBTYPE 0x4B33 /* get keyboard type */
953 #define KB_101 0x02 /* this is what we always answer */
955 int is_a_console(int fd)
960 return (ioctl(fd, KDGKBTYPE, &arg) == 0
961 && ((arg == KB_101) || (arg == KB_84)));
964 static int open_a_console(char *fnam)
969 fd = open(fnam, O_RDWR);
971 /* if failed, try read-only */
972 if (fd < 0 && errno == EACCES)
973 fd = open(fnam, O_RDONLY);
975 /* if failed, try write-only */
976 if (fd < 0 && errno == EACCES)
977 fd = open(fnam, O_WRONLY);
979 /* if failed, fail */
983 /* if not a console, fail */
984 if (!is_a_console(fd)) {
994 * Get an fd for use with kbd/console ioctls.
995 * We try several things because opening /dev/console will fail
996 * if someone else used X (which does a chown on /dev/console).
998 * if tty_name is non-NULL, try this one instead.
1001 int get_console_fd(char *tty_name)
1006 if (-1 == (fd = open_a_console(tty_name)))
1012 fd = open_a_console("/dev/tty");
1016 fd = open_a_console("/dev/tty0");
1020 fd = open_a_console("/dev/console");
1024 for (fd = 0; fd < 3; fd++)
1025 if (is_a_console(fd))
1028 errorMsg("Couldnt get a file descriptor referring to the console\n");
1029 return -1; /* total failure */
1033 #endif /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1036 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
1038 /* Do a case insensitive strstr() */
1039 char *stristr(char *haystack, const char *needle)
1041 int len = strlen(needle);
1044 if (!strncasecmp(haystack, needle, len))
1055 /* This tries to find a needle in a haystack, but does so by
1056 * only trying to match literal strings (look 'ma, no regexps!)
1057 * This is short, sweet, and carries _very_ little baggage,
1058 * unlike its beefier cousin in regexp.c
1061 extern int find_match(char *haystack, char *needle, int ignoreCase)
1064 if (ignoreCase == FALSE)
1065 haystack = strstr(haystack, needle);
1067 haystack = stristr(haystack, needle);
1068 if (haystack == NULL)
1074 /* This performs substitutions after a string match has been found. */
1075 extern int replace_match(char *haystack, char *needle, char *newNeedle,
1079 char *where, *slider, *slider1, *oldhayStack;
1081 if (ignoreCase == FALSE)
1082 where = strstr(haystack, needle);
1084 where = stristr(haystack, needle);
1086 if (strcmp(needle, newNeedle) == 0)
1089 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1090 while (where != NULL) {
1092 strcpy(oldhayStack, haystack);
1093 for (slider = haystack, slider1 = oldhayStack; slider != where;
1094 slider++, slider1++);
1096 haystack = strcat(haystack, newNeedle);
1097 slider1 += strlen(needle);
1098 haystack = strcat(haystack, slider1);
1099 where = strstr(slider, needle);
1109 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1112 #if defined BB_FIND || defined BB_INSMOD
1114 * Routine to see if a text string is matched by a wildcard pattern.
1115 * Returns TRUE if the text is matched, or FALSE if it is not matched
1116 * or if the pattern is invalid.
1117 * * matches zero or more characters
1118 * ? matches a single character
1119 * [abc] matches 'a', 'b' or 'c'
1120 * \c quotes character c
1121 * Adapted from code written by Ingo Wilken, and
1122 * then taken from sash, Copyright (c) 1999 by David I. Bell
1123 * Permission is granted to use, distribute, or modify this source,
1124 * provided that this copyright notice remains intact.
1125 * Permission to distribute this code under the GPL has been granted.
1127 extern int check_wildcard_match(const char *text, const char *pattern)
1129 const char *retryPat;
1130 const char *retryText;
1138 while (*text || *pattern) {
1150 while ((ch = *pattern++) != ']') {
1161 if (found == FALSE && len!=0) {
1164 if (found == TRUE) {
1165 if (strlen(pattern)==0 && len==1) {
1174 /* fall into next case */
1177 if (*text++ == '\0')
1188 /* fall into next case */
1206 if (pattern == NULL)
1212 #endif /* BB_FIND || BB_INSMOD */
1217 #if defined BB_DF || defined BB_MTAB
1219 * Given a block device, find the mount table entry if that block device
1222 * Given any other file (or directory), find the mount table entry for its
1225 extern struct mntent *findMountPoint(const char *name, const char *table)
1230 struct mntent *mountEntry;
1232 if (stat(name, &s) != 0)
1235 if ((s.st_mode & S_IFMT) == S_IFBLK)
1236 mountDevice = s.st_rdev;
1238 mountDevice = s.st_dev;
1241 if ((mountTable = setmntent(table, "r")) == 0)
1244 while ((mountEntry = getmntent(mountTable)) != 0) {
1245 if (strcmp(name, mountEntry->mnt_dir) == 0
1246 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1248 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1250 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1253 endmntent(mountTable);
1256 #endif /* BB_DF || BB_MTAB */
1260 #if defined BB_DD || defined BB_TAIL
1262 * Read a number with a possible multiplier.
1263 * Returns -1 if the number format is illegal.
1265 extern long getNum(const char *cp)
1269 if (!isDecimal(*cp))
1274 while (isDecimal(*cp))
1275 value = value * 10 + *cp++ - '0';
1279 case 'm': /* `tail' uses it traditionally */
1307 #endif /* BB_DD || BB_TAIL */
1310 #if defined BB_INIT || defined BB_SYSLOGD
1311 /* try to open up the specified device */
1312 extern int device_open(char *device, int mode)
1316 m = mode | O_NONBLOCK;
1318 /* Retry up to 5 times */
1319 for (f = 0; f < 5; f++)
1320 if ((fd = open(device, m, 0600)) >= 0)
1324 /* Reset original flags. */
1326 fcntl(fd, F_SETFL, mode);
1329 #endif /* BB_INIT BB_SYSLOGD */
1332 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1333 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1334 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1337 #if defined BB_FEATURE_USE_DEVPS_PATCH
1340 * This finds the pid of the specified process,
1341 * by using the /dev/ps device driver.
1343 * Returns a list of all matching PIDs
1345 extern pid_t* findPidByName( char* pidName)
1348 char device[] = "/dev/ps";
1350 pid_t* pid_array = NULL;
1351 pid_t* pidList=NULL;
1354 fd = open(device, O_RDONLY);
1356 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1358 /* Find out how many processes there are */
1359 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1360 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1362 /* Allocate some memory -- grab a few extras just in case
1363 * some new processes start up while we wait. The kernel will
1364 * just ignore any extras if we give it too many, and will trunc.
1365 * the list if we give it too few. */
1366 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1367 pid_array[0] = num_pids+10;
1369 /* Now grab the pid list */
1370 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1371 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1373 /* Now search for a match */
1374 for (i=1, j=0; i<pid_array[0] ; i++) {
1376 struct pid_info info;
1378 info.pid = pid_array[i];
1379 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1380 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1382 /* Make sure we only match on the process name */
1383 p=info.command_line+1;
1384 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1390 if ((strstr(info.command_line, pidName) != NULL)
1391 && (strlen(pidName) == strlen(info.command_line))) {
1392 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1394 fatalError(memory_exhausted);
1395 pidList[j++]=info.pid;
1405 if (close (fd) != 0)
1406 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1410 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1411 #if ! defined BB_FEATURE_USE_PROCFS
1412 #error Sorry, I depend on the /proc filesystem right now.
1417 * This finds the pid of the specified process.
1418 * Currently, it's implemented by rummaging through
1419 * the proc filesystem.
1421 * Returns a list of all matching PIDs
1423 extern pid_t* findPidByName( char* pidName)
1426 struct dirent *next;
1427 pid_t* pidList=NULL;
1430 dir = opendir("/proc");
1432 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1434 while ((next = readdir(dir)) != NULL) {
1440 /* If it isn't a number, we don't want it */
1441 if (!isdigit(*next->d_name))
1444 /* Now open the status file */
1445 sprintf(filename, "/proc/%s/status", next->d_name);
1446 status = fopen(filename, "r");
1450 fgets(buffer, 256, status);
1453 /* Make sure we only match on the process name */
1454 p=buffer+5; /* Skip the name */
1456 if (*p==0 || *p=='\n') {
1461 p=buffer+6; /* Skip the "Name:\t" */
1463 if ((strstr(p, pidName) != NULL)
1464 && (strlen(pidName) == strlen(p))) {
1465 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1467 fatalError(memory_exhausted);
1468 pidList[i++]=strtol(next->d_name, NULL, 0);
1475 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1476 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1479 /* this should really be farmed out to libbusybox.a */
1480 extern void *xmalloc(size_t size)
1482 void *ptr = malloc(size);
1485 fatalError(memory_exhausted);
1489 extern void *xrealloc(void *old, size_t size)
1491 void *ptr = realloc(old, size);
1493 fatalError(memory_exhausted);
1497 extern void *xcalloc(size_t nmemb, size_t size)
1499 void *ptr = calloc(nmemb, size);
1501 fatalError(memory_exhausted);
1506 #if defined BB_FEATURE_NFSMOUNT || defined BB_LSMOD
1508 extern char * xstrdup (const char *s) {
1517 fatalError(memory_exhausted);
1523 extern char * xstrndup (const char *s, int n) {
1527 fatalError("xstrndup bug");
1538 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1539 extern int vdprintf(int d, const char *format, va_list ap)
1544 len = vsprintf(buf, format, ap);
1545 return write(d, buf, len);
1547 #endif /* BB_SYSLOGD */
1549 #if defined BB_FEATURE_MOUNT_LOOP
1550 extern int del_loop(const char *device)
1554 if ((fd = open(device, O_RDONLY)) < 0) {
1558 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1559 perror("ioctl: LOOP_CLR_FD");
1566 extern int set_loop(const char *device, const char *file, int offset,
1569 struct loop_info loopinfo;
1572 mode = *loopro ? O_RDONLY : O_RDWR;
1573 if ((ffd = open(file, mode)) < 0 && !*loopro
1574 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1578 if ((fd = open(device, mode)) < 0) {
1583 *loopro = (mode == O_RDONLY);
1585 memset(&loopinfo, 0, sizeof(loopinfo));
1586 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1587 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1589 loopinfo.lo_offset = offset;
1591 loopinfo.lo_encrypt_key_size = 0;
1592 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1593 perror("ioctl: LOOP_SET_FD");
1598 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1599 (void) ioctl(fd, LOOP_CLR_FD, 0);
1600 perror("ioctl: LOOP_SET_STATUS");
1610 extern char *find_unused_loop_device(void)
1614 struct stat statbuf;
1615 struct loop_info loopinfo;
1617 for (i = 0; i <= 7; i++) {
1618 sprintf(dev, "/dev/loop%d", i);
1619 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1620 if ((fd = open(dev, O_RDONLY)) >= 0) {
1621 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1622 if (errno == ENXIO) { /* probably free */
1633 #endif /* BB_FEATURE_MOUNT_LOOP */
1635 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1636 extern int find_real_root_device_name(char* name)
1639 struct dirent *entry;
1640 struct stat statBuf, rootStat;
1641 char fileName[BUFSIZ];
1643 if (stat("/", &rootStat) != 0) {
1644 errorMsg("could not stat '/'\n");
1648 dir = opendir("/dev");
1650 errorMsg("could not open '/dev'\n");
1654 while((entry = readdir(dir)) != NULL) {
1656 /* Must skip ".." since that is "/", and so we
1657 * would get a false positive on ".." */
1658 if (strcmp(entry->d_name, "..") == 0)
1661 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1663 if (stat(fileName, &statBuf) != 0)
1665 /* Some char devices have the same dev_t as block
1666 * devices, so make sure this is a block device */
1667 if (! S_ISBLK(statBuf.st_mode))
1669 if (statBuf.st_rdev == rootStat.st_rdev) {
1670 strcpy(name, fileName);
1680 /* get_line_from_file() - This function reads an entire line from a text file
1681 * up to a newline. It returns a malloc'ed char * which must be stored and
1682 * free'ed by the caller. */
1683 extern char *get_line_from_file(FILE *file)
1685 static const int GROWBY = 80; /* how large we will grow strings by */
1689 char *linebuf = NULL;
1696 /* grow the line buffer as necessary */
1697 if (idx > linebufsz-2)
1698 linebuf = realloc(linebuf, linebufsz += GROWBY);
1699 linebuf[idx++] = (char)ch;
1700 if ((char)ch == '\n')
1711 #if defined BB_CAT || defined BB_LSMOD
1712 extern void print_file(FILE *file)
1716 while ((c = getc(file)) != EOF)
1722 extern int print_file_by_name(char *filename)
1725 file = fopen(filename, "r");
1732 #endif /* BB_CAT || BB_LSMOD */
1734 #if defined BB_ECHO || defined BB_TR
1735 char process_escape_sequence(char **ptr)
1739 switch (c = *(*ptr)++) {
1761 case '0': case '1': case '2': case '3':
1762 case '4': case '5': case '6': case '7':
1764 if ('0' <= **ptr && **ptr <= '7') {
1765 c = c * 8 + (*(*ptr)++ - '0');
1766 if ('0' <= **ptr && **ptr <= '7')
1767 c = c * 8 + (*(*ptr)++ - '0');
1779 #if defined BB_BASENAME || defined BB_LN
1780 char *get_last_path_component(char *path)
1782 char *s=path+strlen(path)-1;
1784 /* strip trailing slashes */
1785 while (s && *s == '/') {
1789 /* find last component */
1790 s = strrchr(path, '/');
1791 if (s==NULL) return path;
1796 #if defined BB_GREP || defined BB_SED
1797 void xregcomp(regex_t *preg, const char *regex, int cflags)
1800 if ((ret = regcomp(preg, regex, cflags)) != 0) {
1801 int errmsgsz = regerror(ret, preg, NULL, 0);
1802 char *errmsg = xmalloc(errmsgsz);
1803 regerror(ret, preg, errmsg, errmsgsz);
1804 fatalError("bb_regcomp: %s\n", errmsg);
1812 c-file-style: "linux"