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