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