a27aaa2ae005743bb2b5a8cb6ef439253a340281
[oweals/busybox.git] / utility.c
1 /*
2  * Utility routines.
3  *
4  * Copyright (C) tons of folks.  Tracking down who wrote what
5  * isn't something I'm going to worry about...  If you wrote something
6  * here, please feel free to acknowledge your work.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21  *
22  * Based in part on code from sash, Copyright (c) 1999 by David I. Bell 
23  * Permission has been granted to redistribute this code under the GPL.
24  *
25  */
26
27 #include "internal.h"
28 #if defined (BB_CHMOD_CHOWN_CHGRP) \
29  || defined (BB_CP_MV)             \
30  || defined (BB_FIND)              \
31  || defined (BB_LS)                \
32  || defined (BB_INSMOD)
33 /* same conditions as recursiveAction */
34 #define bb_need_name_too_long
35 #endif
36 #define BB_DECLARE_EXTERN
37 #include "messages.c"
38
39 #include <stdio.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <dirent.h>
44 #include <time.h>
45 #include <utime.h>
46 #include <sys/stat.h>
47 #include <unistd.h>
48 #include <ctype.h>
49 #include <sys/param.h>          /* for PATH_MAX */
50
51 #if defined BB_FEATURE_MOUNT_LOOP
52 #include <fcntl.h>
53 #include <sys/ioctl.h>
54 #include <linux/loop.h>
55 #endif
56
57
58 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
59 #  if defined BB_FEATURE_USE_PROCFS
60 const char mtab_file[] = "/proc/mounts";
61 #  else
62 #    if defined BB_MTAB
63 const char mtab_file[] = "/etc/mtab";
64 #    else
65 #      error With (BB_MOUNT||BB_UMOUNT||BB_DF) defined, you must define either BB_MTAB or BB_FEATURE_USE_PROCFS
66 #    endif
67 #  endif
68 #endif
69
70
71 extern void usage(const char *usage)
72 {
73     fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
74             BB_VER, BB_BT);
75     fprintf(stderr, "Usage: %s\n", usage);
76     exit FALSE;
77 }
78
79
80 #if defined (BB_INIT) || defined (BB_PS)
81
82 #if ! defined BB_FEATURE_USE_PROCFS
83 #error Sorry, I depend on the /proc filesystem right now.
84 #endif
85 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
86  * so, for example,  to check if the kernel is greater than 2.2.11:
87  *      if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
88  */
89 int
90 get_kernel_revision()
91 {
92   FILE *file;
93   int major=0, minor=0, patch=0;
94
95   file = fopen("/proc/sys/kernel/osrelease", "r");
96   if (file == NULL) {
97     /* bummer, /proc must not be mounted... */
98     return( 0);
99   }
100   fscanf(file,"%d.%d.%d",&major,&minor,&patch);
101   fclose(file);
102   return major*65536 + minor*256 + patch;
103 }
104 #endif /* BB_INIT || BB_PS */
105
106
107
108 #if defined (BB_CP_MV) || defined (BB_DU) || defined (BB_LN)
109 /*
110  * Return TRUE if a fileName is a directory.
111  * Nonexistant files return FALSE.
112  */
113 int isDirectory(const char *fileName, const int followLinks)
114 {
115     struct stat statBuf;
116     int status;
117
118     if (followLinks == TRUE)
119       status = stat(fileName, &statBuf);
120     else
121       status = lstat(fileName, &statBuf);
122
123     if (status < 0)
124       return FALSE;
125     if (S_ISDIR(statBuf.st_mode))
126       return TRUE;
127     return FALSE;
128 }
129 #endif
130
131 #if defined (BB_CP_MV)
132 /*
133  * Copy one file to another, while possibly preserving its modes, times,
134  * and modes.  Returns TRUE if successful, or FALSE on a failure with an
135  * error message output.  (Failure is not indicted if the attributes cannot
136  * be set.)
137  *  -Erik Andersen
138  */
139 int
140 copyFile( const char *srcName, const char *destName, 
141           int setModes, int followLinks)
142 {
143     int rfd;
144     int wfd;
145     int rcc;
146     int status;
147     char buf[BUF_SIZE];
148     struct stat srcStatBuf;
149     struct stat dstStatBuf;
150     struct utimbuf times;
151
152     if (followLinks == TRUE)
153         status = stat(srcName, &srcStatBuf);
154     else 
155         status = lstat(srcName, &srcStatBuf);
156
157     if (status < 0) {
158         perror(srcName);
159         return FALSE;
160     }
161
162     if (followLinks == TRUE)    
163         status = stat(destName, &dstStatBuf);
164     else
165         status = lstat(destName, &dstStatBuf);
166
167     if (status < 0) {
168         dstStatBuf.st_ino = -1;
169         dstStatBuf.st_dev = -1;
170     }
171
172     if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
173         (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
174         fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
175         return FALSE;
176     }
177
178     if (S_ISDIR(srcStatBuf.st_mode)) {
179         //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
180         /* Make sure the directory is writable */
181         status = mkdir(destName, 0777777 ^ umask(0));
182         if (status < 0 && errno != EEXIST) {
183             perror(destName);
184             return FALSE;
185         }
186     } else if (S_ISLNK(srcStatBuf.st_mode)) {
187         char link_val[PATH_MAX + 1];
188         int link_size;
189
190         //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
191         /* Warning: This could possibly truncate silently, to PATH_MAX chars */
192         link_size = readlink(srcName, &link_val[0], PATH_MAX);
193         if (link_size < 0) {
194             perror(srcName);
195             return FALSE;
196         }
197         link_val[link_size] = '\0';
198         status = symlink(link_val, destName);
199         if (status < 0) {
200             perror(destName);
201             return FALSE;
202         }
203 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
204         if (setModes == TRUE) {
205             if (lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
206               perror(destName);
207               return FALSE;
208             }
209         }
210 #endif
211         return TRUE;
212     } else if (S_ISFIFO(srcStatBuf.st_mode)) {
213         //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
214         if (mkfifo(destName, 0644) < 0) {
215             perror(destName);
216             return FALSE;
217         }
218     } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode) 
219                 || S_ISSOCK (srcStatBuf.st_mode)) {
220         //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
221         if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev) < 0) {
222             perror(destName);
223             return FALSE;
224         }
225     } else if (S_ISREG(srcStatBuf.st_mode)) {
226         //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
227         rfd = open(srcName, O_RDONLY);
228         if (rfd < 0) {
229             perror(srcName);
230             return FALSE;
231         }
232
233         wfd = open(destName, O_WRONLY | O_CREAT | O_TRUNC, srcStatBuf.st_mode);
234         if (wfd < 0) {
235             perror(destName);
236             close(rfd);
237             return FALSE;
238         }
239
240         while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
241             if (fullWrite(wfd, buf, rcc) < 0)
242                 goto error_exit;
243         }
244         if (rcc < 0) {
245             goto error_exit;
246         }
247
248         close(rfd);
249         if (close(wfd) < 0) {
250             return FALSE;
251         }
252     }
253
254     if (setModes == TRUE) {
255         /* This is fine, since symlinks never get here */
256         if (chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid) < 0) {
257           perror(destName);
258           exit FALSE;
259         }
260         if (chmod(destName, srcStatBuf.st_mode) < 0) {
261           perror(destName);
262           exit FALSE;
263         }
264         times.actime = srcStatBuf.st_atime;
265         times.modtime = srcStatBuf.st_mtime;
266         if (utime(destName, &times) < 0) {
267           perror(destName);
268           exit FALSE;
269         }
270     }
271
272     return TRUE;
273
274  error_exit:
275     perror(destName);
276     close(rfd);
277     close(wfd);
278
279     return FALSE;
280 }
281 #endif /* BB_CP_MV */
282
283
284
285 #if defined BB_TAR || defined BB_LS
286
287 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
288 #define TYPECHAR(mode)  ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
289
290 /* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
291 static const mode_t SBIT[] = {
292     0, 0, S_ISUID,
293     0, 0, S_ISGID,
294     0, 0, S_ISVTX
295 };
296
297 /* The 9 mode bits to test */
298 static const mode_t MBIT[] = {
299     S_IRUSR, S_IWUSR, S_IXUSR,
300     S_IRGRP, S_IWGRP, S_IXGRP,
301     S_IROTH, S_IWOTH, S_IXOTH
302 };
303
304 #define MODE1  "rwxrwxrwx"
305 #define MODE0  "---------"
306 #define SMODE1 "..s..s..t"
307 #define SMODE0 "..S..S..T"
308
309 /*
310  * Return the standard ls-like mode string from a file mode.
311  * This is static and so is overwritten on each call.
312  */
313 const char *modeString(int mode)
314 {
315     static char buf[12];
316
317     int i;
318     buf[0] = TYPECHAR(mode);
319     for (i=0; i<9; i++) {
320         if (mode & SBIT[i])
321             buf[i+1] = (mode & MBIT[i])? 
322                 SMODE1[i] : SMODE0[i];
323         else
324             buf[i+1] = (mode & MBIT[i])? 
325                 MODE1[i] : MODE0[i];
326     }
327     return buf;
328 }
329 #endif /* BB_TAR || BB_LS */
330
331
332 #if defined BB_TAR
333 /*
334  * Return the standard ls-like time string from a time_t
335  * This is static and so is overwritten on each call.
336  */
337 const char *timeString(time_t timeVal)
338 {
339     time_t now;
340     char *str;
341     static char buf[26];
342
343     time(&now);
344
345     str = ctime(&timeVal);
346
347     strcpy(buf, &str[4]);
348     buf[12] = '\0';
349
350     if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
351         strcpy(&buf[7], &str[20]);
352         buf[11] = '\0';
353     }
354
355     return buf;
356 }
357 #endif /* BB_TAR */
358
359 #if defined BB_TAR || defined BB_CP_MV
360 /*
361  * Write all of the supplied buffer out to a file.
362  * This does multiple writes as necessary.
363  * Returns the amount written, or -1 on an error.
364  */
365 int fullWrite(int fd, const char *buf, int len)
366 {
367     int cc;
368     int total;
369
370     total = 0;
371
372     while (len > 0) {
373         cc = write(fd, buf, len);
374
375         if (cc < 0)
376             return -1;
377
378         buf += cc;
379         total += cc;
380         len -= cc;
381     }
382
383     return total;
384 }
385 #endif /* BB_TAR || BB_CP_MV */
386
387
388 #if defined BB_TAR || defined BB_TAIL
389 /*
390  * Read all of the supplied buffer from a file.
391  * This does multiple reads as necessary.
392  * Returns the amount read, or -1 on an error.
393  * A short read is returned on an end of file.
394  */
395 int fullRead(int fd, char *buf, int len)
396 {
397     int cc;
398     int total;
399
400     total = 0;
401
402     while (len > 0) {
403         cc = read(fd, buf, len);
404
405         if (cc < 0)
406             return -1;
407
408         if (cc == 0)
409             break;
410
411         buf += cc;
412         total += cc;
413         len -= cc;
414     }
415
416     return total;
417 }
418 #endif /* BB_TAR || BB_TAIL */
419
420
421 #if defined (BB_CHMOD_CHOWN_CHGRP) \
422  || defined (BB_CP_MV)             \
423  || defined (BB_FIND)              \
424  || defined (BB_LS)                \
425  || defined (BB_INSMOD)
426 /*
427  * Walk down all the directories under the specified 
428  * location, and do something (something specified
429  * by the fileAction and dirAction function pointers).
430  *
431  * Unfortunatly, while nftw(3) could replace this and reduce 
432  * code size a bit, nftw() wasn't supported before GNU libc 2.1, 
433  * and so isn't sufficiently portable to take over since glibc2.1
434  * is so stinking huge.
435  */
436 int recursiveAction(const char *fileName,
437                     int recurse, int followLinks, int depthFirst,
438                     int (*fileAction) (const char *fileName,
439                                        struct stat* statbuf),
440                     int (*dirAction) (const char *fileName,
441                                       struct stat* statbuf))
442 {
443     int status;
444     struct stat statbuf;
445     struct dirent *next;
446
447     if (followLinks == TRUE)
448         status = stat(fileName, &statbuf);
449     else
450         status = lstat(fileName, &statbuf);
451
452     if (status < 0) {
453 #ifdef BB_DEBUG_PRINT_SCAFFOLD
454       fprintf(stderr,
455               "status=%d followLinks=%d TRUE=%d\n",
456               status, followLinks, TRUE);
457 #endif
458         perror(fileName);
459         return FALSE;
460     }
461
462     if ((followLinks == FALSE) && (S_ISLNK(statbuf.st_mode)) ) {
463         if (fileAction == NULL)
464             return TRUE;
465         else
466             return fileAction(fileName, &statbuf);
467     }
468
469     if (recurse == FALSE) {
470         if (S_ISDIR(statbuf.st_mode)) {
471             if (dirAction != NULL)
472                 return (dirAction(fileName, &statbuf));
473             else
474                 return TRUE;
475         }
476     }
477
478     if (S_ISDIR(statbuf.st_mode)) {
479         DIR *dir;
480         dir = opendir(fileName);
481         if (!dir) {
482             perror(fileName);
483             return FALSE;
484         }
485         if (dirAction != NULL && depthFirst == FALSE) {
486             status = dirAction(fileName, &statbuf);
487             if (status == FALSE) {
488                 perror(fileName);
489                 return FALSE;
490             }
491         }
492         while ((next = readdir(dir)) != NULL) {
493             char nextFile[PATH_MAX + 1];
494             if ((strcmp(next->d_name, "..") == 0)
495                  || (strcmp(next->d_name, ".") == 0)) {
496                 continue;
497             }
498             if (strlen(fileName) + strlen(next->d_name) + 1 > PATH_MAX) {
499                 fprintf(stderr, name_too_long, "ftw");
500                 return FALSE;
501             }
502             sprintf(nextFile, "%s/%s", fileName, next->d_name);
503             status =
504                 recursiveAction(nextFile, TRUE, followLinks, depthFirst, 
505                                 fileAction, dirAction);
506             if (status < 0) {
507                 closedir(dir);
508                 return FALSE;
509             }
510         }
511         status = closedir(dir);
512         if (status < 0) {
513             perror(fileName);
514             return FALSE;
515         }
516         if (dirAction != NULL && depthFirst == TRUE) {
517             status = dirAction(fileName, &statbuf);
518             if (status == FALSE) {
519                 perror(fileName);
520                 return FALSE;
521             }
522         }
523     } else {
524         if (fileAction == NULL)
525             return TRUE;
526         else
527             return fileAction(fileName, &statbuf);
528     }
529     return TRUE;
530 }
531
532 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_CP_MV || BB_FIND || BB_LS || BB_INSMOD */
533
534
535
536 #if defined (BB_TAR) || defined (BB_MKDIR)
537 /*
538  * Attempt to create the directories along the specified path, except for
539  * the final component.  The mode is given for the final directory only,
540  * while all previous ones get default protections.  Errors are not reported
541  * here, as failures to restore files can be reported later.
542  */
543 extern int createPath (const char *name, int mode)
544 {
545     char *cp;
546     char *cpOld;
547     char buf[PATH_MAX + 1];
548     int retVal=0;
549
550     strcpy( buf, name);
551     cp = strchr(buf, '/');
552     while (cp) {
553         cpOld = cp;
554         cp = strchr(cp + 1, '/');
555         *cpOld = '\0';
556         retVal = mkdir(buf, cp ? 0777 : mode);
557         if (retVal != 0 && errno != EEXIST) {
558             perror(buf);
559             return FALSE;
560         }
561         *cpOld = '/';
562     }
563     return TRUE;
564 }
565 #endif /* BB_TAR || BB_MKDIR */
566
567
568
569 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
570 /* [ugoa]{+|-|=}[rwxst] */
571
572
573
574 extern int 
575 parse_mode( const char* s, mode_t* theMode)
576 {
577         mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
578         mode_t orMode = 0;
579         mode_t  mode = 0;
580         mode_t  groups = 0;
581         char    type;
582         char    c;
583
584         do {
585                 for ( ; ; ) {
586                         switch ( c = *s++ ) {
587                         case '\0':
588                                 return -1;
589                         case 'u':
590                                 groups |= S_ISUID|S_IRWXU;
591                                 continue;
592                         case 'g':
593                                 groups |= S_ISGID|S_IRWXG;
594                                 continue;
595                         case 'o':
596                                 groups |= S_IRWXO;
597                                 continue;
598                         case 'a':
599                                 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
600                                 continue;
601                         case '+':
602                         case '=':
603                         case '-':
604                                 type = c;
605                                 if ( groups == 0 ) /* The default is "all" */
606                                         groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
607                                 break;
608                         default:
609                                 if ( isdigit(c) && c >= '0' && c <= '7' && 
610                                                 mode == 0 && groups == 0 ) {
611                                         *theMode = strtol(--s, NULL, 8);
612                                         return (TRUE);
613                                 }
614                                 else
615                                         return (FALSE);
616                         }
617                         break;
618                 }
619
620                 while ( (c = *s++) != '\0' ) {
621                         switch ( c ) {
622                         case ',':
623                                 break;
624                         case 'r':
625                                 mode |= S_IRUSR|S_IRGRP|S_IROTH;
626                                 continue;
627                         case 'w':
628                                 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
629                                 continue;
630                         case 'x':
631                                 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
632                                 continue;
633                         case 's':
634                                 mode |= S_IXGRP|S_ISUID|S_ISGID;
635                                 continue;
636                         case 't':
637                                 mode |= 0;
638                                 continue;
639                         default:
640                                 *theMode &= andMode;
641                                 *theMode |= orMode;
642                                 return( TRUE);
643                         }
644                         break;
645                 }
646                 switch ( type ) {
647                 case '=':
648                         andMode &= ~(groups);
649                         /* fall through */
650                 case '+':
651                         orMode |= mode & groups;
652                         break;
653                 case '-':
654                         andMode &= ~(mode & groups);
655                         orMode &= andMode;
656                         break;
657                 }
658         } while ( c == ',' );
659         *theMode &= andMode;
660         *theMode |= orMode;
661         return (TRUE);
662 }
663
664
665 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
666
667
668
669
670
671
672
673 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
674
675 /* Use this to avoid needing the glibc NSS stuff 
676  * This uses storage buf to hold things.
677  * */
678 uid_t 
679 my_getid(const char *filename, char *name, uid_t id) 
680 {
681         FILE *file;
682         char *rname, *start, *end, buf[128];
683         uid_t rid;
684
685         file=fopen(filename,"r");
686         if (file == NULL) {
687             perror(filename);
688             return (-1);
689         }
690
691         while (fgets (buf, 128, file) != NULL) {
692                 if (buf[0] == '#')
693                         continue;
694
695                 start = buf;
696                 end = strchr (start, ':');
697                 if (end == NULL)
698                         continue;
699                 *end = '\0';
700                 rname = start;
701
702                 start = end + 1;
703                 end = strchr (start, ':');
704                 if (end == NULL)
705                         continue;
706
707                 start = end + 1;
708                 rid = (uid_t) strtol (start, &end, 10);
709                 if (end == start)
710                         continue;
711
712                 if (name) {
713                     if (0 == strcmp(rname, name)) {
714                         fclose( file);
715                         return( rid);
716                     }
717                 }
718                 if ( id != -1 && id == rid ) {
719                     strncpy(name, rname, 8);
720                     fclose( file);
721                     return( TRUE);
722                 }
723         }
724         fclose(file);
725         return (-1);
726 }
727
728 uid_t 
729 my_getpwnam(char *name) 
730 {
731     return my_getid("/etc/passwd", name, -1);
732 }
733
734 gid_t 
735 my_getgrnam(char *name) 
736 {
737     return my_getid("/etc/group", name, -1);
738 }
739
740 void
741 my_getpwuid(char* name, uid_t uid) 
742 {
743     my_getid("/etc/passwd", name, uid);
744 }
745
746 void
747 my_getgrgid(char* group, gid_t gid) 
748 {
749     my_getid("/etc/group", group, gid);
750 }
751
752
753 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS */
754
755
756
757
758 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
759
760
761 #include <linux/kd.h>
762 #include <sys/ioctl.h>
763
764 int is_a_console(int fd) 
765 {
766   char arg;
767   
768   arg = 0;
769   return (ioctl(fd, KDGKBTYPE, &arg) == 0
770           && ((arg == KB_101) || (arg == KB_84)));
771 }
772
773 static int open_a_console(char *fnam) 
774 {
775   int fd;
776   
777   /* try read-only */
778   fd = open(fnam, O_RDWR);
779   
780   /* if failed, try read-only */
781   if (fd < 0 && errno == EACCES)
782       fd = open(fnam, O_RDONLY);
783   
784   /* if failed, try write-only */
785   if (fd < 0 && errno == EACCES)
786       fd = open(fnam, O_WRONLY);
787   
788   /* if failed, fail */
789   if (fd < 0)
790       return -1;
791   
792   /* if not a console, fail */
793   if (! is_a_console(fd))
794     {
795       close(fd);
796       return -1;
797     }
798   
799   /* success */
800   return fd;
801 }
802
803 /*
804  * Get an fd for use with kbd/console ioctls.
805  * We try several things because opening /dev/console will fail
806  * if someone else used X (which does a chown on /dev/console).
807  *
808  * if tty_name is non-NULL, try this one instead.
809  */
810
811 int get_console_fd(char* tty_name) 
812 {
813   int fd;
814
815   if (tty_name)
816     {
817       if (-1 == (fd = open_a_console(tty_name)))
818         return -1;
819       else
820         return fd;
821     }
822   
823   fd = open_a_console("/dev/tty");
824   if (fd >= 0)
825     return fd;
826   
827   fd = open_a_console("/dev/tty0");
828   if (fd >= 0)
829     return fd;
830   
831   fd = open_a_console("/dev/console");
832   if (fd >= 0)
833     return fd;
834   
835   for (fd = 0; fd < 3; fd++)
836     if (is_a_console(fd))
837       return fd;
838   
839   fprintf(stderr,
840           "Couldnt get a file descriptor referring to the console\n");
841   return -1;            /* total failure */
842 }
843
844
845 #endif /* BB_CHVT || BB_DEALLOCVT */
846
847
848 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)  
849
850 /* Do a case insensitive strstr() */
851 char* stristr(char *haystack, const char *needle)
852 {
853     int len = strlen( needle );
854     while( *haystack ) {
855         if( !strncasecmp( haystack, needle, len ) )
856             break;
857         haystack++;
858     }
859
860     if( !(*haystack) )
861             haystack = NULL;
862
863     return haystack;
864 }
865
866 /* This tries to find a needle in a haystack, but does so by
867  * only trying to match literal strings (look 'ma, no regexps!)
868  * This is short, sweet, and carries _very_ little baggage,
869  * unlike its beefier cousin in regexp.c
870  *  -Erik Andersen
871  */
872 extern int find_match(char *haystack, char *needle, int ignoreCase)
873 {
874
875     if (ignoreCase == FALSE)
876         haystack = strstr (haystack, needle);
877     else
878         haystack = stristr (haystack, needle);
879     if (haystack == NULL)
880         return FALSE;
881     return TRUE;
882 }
883
884
885 /* This performs substitutions after a string match has been found.  */
886 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
887 {
888     int foundOne=0;
889     char *where, *slider, *slider1, *oldhayStack;
890
891     if (ignoreCase == FALSE)
892         where = strstr (haystack, needle);
893     else
894         where = stristr (haystack, needle);
895
896     if (strcmp(needle, newNeedle)==0)
897         return FALSE;
898
899     oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
900     while(where!=NULL) {
901         foundOne++;
902         strcpy(oldhayStack, haystack);
903 #if 0
904         if ( strlen(newNeedle) > strlen(needle)) {
905             haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) - 
906                 strlen(needle) + strlen(newNeedle)));
907         }
908 #endif
909         for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
910         *slider=0;
911         haystack=strcat(haystack, newNeedle);
912         slider1+=strlen(needle);
913         haystack = strcat(haystack, slider1);
914         where = strstr (slider, needle);
915     }
916     free( oldhayStack);
917
918     if (foundOne > 0)
919         return TRUE;
920     else
921         return FALSE;
922 }
923
924 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
925
926
927 #if defined BB_FIND
928 /*
929  * Routine to see if a text string is matched by a wildcard pattern.
930  * Returns TRUE if the text is matched, or FALSE if it is not matched
931  * or if the pattern is invalid.
932  *  *           matches zero or more characters
933  *  ?           matches a single character
934  *  [abc]       matches 'a', 'b' or 'c'
935  *  \c          quotes character c
936  * Adapted from code written by Ingo Wilken, and
937  * then taken from sash, Copyright (c) 1999 by David I. Bell
938  * Permission is granted to use, distribute, or modify this source,
939  * provided that this copyright notice remains intact.
940  * Permission to distribute this code under the GPL has been granted.
941  */
942 extern int
943 check_wildcard_match(const char* text, const char* pattern)
944 {
945     const char* retryPat;
946     const char* retryText;
947     int         ch;
948     int         found;
949
950     retryPat = NULL;
951     retryText = NULL;
952
953     while (*text || *pattern)
954     {
955         ch = *pattern++;
956
957         switch (ch)
958         {
959             case '*':  
960                 retryPat = pattern;
961                 retryText = text;
962                 break;
963
964             case '[':  
965                 found = FALSE;
966
967                 while ((ch = *pattern++) != ']')
968                 {
969                     if (ch == '\\')
970                         ch = *pattern++;
971
972                     if (ch == '\0')
973                         return FALSE;
974
975                     if (*text == ch)
976                         found = TRUE;
977                 }
978
979                 //if (!found)
980                 if (found==TRUE)
981                 {
982                     pattern = retryPat;
983                     text = ++retryText;
984                 }
985
986                 /* fall into next case */
987
988             case '?':  
989                 if (*text++ == '\0')
990                     return FALSE;
991
992                 break;
993
994             case '\\':  
995                 ch = *pattern++;
996
997                 if (ch == '\0')
998                         return FALSE;
999
1000                 /* fall into next case */
1001
1002             default:        
1003                 if (*text == ch)
1004                 {
1005                     if (*text)
1006                         text++;
1007                     break;
1008                 }
1009
1010                 if (*text)
1011                 {
1012                     pattern = retryPat;
1013                     text = ++retryText;
1014                     break;
1015                 }
1016
1017                 return FALSE;
1018         }
1019
1020         if (pattern == NULL)
1021                 return FALSE;
1022     }
1023
1024     return TRUE;
1025 }
1026 #endif /* BB_FIND */
1027
1028
1029
1030
1031 #if defined BB_DF || defined BB_MTAB
1032 /*
1033  * Given a block device, find the mount table entry if that block device
1034  * is mounted.
1035  *
1036  * Given any other file (or directory), find the mount table entry for its
1037  * filesystem.
1038  */
1039 extern struct mntent *findMountPoint(const char *name, const char *table)
1040 {
1041     struct stat s;
1042     dev_t mountDevice;
1043     FILE *mountTable;
1044     struct mntent *mountEntry;
1045
1046     if (stat(name, &s) != 0)
1047         return 0;
1048
1049     if ((s.st_mode & S_IFMT) == S_IFBLK)
1050         mountDevice = s.st_rdev;
1051     else
1052         mountDevice = s.st_dev;
1053
1054
1055     if ((mountTable = setmntent(table, "r")) == 0)
1056         return 0;
1057
1058     while ((mountEntry = getmntent(mountTable)) != 0) {
1059         if (strcmp(name, mountEntry->mnt_dir) == 0
1060             || strcmp(name, mountEntry->mnt_fsname) == 0)       /* String match. */
1061             break;
1062         if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice)  /* Match the device. */
1063             break;
1064         if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice)      /* Match the directory's mount point. */
1065             break;
1066     }
1067     endmntent(mountTable);
1068     return mountEntry;
1069 }
1070 #endif /* BB_DF || BB_MTAB */
1071
1072
1073
1074 #if defined BB_DD || defined BB_TAIL
1075 /*
1076  * Read a number with a possible multiplier.
1077  * Returns -1 if the number format is illegal.
1078  */
1079 extern long getNum (const char *cp)
1080 {
1081     long value;
1082
1083     if (!isDecimal (*cp))
1084         return -1;
1085
1086     value = 0;
1087
1088     while (isDecimal (*cp))
1089         value = value * 10 + *cp++ - '0';
1090
1091     switch (*cp++) {
1092     case 'M':
1093     case 'm': /* `tail' uses it traditionally */
1094         value *= 1048576;
1095         break;
1096
1097     case 'k':
1098         value *= 1024;
1099         break;
1100
1101     case 'b':
1102         value *= 512;
1103         break;
1104
1105     case 'w':
1106         value *= 2;
1107         break;
1108
1109     case '\0':
1110         return value;
1111
1112     default:
1113         return -1;
1114     }
1115
1116     if (*cp)
1117         return -1;
1118
1119     return value;
1120 }
1121 #endif /* BB_DD || BB_TAIL */
1122
1123
1124 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT 
1125
1126 #if ! defined BB_FEATURE_USE_PROCFS
1127 #error Sorry, I depend on the /proc filesystem right now.
1128 #endif
1129 /* findInitPid()
1130  *  
1131  *  This finds the pid of init (which is not always 1).
1132  *  Currently, it's implemented by rummaging through the proc filesystem.
1133  *
1134  *  [return]
1135  *  0       failure
1136  *  pid     when init's pid is found.
1137  */
1138 extern pid_t
1139 findInitPid()
1140 {
1141     pid_t   init_pid;
1142     char    filename[256];
1143     char    buffer[256];
1144
1145     /* no need to opendir ;) */
1146     for (init_pid = 1; init_pid < 65536; init_pid++) {
1147         FILE    *status;
1148
1149         sprintf(filename, "/proc/%d/status", init_pid);
1150         status = fopen(filename, "r");
1151         if (!status) { continue; }
1152         fgets(buffer, 256, status);
1153         fclose(status);
1154
1155         if ( (strstr(buffer, "init\n") != NULL )) {
1156             return init_pid;
1157         }
1158     }
1159     return 0;
1160 }
1161 #endif /* BB_INIT || BB_HALT || BB_REBOOT */
1162
1163 #if defined BB_GUNZIP \
1164  || defined BB_GZIP   \
1165  || defined BB_PRINTF \
1166  || defined BB_TAIL
1167 extern void *xmalloc (size_t size)
1168 {
1169     void *cp = malloc (size);
1170
1171     if (cp == NULL) {
1172         error("out of memory");
1173     }
1174     return cp;
1175 }
1176
1177 extern void error(char *msg)
1178 {
1179     fprintf(stderr, "\n%s\n", msg);
1180     exit(1);
1181 }
1182 #endif /* BB_GUNZIP || BB_GZIP || BB_PRINTF || BB_TAIL */
1183
1184 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1185 extern int vdprintf(int d, const char *format, va_list ap)
1186 {
1187     char buf[BUF_SIZE];
1188     int len;
1189
1190     len = vsprintf(buf, format, ap);
1191     return write(d, buf, len);
1192 }
1193 #endif /* BB_SYSLOGD */
1194
1195 #if defined BB_FEATURE_MOUNT_LOOP
1196 extern int del_loop(const char *device)
1197 {
1198     int fd;
1199
1200     if ((fd = open(device, O_RDONLY)) < 0) {
1201         perror(device);
1202         return( FALSE);
1203     }
1204     if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1205         perror("ioctl: LOOP_CLR_FD");
1206         return( FALSE);
1207     }
1208     close(fd);
1209     return( TRUE);
1210 }
1211
1212 extern int set_loop(const char *device, const char *file, int offset, int *loopro)
1213 {
1214         struct loop_info loopinfo;
1215         int     fd, ffd, mode;
1216         
1217         mode = *loopro ? O_RDONLY : O_RDWR;
1218         if ((ffd = open (file, mode)) < 0 && !*loopro
1219             && (errno != EROFS || (ffd = open (file, mode = O_RDONLY)) < 0)) {
1220           perror (file);
1221           return 1;
1222         }
1223         if ((fd = open (device, mode)) < 0) {
1224           close(ffd);
1225           perror (device);
1226           return 1;
1227         }
1228         *loopro = (mode == O_RDONLY);
1229
1230         memset(&loopinfo, 0, sizeof(loopinfo));
1231         strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1232         loopinfo.lo_name[LO_NAME_SIZE-1] = 0;
1233
1234         loopinfo.lo_offset = offset;
1235
1236         loopinfo.lo_encrypt_key_size = 0;
1237         if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1238                 perror("ioctl: LOOP_SET_FD");
1239                 close(fd);
1240                 close(ffd);
1241                 return 1;
1242         }
1243         if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1244                 (void) ioctl(fd, LOOP_CLR_FD, 0);
1245                 perror("ioctl: LOOP_SET_STATUS");
1246                 close(fd);
1247                 close(ffd);
1248                 return 1;
1249         }
1250         close(fd);
1251         close(ffd);
1252         return 0;
1253 }
1254
1255 extern char *find_unused_loop_device (void)
1256 {
1257         char dev[20];
1258         int i, fd;
1259         struct stat statbuf;
1260         struct loop_info loopinfo;
1261
1262         for(i = 0; i <= 7; i++) {
1263             sprintf(dev, "/dev/loop%d", i);
1264             if (stat (dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1265                 if ((fd = open (dev, O_RDONLY)) >= 0) {
1266                     if(ioctl (fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1267                         if (errno == ENXIO) { /* probably free */
1268                             close (fd);
1269                             return strdup(dev);
1270                         }
1271                     }
1272                     close (fd);
1273                 }
1274             }
1275         }
1276         return NULL;
1277 }
1278 #endif /* BB_FEATURE_MOUNT_LOOP */
1279
1280
1281 /* END CODE */