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