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) \
33 || defined (BB_INSMOD)
34 /* same conditions as recursiveAction */
35 #define bb_need_name_too_long
37 #define BB_DECLARE_EXTERN
50 #include <sys/param.h> /* for PATH_MAX */
51 #include <sys/utsname.h> /* for uname(2) */
53 #if defined BB_FEATURE_MOUNT_LOOP
55 #include <sys/ioctl.h>
56 #include <linux/loop.h>
59 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
60 * list of available filesystems used for the -t auto option */
61 #if defined BB_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
62 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
63 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
67 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
68 # if defined BB_FEATURE_USE_PROCFS
69 const char mtab_file[] = "/proc/mounts";
72 const char mtab_file[] = "/etc/mtab";
74 # if defined BB_FEATURE_USE_DEVPS_PATCH
75 const char mtab_file[] = "/dev/mtab";
77 # 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)
84 extern void usage(const char *usage)
86 fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
88 fprintf(stderr, "Usage: %s\n", usage);
92 extern void errorMsg(const char *s, ...)
98 vfprintf(stderr, s, p);
103 extern void fatalError(const char *s, ...)
109 vfprintf(stderr, s, p);
116 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
117 * so, for example, to check if the kernel is greater than 2.2.11:
118 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
120 extern int get_kernel_revision(void)
123 int major = 0, minor = 0, patch = 0;
125 if (uname(&name) == -1) {
126 perror("cannot get system information");
129 sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
130 return major * 65536 + minor * 256 + patch;
134 #if defined (BB_CP_MV) || defined (BB_DU)
136 #define HASH_SIZE 311 /* Should be prime */
137 #define hash_inode(i) ((i) % HASH_SIZE)
139 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
142 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
143 * `ino_dev_hashtable', else return 0
145 * If NAME is a non-NULL pointer to a character pointer, and there is
146 * a match, then set *NAME to the value of the name slot in that
149 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
151 ino_dev_hashtable_bucket_t *bucket;
153 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
154 while (bucket != NULL) {
155 if ((bucket->ino == statbuf->st_ino) &&
156 (bucket->dev == statbuf->st_dev))
158 if (name) *name = bucket->name;
161 bucket = bucket->next;
166 /* Add statbuf to statbuf hash table */
167 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
171 ino_dev_hashtable_bucket_t *bucket;
173 i = hash_inode(statbuf->st_ino);
174 s = name ? strlen(name) : 0;
175 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
176 bucket->ino = statbuf->st_ino;
177 bucket->dev = statbuf->st_dev;
179 strcpy(bucket->name, name);
181 bucket->name[0] = '\0';
182 bucket->next = ino_dev_hashtable[i];
183 ino_dev_hashtable[i] = bucket;
186 /* Clear statbuf hash table */
187 void reset_ino_dev_hashtable(void)
190 ino_dev_hashtable_bucket_t *bucket;
192 for (i = 0; i < HASH_SIZE; i++) {
193 while (ino_dev_hashtable[i] != NULL) {
194 bucket = ino_dev_hashtable[i]->next;
195 free(ino_dev_hashtable[i]);
196 ino_dev_hashtable[i] = bucket;
201 #endif /* BB_CP_MV || BB_DU */
203 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
205 * Return TRUE if a fileName is a directory.
206 * Nonexistant files return FALSE.
208 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
213 if (statBuf == NULL) {
214 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
218 if (followLinks == TRUE)
219 status = stat(fileName, statBuf);
221 status = lstat(fileName, statBuf);
223 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
236 #if defined (BB_CP_MV)
238 * Copy one file to another, while possibly preserving its modes, times,
239 * and modes. Returns TRUE if successful, or FALSE on a failure with an
240 * error message output. (Failure is not indicated if the attributes cannot
245 copyFile(const char *srcName, const char *destName,
246 int setModes, int followLinks)
253 struct stat srcStatBuf;
254 struct stat dstStatBuf;
255 struct utimbuf times;
257 if (followLinks == TRUE)
258 status = stat(srcName, &srcStatBuf);
260 status = lstat(srcName, &srcStatBuf);
267 if (followLinks == TRUE)
268 status = stat(destName, &dstStatBuf);
270 status = lstat(destName, &dstStatBuf);
273 dstStatBuf.st_ino = -1;
274 dstStatBuf.st_dev = -1;
277 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
278 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
279 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
283 if (S_ISDIR(srcStatBuf.st_mode)) {
284 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
285 /* Make sure the directory is writable */
286 status = mkdir(destName, 0777777 ^ umask(0));
287 if (status < 0 && errno != EEXIST) {
291 } else if (S_ISLNK(srcStatBuf.st_mode)) {
292 char link_val[PATH_MAX + 1];
295 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
296 /* Warning: This could possibly truncate silently, to PATH_MAX chars */
297 link_size = readlink(srcName, &link_val[0], PATH_MAX);
302 link_val[link_size] = '\0';
303 status = symlink(link_val, destName);
308 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
309 if (setModes == TRUE) {
310 if (lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
317 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
318 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
319 if (mkfifo(destName, 0644) < 0) {
323 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
324 || S_ISSOCK(srcStatBuf.st_mode)) {
325 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
326 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
330 } else if (S_ISREG(srcStatBuf.st_mode)) {
331 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
332 rfd = open(srcName, O_RDONLY);
339 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
347 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
348 if (fullWrite(wfd, buf, rcc) < 0)
356 if (close(wfd) < 0) {
361 if (setModes == TRUE) {
362 /* This is fine, since symlinks never get here */
363 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
367 if (chmod(destName, srcStatBuf.st_mode) < 0) {
371 times.actime = srcStatBuf.st_atime;
372 times.modtime = srcStatBuf.st_mtime;
373 if (utime(destName, ×) < 0) {
388 #endif /* BB_CP_MV */
392 #if defined BB_TAR || defined BB_LS
394 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
395 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
397 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
398 static const mode_t SBIT[] = {
404 /* The 9 mode bits to test */
405 static const mode_t MBIT[] = {
406 S_IRUSR, S_IWUSR, S_IXUSR,
407 S_IRGRP, S_IWGRP, S_IXGRP,
408 S_IROTH, S_IWOTH, S_IXOTH
411 #define MODE1 "rwxrwxrwx"
412 #define MODE0 "---------"
413 #define SMODE1 "..s..s..t"
414 #define SMODE0 "..S..S..T"
417 * Return the standard ls-like mode string from a file mode.
418 * This is static and so is overwritten on each call.
420 const char *modeString(int mode)
426 buf[0] = TYPECHAR(mode);
427 for (i = 0; i < 9; i++) {
429 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
431 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
435 #endif /* BB_TAR || BB_LS */
440 * Return the standard ls-like time string from a time_t
441 * This is static and so is overwritten on each call.
443 const char *timeString(time_t timeVal)
451 str = ctime(&timeVal);
453 strcpy(buf, &str[4]);
456 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
457 strcpy(&buf[7], &str[20]);
465 #if defined BB_TAR || defined BB_CP_MV
467 * Write all of the supplied buffer out to a file.
468 * This does multiple writes as necessary.
469 * Returns the amount written, or -1 on an error.
471 int fullWrite(int fd, const char *buf, int len)
479 cc = write(fd, buf, len);
491 #endif /* BB_TAR || BB_CP_MV */
494 #if defined BB_TAR || defined BB_TAIL
496 * Read all of the supplied buffer from a file.
497 * This does multiple reads as necessary.
498 * Returns the amount read, or -1 on an error.
499 * A short read is returned on an end of file.
501 int fullRead(int fd, char *buf, int len)
509 cc = read(fd, buf, len);
524 #endif /* BB_TAR || BB_TAIL */
527 #if defined (BB_CHMOD_CHOWN_CHGRP) \
528 || defined (BB_CP_MV) \
529 || defined (BB_FIND) \
531 || defined (BB_INSMOD)
533 * Walk down all the directories under the specified
534 * location, and do something (something specified
535 * by the fileAction and dirAction function pointers).
537 * Unfortunatly, while nftw(3) could replace this and reduce
538 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
539 * and so isn't sufficiently portable to take over since glibc2.1
540 * is so stinking huge.
542 int recursiveAction(const char *fileName,
543 int recurse, int followLinks, int depthFirst,
544 int (*fileAction) (const char *fileName,
545 struct stat * statbuf,
547 int (*dirAction) (const char *fileName,
548 struct stat * statbuf,
556 if (followLinks == TRUE)
557 status = stat(fileName, &statbuf);
559 status = lstat(fileName, &statbuf);
562 #ifdef BB_DEBUG_PRINT_SCAFFOLD
564 "status=%d followLinks=%d TRUE=%d\n",
565 status, followLinks, TRUE);
571 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
572 if (fileAction == NULL)
575 return fileAction(fileName, &statbuf, userData);
578 if (recurse == FALSE) {
579 if (S_ISDIR(statbuf.st_mode)) {
580 if (dirAction != NULL)
581 return (dirAction(fileName, &statbuf, userData));
587 if (S_ISDIR(statbuf.st_mode)) {
590 dir = opendir(fileName);
595 if (dirAction != NULL && depthFirst == FALSE) {
596 status = dirAction(fileName, &statbuf, userData);
597 if (status == FALSE) {
602 while ((next = readdir(dir)) != NULL) {
603 char nextFile[PATH_MAX + 1];
605 if ((strcmp(next->d_name, "..") == 0)
606 || (strcmp(next->d_name, ".") == 0)) {
609 if (strlen(fileName) + strlen(next->d_name) + 1 > PATH_MAX) {
610 fprintf(stderr, name_too_long, "ftw");
613 sprintf(nextFile, "%s/%s", fileName, next->d_name);
615 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
616 fileAction, dirAction, userData);
622 status = closedir(dir);
627 if (dirAction != NULL && depthFirst == TRUE) {
628 status = dirAction(fileName, &statbuf, userData);
629 if (status == FALSE) {
635 if (fileAction == NULL)
638 return fileAction(fileName, &statbuf, userData);
643 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
647 #if defined (BB_TAR) || defined (BB_MKDIR)
649 * Attempt to create the directories along the specified path, except for
650 * the final component. The mode is given for the final directory only,
651 * while all previous ones get default protections. Errors are not reported
652 * here, as failures to restore files can be reported later.
654 extern int createPath(const char *name, int mode)
658 char buf[PATH_MAX + 1];
662 for (cp = buf; *cp == '/'; cp++);
663 cp = strchr(cp, '/');
666 cp = strchr(cp + 1, '/');
668 retVal = mkdir(buf, cp ? 0777 : mode);
669 if (retVal != 0 && errno != EEXIST) {
677 #endif /* BB_TAR || BB_MKDIR */
681 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
682 /* [ugoa]{+|-|=}[rwxst] */
686 extern int parse_mode(const char *s, mode_t * theMode)
690 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
703 groups |= S_ISUID | S_IRWXU;
706 groups |= S_ISGID | S_IRWXG;
712 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
718 if (groups == 0) /* The default is "all" */
720 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
723 if (isdigit(c) && c >= '0' && c <= '7' &&
724 mode == 0 && groups == 0) {
725 *theMode = strtol(--s, NULL, 8);
733 while ((c = *s++) != '\0') {
738 mode |= S_IRUSR | S_IRGRP | S_IROTH;
741 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
744 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
747 mode |= S_IXGRP | S_ISUID | S_ISGID;
761 andMode &= ~(groups);
764 orMode |= mode & groups;
767 andMode &= ~(mode & groups);
778 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
786 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS || defined BB_TAR
788 /* Use this to avoid needing the glibc NSS stuff
789 * This uses storage buf to hold things.
791 uid_t my_getid(const char *filename, char *name, uid_t id)
794 char *rname, *start, *end, buf[128];
797 file = fopen(filename, "r");
803 while (fgets(buf, 128, file) != NULL) {
808 end = strchr(start, ':');
815 end = strchr(start, ':');
820 rid = (uid_t) strtol(start, &end, 10);
825 if (0 == strcmp(rname, name)) {
830 if (id != -1 && id == rid) {
831 strncpy(name, rname, 8);
840 uid_t my_getpwnam(char *name)
842 return my_getid("/etc/passwd", name, -1);
845 gid_t my_getgrnam(char *name)
847 return my_getid("/etc/group", name, -1);
850 void my_getpwuid(char *name, uid_t uid)
852 my_getid("/etc/passwd", name, uid);
855 void my_getgrgid(char *group, gid_t gid)
857 my_getid("/etc/group", group, gid);
861 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR */
866 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
869 #include <linux/kd.h>
870 #include <sys/ioctl.h>
872 int is_a_console(int fd)
877 return (ioctl(fd, KDGKBTYPE, &arg) == 0
878 && ((arg == KB_101) || (arg == KB_84)));
881 static int open_a_console(char *fnam)
886 fd = open(fnam, O_RDWR);
888 /* if failed, try read-only */
889 if (fd < 0 && errno == EACCES)
890 fd = open(fnam, O_RDONLY);
892 /* if failed, try write-only */
893 if (fd < 0 && errno == EACCES)
894 fd = open(fnam, O_WRONLY);
896 /* if failed, fail */
900 /* if not a console, fail */
901 if (!is_a_console(fd)) {
911 * Get an fd for use with kbd/console ioctls.
912 * We try several things because opening /dev/console will fail
913 * if someone else used X (which does a chown on /dev/console).
915 * if tty_name is non-NULL, try this one instead.
918 int get_console_fd(char *tty_name)
923 if (-1 == (fd = open_a_console(tty_name)))
929 fd = open_a_console("/dev/tty");
933 fd = open_a_console("/dev/tty0");
937 fd = open_a_console("/dev/console");
941 for (fd = 0; fd < 3; fd++)
942 if (is_a_console(fd))
946 "Couldnt get a file descriptor referring to the console\n");
947 return -1; /* total failure */
951 #endif /* BB_CHVT || BB_DEALLOCVT */
954 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
956 /* Do a case insensitive strstr() */
957 char *stristr(char *haystack, const char *needle)
959 int len = strlen(needle);
962 if (!strncasecmp(haystack, needle, len))
973 /* This tries to find a needle in a haystack, but does so by
974 * only trying to match literal strings (look 'ma, no regexps!)
975 * This is short, sweet, and carries _very_ little baggage,
976 * unlike its beefier cousin in regexp.c
979 extern int find_match(char *haystack, char *needle, int ignoreCase)
982 if (ignoreCase == FALSE)
983 haystack = strstr(haystack, needle);
985 haystack = stristr(haystack, needle);
986 if (haystack == NULL)
992 /* This performs substitutions after a string match has been found. */
993 extern int replace_match(char *haystack, char *needle, char *newNeedle,
997 char *where, *slider, *slider1, *oldhayStack;
999 if (ignoreCase == FALSE)
1000 where = strstr(haystack, needle);
1002 where = stristr(haystack, needle);
1004 if (strcmp(needle, newNeedle) == 0)
1007 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1008 while (where != NULL) {
1010 strcpy(oldhayStack, haystack);
1012 if (strlen(newNeedle) > strlen(needle)) {
1014 (char *) realloc(haystack,
1015 (unsigned) (strlen(haystack) -
1017 strlen(newNeedle)));
1020 for (slider = haystack, slider1 = oldhayStack; slider != where;
1021 slider++, slider1++);
1023 haystack = strcat(haystack, newNeedle);
1024 slider1 += strlen(needle);
1025 haystack = strcat(haystack, slider1);
1026 where = strstr(slider, needle);
1036 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1041 * Routine to see if a text string is matched by a wildcard pattern.
1042 * Returns TRUE if the text is matched, or FALSE if it is not matched
1043 * or if the pattern is invalid.
1044 * * matches zero or more characters
1045 * ? matches a single character
1046 * [abc] matches 'a', 'b' or 'c'
1047 * \c quotes character c
1048 * Adapted from code written by Ingo Wilken, and
1049 * then taken from sash, Copyright (c) 1999 by David I. Bell
1050 * Permission is granted to use, distribute, or modify this source,
1051 * provided that this copyright notice remains intact.
1052 * Permission to distribute this code under the GPL has been granted.
1054 extern int check_wildcard_match(const char *text, const char *pattern)
1056 const char *retryPat;
1057 const char *retryText;
1064 while (*text || *pattern) {
1076 while ((ch = *pattern++) != ']') {
1088 if (found == TRUE) {
1093 /* fall into next case */
1096 if (*text++ == '\0')
1107 /* fall into next case */
1125 if (pattern == NULL)
1131 #endif /* BB_FIND */
1136 #if defined BB_DF || defined BB_MTAB
1138 * Given a block device, find the mount table entry if that block device
1141 * Given any other file (or directory), find the mount table entry for its
1144 extern struct mntent *findMountPoint(const char *name, const char *table)
1149 struct mntent *mountEntry;
1151 if (stat(name, &s) != 0)
1154 if ((s.st_mode & S_IFMT) == S_IFBLK)
1155 mountDevice = s.st_rdev;
1157 mountDevice = s.st_dev;
1160 if ((mountTable = setmntent(table, "r")) == 0)
1163 while ((mountEntry = getmntent(mountTable)) != 0) {
1164 if (strcmp(name, mountEntry->mnt_dir) == 0
1165 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1167 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1169 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1172 endmntent(mountTable);
1175 #endif /* BB_DF || BB_MTAB */
1179 #if defined BB_DD || defined BB_TAIL
1181 * Read a number with a possible multiplier.
1182 * Returns -1 if the number format is illegal.
1184 extern long getNum(const char *cp)
1188 if (!isDecimal(*cp))
1193 while (isDecimal(*cp))
1194 value = value * 10 + *cp++ - '0';
1198 case 'm': /* `tail' uses it traditionally */
1226 #endif /* BB_DD || BB_TAIL */
1229 #if defined BB_INIT || defined BB_SYSLOGD
1230 /* try to open up the specified device */
1231 extern int device_open(char *device, int mode)
1235 m = mode | O_NONBLOCK;
1237 /* Retry up to 5 times */
1238 for (f = 0; f < 5; f++)
1239 if ((fd = open(device, m, 0600)) >= 0)
1243 /* Reset original flags. */
1245 fcntl(fd, F_SETFL, mode);
1248 #endif /* BB_INIT BB_SYSLOGD */
1251 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1252 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1253 #include <linux/devps.h>
1256 #if defined BB_FEATURE_USE_DEVPS_PATCH
1259 * This finds the pid of the specified process,
1260 * by using the /dev/ps device driver.
1262 * Returns a list of all matching PIDs
1264 extern pid_t* findPidByName( char* pidName)
1267 char device[] = "/dev/ps";
1269 pid_t* pid_array = NULL;
1270 pid_t* pidList=NULL;
1273 fd = open(device, O_RDONLY);
1275 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1277 /* Find out how many processes there are */
1278 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1279 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1281 /* Allocate some memory -- grab a few extras just in case
1282 * some new processes start up while we wait. The kernel will
1283 * just ignore any extras if we give it too many, and will trunc.
1284 * the list if we give it too few. */
1285 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1286 pid_array[0] = num_pids+10;
1288 /* Now grab the pid list */
1289 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1290 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1292 /* Now search for a match */
1293 for (i=1; i<pid_array[0] ; i++) {
1294 struct pid_info info;
1296 info.pid = pid_array[i];
1297 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1298 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1300 if ((strstr(info.command_line, pidName) != NULL)) {
1301 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1303 fatalError("out of memory\n");
1304 pidList[j++]=info.pid;
1313 if (close (fd) != 0)
1314 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1318 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1319 #if ! defined BB_FEATURE_USE_PROCFS
1320 #error Sorry, I depend on the /proc filesystem right now.
1325 * This finds the pid of the specified process.
1326 * Currently, it's implemented by rummaging through
1327 * the proc filesystem.
1329 * Returns a list of all matching PIDs
1331 extern pid_t* findPidByName( char* pidName)
1334 struct dirent *next;
1335 pid_t* pidList=NULL;
1338 dir = opendir("/proc");
1340 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1342 while ((next = readdir(dir)) != NULL) {
1348 /* If it isn't a number, we don't want it */
1349 if (!isdigit(*next->d_name))
1352 /* Now open the status file */
1353 sprintf(filename, "/proc/%s/status", next->d_name);
1354 status = fopen(filename, "r");
1358 fgets(buffer, 256, status);
1361 if (((p=strstr(buffer, pidName)) != NULL)
1362 && (strncmp(p, pidName, strlen(pidName)) != 0)) {
1363 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1365 fatalError("out of memory\n");
1366 pidList[i++]=strtol(next->d_name, NULL, 0);
1373 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1374 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1376 /* this should really be farmed out to libbusybox.a */
1377 extern void *xmalloc(size_t size)
1379 void *cp = malloc(size);
1382 fatalError("out of memory\n");
1386 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1387 extern int vdprintf(int d, const char *format, va_list ap)
1392 len = vsprintf(buf, format, ap);
1393 return write(d, buf, len);
1395 #endif /* BB_SYSLOGD */
1397 #if defined BB_FEATURE_MOUNT_LOOP
1398 extern int del_loop(const char *device)
1402 if ((fd = open(device, O_RDONLY)) < 0) {
1406 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1407 perror("ioctl: LOOP_CLR_FD");
1414 extern int set_loop(const char *device, const char *file, int offset,
1417 struct loop_info loopinfo;
1420 mode = *loopro ? O_RDONLY : O_RDWR;
1421 if ((ffd = open(file, mode)) < 0 && !*loopro
1422 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1426 if ((fd = open(device, mode)) < 0) {
1431 *loopro = (mode == O_RDONLY);
1433 memset(&loopinfo, 0, sizeof(loopinfo));
1434 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1435 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1437 loopinfo.lo_offset = offset;
1439 loopinfo.lo_encrypt_key_size = 0;
1440 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1441 perror("ioctl: LOOP_SET_FD");
1446 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1447 (void) ioctl(fd, LOOP_CLR_FD, 0);
1448 perror("ioctl: LOOP_SET_STATUS");
1458 extern char *find_unused_loop_device(void)
1462 struct stat statbuf;
1463 struct loop_info loopinfo;
1465 for (i = 0; i <= 7; i++) {
1466 sprintf(dev, "/dev/loop%d", i);
1467 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1468 if ((fd = open(dev, O_RDONLY)) >= 0) {
1469 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1470 if (errno == ENXIO) { /* probably free */
1481 #endif /* BB_FEATURE_MOUNT_LOOP */
1483 #if defined BB_MOUNT || defined BB_DF
1484 extern int find_real_root_device_name(char* name)
1487 struct dirent *entry;
1488 struct stat statBuf, rootStat;
1489 char fileName[BUFSIZ];
1491 if (stat("/", &rootStat) != 0) {
1492 errorMsg("could not stat '/'\n");
1496 dir = opendir("/dev");
1498 errorMsg("could not open '/dev'\n");
1502 while((entry = readdir(dir)) != NULL) {
1504 /* Must skip ".." since that is "/", and so we
1505 * would get a false positive on ".." */
1506 if (strcmp(entry->d_name, "..") == 0)
1509 sprintf( fileName, "/dev/%s", entry->d_name);
1511 if (stat(fileName, &statBuf) != 0)
1513 /* Some char devices have the same dev_t as block
1514 * devices, so make sure this is a block device */
1515 if (! S_ISBLK(statBuf.st_mode))
1517 if (statBuf.st_rdev == rootStat.st_rdev) {
1518 strcpy(name, fileName);
1527 const unsigned int CSTRING_BUFFER_LENGTH = 128;
1528 /* recursive parser that returns cstrings of arbitrary length
1532 cstring_alloc(FILE* f, int depth)
1535 char buffer[CSTRING_BUFFER_LENGTH];
1536 int target = CSTRING_BUFFER_LENGTH * depth;
1542 while ((buffer[i] = fgetc(f)) != EOF) {
1543 if (buffer[i++] == 0x0a) { break; }
1544 if (i == CSTRING_BUFFER_LENGTH) { break; }
1548 /* recurse or malloc? */
1549 if (len == CSTRING_BUFFER_LENGTH) {
1550 cstring = cstring_alloc(f, (depth + 1));
1552 /* [special case] EOF */
1553 if ((depth | len) == 0) { return NULL; }
1556 size = target + len + 1;
1557 cstring = malloc(size);
1558 if (!cstring) { return NULL; }
1559 cstring[size - 1] = 0;
1564 memcpy(&cstring[target], buffer, len);
1570 * wrapper around recursive cstring_alloc
1571 * it's the caller's responsibility to free the cstring
1574 cstring_lineFromFile(FILE *f)
1576 return cstring_alloc(f, 0);
1582 c-file-style: "linux"