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