fleshed out a bit more... just wanted to put the current
[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 #endif
321
322 #if defined BB_TAR || defined BB_CP || defined BB_MV
323 /*
324  * Write all of the supplied buffer out to a file.
325  * This does multiple writes as necessary.
326  * Returns the amount written, or -1 on an error.
327  */
328 int fullWrite(int fd, const char *buf, int len)
329 {
330     int cc;
331     int total;
332
333     total = 0;
334
335     while (len > 0) {
336         cc = write(fd, buf, len);
337
338         if (cc < 0)
339             return -1;
340
341         buf += cc;
342         total += cc;
343         len -= cc;
344     }
345
346     return total;
347 }
348 #endif
349
350
351 #if defined BB_TAR || defined BB_TAIL
352 /*
353  * Read all of the supplied buffer from a file.
354  * This does multiple reads as necessary.
355  * Returns the amount read, or -1 on an error.
356  * A short read is returned on an end of file.
357  */
358 int fullRead(int fd, char *buf, int len)
359 {
360     int cc;
361     int total;
362
363     total = 0;
364
365     while (len > 0) {
366         cc = read(fd, buf, len);
367
368         if (cc < 0)
369             return -1;
370
371         if (cc == 0)
372             break;
373
374         buf += cc;
375         total += cc;
376         len -= cc;
377     }
378
379     return total;
380 }
381 #endif
382
383
384 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_CP) || defined (BB_FIND) || defined (BB_LS) || defined (BB_INSMOD)
385 /*
386  * Walk down all the directories under the specified 
387  * location, and do something (something specified
388  * by the fileAction and dirAction function pointers).
389  *
390  * Unfortunatly, while nftw(3) could replace this and reduce 
391  * code size a bit, nftw() wasn't supported before GNU libc 2.1, 
392  * and so isn't sufficiently portable to take over since glibc2.1
393  * is so stinking huge.
394  */
395 int
396 recursiveAction(const char *fileName, int recurse, int followLinks, int depthFirst,
397                 int (*fileAction) (const char *fileName, struct stat* statbuf),
398                 int (*dirAction) (const char *fileName, struct stat* statbuf))
399 {
400     int status;
401     struct stat statbuf, statbuf1;
402     struct dirent *next;
403
404     if (followLinks == TRUE)
405         status = stat(fileName, &statbuf);
406     else
407         status = lstat(fileName, &statbuf);
408
409     status = lstat(fileName, &statbuf);
410     if (status < 0) {
411         perror(fileName);
412         return (FALSE);
413     }
414
415     if ( (followLinks == FALSE) && (S_ISLNK(statbuf.st_mode)) ) {
416         if (fileAction == NULL)
417             return (TRUE);
418         else
419             return (fileAction(fileName, &statbuf));
420     }
421
422     if (recurse == FALSE) {
423         if (S_ISDIR(statbuf.st_mode)) {
424             if (dirAction != NULL)
425                 return (dirAction(fileName, &statbuf));
426             else
427                 return (TRUE);
428         } 
429     }
430     
431     status = lstat(fileName, &statbuf1);
432     if (status < 0) {
433         perror(fileName);
434         return (FALSE);
435     }
436
437     if (S_ISDIR(statbuf.st_mode) && S_ISDIR(statbuf1.st_mode)) {
438         DIR *dir;
439         dir = opendir(fileName);
440         if (!dir) {
441             perror(fileName);
442             return (FALSE);
443         }
444         if (dirAction != NULL && depthFirst == FALSE) {
445             status = dirAction(fileName, &statbuf);
446             if (status == FALSE) {
447                 perror(fileName);
448                 return (FALSE);
449             }
450         }
451         while ((next = readdir(dir)) != NULL) {
452             char nextFile[NAME_MAX];
453             if ((strcmp(next->d_name, "..") == 0)
454                 || (strcmp(next->d_name, ".") == 0)) {
455                 continue;
456             }
457             sprintf(nextFile, "%s/%s", fileName, next->d_name);
458             status =
459                 recursiveAction(nextFile, TRUE, followLinks, depthFirst, 
460                         fileAction, dirAction);
461             if (status < 0) {
462                 closedir(dir);
463                 return (FALSE);
464             }
465         }
466         status = closedir(dir);
467         if (status < 0) {
468             perror(fileName);
469             return (FALSE);
470         }
471         if (dirAction != NULL && depthFirst == TRUE) {
472             status = dirAction(fileName, &statbuf);
473             if (status == FALSE) {
474                 perror(fileName);
475                 return (FALSE);
476             }
477         }
478     } else {
479         if (fileAction == NULL)
480             return (TRUE);
481         else
482             return (fileAction(fileName, &statbuf));
483     }
484     return (TRUE);
485 }
486
487 #endif
488
489
490
491 #if defined (BB_TAR) || defined (BB_MKDIR)
492 /*
493  * Attempt to create the directories along the specified path, except for
494  * the final component.  The mode is given for the final directory only,
495  * while all previous ones get default protections.  Errors are not reported
496  * here, as failures to restore files can be reported later.
497  */
498 extern void createPath (const char *name, int mode)
499 {
500     char *cp;
501     char *cpOld;
502     char buf[NAME_MAX];
503
504     strcpy( buf, name);
505     cp = strchr (buf, '/');
506     while (cp) {
507         cpOld = cp;
508         cp = strchr (cp + 1, '/');
509         *cpOld = '\0';
510         mkdir (buf, cp ? 0777 : mode);
511         *cpOld = '/';
512     }
513 }
514 #endif
515
516
517
518 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
519 /* [ugoa]{+|-|=}[rwxst] */
520
521
522
523 extern int 
524 parse_mode( const char* s, mode_t* theMode)
525 {
526         mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
527         mode_t orMode = 0;
528         mode_t  mode = 0;
529         mode_t  groups = 0;
530         char    type;
531         char    c;
532
533         do {
534                 for ( ; ; ) {
535                         switch ( c = *s++ ) {
536                         case '\0':
537                                 return -1;
538                         case 'u':
539                                 groups |= S_ISUID|S_IRWXU;
540                                 continue;
541                         case 'g':
542                                 groups |= S_ISGID|S_IRWXG;
543                                 continue;
544                         case 'o':
545                                 groups |= S_IRWXO;
546                                 continue;
547                         case 'a':
548                                 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
549                                 continue;
550                         case '+':
551                         case '=':
552                         case '-':
553                                 type = c;
554                                 if ( groups == 0 ) /* The default is "all" */
555                                         groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
556                                 break;
557                         default:
558                                 if ( isdigit(c) && c >= '0' && c <= '7' && 
559                                                 mode == 0 && groups == 0 ) {
560                                         *theMode = strtol(--s, NULL, 8);
561                                         return (TRUE);
562                                 }
563                                 else
564                                         return (FALSE);
565                         }
566                         break;
567                 }
568
569                 while ( (c = *s++) != '\0' ) {
570                         switch ( c ) {
571                         case ',':
572                                 break;
573                         case 'r':
574                                 mode |= S_IRUSR|S_IRGRP|S_IROTH;
575                                 continue;
576                         case 'w':
577                                 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
578                                 continue;
579                         case 'x':
580                                 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
581                                 continue;
582                         case 's':
583                                 mode |= S_IXGRP|S_ISUID|S_ISGID;
584                                 continue;
585                         case 't':
586                                 mode |= 0;
587                                 continue;
588                         default:
589                                 *theMode &= andMode;
590                                 *theMode |= orMode;
591                                 return( TRUE);
592                         }
593                         break;
594                 }
595                 switch ( type ) {
596                 case '=':
597                         andMode &= ~(groups);
598                         /* fall through */
599                 case '+':
600                         orMode |= mode & groups;
601                         break;
602                 case '-':
603                         andMode &= ~(mode & groups);
604                         orMode &= andMode;
605                         break;
606                 }
607         } while ( c == ',' );
608         *theMode &= andMode;
609         *theMode |= orMode;
610         return (TRUE);
611 }
612
613
614 #endif
615
616
617
618
619
620
621
622 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
623
624 /* Use this to avoid needing the glibc NSS stuff 
625  * This uses storage buf to hold things.
626  * */
627 uid_t 
628 my_getid(const char *filename, char *name, uid_t id) 
629 {
630         FILE *file;
631         char *rname, *start, *end, buf[128];
632         uid_t rid;
633
634         file=fopen(filename,"r");
635         if (file == NULL) {
636             perror(filename);
637             return (-1);
638         }
639
640         while (fgets (buf, 128, file) != NULL) {
641                 if (buf[0] == '#')
642                         continue;
643
644                 start = buf;
645                 end = strchr (start, ':');
646                 if (end == NULL)
647                         continue;
648                 *end = '\0';
649                 rname = start;
650
651                 start = end + 1;
652                 end = strchr (start, ':');
653                 if (end == NULL)
654                         continue;
655
656                 start = end + 1;
657                 rid = (uid_t) strtol (start, &end, 10);
658                 if (end == start)
659                         continue;
660
661                 if (name) {
662                     if (0 == strcmp(rname, name)) {
663                         fclose( file);
664                         return( rid);
665                     }
666                 }
667                 if ( id != -1 && id == rid ) {
668                     strncpy(name, rname, 8);
669                     fclose( file);
670                     return( TRUE);
671                 }
672         }
673         fclose(file);
674         return (-1);
675 }
676
677 uid_t 
678 my_getpwnam(char *name) 
679 {
680     return my_getid("/etc/passwd", name, -1);
681 }
682
683 gid_t 
684 my_getgrnam(char *name) 
685 {
686     return my_getid("/etc/group", name, -1);
687 }
688
689 void
690 my_getpwuid(char* name, uid_t uid) 
691 {
692     my_getid("/etc/passwd", name, uid);
693 }
694
695 void
696 my_getgrgid(char* group, gid_t gid) 
697 {
698     my_getid("/etc/group", group, gid);
699 }
700
701
702 #endif
703
704
705
706
707 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
708
709
710 #include <linux/kd.h>
711 #include <sys/ioctl.h>
712
713 int is_a_console(int fd) 
714 {
715   char arg;
716   
717   arg = 0;
718   return (ioctl(fd, KDGKBTYPE, &arg) == 0
719           && ((arg == KB_101) || (arg == KB_84)));
720 }
721
722 static int open_a_console(char *fnam) 
723 {
724   int fd;
725   
726   /* try read-only */
727   fd = open(fnam, O_RDWR);
728   
729   /* if failed, try read-only */
730   if (fd < 0 && errno == EACCES)
731       fd = open(fnam, O_RDONLY);
732   
733   /* if failed, try write-only */
734   if (fd < 0 && errno == EACCES)
735       fd = open(fnam, O_WRONLY);
736   
737   /* if failed, fail */
738   if (fd < 0)
739       return -1;
740   
741   /* if not a console, fail */
742   if (! is_a_console(fd))
743     {
744       close(fd);
745       return -1;
746     }
747   
748   /* success */
749   return fd;
750 }
751
752 /*
753  * Get an fd for use with kbd/console ioctls.
754  * We try several things because opening /dev/console will fail
755  * if someone else used X (which does a chown on /dev/console).
756  *
757  * if tty_name is non-NULL, try this one instead.
758  */
759
760 int get_console_fd(char* tty_name) 
761 {
762   int fd;
763
764   if (tty_name)
765     {
766       if (-1 == (fd = open_a_console(tty_name)))
767         return -1;
768       else
769         return fd;
770     }
771   
772   fd = open_a_console("/dev/tty");
773   if (fd >= 0)
774     return fd;
775   
776   fd = open_a_console("/dev/tty0");
777   if (fd >= 0)
778     return fd;
779   
780   fd = open_a_console("/dev/console");
781   if (fd >= 0)
782     return fd;
783   
784   for (fd = 0; fd < 3; fd++)
785     if (is_a_console(fd))
786       return fd;
787   
788   fprintf(stderr,
789           "Couldnt get a file descriptor referring to the console\n");
790   return -1;            /* total failure */
791 }
792
793
794 #endif
795
796
797 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)  
798
799 /* Do a case insensitive strstr() */
800 char* stristr(char *haystack, const char *needle)
801 {
802     int len = strlen( needle );
803     while( *haystack ) {
804         if( !strncasecmp( haystack, needle, len ) )
805             break;
806         haystack++;
807     }
808
809     if( !(*haystack) )
810             haystack = NULL;
811
812     return haystack;
813 }
814
815 /* This tries to find a needle in a haystack, but does so by
816  * only trying to match literal strings (look 'ma, no regexps!)
817  * This is short, sweet, and carries _very_ little baggage,
818  * unlike its beefier cousin in regexp.c
819  *  -Erik Andersen
820  */
821 extern int find_match(char *haystack, char *needle, int ignoreCase)
822 {
823
824     if (ignoreCase == FALSE)
825         haystack = strstr (haystack, needle);
826     else
827         haystack = stristr (haystack, needle);
828     if (haystack == NULL)
829         return FALSE;
830     return TRUE;
831 }
832
833
834 /* This performs substitutions after a string match has been found.  */
835 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
836 {
837     int foundOne=0;
838     char *where, *slider, *slider1, *oldhayStack;
839
840     if (ignoreCase == FALSE)
841         where = strstr (haystack, needle);
842     else
843         where = stristr (haystack, needle);
844
845     if (strcmp(needle, newNeedle)==0)
846         return FALSE;
847
848     oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
849     while(where!=NULL) {
850         foundOne++;
851         strcpy(oldhayStack, haystack);
852 #if 0
853         if ( strlen(newNeedle) > strlen(needle)) {
854             haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) - 
855                 strlen(needle) + strlen(newNeedle)));
856         }
857 #endif
858         for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
859         *slider=0;
860         haystack=strcat(haystack, newNeedle);
861         slider1+=strlen(needle);
862         haystack = strcat(haystack, slider1);
863         where = strstr (slider, needle);
864     }
865     free( oldhayStack);
866
867     if (foundOne > 0)
868         return TRUE;
869     else
870         return FALSE;
871 }
872
873
874 #endif
875
876
877 #if defined BB_FIND
878 /*
879  * Routine to see if a text string is matched by a wildcard pattern.
880  * Returns TRUE if the text is matched, or FALSE if it is not matched
881  * or if the pattern is invalid.
882  *  *           matches zero or more characters
883  *  ?           matches a single character
884  *  [abc]       matches 'a', 'b' or 'c'
885  *  \c          quotes character c
886  * Adapted from code written by Ingo Wilken, and
887  * then taken from sash, Copyright (c) 1999 by David I. Bell
888  * Permission is granted to use, distribute, or modify this source,
889  * provided that this copyright notice remains intact.
890  * Permission to distribute this code under the GPL has been granted.
891  */
892 extern int
893 check_wildcard_match(const char* text, const char* pattern)
894 {
895     const char* retryPat;
896     const char* retryText;
897     int         ch;
898     int         found;
899
900     retryPat = NULL;
901     retryText = NULL;
902
903     while (*text || *pattern)
904     {
905         ch = *pattern++;
906
907         switch (ch)
908         {
909             case '*':  
910                 retryPat = pattern;
911                 retryText = text;
912                 break;
913
914             case '[':  
915                 found = FALSE;
916
917                 while ((ch = *pattern++) != ']')
918                 {
919                     if (ch == '\\')
920                         ch = *pattern++;
921
922                     if (ch == '\0')
923                         return FALSE;
924
925                     if (*text == ch)
926                         found = TRUE;
927                 }
928
929                 //if (!found)
930                 if (found==TRUE)
931                 {
932                     pattern = retryPat;
933                     text = ++retryText;
934                 }
935
936                 /* fall into next case */
937
938             case '?':  
939                 if (*text++ == '\0')
940                     return FALSE;
941
942                 break;
943
944             case '\\':  
945                 ch = *pattern++;
946
947                 if (ch == '\0')
948                         return FALSE;
949
950                 /* fall into next case */
951
952             default:        
953                 if (*text == ch)
954                 {
955                     if (*text)
956                         text++;
957                     break;
958                 }
959
960                 if (*text)
961                 {
962                     pattern = retryPat;
963                     text = ++retryText;
964                     break;
965                 }
966
967                 return FALSE;
968         }
969
970         if (pattern == NULL)
971                 return FALSE;
972     }
973
974     return TRUE;
975 }
976 #endif
977
978
979
980
981 #if defined BB_DF || defined BB_MTAB
982 /*
983  * Given a block device, find the mount table entry if that block device
984  * is mounted.
985  *
986  * Given any other file (or directory), find the mount table entry for its
987  * filesystem.
988  */
989 extern struct mntent *findMountPoint(const char *name, const char *table)
990 {
991     struct stat s;
992     dev_t mountDevice;
993     FILE *mountTable;
994     struct mntent *mountEntry;
995
996     if (stat(name, &s) != 0)
997         return 0;
998
999     if ((s.st_mode & S_IFMT) == S_IFBLK)
1000         mountDevice = s.st_rdev;
1001     else
1002         mountDevice = s.st_dev;
1003
1004
1005     if ((mountTable = setmntent(table, "r")) == 0)
1006         return 0;
1007
1008     while ((mountEntry = getmntent(mountTable)) != 0) {
1009         if (strcmp(name, mountEntry->mnt_dir) == 0
1010             || strcmp(name, mountEntry->mnt_fsname) == 0)       /* String match. */
1011             break;
1012         if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice)  /* Match the device. */
1013             break;
1014         if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice)      /* Match the directory's mount point. */
1015             break;
1016     }
1017     endmntent(mountTable);
1018     return mountEntry;
1019 }
1020 #endif
1021
1022
1023
1024 #if defined BB_DD || defined BB_TAIL
1025 /*
1026  * Read a number with a possible multiplier.
1027  * Returns -1 if the number format is illegal.
1028  */
1029 extern long getNum (const char *cp)
1030 {
1031     long value;
1032
1033     if (!isDecimal (*cp))
1034         return -1;
1035
1036     value = 0;
1037
1038     while (isDecimal (*cp))
1039         value = value * 10 + *cp++ - '0';
1040
1041     switch (*cp++) {
1042     case 'm':
1043         value *= 1048576;
1044         break;
1045
1046     case 'k':
1047         value *= 1024;
1048         break;
1049
1050     case 'b':
1051         value *= 512;
1052         break;
1053
1054     case 'w':
1055         value *= 2;
1056         break;
1057
1058     case '\0':
1059         return value;
1060
1061     default:
1062         return -1;
1063     }
1064
1065     if (*cp)
1066         return -1;
1067
1068     return value;
1069 }
1070 #endif
1071
1072
1073 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT 
1074
1075 #if ! defined BB_FEATURE_USE_PROCFS
1076 #error Sorry, I depend on the /proc filesystem right now.
1077 #endif
1078 /* findInitPid()
1079  *  
1080  *  This finds the pid of init (which is not always 1).
1081  *  Currently, it's implemented by rummaging through the proc filesystem.
1082  *
1083  *  [return]
1084  *  0       failure
1085  *  pid     when init's pid is found.
1086  */
1087 extern pid_t
1088 findInitPid()
1089 {
1090     pid_t   init_pid;
1091     char    filename[256];
1092     char    buffer[256];
1093
1094     /* no need to opendir ;) */
1095     for (init_pid = 1; init_pid < 65536; init_pid++) {
1096         FILE    *status;
1097
1098         sprintf(filename, "/proc/%d/status", init_pid);
1099         status = fopen(filename, "r");
1100         if (!status) { continue; }
1101         fgets(buffer, 256, status);
1102         fclose(status);
1103
1104         if ( (strstr(buffer, "init\n") != NULL )) {
1105             return init_pid;
1106         }
1107     }
1108     return 0;
1109 }
1110 #endif
1111
1112 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1113 extern int vdprintf(int d, const char *format, va_list ap)
1114 {
1115     char buf[BUF_SIZE];
1116     int len;
1117
1118     len = vsprintf(buf, format, ap);
1119     return write(d, buf, len);
1120 }
1121 #endif
1122
1123 /* END CODE */