Update files to reduce dependance on kernel version...
[oweals/busybox.git] / utility.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
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.
8  *
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.
13  *
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.
18  *
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
22  *
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.
25  *
26  */
27
28 #include "internal.h"
29 #if defined (BB_CHMOD_CHOWN_CHGRP) \
30  || defined (BB_CP_MV)             \
31  || defined (BB_FIND)              \
32  || defined (BB_LS)                \
33  || defined (BB_INSMOD)
34 /* same conditions as recursiveAction */
35 #define bb_need_name_too_long
36 #endif
37 #define bb_need_memory_exhausted
38 #define BB_DECLARE_EXTERN
39 #include "messages.c"
40
41 #include <stdio.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <dirent.h>
46 #include <time.h>
47 #include <utime.h>
48 #include <unistd.h>
49 #include <ctype.h>
50 #include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <sys/utsname.h>                /* for uname(2) */
53
54 #if defined BB_FEATURE_MOUNT_LOOP
55 #include <fcntl.h>
56 #include <linux/loop.h>
57 #endif
58
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."
64 #endif
65
66
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";
70 #  else
71 #    if defined BB_MTAB
72 const char mtab_file[] = "/etc/mtab";
73 #    else
74 #      if defined BB_FEATURE_USE_DEVPS_PATCH
75 const char mtab_file[] = "/dev/mtab";
76 #    else
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)
78 #    endif
79 #  endif
80 #  endif
81 #endif
82
83
84 extern void usage(const char *usage)
85 {
86         fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
87                         BB_VER, BB_BT);
88         fprintf(stderr, "Usage: %s\n", usage);
89         exit FALSE;
90 }
91
92 extern void errorMsg(const char *s, ...)
93 {
94         va_list p;
95
96         va_start(p, s);
97         fflush(stdout);
98         vfprintf(stderr, s, p);
99         va_end(p);
100         fflush(stderr);
101 }
102
103 extern void fatalError(const char *s, ...)
104 {
105         va_list p;
106
107         va_start(p, s);
108         fflush(stdout);
109         vfprintf(stderr, s, p);
110         va_end(p);
111         fflush(stderr);
112         exit( FALSE);
113 }
114
115 #if defined BB_INIT
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> }
119  */
120 extern int get_kernel_revision(void)
121 {
122         struct utsname name;
123         int major = 0, minor = 0, patch = 0;
124
125         if (uname(&name) == -1) {
126                 perror("cannot get system information");
127                 return (0);
128         }
129         sscanf(name.version, "%d.%d.%d", &major, &minor, &patch);
130         return major * 65536 + minor * 256 + patch;
131 }
132 #endif                                                 /* BB_INIT */
133
134
135
136 #if defined BB_FREE || defined BB_INIT || defined BB_UNAME || defined BB_UPTIME
137 #include <sys/syscall.h>
138 #include <linux/unistd.h>
139 _syscall1(int, sysinfo, struct sysinfo *, info);
140 #endif                                                 /* BB_INIT */
141
142
143
144 #if defined (BB_CP_MV) || defined (BB_DU)
145
146 #define HASH_SIZE       311             /* Should be prime */
147 #define hash_inode(i)   ((i) % HASH_SIZE)
148
149 static ino_dev_hashtable_bucket_t *ino_dev_hashtable[HASH_SIZE];
150
151 /*
152  * Return 1 if statbuf->st_ino && statbuf->st_dev are recorded in
153  * `ino_dev_hashtable', else return 0
154  *
155  * If NAME is a non-NULL pointer to a character pointer, and there is
156  * a match, then set *NAME to the value of the name slot in that
157  * bucket.
158  */
159 int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name)
160 {
161         ino_dev_hashtable_bucket_t *bucket;
162
163         bucket = ino_dev_hashtable[hash_inode(statbuf->st_ino)];
164         while (bucket != NULL) {
165           if ((bucket->ino == statbuf->st_ino) &&
166                   (bucket->dev == statbuf->st_dev))
167           {
168                 if (name) *name = bucket->name;
169                 return 1;
170           }
171           bucket = bucket->next;
172         }
173         return 0;
174 }
175
176 /* Add statbuf to statbuf hash table */
177 void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name)
178 {
179         int i;
180         size_t s;
181         ino_dev_hashtable_bucket_t *bucket;
182     
183         i = hash_inode(statbuf->st_ino);
184         s = name ? strlen(name) : 0;
185         bucket = xmalloc(sizeof(ino_dev_hashtable_bucket_t) + s);
186         bucket->ino = statbuf->st_ino;
187         bucket->dev = statbuf->st_dev;
188         if (name)
189                 strcpy(bucket->name, name);
190         else
191                 bucket->name[0] = '\0';
192         bucket->next = ino_dev_hashtable[i];
193         ino_dev_hashtable[i] = bucket;
194 }
195
196 /* Clear statbuf hash table */
197 void reset_ino_dev_hashtable(void)
198 {
199         int i;
200         ino_dev_hashtable_bucket_t *bucket;
201
202         for (i = 0; i < HASH_SIZE; i++) {
203                 while (ino_dev_hashtable[i] != NULL) {
204                         bucket = ino_dev_hashtable[i]->next;
205                         free(ino_dev_hashtable[i]);
206                         ino_dev_hashtable[i] = bucket;
207                 }
208         }
209 }
210
211 #endif /* BB_CP_MV || BB_DU */
212
213 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
214 /*
215  * Return TRUE if a fileName is a directory.
216  * Nonexistant files return FALSE.
217  */
218 int isDirectory(const char *fileName, const int followLinks, struct stat *statBuf)
219 {
220         int status;
221         int didMalloc = 0;
222
223         if (statBuf == NULL) {
224             statBuf = (struct stat *)xmalloc(sizeof(struct stat));
225             ++didMalloc;
226         }
227
228         if (followLinks == TRUE)
229                 status = stat(fileName, statBuf);
230         else
231                 status = lstat(fileName, statBuf);
232
233         if (status < 0 || !(S_ISDIR(statBuf->st_mode))) {
234             status = FALSE;
235         }
236         else status = TRUE;
237
238         if (didMalloc) {
239             free(statBuf);
240             statBuf = NULL;
241         }
242         return status;
243 }
244 #endif
245
246 #if defined (BB_CP_MV)
247 /*
248  * Copy one file to another, while possibly preserving its modes, times, and
249  * modes.  Returns TRUE if successful, or FALSE on a failure with an error
250  * message output.  (Failure is not indicated if attributes cannot be set.)
251  * -Erik Andersen
252  */
253 int
254 copyFile(const char *srcName, const char *destName,
255                  int setModes, int followLinks, int forceFlag)
256 {
257         int rfd;
258         int wfd;
259         int rcc;
260         int status;
261         char buf[BUF_SIZE];
262         struct stat srcStatBuf;
263         struct stat dstStatBuf;
264         struct utimbuf times;
265
266         if (followLinks == TRUE)
267                 status = stat(srcName, &srcStatBuf);
268         else
269                 status = lstat(srcName, &srcStatBuf);
270
271         if (status < 0) {
272                 perror(srcName);
273                 return FALSE;
274         }
275
276         if (followLinks == TRUE)
277                 status = stat(destName, &dstStatBuf);
278         else
279                 status = lstat(destName, &dstStatBuf);
280
281         if (status < 0 || forceFlag==TRUE) {
282                 unlink(destName);
283                 dstStatBuf.st_ino = -1;
284                 dstStatBuf.st_dev = -1;
285         }
286
287         if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
288                 (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
289                 fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
290                 return FALSE;
291         }
292
293         if (S_ISDIR(srcStatBuf.st_mode)) {
294                 //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
295                 /* Make sure the directory is writable */
296                 status = mkdir(destName, 0777777 ^ umask(0));
297                 if (status < 0 && errno != EEXIST) {
298                         perror(destName);
299                         return FALSE;
300                 }
301         } else if (S_ISLNK(srcStatBuf.st_mode)) {
302                 char link_val[BUFSIZ + 1];
303                 int link_size;
304
305                 //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
306                 /* Warning: This could possibly truncate silently, to BUFSIZ chars */
307                 link_size = readlink(srcName, &link_val[0], BUFSIZ);
308                 if (link_size < 0) {
309                         perror(srcName);
310                         return FALSE;
311                 }
312                 link_val[link_size] = '\0';
313                 status = symlink(link_val, destName);
314                 if (status < 0) {
315                         perror(destName);
316                         return FALSE;
317                 }
318 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
319                 if (setModes == TRUE) {
320                         /* Try to set owner, but fail silently like GNU cp */
321                         lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
322                 }
323 #endif
324                 return TRUE;
325         } else if (S_ISFIFO(srcStatBuf.st_mode)) {
326                 //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
327                 if (mkfifo(destName, 0644) < 0) {
328                         perror(destName);
329                         return FALSE;
330                 }
331         } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode)
332                            || S_ISSOCK(srcStatBuf.st_mode)) {
333                 //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
334                 if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
335                         perror(destName);
336                         return FALSE;
337                 }
338         } else if (S_ISREG(srcStatBuf.st_mode)) {
339                 //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
340                 rfd = open(srcName, O_RDONLY);
341                 if (rfd < 0) {
342                         perror(srcName);
343                         return FALSE;
344                 }
345
346                 wfd =
347                         open(destName, O_WRONLY | O_CREAT | O_TRUNC,
348                                  srcStatBuf.st_mode);
349                 if (wfd < 0) {
350                         perror(destName);
351                         close(rfd);
352                         return FALSE;
353                 }
354
355                 while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
356                         if (fullWrite(wfd, buf, rcc) < 0)
357                                 goto error_exit;
358                 }
359                 if (rcc < 0) {
360                         goto error_exit;
361                 }
362
363                 close(rfd);
364                 if (close(wfd) < 0) {
365                         return FALSE;
366                 }
367         }
368
369         if (setModes == TRUE) {
370                 /* This is fine, since symlinks never get here */
371                 if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
372                         perror(destName);
373                         exit FALSE;
374                 }
375                 if (chmod(destName, srcStatBuf.st_mode) < 0) {
376                         perror(destName);
377                         exit FALSE;
378                 }
379                 times.actime = srcStatBuf.st_atime;
380                 times.modtime = srcStatBuf.st_mtime;
381                 if (utime(destName, &times) < 0) {
382                         perror(destName);
383                         exit FALSE;
384                 }
385         }
386
387         return TRUE;
388
389   error_exit:
390         perror(destName);
391         close(rfd);
392         close(wfd);
393
394         return FALSE;
395 }
396 #endif                                                  /* BB_CP_MV */
397
398
399
400 #if defined BB_TAR || defined BB_LS
401
402 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
403 #define TYPECHAR(mode)  ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
404
405 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
406 static const mode_t SBIT[] = {
407         0, 0, S_ISUID,
408         0, 0, S_ISGID,
409         0, 0, S_ISVTX
410 };
411
412 /* The 9 mode bits to test */
413 static const mode_t MBIT[] = {
414         S_IRUSR, S_IWUSR, S_IXUSR,
415         S_IRGRP, S_IWGRP, S_IXGRP,
416         S_IROTH, S_IWOTH, S_IXOTH
417 };
418
419 #define MODE1  "rwxrwxrwx"
420 #define MODE0  "---------"
421 #define SMODE1 "..s..s..t"
422 #define SMODE0 "..S..S..T"
423
424 /*
425  * Return the standard ls-like mode string from a file mode.
426  * This is static and so is overwritten on each call.
427  */
428 const char *modeString(int mode)
429 {
430         static char buf[12];
431
432         int i;
433
434         buf[0] = TYPECHAR(mode);
435         for (i = 0; i < 9; i++) {
436                 if (mode & SBIT[i])
437                         buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
438                 else
439                         buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
440         }
441         return buf;
442 }
443 #endif                                                  /* BB_TAR || BB_LS */
444
445
446 #if defined BB_TAR
447 /*
448  * Return the standard ls-like time string from a time_t
449  * This is static and so is overwritten on each call.
450  */
451 const char *timeString(time_t timeVal)
452 {
453         time_t now;
454         char *str;
455         static char buf[26];
456
457         time(&now);
458
459         str = ctime(&timeVal);
460
461         strcpy(buf, &str[4]);
462         buf[12] = '\0';
463
464         if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
465                 strcpy(&buf[7], &str[20]);
466                 buf[11] = '\0';
467         }
468
469         return buf;
470 }
471 #endif                                                  /* BB_TAR */
472
473 #if defined BB_TAR || defined BB_CP_MV
474 /*
475  * Write all of the supplied buffer out to a file.
476  * This does multiple writes as necessary.
477  * Returns the amount written, or -1 on an error.
478  */
479 int fullWrite(int fd, const char *buf, int len)
480 {
481         int cc;
482         int total;
483
484         total = 0;
485
486         while (len > 0) {
487                 cc = write(fd, buf, len);
488
489                 if (cc < 0)
490                         return -1;
491
492                 buf += cc;
493                 total += cc;
494                 len -= cc;
495         }
496
497         return total;
498 }
499 #endif                                                  /* BB_TAR || BB_CP_MV */
500
501
502 #if defined BB_TAR || defined BB_TAIL
503 /*
504  * Read all of the supplied buffer from a file.
505  * This does multiple reads as necessary.
506  * Returns the amount read, or -1 on an error.
507  * A short read is returned on an end of file.
508  */
509 int fullRead(int fd, char *buf, int len)
510 {
511         int cc;
512         int total;
513
514         total = 0;
515
516         while (len > 0) {
517                 cc = read(fd, buf, len);
518
519                 if (cc < 0)
520                         return -1;
521
522                 if (cc == 0)
523                         break;
524
525                 buf += cc;
526                 total += cc;
527                 len -= cc;
528         }
529
530         return total;
531 }
532 #endif                                                  /* BB_TAR || BB_TAIL */
533
534
535 #if defined (BB_CHMOD_CHOWN_CHGRP) \
536  || defined (BB_CP_MV)                  \
537  || defined (BB_FIND)                   \
538  || defined (BB_INSMOD)                 \
539  || defined (BB_RM)                             \
540  || defined (BB_TAR)
541
542 /*
543  * Walk down all the directories under the specified 
544  * location, and do something (something specified
545  * by the fileAction and dirAction function pointers).
546  *
547  * Unfortunatly, while nftw(3) could replace this and reduce 
548  * code size a bit, nftw() wasn't supported before GNU libc 2.1, 
549  * and so isn't sufficiently portable to take over since glibc2.1
550  * is so stinking huge.
551  */
552 int recursiveAction(const char *fileName,
553                                         int recurse, int followLinks, int depthFirst,
554                                         int (*fileAction) (const char *fileName,
555                                                                            struct stat * statbuf,
556                                                                            void* userData),
557                                         int (*dirAction) (const char *fileName,
558                                                                           struct stat * statbuf,
559                                                                           void* userData),
560                                         void* userData)
561 {
562         int status;
563         struct stat statbuf;
564         struct dirent *next;
565
566         if (followLinks == TRUE)
567                 status = stat(fileName, &statbuf);
568         else
569                 status = lstat(fileName, &statbuf);
570
571         if (status < 0) {
572 #ifdef BB_DEBUG_PRINT_SCAFFOLD
573                 fprintf(stderr,
574                                 "status=%d followLinks=%d TRUE=%d\n",
575                                 status, followLinks, TRUE);
576 #endif
577                 perror(fileName);
578                 return FALSE;
579         }
580
581         if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode))) {
582                 if (fileAction == NULL)
583                         return TRUE;
584                 else
585                         return fileAction(fileName, &statbuf, userData);
586         }
587
588         if (recurse == FALSE) {
589                 if (S_ISDIR(statbuf.st_mode)) {
590                         if (dirAction != NULL)
591                                 return (dirAction(fileName, &statbuf, userData));
592                         else
593                                 return TRUE;
594                 }
595         }
596
597         if (S_ISDIR(statbuf.st_mode)) {
598                 DIR *dir;
599
600                 dir = opendir(fileName);
601                 if (!dir) {
602                         perror(fileName);
603                         return FALSE;
604                 }
605                 if (dirAction != NULL && depthFirst == FALSE) {
606                         status = dirAction(fileName, &statbuf, userData);
607                         if (status == FALSE) {
608                                 perror(fileName);
609                                 return FALSE;
610                         }
611                 }
612                 while ((next = readdir(dir)) != NULL) {
613                         char nextFile[BUFSIZ + 1];
614
615                         if ((strcmp(next->d_name, "..") == 0)
616                                 || (strcmp(next->d_name, ".") == 0)) {
617                                 continue;
618                         }
619                         if (strlen(fileName) + strlen(next->d_name) + 1 > BUFSIZ) {
620                                 fprintf(stderr, name_too_long, "ftw");
621                                 return FALSE;
622                         }
623                         memset(nextFile, 0, sizeof(nextFile));
624                         sprintf(nextFile, "%s/%s", fileName, next->d_name);
625                         status =
626                                 recursiveAction(nextFile, TRUE, followLinks, depthFirst,
627                                                                 fileAction, dirAction, userData);
628                         if (status < 0) {
629                                 closedir(dir);
630                                 return FALSE;
631                         }
632                 }
633                 status = closedir(dir);
634                 if (status < 0) {
635                         perror(fileName);
636                         return FALSE;
637                 }
638                 if (dirAction != NULL && depthFirst == TRUE) {
639                         status = dirAction(fileName, &statbuf, userData);
640                         if (status == FALSE) {
641                                 perror(fileName);
642                                 return FALSE;
643                         }
644                 }
645         } else {
646                 if (fileAction == NULL)
647                         return TRUE;
648                 else
649                         return fileAction(fileName, &statbuf, userData);
650         }
651         return TRUE;
652 }
653
654 #endif                                                  /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
655
656
657
658 #if defined (BB_TAR) || defined (BB_MKDIR)
659 /*
660  * Attempt to create the directories along the specified path, except for
661  * the final component.  The mode is given for the final directory only,
662  * while all previous ones get default protections.  Errors are not reported
663  * here, as failures to restore files can be reported later.
664  */
665 extern int createPath(const char *name, int mode)
666 {
667         char *cp;
668         char *cpOld;
669         char buf[BUFSIZ + 1];
670         int retVal = 0;
671
672         strcpy(buf, name);
673         for (cp = buf; *cp == '/'; cp++);
674         cp = strchr(cp, '/');
675         while (cp) {
676                 cpOld = cp;
677                 cp = strchr(cp + 1, '/');
678                 *cpOld = '\0';
679                 retVal = mkdir(buf, cp ? 0777 : mode);
680                 if (retVal != 0 && errno != EEXIST) {
681                         perror(buf);
682                         return FALSE;
683                 }
684                 *cpOld = '/';
685         }
686         return TRUE;
687 }
688 #endif                                                  /* BB_TAR || BB_MKDIR */
689
690
691
692 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
693 /* [ugoa]{+|-|=}[rwxst] */
694
695
696
697 extern int parse_mode(const char *s, mode_t * theMode)
698 {
699         mode_t andMode =
700
701                 S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
702         mode_t orMode = 0;
703         mode_t mode = 0;
704         mode_t groups = 0;
705         char type;
706         char c;
707
708         do {
709                 for (;;) {
710                         switch (c = *s++) {
711                         case '\0':
712                                 return -1;
713                         case 'u':
714                                 groups |= S_ISUID | S_IRWXU;
715                                 continue;
716                         case 'g':
717                                 groups |= S_ISGID | S_IRWXG;
718                                 continue;
719                         case 'o':
720                                 groups |= S_IRWXO;
721                                 continue;
722                         case 'a':
723                                 groups |= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
724                                 continue;
725                         case '+':
726                         case '=':
727                         case '-':
728                                 type = c;
729                                 if (groups == 0)        /* The default is "all" */
730                                         groups |=
731                                                 S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
732                                 break;
733                         default:
734                                 if (isdigit(c) && c >= '0' && c <= '7' &&
735                                         mode == 0 && groups == 0) {
736                                         *theMode = strtol(--s, NULL, 8);
737                                         return (TRUE);
738                                 } else
739                                         return (FALSE);
740                         }
741                         break;
742                 }
743
744                 while ((c = *s++) != '\0') {
745                         switch (c) {
746                         case ',':
747                                 break;
748                         case 'r':
749                                 mode |= S_IRUSR | S_IRGRP | S_IROTH;
750                                 continue;
751                         case 'w':
752                                 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
753                                 continue;
754                         case 'x':
755                                 mode |= S_IXUSR | S_IXGRP | S_IXOTH;
756                                 continue;
757                         case 's':
758                                 mode |= S_IXGRP | S_ISUID | S_ISGID;
759                                 continue;
760                         case 't':
761                                 mode |= 0;
762                                 continue;
763                         default:
764                                 *theMode &= andMode;
765                                 *theMode |= orMode;
766                                 return (TRUE);
767                         }
768                         break;
769                 }
770                 switch (type) {
771                 case '=':
772                         andMode &= ~(groups);
773                         /* fall through */
774                 case '+':
775                         orMode |= mode & groups;
776                         break;
777                 case '-':
778                         andMode &= ~(mode & groups);
779                         orMode &= andMode;
780                         break;
781                 }
782         } while (c == ',');
783         *theMode &= andMode;
784         *theMode |= orMode;
785         return (TRUE);
786 }
787
788
789 #endif                                                  /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
790
791
792
793
794
795 #if defined BB_CHMOD_CHOWN_CHGRP || defined BB_PS || defined BB_LS || defined BB_TAR || defined BB_ID 
796
797 /* This parses entries in /etc/passwd and /etc/group.  This is desirable
798  * for BusyBox, since we want to avoid using the glibc NSS stuff, which
799  * increases target size and is often not needed or wanted for embedded
800  * systems.
801  *
802  * /etc/passwd entries look like this: 
803  *              root:x:0:0:root:/root:/bin/bash
804  * and /etc/group entries look like this: 
805  *              root:x:0:
806  *
807  * This uses buf as storage to hold things.
808  * 
809  */
810 unsigned long my_getid(const char *filename, char *name, unsigned long id, unsigned long *gid)
811 {
812         FILE *file;
813         char *rname, *start, *end, buf[128];
814         unsigned long rid;
815         unsigned long rgid = 0;
816
817         file = fopen(filename, "r");
818         if (file == NULL) {
819                 /* Do not complain.  It is ok for /etc/passwd and
820                  * friends to be missing... */
821                 return (-1);
822         }
823
824         while (fgets(buf, 128, file) != NULL) {
825                 if (buf[0] == '#')
826                         continue;
827
828                 /* username/group name */
829                 start = buf;
830                 end = strchr(start, ':');
831                 if (end == NULL)
832                         continue;
833                 *end = '\0';
834                 rname = start;
835
836                 /* password */
837                 start = end + 1;
838                 end = strchr(start, ':');
839                 if (end == NULL)
840                         continue;
841
842                 /* uid in passwd, gid in group */
843                 start = end + 1;
844                 rid = (unsigned long) strtol(start, &end, 10);
845                 if (end == start)
846                         continue;
847
848                 /* gid in passwd */
849                 start = end + 1;
850                 rgid = (unsigned long) strtol(start, &end, 10);
851                 
852                 if (name) {
853                         if (0 == strcmp(rname, name)) {
854                             if (gid) *gid = rgid;
855                                 fclose(file);
856                                 return (rid);
857                         }
858                 }
859                 if (id != -1 && id == rid) {
860                         strncpy(name, rname, 8);
861                         if (gid) *gid = rgid;
862                         fclose(file);
863                         return (TRUE);
864                 }
865         }
866         fclose(file);
867         return (-1);
868 }
869
870 /* returns a uid given a username */
871 unsigned long my_getpwnam(char *name)
872 {
873         return my_getid("/etc/passwd", name, -1, NULL);
874 }
875
876 /* returns a gid given a group name */
877 unsigned long my_getgrnam(char *name)
878 {
879         return my_getid("/etc/group", name, -1, NULL);
880 }
881
882 /* gets a username given a uid */
883 void my_getpwuid(char *name, unsigned long uid)
884 {
885         my_getid("/etc/passwd", name, uid, NULL);
886 }
887
888 /* gets a groupname given a gid */
889 void my_getgrgid(char *group, unsigned long gid)
890 {
891         my_getid("/etc/group", group, gid, NULL);
892 }
893
894 /* gets a gid given a user name */
895 unsigned long my_getpwnamegid(char *name)
896 {
897         unsigned long gid;
898         my_getid("/etc/passwd", name, -1, &gid);
899         return gid;
900 }
901
902 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR || BB_ID */ 
903
904
905 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
906
907 /* From <linux/kd.h> */ 
908 #define KDGKBTYPE       0x4B33  /* get keyboard type */
909 #define         KB_84           0x01
910 #define         KB_101          0x02    /* this is what we always answer */
911
912 int is_a_console(int fd)
913 {
914         char arg;
915
916         arg = 0;
917         return (ioctl(fd, KDGKBTYPE, &arg) == 0
918                         && ((arg == KB_101) || (arg == KB_84)));
919 }
920
921 static int open_a_console(char *fnam)
922 {
923         int fd;
924
925         /* try read-only */
926         fd = open(fnam, O_RDWR);
927
928         /* if failed, try read-only */
929         if (fd < 0 && errno == EACCES)
930                 fd = open(fnam, O_RDONLY);
931
932         /* if failed, try write-only */
933         if (fd < 0 && errno == EACCES)
934                 fd = open(fnam, O_WRONLY);
935
936         /* if failed, fail */
937         if (fd < 0)
938                 return -1;
939
940         /* if not a console, fail */
941         if (!is_a_console(fd)) {
942                 close(fd);
943                 return -1;
944         }
945
946         /* success */
947         return fd;
948 }
949
950 /*
951  * Get an fd for use with kbd/console ioctls.
952  * We try several things because opening /dev/console will fail
953  * if someone else used X (which does a chown on /dev/console).
954  *
955  * if tty_name is non-NULL, try this one instead.
956  */
957
958 int get_console_fd(char *tty_name)
959 {
960         int fd;
961
962         if (tty_name) {
963                 if (-1 == (fd = open_a_console(tty_name)))
964                         return -1;
965                 else
966                         return fd;
967         }
968
969         fd = open_a_console("/dev/tty");
970         if (fd >= 0)
971                 return fd;
972
973         fd = open_a_console("/dev/tty0");
974         if (fd >= 0)
975                 return fd;
976
977         fd = open_a_console("/dev/console");
978         if (fd >= 0)
979                 return fd;
980
981         for (fd = 0; fd < 3; fd++)
982                 if (is_a_console(fd))
983                         return fd;
984
985         fprintf(stderr,
986                         "Couldnt get a file descriptor referring to the console\n");
987         return -1;                                      /* total failure */
988 }
989
990
991 #endif                                                  /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
992
993
994 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)
995
996 /* Do a case insensitive strstr() */
997 char *stristr(char *haystack, const char *needle)
998 {
999         int len = strlen(needle);
1000
1001         while (*haystack) {
1002                 if (!strncasecmp(haystack, needle, len))
1003                         break;
1004                 haystack++;
1005         }
1006
1007         if (!(*haystack))
1008                 haystack = NULL;
1009
1010         return haystack;
1011 }
1012
1013 /* This tries to find a needle in a haystack, but does so by
1014  * only trying to match literal strings (look 'ma, no regexps!)
1015  * This is short, sweet, and carries _very_ little baggage,
1016  * unlike its beefier cousin in regexp.c
1017  *  -Erik Andersen
1018  */
1019 extern int find_match(char *haystack, char *needle, int ignoreCase)
1020 {
1021
1022         if (ignoreCase == FALSE)
1023                 haystack = strstr(haystack, needle);
1024         else
1025                 haystack = stristr(haystack, needle);
1026         if (haystack == NULL)
1027                 return FALSE;
1028         return TRUE;
1029 }
1030
1031
1032 /* This performs substitutions after a string match has been found.  */
1033 extern int replace_match(char *haystack, char *needle, char *newNeedle,
1034                                                  int ignoreCase)
1035 {
1036         int foundOne = 0;
1037         char *where, *slider, *slider1, *oldhayStack;
1038
1039         if (ignoreCase == FALSE)
1040                 where = strstr(haystack, needle);
1041         else
1042                 where = stristr(haystack, needle);
1043
1044         if (strcmp(needle, newNeedle) == 0)
1045                 return FALSE;
1046
1047         oldhayStack = (char *) xmalloc((unsigned) (strlen(haystack)));
1048         while (where != NULL) {
1049                 foundOne++;
1050                 strcpy(oldhayStack, haystack);
1051                 for (slider = haystack, slider1 = oldhayStack; slider != where;
1052                          slider++, slider1++);
1053                 *slider = 0;
1054                 haystack = strcat(haystack, newNeedle);
1055                 slider1 += strlen(needle);
1056                 haystack = strcat(haystack, slider1);
1057                 where = strstr(slider, needle);
1058         }
1059         free(oldhayStack);
1060
1061         if (foundOne > 0)
1062                 return TRUE;
1063         else
1064                 return FALSE;
1065 }
1066
1067 #endif                                                  /* ! BB_REGEXP && (BB_GREP || BB_SED) */
1068
1069
1070 #if defined BB_FIND || defined BB_INSMOD
1071 /*
1072  * Routine to see if a text string is matched by a wildcard pattern.
1073  * Returns TRUE if the text is matched, or FALSE if it is not matched
1074  * or if the pattern is invalid.
1075  *  *           matches zero or more characters
1076  *  ?           matches a single character
1077  *  [abc]       matches 'a', 'b' or 'c'
1078  *  \c          quotes character c
1079  * Adapted from code written by Ingo Wilken, and
1080  * then taken from sash, Copyright (c) 1999 by David I. Bell
1081  * Permission is granted to use, distribute, or modify this source,
1082  * provided that this copyright notice remains intact.
1083  * Permission to distribute this code under the GPL has been granted.
1084  */
1085 extern int check_wildcard_match(const char *text, const char *pattern)
1086 {
1087         const char *retryPat;
1088         const char *retryText;
1089         int ch;
1090         int found;
1091         int len;
1092
1093         retryPat = NULL;
1094         retryText = NULL;
1095
1096         while (*text || *pattern) {
1097                 ch = *pattern++;
1098
1099                 switch (ch) {
1100                 case '*':
1101                         retryPat = pattern;
1102                         retryText = text;
1103                         break;
1104
1105                 case '[':
1106                         found = FALSE;
1107
1108                         while ((ch = *pattern++) != ']') {
1109                                 if (ch == '\\')
1110                                         ch = *pattern++;
1111
1112                                 if (ch == '\0')
1113                                         return FALSE;
1114
1115                                 if (*text == ch)
1116                                         found = TRUE;
1117                         }
1118                         len=strlen(text);
1119                         if (found == FALSE && len!=0) {
1120                                 return FALSE;
1121                         }
1122                         if (found == TRUE) {
1123                                 if (strlen(pattern)==0 && len==1) {
1124                                         return TRUE;
1125                                 }
1126                                 if (len!=0) {
1127                                         text++;
1128                                         continue;
1129                                 }
1130                         }
1131
1132                         /* fall into next case */
1133
1134                 case '?':
1135                         if (*text++ == '\0')
1136                                 return FALSE;
1137
1138                         break;
1139
1140                 case '\\':
1141                         ch = *pattern++;
1142
1143                         if (ch == '\0')
1144                                 return FALSE;
1145
1146                         /* fall into next case */
1147
1148                 default:
1149                         if (*text == ch) {
1150                                 if (*text)
1151                                         text++;
1152                                 break;
1153                         }
1154
1155                         if (*text) {
1156                                 pattern = retryPat;
1157                                 text = ++retryText;
1158                                 break;
1159                         }
1160
1161                         return FALSE;
1162                 }
1163
1164                 if (pattern == NULL)
1165                         return FALSE;
1166         }
1167
1168         return TRUE;
1169 }
1170 #endif                            /* BB_FIND || BB_INSMOD */
1171
1172
1173
1174
1175 #if defined BB_DF || defined BB_MTAB
1176 /*
1177  * Given a block device, find the mount table entry if that block device
1178  * is mounted.
1179  *
1180  * Given any other file (or directory), find the mount table entry for its
1181  * filesystem.
1182  */
1183 extern struct mntent *findMountPoint(const char *name, const char *table)
1184 {
1185         struct stat s;
1186         dev_t mountDevice;
1187         FILE *mountTable;
1188         struct mntent *mountEntry;
1189
1190         if (stat(name, &s) != 0)
1191                 return 0;
1192
1193         if ((s.st_mode & S_IFMT) == S_IFBLK)
1194                 mountDevice = s.st_rdev;
1195         else
1196                 mountDevice = s.st_dev;
1197
1198
1199         if ((mountTable = setmntent(table, "r")) == 0)
1200                 return 0;
1201
1202         while ((mountEntry = getmntent(mountTable)) != 0) {
1203                 if (strcmp(name, mountEntry->mnt_dir) == 0
1204                         || strcmp(name, mountEntry->mnt_fsname) == 0)   /* String match. */
1205                         break;
1206                 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice)  /* Match the device. */
1207                         break;
1208                 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice)      /* Match the directory's mount point. */
1209                         break;
1210         }
1211         endmntent(mountTable);
1212         return mountEntry;
1213 }
1214 #endif                                                  /* BB_DF || BB_MTAB */
1215
1216
1217
1218 #if defined BB_DD || defined BB_TAIL
1219 /*
1220  * Read a number with a possible multiplier.
1221  * Returns -1 if the number format is illegal.
1222  */
1223 extern long getNum(const char *cp)
1224 {
1225         long value;
1226
1227         if (!isDecimal(*cp))
1228                 return -1;
1229
1230         value = 0;
1231
1232         while (isDecimal(*cp))
1233                 value = value * 10 + *cp++ - '0';
1234
1235         switch (*cp++) {
1236         case 'M':
1237         case 'm':                                       /* `tail' uses it traditionally */
1238                 value *= 1048576;
1239                 break;
1240
1241         case 'k':
1242                 value *= 1024;
1243                 break;
1244
1245         case 'b':
1246                 value *= 512;
1247                 break;
1248
1249         case 'w':
1250                 value *= 2;
1251                 break;
1252
1253         case '\0':
1254                 return value;
1255
1256         default:
1257                 return -1;
1258         }
1259
1260         if (*cp)
1261                 return -1;
1262
1263         return value;
1264 }
1265 #endif                                                  /* BB_DD || BB_TAIL */
1266
1267
1268 #if defined BB_INIT || defined BB_SYSLOGD
1269 /* try to open up the specified device */
1270 extern int device_open(char *device, int mode)
1271 {
1272         int m, f, fd = -1;
1273
1274         m = mode | O_NONBLOCK;
1275
1276         /* Retry up to 5 times */
1277         for (f = 0; f < 5; f++)
1278                 if ((fd = open(device, m, 0600)) >= 0)
1279                         break;
1280         if (fd < 0)
1281                 return fd;
1282         /* Reset original flags. */
1283         if (m != mode)
1284                 fcntl(fd, F_SETFL, mode);
1285         return fd;
1286 }
1287 #endif                                                  /* BB_INIT BB_SYSLOGD */
1288
1289
1290 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1291 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1292 #include <linux/devps.h>
1293 #endif
1294
1295 #if defined BB_FEATURE_USE_DEVPS_PATCH
1296 /* findPidByName()
1297  *  
1298  *  This finds the pid of the specified process,
1299  *  by using the /dev/ps device driver.
1300  *
1301  *  Returns a list of all matching PIDs
1302  */
1303 extern pid_t* findPidByName( char* pidName)
1304 {
1305         int fd, i, j;
1306         char device[] = "/dev/ps";
1307         pid_t num_pids;
1308         pid_t* pid_array = NULL;
1309         pid_t* pidList=NULL;
1310
1311         /* open device */ 
1312         fd = open(device, O_RDONLY);
1313         if (fd < 0)
1314                 fatalError( "open failed for `%s': %s\n", device, strerror (errno));
1315
1316         /* Find out how many processes there are */
1317         if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0) 
1318                 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1319         
1320         /* Allocate some memory -- grab a few extras just in case 
1321          * some new processes start up while we wait. The kernel will
1322          * just ignore any extras if we give it too many, and will trunc.
1323          * the list if we give it too few.  */
1324         pid_array = (pid_t*) calloc( num_pids+10, sizeof(pid_t));
1325         pid_array[0] = num_pids+10;
1326
1327         /* Now grab the pid list */
1328         if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0) 
1329                 fatalError( "\nDEVPS_GET_PID_LIST: %s\n", strerror (errno));
1330
1331         /* Now search for a match */
1332         for (i=1, j=0; i<pid_array[0] ; i++) {
1333                 char* p;
1334                 struct pid_info info;
1335
1336             info.pid = pid_array[i];
1337             if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1338                         fatalError( "\nDEVPS_GET_PID_INFO: %s\n", strerror (errno));
1339
1340                 /* Make sure we only match on the process name */
1341                 p=info.command_line+1;
1342                 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) { 
1343                         (p)++;
1344                 }
1345                 if (isspace(*(p)))
1346                                 *p='\0';
1347
1348                 if ((strstr(info.command_line, pidName) != NULL)
1349                                 && (strlen(pidName) == strlen(info.command_line))) {
1350                         pidList=realloc( pidList, sizeof(pid_t) * (j+2));
1351                         if (pidList==NULL)
1352                                 fatalError(memory_exhausted, "");
1353                         pidList[j++]=info.pid;
1354                 }
1355         }
1356         if (pidList)
1357                 pidList[j]=0;
1358
1359         /* Free memory */
1360         free( pid_array);
1361
1362         /* close device */
1363         if (close (fd) != 0) 
1364                 fatalError( "close failed for `%s': %s\n",device, strerror (errno));
1365
1366         return pidList;
1367 }
1368 #else           /* BB_FEATURE_USE_DEVPS_PATCH */
1369 #if ! defined BB_FEATURE_USE_PROCFS
1370 #error Sorry, I depend on the /proc filesystem right now.
1371 #endif
1372
1373 /* findPidByName()
1374  *  
1375  *  This finds the pid of the specified process.
1376  *  Currently, it's implemented by rummaging through 
1377  *  the proc filesystem.
1378  *
1379  *  Returns a list of all matching PIDs
1380  */
1381 extern pid_t* findPidByName( char* pidName)
1382 {
1383         DIR *dir;
1384         struct dirent *next;
1385         pid_t* pidList=NULL;
1386         int i=0;
1387
1388         dir = opendir("/proc");
1389         if (!dir)
1390                 fatalError( "Cannot open /proc: %s\n", strerror (errno));
1391         
1392         while ((next = readdir(dir)) != NULL) {
1393                 FILE *status;
1394                 char filename[256];
1395                 char buffer[256];
1396                 char* p;
1397
1398                 /* If it isn't a number, we don't want it */
1399                 if (!isdigit(*next->d_name))
1400                         continue;
1401
1402                 /* Now open the status file */
1403                 sprintf(filename, "/proc/%s/status", next->d_name);
1404                 status = fopen(filename, "r");
1405                 if (!status) {
1406                         continue;
1407                 }
1408                 fgets(buffer, 256, status);
1409                 fclose(status);
1410
1411                 /* Make sure we only match on the process name */
1412                 p=buffer+5; /* Skip the name */
1413                 while ((p)++) {
1414                         if (*p==0 || *p=='\n') {
1415                                 *p='\0';
1416                                 break;
1417                         }
1418                 }
1419                 p=buffer+6; /* Skip the "Name:\t" */
1420
1421                 if ((strstr(p, pidName) != NULL)
1422                                 && (strlen(pidName) == strlen(p))) {
1423                         pidList=realloc( pidList, sizeof(pid_t) * (i+2));
1424                         if (pidList==NULL)
1425                                 fatalError(memory_exhausted, "");
1426                         pidList[i++]=strtol(next->d_name, NULL, 0);
1427                 }
1428         }
1429         if (pidList)
1430                 pidList[i]=0;
1431         return pidList;
1432 }
1433 #endif                                                  /* BB_FEATURE_USE_DEVPS_PATCH */
1434 #endif                                                  /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1435
1436 /* this should really be farmed out to libbusybox.a */
1437 extern void *xmalloc(size_t size)
1438 {
1439         void *cp = malloc(size);
1440
1441         if (cp == NULL)
1442                 fatalError(memory_exhausted, "");
1443         return cp;
1444 }
1445
1446 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1447 extern int vdprintf(int d, const char *format, va_list ap)
1448 {
1449         char buf[BUF_SIZE];
1450         int len;
1451
1452         len = vsprintf(buf, format, ap);
1453         return write(d, buf, len);
1454 }
1455 #endif                                                  /* BB_SYSLOGD */
1456
1457 #if defined BB_FEATURE_MOUNT_LOOP
1458 extern int del_loop(const char *device)
1459 {
1460         int fd;
1461
1462         if ((fd = open(device, O_RDONLY)) < 0) {
1463                 perror(device);
1464                 return (FALSE);
1465         }
1466         if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1467                 perror("ioctl: LOOP_CLR_FD");
1468                 return (FALSE);
1469         }
1470         close(fd);
1471         return (TRUE);
1472 }
1473
1474 extern int set_loop(const char *device, const char *file, int offset,
1475                                         int *loopro)
1476 {
1477         struct loop_info loopinfo;
1478         int fd, ffd, mode;
1479
1480         mode = *loopro ? O_RDONLY : O_RDWR;
1481         if ((ffd = open(file, mode)) < 0 && !*loopro
1482                 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1483                 perror(file);
1484                 return 1;
1485         }
1486         if ((fd = open(device, mode)) < 0) {
1487                 close(ffd);
1488                 perror(device);
1489                 return 1;
1490         }
1491         *loopro = (mode == O_RDONLY);
1492
1493         memset(&loopinfo, 0, sizeof(loopinfo));
1494         strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1495         loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1496
1497         loopinfo.lo_offset = offset;
1498
1499         loopinfo.lo_encrypt_key_size = 0;
1500         if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1501                 perror("ioctl: LOOP_SET_FD");
1502                 close(fd);
1503                 close(ffd);
1504                 return 1;
1505         }
1506         if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1507                 (void) ioctl(fd, LOOP_CLR_FD, 0);
1508                 perror("ioctl: LOOP_SET_STATUS");
1509                 close(fd);
1510                 close(ffd);
1511                 return 1;
1512         }
1513         close(fd);
1514         close(ffd);
1515         return 0;
1516 }
1517
1518 extern char *find_unused_loop_device(void)
1519 {
1520         char dev[20];
1521         int i, fd;
1522         struct stat statbuf;
1523         struct loop_info loopinfo;
1524
1525         for (i = 0; i <= 7; i++) {
1526                 sprintf(dev, "/dev/loop%d", i);
1527                 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1528                         if ((fd = open(dev, O_RDONLY)) >= 0) {
1529                                 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1530                                         if (errno == ENXIO) {   /* probably free */
1531                                                 close(fd);
1532                                                 return strdup(dev);
1533                                         }
1534                                 }
1535                                 close(fd);
1536                         }
1537                 }
1538         }
1539         return NULL;
1540 }
1541 #endif                                                  /* BB_FEATURE_MOUNT_LOOP */
1542
1543 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1544 extern int find_real_root_device_name(char* name)
1545 {
1546         DIR *dir;
1547         struct dirent *entry;
1548         struct stat statBuf, rootStat;
1549         char fileName[BUFSIZ];
1550
1551         if (stat("/", &rootStat) != 0) {
1552                 errorMsg("could not stat '/'\n");
1553                 return( FALSE);
1554         }
1555
1556         dir = opendir("/dev");
1557         if (!dir) {
1558                 errorMsg("could not open '/dev'\n");
1559                 return( FALSE);
1560         }
1561
1562         while((entry = readdir(dir)) != NULL) {
1563
1564                 /* Must skip ".." since that is "/", and so we 
1565                  * would get a false positive on ".."  */
1566                 if (strcmp(entry->d_name, "..") == 0)
1567                         continue;
1568
1569                 sprintf( fileName, "/dev/%s", entry->d_name);
1570
1571                 if (stat(fileName, &statBuf) != 0)
1572                         continue;
1573                 /* Some char devices have the same dev_t as block
1574                  * devices, so make sure this is a block device */
1575                 if (! S_ISBLK(statBuf.st_mode))
1576                         continue;
1577                 if (statBuf.st_rdev == rootStat.st_rdev) {
1578                         strcpy(name, fileName); 
1579                         return ( TRUE);
1580                 }
1581         }
1582
1583         return( FALSE);
1584 }
1585 #endif
1586
1587 static const int GROWBY = 80; /* how large we will grow strings by */
1588
1589 /* get_line_from_file() - This function reads an entire line from a text file
1590  * up to a newline. It returns a malloc'ed char * which must be stored and
1591  * free'ed  by the caller. */
1592 extern char *get_line_from_file(FILE *file)
1593 {
1594         int ch;
1595         int idx = 0;
1596         char *linebuf = NULL;
1597         int linebufsz = 0;
1598
1599         while (1) {
1600                 ch = fgetc(file);
1601                 if (ch == EOF)
1602                         break;
1603                 /* grow the line buffer as necessary */
1604                 if (idx > linebufsz-1)
1605                         linebuf = realloc(linebuf, linebufsz += GROWBY);
1606                 linebuf[idx++] = (char)ch;
1607                 if ((char)ch == '\n')
1608                         break;
1609         }
1610
1611         if (idx == 0)
1612                 return NULL;
1613
1614         linebuf[idx] = 0;
1615         return linebuf;
1616 }
1617
1618 #if defined BB_ECHO || defined BB_TR
1619 char process_escape_sequence(char **ptr)
1620 {
1621         char c;
1622
1623         switch (c = *(*ptr)++) {
1624         case 'a':
1625                 c = '\a';
1626                 break;
1627         case 'b':
1628                 c = '\b';
1629                 break;
1630         case 'f':
1631                 c = '\f';
1632                 break;
1633         case 'n':
1634                 c = '\n';
1635                 break;
1636         case 't':
1637                 c = '\t';
1638                 break;
1639         case 'v':
1640                 c = '\v';
1641                 break;
1642         case '\\':
1643                 c = '\\';
1644                 break;
1645         case '0': case '1': case '2': case '3':
1646         case '4': case '5': case '6': case '7':
1647                 c -= '0';
1648                 if ('0' <= **ptr && **ptr <= '7') {
1649                         c = c * 8 + (*(*ptr)++ - '0');
1650                         if ('0' <= **ptr && **ptr <= '7')
1651                                 c = c * 8 + (*(*ptr)++ - '0');
1652                 }
1653                 break;
1654         default:
1655                 (*ptr)--;
1656                 c = '\\';
1657                 break;
1658         }
1659         return c;
1660 }
1661 #endif
1662
1663 /* END CODE */
1664 /*
1665 Local Variables:
1666 c-file-style: "linux"
1667 c-basic-offset: 4
1668 tab-width: 4
1669 End:
1670 */