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