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