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