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