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