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