Make cin be static
[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 <sys/ioctl.h>
54 #include <sys/utsname.h>                /* for uname(2) */
55
56 /* Busybox mount uses either /proc/filesystems or /dev/mtab to get the 
57  * list of available filesystems used for the -t auto option */ 
58 #if defined BB_FEATURE_USE_PROCFS && defined BB_FEATURE_USE_DEVPS_PATCH
59 //#error Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again.
60 #error "Sorry, but busybox can't use both /proc and /dev/ps at the same time -- Pick one and try again."
61 #endif
62
63
64 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
65 #  if defined BB_MTAB
66 const char mtab_file[] = "/etc/mtab";
67 #  else
68 #    if defined BB_FEATURE_USE_PROCFS
69 const char mtab_file[] = "/proc/mounts";
70 #    else
71 #      if defined BB_FEATURE_USE_DEVPS_PATCH
72 const char mtab_file[] = "/dev/mtab";
73 #    else
74 #        error With (BB_MOUNT||BB_UMOUNT||BB_DF) defined, you must define either BB_MTAB or ( BB_FEATURE_USE_PROCFS | BB_FEATURE_USE_DEVPS_PATCH)
75 #    endif
76 #  endif
77 #  endif
78 #endif
79
80 extern void usage(const char *usage)
81 {
82         fprintf(stderr, "%s\n\nUsage: %s\n", full_version, usage);
83         exit(EXIT_FAILURE);
84 }
85
86 static void verror_msg(const char *s, va_list p)
87 {
88         fflush(stdout);
89         fprintf(stderr, "%s: ", applet_name);
90         vfprintf(stderr, s, p);
91 }
92
93 extern void error_msg(const char *s, ...)
94 {
95         va_list p;
96
97         va_start(p, s);
98         verror_msg(s, p);
99         va_end(p);
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         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\n", 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
860 /* This parses entries in /etc/passwd and /etc/group.  This is desirable
861  * for BusyBox, since we want to avoid using the glibc NSS stuff, which
862  * increases target size and is often not needed or wanted for embedded
863  * systems.
864  *
865  * /etc/passwd entries look like this: 
866  *              root:x:0:0:root:/root:/bin/bash
867  * and /etc/group entries look like this: 
868  *              root:x:0:
869  *
870  * This uses buf as storage to hold things.
871  * 
872  */
873 unsigned long my_getid(const char *filename, char *name, long id, long *gid)
874 {
875         FILE *file;
876         char *rname, *start, *end, buf[128];
877         long rid;
878         long rgid = 0;
879
880         file = fopen(filename, "r");
881         if (file == NULL) {
882                 /* Do not complain.  It is ok for /etc/passwd and
883                  * friends to be missing... */
884                 return (-1);
885         }
886
887         while (fgets(buf, 128, file) != NULL) {
888                 if (buf[0] == '#')
889                         continue;
890
891                 /* username/group name */
892                 start = buf;
893                 end = strchr(start, ':');
894                 if (end == NULL)
895                         continue;
896                 *end = '\0';
897                 rname = start;
898
899                 /* password */
900                 start = end + 1;
901                 end = strchr(start, ':');
902                 if (end == NULL)
903                         continue;
904
905                 /* uid in passwd, gid in group */
906                 start = end + 1;
907                 rid = (unsigned long) strtol(start, &end, 10);
908                 if (end == start)
909                         continue;
910
911                 /* gid in passwd */
912                 start = end + 1;
913                 rgid = (unsigned long) strtol(start, &end, 10);
914                 
915                 if (name) {
916                         if (0 == strcmp(rname, name)) {
917                             if (gid) *gid = rgid;
918                                 fclose(file);
919                                 return (rid);
920                         }
921                 }
922                 if (id != -1 && id == rid) {
923                         strncpy(name, rname, 8);
924                         name[8]='\0';
925                         if (gid) *gid = rgid;
926                         fclose(file);
927                         return (TRUE);
928                 }
929         }
930         fclose(file);
931         return (-1);
932 }
933
934 /* returns a uid given a username */
935 long my_getpwnam(char *name)
936 {
937         return my_getid("/etc/passwd", name, -1, NULL);
938 }
939
940 /* returns a gid given a group name */
941 long my_getgrnam(char *name)
942 {
943         return my_getid("/etc/group", name, -1, NULL);
944 }
945
946 /* gets a username given a uid */
947 void my_getpwuid(char *name, long uid)
948 {
949         name[0] = '\0';
950         my_getid("/etc/passwd", name, uid, NULL);
951 }
952
953 /* gets a groupname given a gid */
954 void my_getgrgid(char *group, long gid)
955 {
956         group[0] = '\0';
957         my_getid("/etc/group", group, gid, NULL);
958 }
959
960 #if defined BB_ID
961 /* gets a gid given a user name */
962 long my_getpwnamegid(char *name)
963 {
964         long gid;
965         my_getid("/etc/passwd", name, -1, &gid);
966         return gid;
967 }
968 #endif
969
970 #endif
971  /* BB_CHMOD_CHOWN_CHGRP || BB_PS || BB_LS || BB_TAR \
972  || BB_ID || BB_LOGGER || BB_LOGNAME || BB_WHOAMI */
973
974
975 #if (defined BB_CHVT) || (defined BB_DEALLOCVT) || (defined BB_SETKEYCODES)
976
977 /* From <linux/kd.h> */ 
978 static const int KDGKBTYPE = 0x4B33;  /* get keyboard type */
979 static const int KB_84 = 0x01;
980 static const int KB_101 = 0x02;    /* this is what we always answer */
981
982 int is_a_console(int fd)
983 {
984         char arg;
985
986         arg = 0;
987         return (ioctl(fd, KDGKBTYPE, &arg) == 0
988                         && ((arg == KB_101) || (arg == KB_84)));
989 }
990
991 static int open_a_console(char *fnam)
992 {
993         int fd;
994
995         /* try read-only */
996         fd = open(fnam, O_RDWR);
997
998         /* if failed, try read-only */
999         if (fd < 0 && errno == EACCES)
1000                 fd = open(fnam, O_RDONLY);
1001
1002         /* if failed, try write-only */
1003         if (fd < 0 && errno == EACCES)
1004                 fd = open(fnam, O_WRONLY);
1005
1006         /* if failed, fail */
1007         if (fd < 0)
1008                 return -1;
1009
1010         /* if not a console, fail */
1011         if (!is_a_console(fd)) {
1012                 close(fd);
1013                 return -1;
1014         }
1015
1016         /* success */
1017         return fd;
1018 }
1019
1020 /*
1021  * Get an fd for use with kbd/console ioctls.
1022  * We try several things because opening /dev/console will fail
1023  * if someone else used X (which does a chown on /dev/console).
1024  *
1025  * if tty_name is non-NULL, try this one instead.
1026  */
1027
1028 int get_console_fd(char *tty_name)
1029 {
1030         int fd;
1031
1032         if (tty_name) {
1033                 if (-1 == (fd = open_a_console(tty_name)))
1034                         return -1;
1035                 else
1036                         return fd;
1037         }
1038
1039         fd = open_a_console("/dev/tty");
1040         if (fd >= 0)
1041                 return fd;
1042
1043         fd = open_a_console("/dev/tty0");
1044         if (fd >= 0)
1045                 return fd;
1046
1047         fd = open_a_console("/dev/console");
1048         if (fd >= 0)
1049                 return fd;
1050
1051         for (fd = 0; fd < 3; fd++)
1052                 if (is_a_console(fd))
1053                         return fd;
1054
1055         error_msg("Couldnt get a file descriptor referring to the console\n");
1056         return -1;                                      /* total failure */
1057 }
1058
1059
1060 #endif                                                  /* BB_CHVT || BB_DEALLOCVT || BB_SETKEYCODES */
1061
1062
1063 #if defined BB_FIND || defined BB_INSMOD
1064 /*
1065  * Routine to see if a text string is matched by a wildcard pattern.
1066  * Returns TRUE if the text is matched, or FALSE if it is not matched
1067  * or if the pattern is invalid.
1068  *  *           matches zero or more characters
1069  *  ?           matches a single character
1070  *  [abc]       matches 'a', 'b' or 'c'
1071  *  \c          quotes character c
1072  * Adapted from code written by Ingo Wilken, and
1073  * then taken from sash, Copyright (c) 1999 by David I. Bell
1074  * Permission is granted to use, distribute, or modify this source,
1075  * provided that this copyright notice remains intact.
1076  * Permission to distribute this code under the GPL has been granted.
1077  */
1078 extern int check_wildcard_match(const char *text, const char *pattern)
1079 {
1080         const char *retryPat;
1081         const char *retryText;
1082         int ch;
1083         int found;
1084         int len;
1085
1086         retryPat = NULL;
1087         retryText = NULL;
1088
1089         while (*text || *pattern) {
1090                 ch = *pattern++;
1091
1092                 switch (ch) {
1093                 case '*':
1094                         retryPat = pattern;
1095                         retryText = text;
1096                         break;
1097
1098                 case '[':
1099                         found = FALSE;
1100
1101                         while ((ch = *pattern++) != ']') {
1102                                 if (ch == '\\')
1103                                         ch = *pattern++;
1104
1105                                 if (ch == '\0')
1106                                         return FALSE;
1107
1108                                 if (*text == ch)
1109                                         found = TRUE;
1110                         }
1111                         len=strlen(text);
1112                         if (found == FALSE && len!=0) {
1113                                 return FALSE;
1114                         }
1115                         if (found == TRUE) {
1116                                 if (strlen(pattern)==0 && len==1) {
1117                                         return TRUE;
1118                                 }
1119                                 if (len!=0) {
1120                                         text++;
1121                                         continue;
1122                                 }
1123                         }
1124
1125                         /* fall into next case */
1126
1127                 case '?':
1128                         if (*text++ == '\0')
1129                                 return FALSE;
1130
1131                         break;
1132
1133                 case '\\':
1134                         ch = *pattern++;
1135
1136                         if (ch == '\0')
1137                                 return FALSE;
1138
1139                         /* fall into next case */
1140
1141                 default:
1142                         if (*text == ch) {
1143                                 if (*text)
1144                                         text++;
1145                                 break;
1146                         }
1147
1148                         if (*text) {
1149                                 pattern = retryPat;
1150                                 text = ++retryText;
1151                                 break;
1152                         }
1153
1154                         return FALSE;
1155                 }
1156
1157                 if (pattern == NULL)
1158                         return FALSE;
1159         }
1160
1161         return TRUE;
1162 }
1163 #endif                            /* BB_FIND || BB_INSMOD */
1164
1165
1166
1167
1168 #if defined BB_DF || defined BB_MTAB
1169 /*
1170  * Given a block device, find the mount table entry if that block device
1171  * is mounted.
1172  *
1173  * Given any other file (or directory), find the mount table entry for its
1174  * filesystem.
1175  */
1176 extern struct mntent *find_mount_point(const char *name, const char *table)
1177 {
1178         struct stat s;
1179         dev_t mountDevice;
1180         FILE *mountTable;
1181         struct mntent *mountEntry;
1182
1183         if (stat(name, &s) != 0)
1184                 return 0;
1185
1186         if ((s.st_mode & S_IFMT) == S_IFBLK)
1187                 mountDevice = s.st_rdev;
1188         else
1189                 mountDevice = s.st_dev;
1190
1191
1192         if ((mountTable = setmntent(table, "r")) == 0)
1193                 return 0;
1194
1195         while ((mountEntry = getmntent(mountTable)) != 0) {
1196                 if (strcmp(name, mountEntry->mnt_dir) == 0
1197                         || strcmp(name, mountEntry->mnt_fsname) == 0)   /* String match. */
1198                         break;
1199                 if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice)  /* Match the device. */
1200                         break;
1201                 if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice)      /* Match the directory's mount point. */
1202                         break;
1203         }
1204         endmntent(mountTable);
1205         return mountEntry;
1206 }
1207 #endif                                                  /* BB_DF || BB_MTAB */
1208
1209 #if defined BB_INIT || defined BB_SYSLOGD 
1210 /* try to open up the specified device */
1211 extern int device_open(char *device, int mode)
1212 {
1213         int m, f, fd = -1;
1214
1215         m = mode | O_NONBLOCK;
1216
1217         /* Retry up to 5 times */
1218         for (f = 0; f < 5; f++)
1219                 if ((fd = open(device, m, 0600)) >= 0)
1220                         break;
1221         if (fd < 0)
1222                 return fd;
1223         /* Reset original flags. */
1224         if (m != mode)
1225                 fcntl(fd, F_SETFL, mode);
1226         return fd;
1227 }
1228 #endif                                                  /* BB_INIT BB_SYSLOGD */
1229
1230
1231 #if defined BB_KILLALL || ( defined BB_FEATURE_LINUXRC && ( defined BB_HALT || defined BB_REBOOT || defined BB_POWEROFF ))
1232 #ifdef BB_FEATURE_USE_DEVPS_PATCH
1233 #include <linux/devps.h> /* For Erik's nifty devps device driver */
1234 #endif
1235
1236 #if defined BB_FEATURE_USE_DEVPS_PATCH
1237 /* find_pid_by_name()
1238  *  
1239  *  This finds the pid of the specified process,
1240  *  by using the /dev/ps device driver.
1241  *
1242  *  Returns a list of all matching PIDs
1243  */
1244 extern pid_t* find_pid_by_name( char* pidName)
1245 {
1246         int fd, i, j;
1247         char device[] = "/dev/ps";
1248         pid_t num_pids;
1249         pid_t* pid_array = NULL;
1250         pid_t* pidList=NULL;
1251
1252         /* open device */ 
1253         fd = open(device, O_RDONLY);
1254         if (fd < 0)
1255                 perror_msg_and_die("open failed for `%s'", device);
1256
1257         /* Find out how many processes there are */
1258         if (ioctl (fd, DEVPS_GET_NUM_PIDS, &num_pids)<0) 
1259                 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1260         
1261         /* Allocate some memory -- grab a few extras just in case 
1262          * some new processes start up while we wait. The kernel will
1263          * just ignore any extras if we give it too many, and will trunc.
1264          * the list if we give it too few.  */
1265         pid_array = (pid_t*) xcalloc( num_pids+10, sizeof(pid_t));
1266         pid_array[0] = num_pids+10;
1267
1268         /* Now grab the pid list */
1269         if (ioctl (fd, DEVPS_GET_PID_LIST, pid_array)<0) 
1270                 perror_msg_and_die("\nDEVPS_GET_PID_LIST");
1271
1272         /* Now search for a match */
1273         for (i=1, j=0; i<pid_array[0] ; i++) {
1274                 char* p;
1275                 struct pid_info info;
1276
1277             info.pid = pid_array[i];
1278             if (ioctl (fd, DEVPS_GET_PID_INFO, &info)<0)
1279                         perror_msg_and_die("\nDEVPS_GET_PID_INFO");
1280
1281                 /* Make sure we only match on the process name */
1282                 p=info.command_line+1;
1283                 while ((*p != 0) && !isspace(*(p)) && (*(p-1) != '\\')) { 
1284                         (p)++;
1285                 }
1286                 if (isspace(*(p)))
1287                                 *p='\0';
1288
1289                 if ((strstr(info.command_line, pidName) != NULL)
1290                                 && (strlen(pidName) == strlen(info.command_line))) {
1291                         pidList=xrealloc( pidList, sizeof(pid_t) * (j+2));
1292                         pidList[j++]=info.pid;
1293                 }
1294         }
1295         if (pidList)
1296                 pidList[j]=0;
1297
1298         /* Free memory */
1299         free( pid_array);
1300
1301         /* close device */
1302         if (close (fd) != 0) 
1303                 perror_msg_and_die("close failed for `%s'", device);
1304
1305         return pidList;
1306 }
1307 #else           /* BB_FEATURE_USE_DEVPS_PATCH */
1308 #if ! defined BB_FEATURE_USE_PROCFS
1309 #error Sorry, I depend on the /proc filesystem right now.
1310 #endif
1311
1312 /* find_pid_by_name()
1313  *  
1314  *  This finds the pid of the specified process.
1315  *  Currently, it's implemented by rummaging through 
1316  *  the proc filesystem.
1317  *
1318  *  Returns a list of all matching PIDs
1319  */
1320 extern pid_t* find_pid_by_name( char* pidName)
1321 {
1322         DIR *dir;
1323         struct dirent *next;
1324         pid_t* pidList=NULL;
1325         int i=0;
1326
1327         dir = opendir("/proc");
1328         if (!dir)
1329                 perror_msg_and_die("Cannot open /proc");
1330         
1331         while ((next = readdir(dir)) != NULL) {
1332                 FILE *status;
1333                 char filename[256];
1334                 char buffer[256];
1335
1336                 /* If it isn't a number, we don't want it */
1337                 if (!isdigit(*next->d_name))
1338                         continue;
1339
1340                 sprintf(filename, "/proc/%s/cmdline", next->d_name);
1341                 status = fopen(filename, "r");
1342                 if (!status) {
1343                         continue;
1344                 }
1345                 fgets(buffer, 256, status);
1346                 fclose(status);
1347
1348                 if (strstr(get_last_path_component(buffer), pidName) != NULL) {
1349                         pidList=xrealloc( pidList, sizeof(pid_t) * (i+2));
1350                         pidList[i++]=strtol(next->d_name, NULL, 0);
1351                 }
1352         }
1353
1354         if (pidList)
1355                 pidList[i]=0;
1356         return pidList;
1357 }
1358 #endif                                                  /* BB_FEATURE_USE_DEVPS_PATCH */
1359 #endif                                                  /* BB_KILLALL || ( BB_FEATURE_LINUXRC && ( BB_HALT || BB_REBOOT || BB_POWEROFF )) */
1360
1361 #ifndef DMALLOC
1362 /* this should really be farmed out to libbusybox.a */
1363 extern void *xmalloc(size_t size)
1364 {
1365         void *ptr = malloc(size);
1366
1367         if (!ptr)
1368                 error_msg_and_die(memory_exhausted);
1369         return ptr;
1370 }
1371
1372 extern void *xrealloc(void *old, size_t size)
1373 {
1374         void *ptr = realloc(old, size);
1375         if (!ptr)
1376                 error_msg_and_die(memory_exhausted);
1377         return ptr;
1378 }
1379
1380 extern void *xcalloc(size_t nmemb, size_t size)
1381 {
1382         void *ptr = calloc(nmemb, size);
1383         if (!ptr)
1384                 error_msg_and_die(memory_exhausted);
1385         return ptr;
1386 }
1387 #endif
1388
1389 #if defined BB_NFSMOUNT || defined BB_LS || defined BB_SH || defined BB_WGET || \
1390         defined BB_DPKG_DEB || defined BB_TAR
1391 # ifndef DMALLOC
1392 extern char * xstrdup (const char *s) {
1393         char *t;
1394
1395         if (s == NULL)
1396                 return NULL;
1397
1398         t = strdup (s);
1399
1400         if (t == NULL)
1401                 error_msg_and_die(memory_exhausted);
1402
1403         return t;
1404 }
1405 # endif
1406 #endif
1407
1408 #if defined BB_NFSMOUNT
1409 extern char * xstrndup (const char *s, int n) {
1410         char *t;
1411
1412         if (s == NULL)
1413                 error_msg_and_die("xstrndup bug\n");
1414
1415         t = xmalloc(n+1);
1416         strncpy(t,s,n);
1417         t[n] = 0;
1418
1419         return t;
1420 }
1421 #endif
1422
1423
1424 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1425 extern int vdprintf(int d, const char *format, va_list ap)
1426 {
1427         char buf[BUF_SIZE];
1428         int len;
1429
1430         len = vsprintf(buf, format, ap);
1431         return write(d, buf, len);
1432 }
1433 #endif                                                  /* BB_SYSLOGD */
1434
1435
1436 #if defined BB_FEATURE_MOUNT_LOOP
1437 #include <fcntl.h>
1438 #include "loop.h" /* Pull in loop device support */
1439
1440 extern int del_loop(const char *device)
1441 {
1442         int fd;
1443
1444         if ((fd = open(device, O_RDONLY)) < 0) {
1445                 perror_msg("%s", device);
1446                 return (FALSE);
1447         }
1448         if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1449                 perror_msg("ioctl: LOOP_CLR_FD");
1450                 return (FALSE);
1451         }
1452         close(fd);
1453         return (TRUE);
1454 }
1455
1456 extern int set_loop(const char *device, const char *file, int offset,
1457                                         int *loopro)
1458 {
1459         struct loop_info loopinfo;
1460         int fd, ffd, mode;
1461
1462         mode = *loopro ? O_RDONLY : O_RDWR;
1463         if ((ffd = open(file, mode)) < 0 && !*loopro
1464                 && (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
1465                 perror_msg("%s", file);
1466                 return 1;
1467         }
1468         if ((fd = open(device, mode)) < 0) {
1469                 close(ffd);
1470                 perror_msg("%s", device);
1471                 return 1;
1472         }
1473         *loopro = (mode == O_RDONLY);
1474
1475         memset(&loopinfo, 0, sizeof(loopinfo));
1476         strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1477         loopinfo.lo_name[LO_NAME_SIZE - 1] = 0;
1478
1479         loopinfo.lo_offset = offset;
1480
1481         loopinfo.lo_encrypt_key_size = 0;
1482         if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1483                 perror_msg("ioctl: LOOP_SET_FD");
1484                 close(fd);
1485                 close(ffd);
1486                 return 1;
1487         }
1488         if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1489                 (void) ioctl(fd, LOOP_CLR_FD, 0);
1490                 perror_msg("ioctl: LOOP_SET_STATUS");
1491                 close(fd);
1492                 close(ffd);
1493                 return 1;
1494         }
1495         close(fd);
1496         close(ffd);
1497         return 0;
1498 }
1499
1500 extern char *find_unused_loop_device(void)
1501 {
1502         char dev[20];
1503         int i, fd;
1504         struct stat statbuf;
1505         struct loop_info loopinfo;
1506
1507         for (i = 0; i <= 7; i++) {
1508                 sprintf(dev, "/dev/loop%d", i);
1509                 if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1510                         if ((fd = open(dev, O_RDONLY)) >= 0) {
1511                                 if (ioctl(fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1512                                         if (errno == ENXIO) {   /* probably free */
1513                                                 close(fd);
1514                                                 return strdup(dev);
1515                                         }
1516                                 }
1517                                 close(fd);
1518                         }
1519                 }
1520         }
1521         return NULL;
1522 }
1523 #endif                                                  /* BB_FEATURE_MOUNT_LOOP */
1524
1525 #if defined BB_MOUNT || defined BB_DF || ( defined BB_UMOUNT && ! defined BB_MTAB)
1526 extern int find_real_root_device_name(char* name)
1527 {
1528         DIR *dir;
1529         struct dirent *entry;
1530         struct stat statBuf, rootStat;
1531         char fileName[BUFSIZ];
1532
1533         if (stat("/", &rootStat) != 0) {
1534                 error_msg("could not stat '/'\n");
1535                 return( FALSE);
1536         }
1537
1538         dir = opendir("/dev");
1539         if (!dir) {
1540                 error_msg("could not open '/dev'\n");
1541                 return( FALSE);
1542         }
1543
1544         while((entry = readdir(dir)) != NULL) {
1545
1546                 /* Must skip ".." since that is "/", and so we 
1547                  * would get a false positive on ".."  */
1548                 if (strcmp(entry->d_name, "..") == 0)
1549                         continue;
1550
1551                 snprintf( fileName, strlen(name)+1, "/dev/%s", entry->d_name);
1552
1553                 if (stat(fileName, &statBuf) != 0)
1554                         continue;
1555                 /* Some char devices have the same dev_t as block
1556                  * devices, so make sure this is a block device */
1557                 if (! S_ISBLK(statBuf.st_mode))
1558                         continue;
1559                 if (statBuf.st_rdev == rootStat.st_rdev) {
1560                         strcpy(name, fileName); 
1561                         return ( TRUE);
1562                 }
1563         }
1564
1565         return( FALSE);
1566 }
1567 #endif
1568
1569
1570 /* get_line_from_file() - This function reads an entire line from a text file
1571  * up to a newline. It returns a malloc'ed char * which must be stored and
1572  * free'ed  by the caller. */
1573 extern char *get_line_from_file(FILE *file)
1574 {
1575         static const int GROWBY = 80; /* how large we will grow strings by */
1576
1577         int ch;
1578         int idx = 0;
1579         char *linebuf = NULL;
1580         int linebufsz = 0;
1581
1582         while (1) {
1583                 ch = fgetc(file);
1584                 if (ch == EOF)
1585                         break;
1586                 /* grow the line buffer as necessary */
1587                 while (idx > linebufsz-2)
1588                         linebuf = xrealloc(linebuf, linebufsz += GROWBY);
1589                 linebuf[idx++] = (char)ch;
1590                 if ((char)ch == '\n')
1591                         break;
1592         }
1593
1594         if (idx == 0)
1595                 return NULL;
1596
1597         linebuf[idx] = 0;
1598         return linebuf;
1599 }
1600
1601 #if defined BB_CAT
1602 extern void print_file(FILE *file)
1603 {
1604         int c;
1605
1606         while ((c = getc(file)) != EOF)
1607                 putc(c, stdout);
1608         fclose(file);
1609         fflush(stdout);
1610 }
1611
1612 extern int print_file_by_name(char *filename)
1613 {
1614         FILE *file;
1615         if ((file = wfopen(filename, "r")) == NULL)
1616                 return FALSE;
1617         print_file(file);
1618         return TRUE;
1619 }
1620 #endif /* BB_CAT */
1621
1622 #if defined BB_ECHO || defined BB_SH || defined BB_TR
1623 char process_escape_sequence(char **ptr)
1624 {
1625         char c;
1626
1627         switch (c = *(*ptr)++) {
1628         case 'a':
1629                 c = '\a';
1630                 break;
1631         case 'b':
1632                 c = '\b';
1633                 break;
1634         case 'f':
1635                 c = '\f';
1636                 break;
1637         case 'n':
1638                 c = '\n';
1639                 break;
1640         case 'r':
1641                 c = '\r';
1642                 break;
1643         case 't':
1644                 c = '\t';
1645                 break;
1646         case 'v':
1647                 c = '\v';
1648                 break;
1649         case '\\':
1650                 c = '\\';
1651                 break;
1652         case '0': case '1': case '2': case '3':
1653         case '4': case '5': case '6': case '7':
1654                 c -= '0';
1655                 if ('0' <= **ptr && **ptr <= '7') {
1656                         c = c * 8 + (*(*ptr)++ - '0');
1657                         if ('0' <= **ptr && **ptr <= '7')
1658                                 c = c * 8 + (*(*ptr)++ - '0');
1659                 }
1660                 break;
1661         default:
1662                 (*ptr)--;
1663                 c = '\\';
1664                 break;
1665         }
1666         return c;
1667 }
1668 #endif
1669
1670 #if defined BB_BASENAME || defined BB_LN || defined BB_SH || defined BB_INIT || \
1671         defined BB_FEATURE_USE_PROCFS || defined BB_WGET
1672 char *get_last_path_component(char *path)
1673 {
1674         char *s=path+strlen(path)-1;
1675
1676         /* strip trailing slashes */
1677         while (s != path && *s == '/') {
1678                 *s-- = '\0';
1679         }
1680
1681         /* find last component */
1682         s = strrchr(path, '/');
1683         if (s == NULL || s[1] == '\0')
1684                 return path;
1685         else
1686                 return s+1;
1687 }
1688 #endif
1689
1690 #if defined BB_GREP || defined BB_SED
1691 void xregcomp(regex_t *preg, const char *regex, int cflags)
1692 {
1693         int ret;
1694         if ((ret = regcomp(preg, regex, cflags)) != 0) {
1695                 int errmsgsz = regerror(ret, preg, NULL, 0);
1696                 char *errmsg = xmalloc(errmsgsz);
1697                 regerror(ret, preg, errmsg, errmsgsz);
1698                 error_msg_and_die("xregcomp: %s\n", errmsg);
1699         }
1700 }
1701 #endif
1702
1703 #if defined BB_CAT || defined BB_HEAD || defined BB_WC
1704 FILE *wfopen(const char *path, const char *mode)
1705 {
1706         FILE *fp;
1707         if ((fp = fopen(path, mode)) == NULL) {
1708                 perror_msg("%s", path);
1709                 errno = 0;
1710         }
1711         return fp;
1712 }
1713 #endif
1714
1715 #if defined BB_HOSTNAME || defined BB_LOADACM || defined BB_MORE \
1716  || defined BB_SED || defined BB_SH || defined BB_TAR || defined BB_UNIQ \
1717  || defined BB_WC || defined BB_CMP || defined BB_SORT
1718 FILE *xfopen(const char *path, const char *mode)
1719 {
1720         FILE *fp;
1721         if ((fp = fopen(path, mode)) == NULL)
1722                 perror_msg_and_die("%s", path);
1723         return fp;
1724 }
1725 #endif
1726
1727 int applet_name_compare(const void *x, const void *y)
1728 {
1729         const struct BB_applet *applet1 = x;
1730         const struct BB_applet *applet2 = y;
1731
1732         return strcmp(applet1->name, applet2->name);
1733 }
1734
1735 #if defined BB_DD || defined BB_TAIL
1736 unsigned long parse_number(const char *numstr, struct suffix_mult *suffixes)
1737 {
1738         struct suffix_mult *sm;
1739         unsigned long int ret;
1740         int len;
1741         char *end;
1742         
1743         ret = strtoul(numstr, &end, 10);
1744         if (numstr == end)
1745                 error_msg_and_die("invalid number `%s'\n", numstr);
1746         while (end[0] != '\0') {
1747                 for (sm = suffixes; sm->suffix != NULL; sm++) {
1748                         len = strlen(sm->suffix);
1749                         if (strncmp(sm->suffix, end, len) == 0) {
1750                                 ret *= sm->mult;
1751                                 end += len;
1752                                 break;
1753                         }
1754                 }
1755                 if (sm->suffix == NULL)
1756                         error_msg_and_die("invalid number `%s'\n", numstr);
1757         }
1758         return ret;
1759 }
1760 #endif
1761
1762 #if defined BB_DD || defined BB_NC || defined BB_TAIL
1763 ssize_t safe_read(int fd, void *buf, size_t count)
1764 {
1765         ssize_t n;
1766
1767         do {
1768                 n = read(fd, buf, count);
1769         } while (n < 0 && errno == EINTR);
1770
1771         return n;
1772 }
1773 #endif
1774
1775 #ifdef BB_FEATURE_HUMAN_READABLE
1776 char *format(unsigned long val, unsigned long hr)
1777 {
1778         static char str[10] = "\0";
1779
1780         if(val == 0)
1781                 return("0");
1782         if(hr)
1783                 snprintf(str, 9, "%ld", val/hr);
1784         else if(val >= GIGABYTE)
1785                 snprintf(str, 9, "%.1LfG", ((long double)(val)/GIGABYTE));
1786         else if(val >= MEGABYTE)
1787                 snprintf(str, 9, "%.1LfM", ((long double)(val)/MEGABYTE));
1788         else if(val >= KILOBYTE)
1789                 snprintf(str, 9, "%.1Lfk", ((long double)(val)/KILOBYTE));
1790         else
1791                 snprintf(str, 9, "%ld", (val));
1792         return(str);
1793 }
1794 #endif
1795
1796 /* END CODE */
1797 /*
1798 Local Variables:
1799 c-file-style: "linux"
1800 c-basic-offset: 4
1801 tab-width: 4
1802 End:
1803 */