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