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
36 #define bb_need_memory_exhausted
38 #define BB_DECLARE_EXTERN
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);
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 #define HASH_SIZE 311 /* Should be prime */
134 #define hash_inode(i) ((i) % HASH_SIZE)
136 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
139 * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
140 * `ino_dev_hashtable', else return 0
142 * If NAME is a non-NULL pointer to a character pointer, and there is
143 * a match, then set *NAME to the value of the name slot in that
146 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
148 ino_dev_hashtable_bucket_t *bucket;
150 bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
151 while (bucket != NULL) {
152 if ((bucket->ino == statbuf->st_ino) &&
153 (bucket->dev == statbuf->st_dev))
155 if (name) *name = bucket->name;
158 bucket = bucket->next;
163 /* Add statbuf to statbuf hash table */
164 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
168 ino_dev_hashtable_bucket_t *bucket;
170 i = hash_inode(statbuf->st_ino);
171 s = name ? strlen(name) : 0;
172 bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
173 bucket->ino = statbuf->st_ino;
174 bucket->dev = statbuf->st_dev;
176 strcpy(bucket->name, name);
178 bucket->name[0] = '\0';
179 bucket->next = ino_dev_hashtable[i];
180 ino_dev_hashtable[i] = bucket;
183 /* Clear statbuf hash table */
184 void reset_ino_dev_hashtable(void)
187 ino_dev_hashtable_bucket_t *bucket;
189 for (i = 0; i < HASH_SIZE; i++) {
190 while (ino_dev_hashtable[i] != NULL) {
191 bucket = ino_dev_hashtable[i]->next;
192 free(ino_dev_hashtable[i]);
193 ino_dev_hashtable[i] = bucket;
200 * Return TRUE if a fileName is a directory.
201 * Nonexistant files return FALSE.
203 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
208 if (statBuf == NULL) {
209 statBuf = (struct stat *)xmalloc(sizeof(struct stat));
213 if (followLinks == TRUE)
214 status = stat(fileName, statBuf);
216 status = lstat(fileName, statBuf);
218 if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
231 * Copy one file to another, while possibly preserving its modes, times, and
232 * modes. Returns TRUE if successful, or FALSE on a failure with an error
233 * message output. (Failure is not indicated if attributes cannot be set.)
237 copyFile(const char *srcName, const char *destName,
238 int setModes, int followLinks, int forceFlag)
245 struct stat srcStatBuf;
246 struct stat dstStatBuf;
247 struct utimbuf times;
249 if (followLinks == TRUE)
250 status = stat(srcName, &srcStatBuf);
252 status = lstat(srcName, &srcStatBuf);
259 if (followLinks == TRUE)
260 status = stat(destName, &dstStatBuf);
262 status = lstat(destName, &dstStatBuf);
264 if (status < 0 || forceFlag==TRUE) {
266 dstStatBuf.st_ino = -1;
267 dstStatBuf.st_dev = -1;
270 if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
271 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
272 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
276 if (S_ISDIR(srcStatBuf.st_mode)) {
277 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
278 /* Make sure the directory is writable */
279 status = mkdir(destName, 0777777 ^ umask(0));
280 if (status < 0 && errno != EEXIST) {
284 } else if (S_ISLNK(srcStatBuf.st_mode)) {
285 char link_val[BUFSIZ + 1];
288 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
289 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
290 link_size = readlink(srcName, &link_val[0], BUFSIZ);
295 link_val[link_size] = '\0';
296 status = symlink(link_val, destName);
301 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
302 if (setModes == TRUE) {
303 /* Try to set owner, but fail silently like GNU cp */
304 lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
308 } else if (S_ISFIFO(srcStatBuf.st_mode)) {
309 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
310 if (mkfifo(destName, 0644) < 0) {
314 } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
315 || S_ISSOCK(srcStatBuf.st_mode)) {
316 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
317 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
321 } else if (S_ISREG(srcStatBuf.st_mode)) {
322 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
323 rfd = open(srcName, O_RDONLY);
330 open(destName, O_WRONLY | O_CREAT | O_TRUNC,
338 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
339 if (fullWrite(wfd, buf, rcc) < 0)
347 if (close(wfd) < 0) {
352 if (setModes == TRUE) {
353 /* This is fine, since symlinks never get here */
354 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
358 if (chmod(destName, srcStatBuf.st_mode) < 0) {
362 times.actime = srcStatBuf.st_atime;
363 times.modtime = srcStatBuf.st_mtime;
364 if (utime(destName, ×) < 0) {
382 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
383 #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
385 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
386 static const mode_t SBIT[] = {
392 /* The 9 mode bits to test */
393 static const mode_t MBIT[] = {
394 S_IRUSR, S_IWUSR, S_IXUSR,
395 S_IRGRP, S_IWGRP, S_IXGRP,
396 S_IROTH, S_IWOTH, S_IXOTH
399 #define MODE1 "rwxrwxrwx"
400 #define MODE0 "---------"
401 #define SMODE1 "..s..s..t"
402 #define SMODE0 "..S..S..T"
405 * Return the standard ls-like mode string from a file mode.
406 * This is static and so is overwritten on each call.
408 const char *modeString(int mode)
414 buf[0] = TYPECHAR(mode);
415 for (i = 0; i < 9; i++) {
417 buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
419 buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
426 * Return the standard ls-like time string from a time_t
427 * This is static and so is overwritten on each call.
429 const char *timeString(time_t timeVal)
437 str = ctime(&timeVal);
439 strcpy(buf, &str[4]);
442 if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
443 strcpy(&buf[7], &str[20]);
451 * Write all of the supplied buffer out to a file.
452 * This does multiple writes as necessary.
453 * Returns the amount written, or -1 on an error.
455 int fullWrite(int fd, const char *buf, int len)
463 cc = write(fd, buf, len);
478 * Read all of the supplied buffer from a file.
479 * This does multiple reads as necessary.
480 * Returns the amount read, or -1 on an error.
481 * A short read is returned on an end of file.
483 int fullRead(int fd, char *buf, int len)
491 cc = read(fd, buf, len);
509 * Walk down all the directories under the specified
510 * location, and do something (something specified
511 * by the fileAction and dirAction function pointers).
513 * Unfortunatly, while nftw(3) could replace this and reduce
514 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
515 * and so isn't sufficiently portable to take over since glibc2.1
516 * is so stinking huge.
518 int recursiveAction(const char *fileName,
519 int recurse, int followLinks, int depthFirst,
520 int (*fileAction) (const char *fileName,
521 struct stat * statbuf,
523 int (*dirAction) (const char *fileName,
524 struct stat * statbuf,
532 if (followLinks == TRUE)
533 status = stat(fileName, &statbuf);
535 status = lstat(fileName, &statbuf);
538 #ifdef BB_DEBUG_PRINT_SCAFFOLD
540 "status=%d followLinks=%d TRUE=%d\n",
541 status, followLinks, TRUE);
547 if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
548 if (fileAction == NULL)
551 return fileAction(fileName, &statbuf, userData);
554 if (recurse == FALSE) {
555 if (S_ISDIR(statbuf.st_mode)) {
556 if (dirAction != NULL)
557 return (dirAction(fileName, &statbuf, userData));
563 if (S_ISDIR(statbuf.st_mode)) {
566 dir = opendir(fileName);
571 if (dirAction != NULL && depthFirst == FALSE) {
572 status = dirAction(fileName, &statbuf, userData);
573 if (status == FALSE) {
578 while ((next = readdir(dir)) != NULL) {
579 char nextFile[BUFSIZ + 1];
581 if ((strcmp(next->d_name, "..") == 0)
582 || (strcmp(next->d_name, ".") == 0)) {
585 if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
586 fprintf(stderr, name_too_long, "ftw");
589 memset(nextFile, 0, sizeof(nextFile));
590 sprintf(nextFile, "%s/%s", fileName, next->d_name);
592 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
593 fileAction, dirAction, userData);
599 status = closedir(dir);
604 if (dirAction != NULL && depthFirst == TRUE) {
605 status = dirAction(fileName, &statbuf, userData);
606 if (status == FALSE) {
612 if (fileAction == NULL)
615 return fileAction(fileName, &statbuf, userData);
624 * Attempt to create the directories along the specified path, except for
625 * the final component. The mode is given for the final directory only,
626 * while all previous ones get default protections. Errors are not reported
627 * here, as failures to restore files can be reported later.
629 extern int createPath(const char *name, int mode)
633 char buf[BUFSIZ + 1];
637 for (cp = buf; *cp == '/'; cp++);
638 cp = strchr(cp, '/');
641 cp = strchr(cp + 1, '/');
643 retVal = mkdir(buf, cp ? 0777 : mode);
644 if (retVal != 0 && errno != EEXIST) {
655 /* [ugoa]{+|-|=}[rwxst] */
656 extern int parse_mode(const char *s, mode_t * theMode)
660 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
673 groups |= S_ISUID | S_IRWXU;
676 groups |= S_ISGID | S_IRWXG;
682 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
688 if (groups == 0) /* The default is "all" */
690 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
693 if (isdigit(c) && c >= '0' && c <= '7' &&
694 mode == 0 && groups == 0) {
695 *theMode = strtol(--s, NULL, 8);
703 while ((c = *s++) != '\0') {
708 mode |= S_IRUSR | S_IRGRP | S_IROTH;
711 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
714 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
717 mode |= S_IXGRP | S_ISUID | S_ISGID;
731 andMode &= ~(groups);
734 orMode |= mode & groups;
737 andMode &= ~(mode & groups);
751 /* This parses entries in /etc/passwd and /etc/group. This is desirable
752 * for BusyBox, since we want to avoid using the glibc NSS stuff, which
753 * increases target size and is often not needed or wanted for embedded
756 * /etc/passwd entries look like this:
757 * root:x:0:0:root:/root:/bin/bash
758 * and /etc/group entries look like this:
761 * This uses buf as storage to hold things.
764 uid_t my_getid(const char *filename, char *name, uid_t id, gid_t *gid)
767 char *rname, *start, *end, buf[128];
771 file = fopen(filename, "r");
777 while (fgets(buf, 128, file) != NULL) {
781 /* username/group name */
783 end = strchr(start, ':');
791 end = strchr(start, ':');
795 /* uid in passwd, gid in group */
797 rid = (uid_t) strtol(start, &end, 10);
803 rgid = (gid_t) strtol(start, &end, 10);
806 if (0 == strcmp(rname, name)) {
807 if (gid) *gid = rgid;
812 if (id != -1 && id == rid) {
813 strncpy(name, rname, 8);
814 if (gid) *gid = rgid;
823 /* returns a uid given a username */
824 uid_t my_getpwnam(char *name)
826 return my_getid("/etc/passwd", name, -1, NULL);
829 /* returns a gid given a group name */
830 gid_t my_getgrnam(char *name)
832 return my_getid("/etc/group", name, -1, NULL);
835 /* gets a username given a uid */
836 void my_getpwuid(char *name, uid_t uid)
838 my_getid("/etc/passwd", name, uid, NULL);
841 /* gets a groupname given a gid */
842 void my_getgrgid(char *group, gid_t gid)
844 my_getid("/etc/group", group, gid, NULL);
847 /* gets a gid given a user name */
848 gid_t my_getpwnamegid(char *name)
851 my_getid("/etc/passwd", name, -1, &gid);
857 #include <linux/kd.h>
858 #include <sys/ioctl.h>
860 int is_a_console(int fd)
865 return (ioctl(fd, KDGKBTYPE, &arg) == 0
866 && ((arg == KB_101) || (arg == KB_84)));
869 static int open_a_console(char *fnam)
874 fd = open(fnam, O_RDWR);
876 /* if failed, try read-only */
877 if (fd < 0 && errno == EACCES)
878 fd = open(fnam, O_RDONLY);
880 /* if failed, try write-only */
881 if (fd < 0 && errno == EACCES)
882 fd = open(fnam, O_WRONLY);
884 /* if failed, fail */
888 /* if not a console, fail */
889 if (!is_a_console(fd)) {
899 * Get an fd for use with kbd/console ioctls.
900 * We try several things because opening /dev/console will fail
901 * if someone else used X (which does a chown on /dev/console).
903 * if tty_name is non-NULL, try this one instead.
906 int get_console_fd(char *tty_name)
911 if (-1 == (fd = open_a_console(tty_name)))
917 fd = open_a_console("/dev/tty");
921 fd = open_a_console("/dev/tty0");
925 fd = open_a_console("/dev/console");
929 for (fd = 0; fd < 3; fd++)
930 if (is_a_console(fd))
934 "Couldnt get a file descriptor referring to the console\n");
935 return -1; /* total failure */
941 #if !defined BB_REGEXP
942 /* Do a case insensitive strstr() */
943 char *stristr(char *haystack, const char *needle)
945 int len = strlen(needle);
948 if (!strncasecmp(haystack, needle, len))
959 /* This tries to find a needle in a haystack, but does so by
960 * only trying to match literal strings (look 'ma, no regexps!)
961 * This is short, sweet, and carries _very_ little baggage,
962 * unlike its beefier cousin in regexp.c
965 extern int find_match(char *haystack, char *needle, int ignoreCase)
968 if (ignoreCase == FALSE)
969 haystack = strstr(haystack, needle);
971 haystack = stristr(haystack, needle);
972 if (haystack == NULL)
978 /* This performs substitutions after a string match has been found. */
979 extern int replace_match(char *haystack, char *needle, char *newNeedle,
983 char *where, *slider, *slider1, *oldhayStack;
985 if (ignoreCase == FALSE)
986 where = strstr(haystack, needle);
988 where = stristr(haystack, needle);
990 if (strcmp(needle, newNeedle) == 0)
993 oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
994 while (where != NULL) {
996 strcpy(oldhayStack, haystack);
997 for (slider = haystack, slider1 = oldhayStack; slider != where;
998 slider++, slider1++);
1000 haystack = strcat(haystack, newNeedle);
1001 slider1 += strlen(needle);
1002 haystack = strcat(haystack, slider1);
1003 where = strstr(slider, needle);
1012 #endif /* ! BB_REGEXP */
1016 * Routine to see if a text string is matched by a wildcard pattern.
1017 * Returns TRUE if the text is matched, or FALSE if it is not matched
1018 * or if the pattern is invalid.
1019 * * matches zero or more characters
1020 * ? matches a single character
1021 * [abc] matches 'a', 'b' or 'c'
1022 * \c quotes character c
1023 * Adapted from code written by Ingo Wilken, and
1024 * then taken from sash, Copyright (c) 1999 by David I. Bell
1025 * Permission is granted to use, distribute, or modify this source,
1026 * provided that this copyright notice remains intact.
1027 * Permission to distribute this code under the GPL has been granted.
1029 extern int check_wildcard_match(const char *text, const char *pattern)
1031 const char *retryPat;
1032 const char *retryText;
1040 while (*text || *pattern) {
1052 while ((ch = *pattern++) != ']') {
1063 if (found == FALSE && len!=0) {
1066 if (found == TRUE) {
1067 if (strlen(pattern)==0 && len==1) {
1076 /* fall into next case */
1079 if (*text++ == '\0')
1090 /* fall into next case */
1108 if (pattern == NULL)
1119 * Given a block device, find the mount table entry if that block device
1122 * Given any other file (or directory), find the mount table entry for its
1125 extern struct mntent *findMountPoint(const char *name, const char *table)
1130 struct mntent *mountEntry;
1132 if (stat(name, &s) != 0)
1135 if ((s.st_mode & S_IFMT) == S_IFBLK)
1136 mountDevice = s.st_rdev;
1138 mountDevice = s.st_dev;
1141 if ((mountTable = setmntent(table, "r")) == 0)
1144 while ((mountEntry = getmntent(mountTable)) != 0) {
1145 if (strcmp(name, mountEntry->mnt_dir) == 0
1146 || strcmp(name, mountEntry->mnt_fsname) == 0) /* String match. */
1148 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice) /* Match the device. */
1150 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice) /* Match the directory's mount point. */
1153 endmntent(mountTable);
1160 * Read a number with a possible multiplier.
1161 * Returns -1 if the number format is illegal.
1163 extern long getNum(const char *cp)
1167 if (!isDecimal(*cp))
1172 while (isDecimal(*cp))
1173 value = value * 10 + *cp++ - '0';
1177 case 'm': /* `tail' uses it traditionally */
1207 /* try to open up the specified device */
1208 extern int device_open(char *device, int mode)
1212 m = mode | O_NONBLOCK;
1214 /* Retry up to 5 times */
1215 for (f = 0; f < 5; f++)
1216 if ((fd = open(device, m, 0600)) >= 0)
1220 /* Reset original flags. */
1222 fcntl(fd, F_SETFL, mode);
1227 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1228 #include <linux/devps.h>
1232 * This finds the pid of the specified process,
1233 * by using the /dev/ps device driver.
1235 * Returns a list of all matching PIDs
1237 extern pid_t* findPidByName( char* pidName)
1240 char device[] = "/dev/ps";
1242 pid_t* pid_array = NULL;
1243 pid_t* pidList=NULL;
1246 fd = open(device, O_RDONLY);
1248 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1250 /* Find out how many processes there are */
1251 if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0)
1252 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1254 /* Allocate some memory -- grab a few extras just in case
1255 * some new processes start up while we wait. The kernel will
1256 * just ignore any extras if we give it too many, and will trunc.
1257 * the list if we give it too few. */
1258 pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1259 pid_array[0] = num_pids+10;
1261 /* Now grab the pid list */
1262 if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0)
1263 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1265 /* Now search for a match */
1266 for (i=1; i<pid_array[0] ; i++) {
1268 struct pid_info info;
1270 info.pid = pid_array[i];
1271 if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1272 fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1274 /* Make sure we only match on the process name */
1275 p=info.command_line+1;
1276 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) {
1282 if ((strstr(info.command_line, pidName) != NULL)
1283 && (strlen(pidName) == strlen(info.command_line))) {
1284 pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1286 fatalError(memory_exhausted, "");
1287 pidList[j++]=info.pid;
1297 if (close (fd) != 0)
1298 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1302 #else /* BB_FEATURE_USE_DEVPS_PATCH */
1303 #if ! defined BB_FEATURE_USE_PROCFS
1304 #error Sorry, I depend on the /proc filesystem right now.
1309 * This finds the pid of the specified process.
1310 * Currently, it's implemented by rummaging through
1311 * the proc filesystem.
1313 * Returns a list of all matching PIDs
1315 extern pid_t* findPidByName( char* pidName)
1318 struct dirent *next;
1319 pid_t* pidList=NULL;
1322 dir = opendir("/proc");
1324 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1326 while ((next = readdir(dir)) != NULL) {
1332 /* If it isn't a number, we don't want it */
1333 if (!isdigit(*next->d_name))
1336 /* Now open the status file */
1337 sprintf(filename, "/proc/%s/status", next->d_name);
1338 status = fopen(filename, "r");
1342 fgets(buffer, 256, status);
1345 /* Make sure we only match on the process name */
1346 p=buffer+5; /* Skip the name */
1348 if (*p==0 || *p=='\n') {
1353 p=buffer+6; /* Skip the "Name:\t" */
1355 if ((strstr(p, pidName) != NULL)
1356 && (strlen(pidName) == strlen(p))) {
1357 pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1359 fatalError(memory_exhausted, "");
1360 pidList[i++]=strtol(next->d_name, NULL, 0);
1367 #endif /* BB_FEATURE_USE_DEVPS_PATCH */
1369 /* this should really be farmed out to libbusybox.a */
1370 extern void *xmalloc(size_t size)
1372 void *cp = malloc(size);
1375 fatalError(memory_exhausted, "");
1380 extern int vdprintf(int d, const char *format, va_list ap)
1385 len = vsprintf(buf, format, ap);
1386 return write(d, buf, len);
1390 extern int del_loop(const char *device)
1394 if ((fd = open(device, O_RDONLY)) < 0) {
1398 if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1399 perror("ioctl: LOOP_CLR_FD");
1406 extern int set_loop(const char *device, const char *file, int offset,
1409 struct loop_info loopinfo;
1412 mode = *loopro ? O_RDONLY : O_RDWR;
1413 if ((ffd = open(file, mode)) < 0 && !*loopro
1414 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1418 if ((fd = open(device, mode)) < 0) {
1423 *loopro = (mode == O_RDONLY);
1425 memset(&loopinfo, 0, sizeof(loopinfo));
1426 strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1427 loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1429 loopinfo.lo_offset = offset;
1431 loopinfo.lo_encrypt_key_size = 0;
1432 if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1433 perror("ioctl: LOOP_SET_FD");
1438 if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1439 (void) ioctl(fd, LOOP_CLR_FD, 0);
1440 perror("ioctl: LOOP_SET_STATUS");
1450 extern char *find_unused_loop_device(void)
1454 struct stat statbuf;
1455 struct loop_info loopinfo;
1457 for (i = 0; i <= 7; i++) {
1458 sprintf(dev, "/dev/loop%d", i);
1459 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1460 if ((fd = open(dev, O_RDONLY)) >= 0) {
1461 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1462 if (errno == ENXIO) { /* probably free */
1474 extern int find_real_root_device_name(char* name)
1477 struct dirent *entry;
1478 struct stat statBuf, rootStat;
1479 char fileName[BUFSIZ];
1481 if (stat("/", &rootStat) != 0) {
1482 errorMsg("could not stat '/'\n");
1486 dir = opendir("/dev");
1488 errorMsg("could not open '/dev'\n");
1492 while((entry = readdir(dir)) != NULL) {
1494 /* Must skip ".." since that is "/", and so we
1495 * would get a false positive on ".." */
1496 if (strcmp(entry->d_name, "..") == 0)
1499 sprintf( fileName, "/dev/%s", entry->d_name);
1501 if (stat(fileName, &statBuf) != 0)
1503 /* Some char devices have the same dev_t as block
1504 * devices, so make sure this is a block device */
1505 if (! S_ISBLK(statBuf.st_mode))
1507 if (statBuf.st_rdev == rootStat.st_rdev) {
1508 strcpy(name, fileName);
1516 const unsigned int CSTRING_BUFFER_LENGTH = 128;
1517 /* recursive parser that returns cstrings of arbitrary length
1521 cstring_alloc(FILE* f, int depth)
1524 char buffer[CSTRING_BUFFER_LENGTH];
1525 int target = CSTRING_BUFFER_LENGTH * depth;
1531 while ((buffer[i] = fgetc(f)) != EOF) {
1532 if (buffer[i++] == 0x0a) { break; }
1533 if (i == CSTRING_BUFFER_LENGTH) { break; }
1537 /* recurse or malloc? */
1538 if (len == CSTRING_BUFFER_LENGTH) {
1539 cstring = cstring_alloc(f, (depth + 1));
1541 /* [special case] EOF */
1542 if ((depth | len) == 0) { return NULL; }
1545 size = target + len + 1;
1546 cstring = malloc(size);
1547 if (!cstring) { return NULL; }
1548 cstring[size - 1] = 0;
1553 memcpy(&cstring[target], buffer, len);
1559 * wrapper around recursive cstring_alloc
1560 * it's the caller's responsibility to free the cstring
1563 cstring_lineFromFile(FILE *f)
1565 return cstring_alloc(f, 0);
1571 c-file-style: "linux"