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