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/utsname.h> /* for uname(2) */
52 #if defined BB_FEATURE_MOUNT_LOOP
54 #include <sys/ioctl.h>
55 #include <linux/loop.h>
58 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the
59 * list of available filesystems used for the -t auto option */
60 #if defined BB_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
61 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
62 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
66 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
67 # if defined BB_FEATURE_USE_PROCFS
68 const char mtab_file[] = "/proc/mounts";
71 const char mtab_file[] = "/etc/mtab";
73 # if defined BB_FEATURE_USE_DEVPS_PATCH
74 const char mtab_file[] = "/dev/mtab";
76 # 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)
83 extern void usage(const char *usage)
85 fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
87 fprintf(stderr, "Usage: %s\n", usage);
91 extern void errorMsg(const char *s, ...)
97 vfprintf(stderr, s, p);
102 extern void fatalError(const char *s, ...)
108 vfprintf(stderr, s, p);
115 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
116 * so, for example, to check if the kernel is greater than 2.2.11:
117 * if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
119 extern int get_kernel_revision(void)
122 int major = 0, minor = 0, patch = 0;
124 if (uname(&name) == -1) {
125 perror("cannot get system information");
128 sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
129 return major * 65536 + minor * 256 + patch;
133 #if defined (BB_CP_MV) || defined (BB_DU)
135 #define HASH_SIZE 311 /* Should be prime */
136 #define hash_inode(i) ((i) % HASH_SIZE)
138 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
141 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
142 * `ino_dev_hashtable', else return 0
144 * If NAME is a non-NULL pointer to a character pointer, and there is
145 * a match, then set *NAME to the value of the name slot in that
148 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
150 ino_dev_hashtable_bucket_t *bucket;
152 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
153 while (bucket != NULL) {
154 if ((bucket->ino == statbuf->st_ino) &&
155 (bucket->dev == statbuf->st_dev))
157 if (name) *name = bucket->name;
160 bucket = bucket->next;
165 /* Add statbuf to statbuf hash table */
166 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
170 ino_dev_hashtable_bucket_t *bucket;
172 i = hash_inode(statbuf->st_ino);
173 s = name ? strlen(name) : 0;
174 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
175 bucket->ino = statbuf->st_ino;
176 bucket->dev = statbuf->st_dev;
178 strcpy(bucket->name, name);
180 bucket->name[0] = '\0';
181 bucket->next = ino_dev_hashtable[i];
182 ino_dev_hashtable[i] = bucket;
185 /* Clear statbuf hash table */
186 void reset_ino_dev_hashtable(void)
189 ino_dev_hashtable_bucket_t *bucket;
191 for (i = 0; i < HASH_SIZE; i++) {
192 while (ino_dev_hashtable[i] != NULL) {
193 bucket = ino_dev_hashtable[i]->next;
194 free(ino_dev_hashtable[i]);
195 ino_dev_hashtable[i] = bucket;
200 #endif /* BB_CP_MV || BB_DU */
202 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
204 * Return TRUE if a fileName is a directory.
205 * Nonexistant files return FALSE.
207 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
212 if (statBuf == NULL) {
213 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
217 if (followLinks == TRUE)
218 status = stat(fileName, statBuf);
220 status = lstat(fileName, statBuf);
222 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
235 #if defined (BB_CP_MV)
237 * Copy one file to another, while possibly preserving its modes, times,
238 * and modes. Returns TRUE if successful, or FALSE on a failure with an
239 * error message output. (Failure is not indicated if the attributes cannot
244 copyFile(const char *srcName, const char *destName,
245 int setModes, int followLinks)
252 struct stat srcStatBuf;
253 struct stat dstStatBuf;
254 struct utimbuf times;
256 if (followLinks == TRUE)
257 status = stat(srcName, &srcStatBuf);
259 status = lstat(srcName, &srcStatBuf);
266 if (followLinks == TRUE)
267 status = stat(destName, &dstStatBuf);
269 status = lstat(destName, &dstStatBuf);
272 dstStatBuf.st_ino = -1;
273 dstStatBuf.st_dev = -1;
276 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
277 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
278 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
282 if (S_ISDIR(srcStatBuf.st_mode)) {
283 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
284 /* Make sure the directory is writable */
285 status = mkdir(destName, 0777777 ^ umask(0));
286 if (status < 0 && errno != EEXIST) {
290 } else if (S_ISLNK(srcStatBuf.st_mode)) {
291 char link_val[BUFSIZ + 1];
294 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
295 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
296 link_size = readlink(srcName, &link_val[0], BUFSIZ);
301 link_val[link_size] = '\0';
302 status = symlink(link_val, destName);
307 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
308 if (setModes == TRUE) {
309 if (lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
316 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
317 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
318 if (mkfifo(destName, 0644) < 0) {
322 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
323 || S_ISSOCK(srcStatBuf.st_mode)) {
324 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
325 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
329 } else if (S_ISREG(srcStatBuf.st_mode)) {
330 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
331 rfd = open(srcName, O_RDONLY);
338 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
346 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
347 if (fullWrite(wfd, buf, rcc) < 0)
355 if (close(wfd) < 0) {
360 if (setModes == TRUE) {
361 /* This is fine, since symlinks never get here */
362 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
366 if (chmod(destName, srcStatBuf.st_mode) < 0) {
370 times.actime = srcStatBuf.st_atime;
371 times.modtime = srcStatBuf.st_mtime;
372 if (utime(destName, ×) < 0) {
387 #endif /* BB_CP_MV */
391 #if defined BB_TAR || defined BB_LS
393 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
394 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
396 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
397 static const mode_t SBIT[] = {
403 /* The 9 mode bits to test */
404 static const mode_t MBIT[] = {
405 S_IRUSR, S_IWUSR, S_IXUSR,
406 S_IRGRP, S_IWGRP, S_IXGRP,
407 S_IROTH, S_IWOTH, S_IXOTH
410 #define MODE1 "rwxrwxrwx"
411 #define MODE0 "---------"
412 #define SMODE1 "..s..s..t"
413 #define SMODE0 "..S..S..T"
416 * Return the standard ls-like mode string from a file mode.
417 * This is static and so is overwritten on each call.
419 const char *modeString(int mode)
425 buf[0] = TYPECHAR(mode);
426 for (i = 0; i < 9; i++) {
428 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
430 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
434 #endif /* BB_TAR || BB_LS */
439 * Return the standard ls-like time string from a time_t
440 * This is static and so is overwritten on each call.
442 const char *timeString(time_t timeVal)
450 str = ctime(&timeVal);
452 strcpy(buf, &str[4]);
455 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
456 strcpy(&buf[7], &str[20]);
464 #if defined BB_TAR || defined BB_CP_MV
466 * Write all of the supplied buffer out to a file.
467 * This does multiple writes as necessary.
468 * Returns the amount written, or -1 on an error.
470 int fullWrite(int fd, const char *buf, int len)
478 cc = write(fd, buf, len);
490 #endif /* BB_TAR || BB_CP_MV */
493 #if defined BB_TAR || defined BB_TAIL
495 * Read all of the supplied buffer from a file.
496 * This does multiple reads as necessary.
497 * Returns the amount read, or -1 on an error.
498 * A short read is returned on an end of file.
500 int fullRead(int fd, char *buf, int len)
508 cc = read(fd, buf, len);
523 #endif /* BB_TAR || BB_TAIL */
526 #if defined (BB_CHMOD_CHOWN_CHGRP) \
527 || defined (BB_CP_MV) \
528 || defined (BB_FIND) \
529 || defined (BB_INSMOD) \
534 * Walk down all the directories under the specified
535 * location, and do something (something specified
536 * by the fileAction and dirAction function pointers).
538 * Unfortunatly, while nftw(3) could replace this and reduce
539 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
540 * and so isn't sufficiently portable to take over since glibc2.1
541 * is so stinking huge.
543 int recursiveAction(const char *fileName,
544 int recurse, int followLinks, int depthFirst,
545 int (*fileAction) (const char *fileName,
546 struct stat * statbuf,
548 int (*dirAction) (const char *fileName,
549 struct stat * statbuf,
557 if (followLinks == TRUE)
558 status = stat(fileName, &statbuf);
560 status = lstat(fileName, &statbuf);
563 #ifdef BB_DEBUG_PRINT_SCAFFOLD
565 "status=%d followLinks=%d TRUE=%d\n",
566 status, followLinks, TRUE);
572 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
573 if (fileAction == NULL)
576 return fileAction(fileName, &statbuf, userData);
579 if (recurse == FALSE) {
580 if (S_ISDIR(statbuf.st_mode)) {
581 if (dirAction != NULL)
582 return (dirAction(fileName, &statbuf, userData));
588 if (S_ISDIR(statbuf.st_mode)) {
591 dir = opendir(fileName);
596 if (dirAction != NULL && depthFirst == FALSE) {
597 status = dirAction(fileName, &statbuf, userData);
598 if (status == FALSE) {
603 while ((next = readdir(dir)) != NULL) {
604 char nextFile[BUFSIZ + 1];
606 if ((strcmp(next->d_name, "..") == 0)
607 || (strcmp(next->d_name, ".") == 0)) {
610 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
611 fprintf(stderr, name_too_long, "ftw");
614 memset(nextFile, 0, sizeof(nextFile));
615 sprintf(nextFile, "%s/%s", fileName, next->d_name);
617 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
618 fileAction, dirAction, userData);
624 status = closedir(dir);
629 if (dirAction != NULL && depthFirst == TRUE) {
630 status = dirAction(fileName, &statbuf, userData);
631 if (status == FALSE) {
637 if (fileAction == NULL)
640 return fileAction(fileName, &statbuf, userData);
645 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
649 #if defined (BB_TAR) || defined (BB_MKDIR)
651 * Attempt to create the directories along the specified path, except for
652 * the final component. The mode is given for the final directory only,
653 * while all previous ones get default protections. Errors are not reported
654 * here, as failures to restore files can be reported later.
656 extern int createPath(const char *name, int mode)
660 char buf[BUFSIZ + 1];
664 for (cp = buf; *cp == '/'; cp++);
665 cp = strchr(cp, '/');
668 cp = strchr(cp + 1, '/');
670 retVal = mkdir(buf, cp ? 0777 : mode);
671 if (retVal != 0 && errno != EEXIST) {
679 #endif /* BB_TAR || BB_MKDIR */
683 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
684 /* [ugoa]{+|-|=}[rwxst] */
688 extern int parse_mode(const char *s, mode_t * theMode)
692 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
705 groups |= S_ISUID | S_IRWXU;
708 groups |= S_ISGID | S_IRWXG;
714 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
720 if (groups == 0) /* The default is "all" */
722 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
725 if (isdigit(c) && c >= '0' && c <= '7' &&
726 mode == 0 && groups == 0) {
727 *theMode = strtol(--s, NULL, 8);
735 while ((c = *s++) != '\0') {
740 mode |= S_IRUSR | S_IRGRP | S_IROTH;
743 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
746 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
749 mode |= S_IXGRP | S_ISUID | S_ISGID;
763 andMode &= ~(groups);
766 orMode |= mode & groups;
769 andMode &= ~(mode & groups);
780 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
788 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS || defined BB_TAR
790 /* Use this to avoid needing the glibc NSS stuff
791 * This uses storage buf to hold things.
793 uid_t my_getid(const char *filename, char *name, uid_t id)
796 char *rname, *start, *end, buf[128];
799 file = fopen(filename, "r");
805 while (fgets(buf, 128, file) != NULL) {
810 end = strchr(start, ':');
817 end = strchr(start, ':');
822 rid = (uid_t) strtol(start, &end, 10);
827 if (0 == strcmp(rname, name)) {
832 if (id != -1 && id == rid) {
833 strncpy(name, rname, 8);
842 uid_t my_getpwnam(char *name)
844 return my_getid("/etc/passwd", name, -1);
847 gid_t my_getgrnam(char *name)
849 return my_getid("/etc/group", name, -1);
852 void my_getpwuid(char *name, uid_t uid)
854 my_getid("/etc/passwd", name, uid);
857 void my_getgrgid(char *group, gid_t gid)
859 my_getid("/etc/group", group, gid);
863 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR */
868 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
871 #include <linux/kd.h>
872 #include <sys/ioctl.h>
874 int is_a_console(int fd)
879 return (ioctl(fd, KDGKBTYPE, &arg) == 0
880 && ((arg == KB_101) || (arg == KB_84)));
883 static int open_a_console(char *fnam)
888 fd = open(fnam, O_RDWR);
890 /* if failed, try read-only */
891 if (fd < 0 && errno == EACCES)
892 fd = open(fnam, O_RDONLY);
894 /* if failed, try write-only */
895 if (fd < 0 && errno == EACCES)
896 fd = open(fnam, O_WRONLY);
898 /* if failed, fail */
902 /* if not a console, fail */
903 if (!is_a_console(fd)) {
913 * Get an fd for use with kbd/console ioctls.
914 * We try several things because opening /dev/console will fail
915 * if someone else used X (which does a chown on /dev/console).
917 * if tty_name is non-NULL, try this one instead.
920 int get_console_fd(char *tty_name)
925 if (-1 == (fd = open_a_console(tty_name)))
931 fd = open_a_console("/dev/tty");
935 fd = open_a_console("/dev/tty0");
939 fd = open_a_console("/dev/console");
943 for (fd = 0; fd < 3; fd++)
944 if (is_a_console(fd))
948 "Couldnt get a file descriptor referring to the console\n");
949 return -1; /* total failure */
953 #endif /* BB_CHVT || BB_DEALLOCVT */
956 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
958 /* Do a case insensitive strstr() */
959 char *stristr(char *haystack, const char *needle)
961 int len = strlen(needle);
964 if (!strncasecmp(haystack, needle, len))
975 /* This tries to find a needle in a haystack, but does so by
976 * only trying to match literal strings (look 'ma, no regexps!)
977 * This is short, sweet, and carries _very_ little baggage,
978 * unlike its beefier cousin in regexp.c
981 extern int find_match(char *haystack, char *needle, int ignoreCase)
984 if (ignoreCase == FALSE)
985 haystack = strstr(haystack, needle);
987 haystack = stristr(haystack, needle);
988 if (haystack == NULL)
994 /* This performs substitutions after a string match has been found. */
995 extern int replace_match(char *haystack, char *needle, char *newNeedle,
999 char *where, *slider, *slider1, *oldhayStack;
1001 if (ignoreCase == FALSE)
1002 where = strstr(haystack, needle);
1004 where = stristr(haystack, needle);
1006 if (strcmp(needle, newNeedle) == 0)
1009 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1010 while (where != NULL) {
1012 strcpy(oldhayStack, haystack);
1014 if (strlen(newNeedle) > strlen(needle)) {
1016 (char *) realloc(haystack,
1017 (unsigned) (strlen(haystack) -
1019 strlen(newNeedle)));
1022 for (slider = haystack, slider1 = oldhayStack; slider != where;
1023 slider++, slider1++);
1025 haystack = strcat(haystack, newNeedle);
1026 slider1 += strlen(needle);
1027 haystack = strcat(haystack, slider1);
1028 where = strstr(slider, needle);
1038 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1043 * Routine to see if a text string is matched by a wildcard pattern.
1044 * Returns TRUE if the text is matched, or FALSE if it is not matched
1045 * or if the pattern is invalid.
1046 * * matches zero or more characters
1047 * ? matches a single character
1048 * [abc] matches 'a', 'b' or 'c'
1049 * \c quotes character c
1050 * Adapted from code written by Ingo Wilken, and
1051 * then taken from sash, Copyright (c) 1999 by David I. Bell
1052 * Permission is granted to use, distribute, or modify this source,
1053 * provided that this copyright notice remains intact.
1054 * Permission to distribute this code under the GPL has been granted.
1056 extern int check_wildcard_match(const char *text, const char *pattern)
1058 const char *retryPat;
1059 const char *retryText;
1067 while (*text || *pattern) {
1079 while ((ch = *pattern++) != ']') {
1090 if (found == FALSE && len!=0) {
1093 if (found == TRUE) {
1094 if (strlen(pattern)==0 && len==1) {
1103 /* fall into next case */
1106 if (*text++ == '\0')
1117 /* fall into next case */
1135 if (pattern == NULL)
1141 #endif /* BB_FIND */
1146 #if defined BB_DF || defined BB_MTAB
1148 * Given a block device, find the mount table entry if that block device
1151 * Given any other file (or directory), find the mount table entry for its
1154 extern struct mntent *findMountPoint(const char *name, const char *table)
1159 struct mntent *mountEntry;
1161 if (stat(name, &s) != 0)
1164 if ((s.st_mode & S_IFMT) == S_IFBLK)
1165 mountDevice = s.st_rdev;
1167 mountDevice = s.st_dev;
1170 if ((mountTable = setmntent(table, "r")) == 0)
1173 while ((mountEntry = getmntent(mountTable)) != 0) {
1174 if (strcmp(name, mountEntry->mnt_dir) == 0
1175 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1177 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1179 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1182 endmntent(mountTable);
1185 #endif /* BB_DF || BB_MTAB */
1189 #if defined BB_DD || defined BB_TAIL
1191 * Read a number with a possible multiplier.
1192 * Returns -1 if the number format is illegal.
1194 extern long getNum(const char *cp)
1198 if (!isDecimal(*cp))
1203 while (isDecimal(*cp))
1204 value = value * 10 + *cp++ - '0';
1208 case 'm': /* `tail' uses it traditionally */
1236 #endif /* BB_DD || BB_TAIL */
1239 #if defined BB_INIT || defined BB_SYSLOGD
1240 /* try to open up the specified device */
1241 extern int device_open(char *device, int mode)
1245 m = mode | O_NONBLOCK;
1247 /* Retry up to 5 times */
1248 for (f = 0; f < 5; f++)
1249 if ((fd = open(device, m, 0600)) >= 0)
1253 /* Reset original flags. */
1255 fcntl(fd, F_SETFL, mode);
1258 #endif /* BB_INIT BB_SYSLOGD */
1261 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1262 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1263 #include <linux/devps.h>
1266 #if defined BB_FEATURE_USE_DEVPS_PATCH
1269 * This finds the pid of the specified process,
1270 * by using the /dev/ps device driver.
1272 * Returns a list of all matching PIDs
1274 extern pid_t* findPidByName( char* pidName)
1277 char device[] = "/dev/ps";
1279 pid_t* pid_array = NULL;
1280 pid_t* pidList=NULL;
1283 fd = open(device, O_RDONLY);
1285 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1287 /* Find out how many processes there are */
1288 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1289 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1291 /* Allocate some memory -- grab a few extras just in case
1292 * some new processes start up while we wait. The kernel will
1293 * just ignore any extras if we give it too many, and will trunc.
1294 * the list if we give it too few. */
1295 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1296 pid_array[0] = num_pids+10;
1298 /* Now grab the pid list */
1299 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1300 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1302 /* Now search for a match */
1303 for (i=1; i<pid_array[0] ; i++) {
1305 struct pid_info info;
1307 info.pid = pid_array[i];
1308 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1309 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1311 /* Make sure we only match on the process name */
1312 p=info.command_line+1;
1313 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1319 if ((strstr(info.command_line, pidName) != NULL)
1320 && (strlen(pidName) == strlen(info.command_line))) {
1321 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1323 fatalError("out of memory\n");
1324 pidList[j++]=info.pid;
1334 if (close (fd) != 0)
1335 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1339 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1340 #if ! defined BB_FEATURE_USE_PROCFS
1341 #error Sorry, I depend on the /proc filesystem right now.
1346 * This finds the pid of the specified process.
1347 * Currently, it's implemented by rummaging through
1348 * the proc filesystem.
1350 * Returns a list of all matching PIDs
1352 extern pid_t* findPidByName( char* pidName)
1355 struct dirent *next;
1356 pid_t* pidList=NULL;
1359 dir = opendir("/proc");
1361 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1363 while ((next = readdir(dir)) != NULL) {
1369 /* If it isn't a number, we don't want it */
1370 if (!isdigit(*next->d_name))
1373 /* Now open the status file */
1374 sprintf(filename, "/proc/%s/status", next->d_name);
1375 status = fopen(filename, "r");
1379 fgets(buffer, 256, status);
1382 /* Make sure we only match on the process name */
1383 p=buffer+5; /* Skip the name */
1385 if (*p==0 || *p=='\n') {
1390 p=buffer+6; /* Skip the "Name:\t" */
1392 if ((strstr(p, pidName) != NULL)
1393 && (strlen(pidName) == strlen(p))) {
1394 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1396 fatalError("out of memory\n");
1397 pidList[i++]=strtol(next->d_name, NULL, 0);
1404 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1405 #endif /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1407 /* this should really be farmed out to libbusybox.a */
1408 extern void *xmalloc(size_t size)
1410 void *cp = malloc(size);
1413 fatalError("out of memory\n");
1417 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1418 extern int vdprintf(int d, const char *format, va_list ap)
1423 len = vsprintf(buf, format, ap);
1424 return write(d, buf, len);
1426 #endif /* BB_SYSLOGD */
1428 #if defined BB_FEATURE_MOUNT_LOOP
1429 extern int del_loop(const char *device)
1433 if ((fd = open(device, O_RDONLY)) < 0) {
1437 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1438 perror("ioctl: LOOP_CLR_FD");
1445 extern int set_loop(const char *device, const char *file, int offset,
1448 struct loop_info loopinfo;
1451 mode = *loopro ? O_RDONLY : O_RDWR;
1452 if ((ffd = open(file, mode)) < 0 && !*loopro
1453 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1457 if ((fd = open(device, mode)) < 0) {
1462 *loopro = (mode == O_RDONLY);
1464 memset(&loopinfo, 0, sizeof(loopinfo));
1465 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1466 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1468 loopinfo.lo_offset = offset;
1470 loopinfo.lo_encrypt_key_size = 0;
1471 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1472 perror("ioctl: LOOP_SET_FD");
1477 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1478 (void) ioctl(fd, LOOP_CLR_FD, 0);
1479 perror("ioctl: LOOP_SET_STATUS");
1489 extern char *find_unused_loop_device(void)
1493 struct stat statbuf;
1494 struct loop_info loopinfo;
1496 for (i = 0; i <= 7; i++) {
1497 sprintf(dev, "/dev/loop%d", i);
1498 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1499 if ((fd = open(dev, O_RDONLY)) >= 0) {
1500 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1501 if (errno == ENXIO) { /* probably free */
1512 #endif /* BB_FEATURE_MOUNT_LOOP */
1514 #if defined BB_MOUNT || defined BB_DF
1515 extern int find_real_root_device_name(char* name)
1518 struct dirent *entry;
1519 struct stat statBuf, rootStat;
1520 char fileName[BUFSIZ];
1522 if (stat("/", &rootStat) != 0) {
1523 errorMsg("could not stat '/'\n");
1527 dir = opendir("/dev");
1529 errorMsg("could not open '/dev'\n");
1533 while((entry = readdir(dir)) != NULL) {
1535 /* Must skip ".." since that is "/", and so we
1536 * would get a false positive on ".." */
1537 if (strcmp(entry->d_name, "..") == 0)
1540 sprintf( fileName, "/dev/%s", entry->d_name);
1542 if (stat(fileName, &statBuf) != 0)
1544 /* Some char devices have the same dev_t as block
1545 * devices, so make sure this is a block device */
1546 if (! S_ISBLK(statBuf.st_mode))
1548 if (statBuf.st_rdev == rootStat.st_rdev) {
1549 strcpy(name, fileName);
1558 const unsigned int CSTRING_BUFFER_LENGTH = 128;
1559 /* recursive parser that returns cstrings of arbitrary length
1563 cstring_alloc(FILE* f, int depth)
1566 char buffer[CSTRING_BUFFER_LENGTH];
1567 int target = CSTRING_BUFFER_LENGTH * depth;
1573 while ((buffer[i] = fgetc(f)) != EOF) {
1574 if (buffer[i++] == 0x0a) { break; }
1575 if (i == CSTRING_BUFFER_LENGTH) { break; }
1579 /* recurse or malloc? */
1580 if (len == CSTRING_BUFFER_LENGTH) {
1581 cstring = cstring_alloc(f, (depth + 1));
1583 /* [special case] EOF */
1584 if ((depth | len) == 0) { return NULL; }
1587 size = target + len + 1;
1588 cstring = malloc(size);
1589 if (!cstring) { return NULL; }
1590 cstring[size - 1] = 0;
1595 memcpy(&cstring[target], buffer, len);
1601 * wrapper around recursive cstring_alloc
1602 * it's the caller's responsibility to free the cstring
1605 cstring_lineFromFile(FILE *f)
1607 return cstring_alloc(f, 0);
1613 c-file-style: "linux"