mkdir -p had gotten broken. Fixed now.
[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     for (cp = buf; *cp == '/'; cp++);
552     cp = strchr(cp, '/');
553     while (cp) {
554         cpOld = cp;
555         cp = strchr(cp + 1, '/');
556         *cpOld = '\0';
557         retVal = mkdir(buf, cp ? 0777 : mode);
558         if (retVal != 0 && errno != EEXIST) {
559             perror(buf);
560             return FALSE;
561         }
562         *cpOld = '/';
563     }
564     return TRUE;
565 }
566 #endif /* BB_TAR || BB_MKDIR */
567
568
569
570 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
571 /* [ugoa]{+|-|=}[rwxst] */
572
573
574
575 extern int 
576 parse_mode( const char* s, mode_t* theMode)
577 {
578         mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
579         mode_t orMode = 0;
580         mode_t  mode = 0;
581         mode_t  groups = 0;
582         char    type;
583         char    c;
584
585         do {
586                 for ( ; ; ) {
587                         switch ( c = *s++ ) {
588                         case '\0':
589                                 return -1;
590                         case 'u':
591                                 groups |= S_ISUID|S_IRWXU;
592                                 continue;
593                         case 'g':
594                                 groups |= S_ISGID|S_IRWXG;
595                                 continue;
596                         case 'o':
597                                 groups |= S_IRWXO;
598                                 continue;
599                         case 'a':
600                                 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
601                                 continue;
602                         case '+':
603                         case '=':
604                         case '-':
605                                 type = c;
606                                 if ( groups == 0 ) /* The default is "all" */
607                                         groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
608                                 break;
609                         default:
610                                 if ( isdigit(c) && c >= '0' && c <= '7' && 
611                                                 mode == 0 && groups == 0 ) {
612                                         *theMode = strtol(--s, NULL, 8);
613                                         return (TRUE);
614                                 }
615                                 else
616                                         return (FALSE);
617                         }
618                         break;
619                 }
620
621                 while ( (c = *s++) != '\0' ) {
622                         switch ( c ) {
623                         case ',':
624                                 break;
625                         case 'r':
626                                 mode |= S_IRUSR|S_IRGRP|S_IROTH;
627                                 continue;
628                         case 'w':
629                                 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
630                                 continue;
631                         case 'x':
632                                 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
633                                 continue;
634                         case 's':
635                                 mode |= S_IXGRP|S_ISUID|S_ISGID;
636                                 continue;
637                         case 't':
638                                 mode |= 0;
639                                 continue;
640                         default:
641                                 *theMode &= andMode;
642                                 *theMode |= orMode;
643                                 return( TRUE);
644                         }
645                         break;
646                 }
647                 switch ( type ) {
648                 case '=':
649                         andMode &= ~(groups);
650                         /* fall through */
651                 case '+':
652                         orMode |= mode & groups;
653                         break;
654                 case '-':
655                         andMode &= ~(mode & groups);
656                         orMode &= andMode;
657                         break;
658                 }
659         } while ( c == ',' );
660         *theMode &= andMode;
661         *theMode |= orMode;
662         return (TRUE);
663 }
664
665
666 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_MKDIR */
667
668
669
670
671
672
673
674 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
675
676 /* Use this to avoid needing the glibc NSS stuff 
677  * This uses storage buf to hold things.
678  * */
679 uid_t 
680 my_getid(const char *filename, char *name, uid_t id) 
681 {
682         FILE *file;
683         char *rname, *start, *end, buf[128];
684         uid_t rid;
685
686         file=fopen(filename,"r");
687         if (file == NULL) {
688             perror(filename);
689             return (-1);
690         }
691
692         while (fgets (buf, 128, file) != NULL) {
693                 if (buf[0] == '#')
694                         continue;
695
696                 start = buf;
697                 end = strchr (start, ':');
698                 if (end == NULL)
699                         continue;
700                 *end = '\0';
701                 rname = start;
702
703                 start = end + 1;
704                 end = strchr (start, ':');
705                 if (end == NULL)
706                         continue;
707
708                 start = end + 1;
709                 rid = (uid_t) strtol (start, &end, 10);
710                 if (end == start)
711                         continue;
712
713                 if (name) {
714                     if (0 == strcmp(rname, name)) {
715                         fclose( file);
716                         return( rid);
717                     }
718                 }
719                 if ( id != -1 && id == rid ) {
720                     strncpy(name, rname, 8);
721                     fclose( file);
722                     return( TRUE);
723                 }
724         }
725         fclose(file);
726         return (-1);
727 }
728
729 uid_t 
730 my_getpwnam(char *name) 
731 {
732     return my_getid("/etc/passwd", name, -1);
733 }
734
735 gid_t 
736 my_getgrnam(char *name) 
737 {
738     return my_getid("/etc/group", name, -1);
739 }
740
741 void
742 my_getpwuid(char* name, uid_t uid) 
743 {
744     my_getid("/etc/passwd", name, uid);
745 }
746
747 void
748 my_getgrgid(char* group, gid_t gid) 
749 {
750     my_getid("/etc/group", group, gid);
751 }
752
753
754 #endif /* BB_CHMOD_CHOWN_CHGRP || BB_PS */
755
756
757
758
759 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
760
761
762 #include <linux/kd.h>
763 #include <sys/ioctl.h>
764
765 int is_a_console(int fd) 
766 {
767   char arg;
768   
769   arg = 0;
770   return (ioctl(fd, KDGKBTYPE, &arg) == 0
771           && ((arg == KB_101) || (arg == KB_84)));
772 }
773
774 static int open_a_console(char *fnam) 
775 {
776   int fd;
777   
778   /* try read-only */
779   fd = open(fnam, O_RDWR);
780   
781   /* if failed, try read-only */
782   if (fd < 0 && errno == EACCES)
783       fd = open(fnam, O_RDONLY);
784   
785   /* if failed, try write-only */
786   if (fd < 0 && errno == EACCES)
787       fd = open(fnam, O_WRONLY);
788   
789   /* if failed, fail */
790   if (fd < 0)
791       return -1;
792   
793   /* if not a console, fail */
794   if (! is_a_console(fd))
795     {
796       close(fd);
797       return -1;
798     }
799   
800   /* success */
801   return fd;
802 }
803
804 /*
805  * Get an fd for use with kbd/console ioctls.
806  * We try several things because opening /dev/console will fail
807  * if someone else used X (which does a chown on /dev/console).
808  *
809  * if tty_name is non-NULL, try this one instead.
810  */
811
812 int get_console_fd(char* tty_name) 
813 {
814   int fd;
815
816   if (tty_name)
817     {
818       if (-1 == (fd = open_a_console(tty_name)))
819         return -1;
820       else
821         return fd;
822     }
823   
824   fd = open_a_console("/dev/tty");
825   if (fd >= 0)
826     return fd;
827   
828   fd = open_a_console("/dev/tty0");
829   if (fd >= 0)
830     return fd;
831   
832   fd = open_a_console("/dev/console");
833   if (fd >= 0)
834     return fd;
835   
836   for (fd = 0; fd < 3; fd++)
837     if (is_a_console(fd))
838       return fd;
839   
840   fprintf(stderr,
841           "Couldnt get a file descriptor referring to the console\n");
842   return -1;            /* total failure */
843 }
844
845
846 #endif /* BB_CHVT || BB_DEALLOCVT */
847
848
849 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)  
850
851 /* Do a case insensitive strstr() */
852 char* stristr(char *haystack, const char *needle)
853 {
854     int len = strlen( needle );
855     while( *haystack ) {
856         if( !strncasecmp( haystack, needle, len ) )
857             break;
858         haystack++;
859     }
860
861     if( !(*haystack) )
862             haystack = NULL;
863
864     return haystack;
865 }
866
867 /* This tries to find a needle in a haystack, but does so by
868  * only trying to match literal strings (look 'ma, no regexps!)
869  * This is short, sweet, and carries _very_ little baggage,
870  * unlike its beefier cousin in regexp.c
871  *  -Erik Andersen
872  */
873 extern int find_match(char *haystack, char *needle, int ignoreCase)
874 {
875
876     if (ignoreCase == FALSE)
877         haystack = strstr (haystack, needle);
878     else
879         haystack = stristr (haystack, needle);
880     if (haystack == NULL)
881         return FALSE;
882     return TRUE;
883 }
884
885
886 /* This performs substitutions after a string match has been found.  */
887 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
888 {
889     int foundOne=0;
890     char *where, *slider, *slider1, *oldhayStack;
891
892     if (ignoreCase == FALSE)
893         where = strstr (haystack, needle);
894     else
895         where = stristr (haystack, needle);
896
897     if (strcmp(needle, newNeedle)==0)
898         return FALSE;
899
900     oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
901     while(where!=NULL) {
902         foundOne++;
903         strcpy(oldhayStack, haystack);
904 #if 0
905         if ( strlen(newNeedle) > strlen(needle)) {
906             haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) - 
907                 strlen(needle) + strlen(newNeedle)));
908         }
909 #endif
910         for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
911         *slider=0;
912         haystack=strcat(haystack, newNeedle);
913         slider1+=strlen(needle);
914         haystack = strcat(haystack, slider1);
915         where = strstr (slider, needle);
916     }
917     free( oldhayStack);
918
919     if (foundOne > 0)
920         return TRUE;
921     else
922         return FALSE;
923 }
924
925 #endif /* ! BB_REGEXP && (BB_GREP || BB_SED) */
926
927
928 #if defined BB_FIND
929 /*
930  * Routine to see if a text string is matched by a wildcard pattern.
931  * Returns TRUE if the text is matched, or FALSE if it is not matched
932  * or if the pattern is invalid.
933  *  *           matches zero or more characters
934  *  ?           matches a single character
935  *  [abc]       matches 'a', 'b' or 'c'
936  *  \c          quotes character c
937  * Adapted from code written by Ingo Wilken, and
938  * then taken from sash, Copyright (c) 1999 by David I. Bell
939  * Permission is granted to use, distribute, or modify this source,
940  * provided that this copyright notice remains intact.
941  * Permission to distribute this code under the GPL has been granted.
942  */
943 extern int
944 check_wildcard_match(const char* text, const char* pattern)
945 {
946     const char* retryPat;
947     const char* retryText;
948     int         ch;
949     int         found;
950
951     retryPat = NULL;
952     retryText = NULL;
953
954     while (*text || *pattern)
955     {
956         ch = *pattern++;
957
958         switch (ch)
959         {
960             case '*':  
961                 retryPat = pattern;
962                 retryText = text;
963                 break;
964
965             case '[':  
966                 found = FALSE;
967
968                 while ((ch = *pattern++) != ']')
969                 {
970                     if (ch == '\\')
971                         ch = *pattern++;
972
973                     if (ch == '\0')
974                         return FALSE;
975
976                     if (*text == ch)
977                         found = TRUE;
978                 }
979
980                 //if (!found)
981                 if (found==TRUE)
982                 {
983                     pattern = retryPat;
984                     text = ++retryText;
985                 }
986
987                 /* fall into next case */
988
989             case '?':  
990                 if (*text++ == '\0')
991                     return FALSE;
992
993                 break;
994
995             case '\\':  
996                 ch = *pattern++;
997
998                 if (ch == '\0')
999                         return FALSE;
1000
1001                 /* fall into next case */
1002
1003             default:        
1004                 if (*text == ch)
1005                 {
1006                     if (*text)
1007                         text++;
1008                     break;
1009                 }
1010
1011                 if (*text)
1012                 {
1013                     pattern = retryPat;
1014                     text = ++retryText;
1015                     break;
1016                 }
1017
1018                 return FALSE;
1019         }
1020
1021         if (pattern == NULL)
1022                 return FALSE;
1023     }
1024
1025     return TRUE;
1026 }
1027 #endif /* BB_FIND */
1028
1029
1030
1031
1032 #if defined BB_DF || defined BB_MTAB
1033 /*
1034  * Given a block device, find the mount table entry if that block device
1035  * is mounted.
1036  *
1037  * Given any other file (or directory), find the mount table entry for its
1038  * filesystem.
1039  */
1040 extern struct mntent *findMountPoint(const char *name, const char *table)
1041 {
1042     struct stat s;
1043     dev_t mountDevice;
1044     FILE *mountTable;
1045     struct mntent *mountEntry;
1046
1047     if (stat(name, &s) != 0)
1048         return 0;
1049
1050     if ((s.st_mode & S_IFMT) == S_IFBLK)
1051         mountDevice = s.st_rdev;
1052     else
1053         mountDevice = s.st_dev;
1054
1055
1056     if ((mountTable = setmntent(table, "r")) == 0)
1057         return 0;
1058
1059     while ((mountEntry = getmntent(mountTable)) != 0) {
1060         if (strcmp(name, mountEntry->mnt_dir) == 0
1061             || strcmp(name, mountEntry->mnt_fsname) == 0)       /* String match. */
1062             break;
1063         if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice)  /* Match the device. */
1064             break;
1065         if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice)      /* Match the directory's mount point. */
1066             break;
1067     }
1068     endmntent(mountTable);
1069     return mountEntry;
1070 }
1071 #endif /* BB_DF || BB_MTAB */
1072
1073
1074
1075 #if defined BB_DD || defined BB_TAIL
1076 /*
1077  * Read a number with a possible multiplier.
1078  * Returns -1 if the number format is illegal.
1079  */
1080 extern long getNum (const char *cp)
1081 {
1082     long value;
1083
1084     if (!isDecimal (*cp))
1085         return -1;
1086
1087     value = 0;
1088
1089     while (isDecimal (*cp))
1090         value = value * 10 + *cp++ - '0';
1091
1092     switch (*cp++) {
1093     case 'M':
1094     case 'm': /* `tail' uses it traditionally */
1095         value *= 1048576;
1096         break;
1097
1098     case 'k':
1099         value *= 1024;
1100         break;
1101
1102     case 'b':
1103         value *= 512;
1104         break;
1105
1106     case 'w':
1107         value *= 2;
1108         break;
1109
1110     case '\0':
1111         return value;
1112
1113     default:
1114         return -1;
1115     }
1116
1117     if (*cp)
1118         return -1;
1119
1120     return value;
1121 }
1122 #endif /* BB_DD || BB_TAIL */
1123
1124
1125 #if defined BB_INIT || defined BB_SYSLOGD
1126 /* try to open up the specified device */
1127 extern int device_open(char *device, int mode)
1128 {
1129     int m, f, fd = -1;
1130
1131     m = mode | O_NONBLOCK;
1132
1133     /* Retry up to 5 times */
1134     for (f = 0; f < 5; f++)
1135         if ((fd = open(device, m, 0600)) >= 0)
1136             break;
1137     if (fd < 0)
1138         return fd;
1139     /* Reset original flags. */
1140     if (m != mode)
1141         fcntl(fd, F_SETFL, mode);
1142     return fd;
1143 }
1144 #endif /* BB_INIT BB_SYSLOGD */
1145
1146
1147 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT 
1148
1149 #if ! defined BB_FEATURE_USE_PROCFS
1150 #error Sorry, I depend on the /proc filesystem right now.
1151 #endif
1152 /* findInitPid()
1153  *  
1154  *  This finds the pid of init (which is not always 1).
1155  *  Currently, it's implemented by rummaging through the proc filesystem.
1156  *
1157  *  [return]
1158  *  0       failure
1159  *  pid     when init's pid is found.
1160  */
1161 extern pid_t
1162 findInitPid()
1163 {
1164     pid_t   init_pid;
1165     char    filename[256];
1166     char    buffer[256];
1167
1168     /* no need to opendir ;) */
1169     for (init_pid = 1; init_pid < 65536; init_pid++) {
1170         FILE    *status;
1171
1172         sprintf(filename, "/proc/%d/status", init_pid);
1173         status = fopen(filename, "r");
1174         if (!status) { continue; }
1175         fgets(buffer, 256, status);
1176         fclose(status);
1177
1178         if ( (strstr(buffer, "init\n") != NULL )) {
1179             return init_pid;
1180         }
1181     }
1182     return 0;
1183 }
1184 #endif /* BB_INIT || BB_HALT || BB_REBOOT */
1185
1186 #if defined BB_GUNZIP \
1187  || defined BB_GZIP   \
1188  || defined BB_PRINTF \
1189  || defined BB_TAIL
1190 extern void *xmalloc (size_t size)
1191 {
1192     void *cp = malloc (size);
1193
1194     if (cp == NULL) {
1195         error("out of memory");
1196     }
1197     return cp;
1198 }
1199
1200 extern void error(char *msg)
1201 {
1202     fprintf(stderr, "\n%s\n", msg);
1203     exit(1);
1204 }
1205 #endif /* BB_GUNZIP || BB_GZIP || BB_PRINTF || BB_TAIL */
1206
1207 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1208 extern int vdprintf(int d, const char *format, va_list ap)
1209 {
1210     char buf[BUF_SIZE];
1211     int len;
1212
1213     len = vsprintf(buf, format, ap);
1214     return write(d, buf, len);
1215 }
1216 #endif /* BB_SYSLOGD */
1217
1218 #if defined BB_FEATURE_MOUNT_LOOP
1219 extern int del_loop(const char *device)
1220 {
1221     int fd;
1222
1223     if ((fd = open(device, O_RDONLY)) < 0) {
1224         perror(device);
1225         return( FALSE);
1226     }
1227     if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
1228         perror("ioctl: LOOP_CLR_FD");
1229         return( FALSE);
1230     }
1231     close(fd);
1232     return( TRUE);
1233 }
1234
1235 extern int set_loop(const char *device, const char *file, int offset, int *loopro)
1236 {
1237         struct loop_info loopinfo;
1238         int     fd, ffd, mode;
1239         
1240         mode = *loopro ? O_RDONLY : O_RDWR;
1241         if ((ffd = open (file, mode)) < 0 && !*loopro
1242             && (errno != EROFS || (ffd = open (file, mode = O_RDONLY)) < 0)) {
1243           perror (file);
1244           return 1;
1245         }
1246         if ((fd = open (device, mode)) < 0) {
1247           close(ffd);
1248           perror (device);
1249           return 1;
1250         }
1251         *loopro = (mode == O_RDONLY);
1252
1253         memset(&loopinfo, 0, sizeof(loopinfo));
1254         strncpy(loopinfo.lo_name, file, LO_NAME_SIZE);
1255         loopinfo.lo_name[LO_NAME_SIZE-1] = 0;
1256
1257         loopinfo.lo_offset = offset;
1258
1259         loopinfo.lo_encrypt_key_size = 0;
1260         if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
1261                 perror("ioctl: LOOP_SET_FD");
1262                 close(fd);
1263                 close(ffd);
1264                 return 1;
1265         }
1266         if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
1267                 (void) ioctl(fd, LOOP_CLR_FD, 0);
1268                 perror("ioctl: LOOP_SET_STATUS");
1269                 close(fd);
1270                 close(ffd);
1271                 return 1;
1272         }
1273         close(fd);
1274         close(ffd);
1275         return 0;
1276 }
1277
1278 extern char *find_unused_loop_device (void)
1279 {
1280         char dev[20];
1281         int i, fd;
1282         struct stat statbuf;
1283         struct loop_info loopinfo;
1284
1285         for(i = 0; i <= 7; i++) {
1286             sprintf(dev, "/dev/loop%d", i);
1287             if (stat (dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
1288                 if ((fd = open (dev, O_RDONLY)) >= 0) {
1289                     if(ioctl (fd, LOOP_GET_STATUS, &loopinfo) == -1) {
1290                         if (errno == ENXIO) { /* probably free */
1291                             close (fd);
1292                             return strdup(dev);
1293                         }
1294                     }
1295                     close (fd);
1296                 }
1297             }
1298         }
1299         return NULL;
1300 }
1301 #endif /* BB_FEATURE_MOUNT_LOOP */
1302
1303
1304 /* END CODE */