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