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