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