Making note of my changes
[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 int createPath (const char *name, int mode)
499 {
500     char *cp;
501     char *cpOld;
502     char buf[NAME_MAX];
503     int retVal=0;
504
505     strcpy( buf, name);
506     cp = strchr (buf, '/');
507     while (cp) {
508         cpOld = cp;
509         cp = strchr (cp + 1, '/');
510         *cpOld = '\0';
511         retVal = mkdir (buf, cp ? 0777 : mode);
512         *cpOld = '/';
513     }
514     /* Return the result from the final directory, as that
515      * is the one that counts */
516     if( retVal!=0) {
517         if ( errno!=EEXIST) {
518             return( FALSE);
519         }
520     }
521     return( TRUE);
522 }
523 #endif
524
525
526
527 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
528 /* [ugoa]{+|-|=}[rwxst] */
529
530
531
532 extern int 
533 parse_mode( const char* s, mode_t* theMode)
534 {
535         mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
536         mode_t orMode = 0;
537         mode_t  mode = 0;
538         mode_t  groups = 0;
539         char    type;
540         char    c;
541
542         do {
543                 for ( ; ; ) {
544                         switch ( c = *s++ ) {
545                         case '\0':
546                                 return -1;
547                         case 'u':
548                                 groups |= S_ISUID|S_IRWXU;
549                                 continue;
550                         case 'g':
551                                 groups |= S_ISGID|S_IRWXG;
552                                 continue;
553                         case 'o':
554                                 groups |= S_IRWXO;
555                                 continue;
556                         case 'a':
557                                 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
558                                 continue;
559                         case '+':
560                         case '=':
561                         case '-':
562                                 type = c;
563                                 if ( groups == 0 ) /* The default is "all" */
564                                         groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
565                                 break;
566                         default:
567                                 if ( isdigit(c) && c >= '0' && c <= '7' && 
568                                                 mode == 0 && groups == 0 ) {
569                                         *theMode = strtol(--s, NULL, 8);
570                                         return (TRUE);
571                                 }
572                                 else
573                                         return (FALSE);
574                         }
575                         break;
576                 }
577
578                 while ( (c = *s++) != '\0' ) {
579                         switch ( c ) {
580                         case ',':
581                                 break;
582                         case 'r':
583                                 mode |= S_IRUSR|S_IRGRP|S_IROTH;
584                                 continue;
585                         case 'w':
586                                 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
587                                 continue;
588                         case 'x':
589                                 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
590                                 continue;
591                         case 's':
592                                 mode |= S_IXGRP|S_ISUID|S_ISGID;
593                                 continue;
594                         case 't':
595                                 mode |= 0;
596                                 continue;
597                         default:
598                                 *theMode &= andMode;
599                                 *theMode |= orMode;
600                                 return( TRUE);
601                         }
602                         break;
603                 }
604                 switch ( type ) {
605                 case '=':
606                         andMode &= ~(groups);
607                         /* fall through */
608                 case '+':
609                         orMode |= mode & groups;
610                         break;
611                 case '-':
612                         andMode &= ~(mode & groups);
613                         orMode &= andMode;
614                         break;
615                 }
616         } while ( c == ',' );
617         *theMode &= andMode;
618         *theMode |= orMode;
619         return (TRUE);
620 }
621
622
623 #endif
624
625
626
627
628
629
630
631 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
632
633 /* Use this to avoid needing the glibc NSS stuff 
634  * This uses storage buf to hold things.
635  * */
636 uid_t 
637 my_getid(const char *filename, char *name, uid_t id) 
638 {
639         FILE *file;
640         char *rname, *start, *end, buf[128];
641         uid_t rid;
642
643         file=fopen(filename,"r");
644         if (file == NULL) {
645             perror(filename);
646             return (-1);
647         }
648
649         while (fgets (buf, 128, file) != NULL) {
650                 if (buf[0] == '#')
651                         continue;
652
653                 start = buf;
654                 end = strchr (start, ':');
655                 if (end == NULL)
656                         continue;
657                 *end = '\0';
658                 rname = start;
659
660                 start = end + 1;
661                 end = strchr (start, ':');
662                 if (end == NULL)
663                         continue;
664
665                 start = end + 1;
666                 rid = (uid_t) strtol (start, &end, 10);
667                 if (end == start)
668                         continue;
669
670                 if (name) {
671                     if (0 == strcmp(rname, name)) {
672                         fclose( file);
673                         return( rid);
674                     }
675                 }
676                 if ( id != -1 && id == rid ) {
677                     strncpy(name, rname, 8);
678                     fclose( file);
679                     return( TRUE);
680                 }
681         }
682         fclose(file);
683         return (-1);
684 }
685
686 uid_t 
687 my_getpwnam(char *name) 
688 {
689     return my_getid("/etc/passwd", name, -1);
690 }
691
692 gid_t 
693 my_getgrnam(char *name) 
694 {
695     return my_getid("/etc/group", name, -1);
696 }
697
698 void
699 my_getpwuid(char* name, uid_t uid) 
700 {
701     my_getid("/etc/passwd", name, uid);
702 }
703
704 void
705 my_getgrgid(char* group, gid_t gid) 
706 {
707     my_getid("/etc/group", group, gid);
708 }
709
710
711 #endif
712
713
714
715
716 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
717
718
719 #include <linux/kd.h>
720 #include <sys/ioctl.h>
721
722 int is_a_console(int fd) 
723 {
724   char arg;
725   
726   arg = 0;
727   return (ioctl(fd, KDGKBTYPE, &arg) == 0
728           && ((arg == KB_101) || (arg == KB_84)));
729 }
730
731 static int open_a_console(char *fnam) 
732 {
733   int fd;
734   
735   /* try read-only */
736   fd = open(fnam, O_RDWR);
737   
738   /* if failed, try read-only */
739   if (fd < 0 && errno == EACCES)
740       fd = open(fnam, O_RDONLY);
741   
742   /* if failed, try write-only */
743   if (fd < 0 && errno == EACCES)
744       fd = open(fnam, O_WRONLY);
745   
746   /* if failed, fail */
747   if (fd < 0)
748       return -1;
749   
750   /* if not a console, fail */
751   if (! is_a_console(fd))
752     {
753       close(fd);
754       return -1;
755     }
756   
757   /* success */
758   return fd;
759 }
760
761 /*
762  * Get an fd for use with kbd/console ioctls.
763  * We try several things because opening /dev/console will fail
764  * if someone else used X (which does a chown on /dev/console).
765  *
766  * if tty_name is non-NULL, try this one instead.
767  */
768
769 int get_console_fd(char* tty_name) 
770 {
771   int fd;
772
773   if (tty_name)
774     {
775       if (-1 == (fd = open_a_console(tty_name)))
776         return -1;
777       else
778         return fd;
779     }
780   
781   fd = open_a_console("/dev/tty");
782   if (fd >= 0)
783     return fd;
784   
785   fd = open_a_console("/dev/tty0");
786   if (fd >= 0)
787     return fd;
788   
789   fd = open_a_console("/dev/console");
790   if (fd >= 0)
791     return fd;
792   
793   for (fd = 0; fd < 3; fd++)
794     if (is_a_console(fd))
795       return fd;
796   
797   fprintf(stderr,
798           "Couldnt get a file descriptor referring to the console\n");
799   return -1;            /* total failure */
800 }
801
802
803 #endif
804
805
806 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_SED)  
807
808 /* Do a case insensitive strstr() */
809 char* stristr(char *haystack, const char *needle)
810 {
811     int len = strlen( needle );
812     while( *haystack ) {
813         if( !strncasecmp( haystack, needle, len ) )
814             break;
815         haystack++;
816     }
817
818     if( !(*haystack) )
819             haystack = NULL;
820
821     return haystack;
822 }
823
824 /* This tries to find a needle in a haystack, but does so by
825  * only trying to match literal strings (look 'ma, no regexps!)
826  * This is short, sweet, and carries _very_ little baggage,
827  * unlike its beefier cousin in regexp.c
828  *  -Erik Andersen
829  */
830 extern int find_match(char *haystack, char *needle, int ignoreCase)
831 {
832
833     if (ignoreCase == FALSE)
834         haystack = strstr (haystack, needle);
835     else
836         haystack = stristr (haystack, needle);
837     if (haystack == NULL)
838         return FALSE;
839     return TRUE;
840 }
841
842
843 /* This performs substitutions after a string match has been found.  */
844 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
845 {
846     int foundOne=0;
847     char *where, *slider, *slider1, *oldhayStack;
848
849     if (ignoreCase == FALSE)
850         where = strstr (haystack, needle);
851     else
852         where = stristr (haystack, needle);
853
854     if (strcmp(needle, newNeedle)==0)
855         return FALSE;
856
857     oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
858     while(where!=NULL) {
859         foundOne++;
860         strcpy(oldhayStack, haystack);
861 #if 0
862         if ( strlen(newNeedle) > strlen(needle)) {
863             haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) - 
864                 strlen(needle) + strlen(newNeedle)));
865         }
866 #endif
867         for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
868         *slider=0;
869         haystack=strcat(haystack, newNeedle);
870         slider1+=strlen(needle);
871         haystack = strcat(haystack, slider1);
872         where = strstr (slider, needle);
873     }
874     free( oldhayStack);
875
876     if (foundOne > 0)
877         return TRUE;
878     else
879         return FALSE;
880 }
881
882
883 #endif
884
885
886 #if defined BB_FIND
887 /*
888  * Routine to see if a text string is matched by a wildcard pattern.
889  * Returns TRUE if the text is matched, or FALSE if it is not matched
890  * or if the pattern is invalid.
891  *  *           matches zero or more characters
892  *  ?           matches a single character
893  *  [abc]       matches 'a', 'b' or 'c'
894  *  \c          quotes character c
895  * Adapted from code written by Ingo Wilken, and
896  * then taken from sash, Copyright (c) 1999 by David I. Bell
897  * Permission is granted to use, distribute, or modify this source,
898  * provided that this copyright notice remains intact.
899  * Permission to distribute this code under the GPL has been granted.
900  */
901 extern int
902 check_wildcard_match(const char* text, const char* pattern)
903 {
904     const char* retryPat;
905     const char* retryText;
906     int         ch;
907     int         found;
908
909     retryPat = NULL;
910     retryText = NULL;
911
912     while (*text || *pattern)
913     {
914         ch = *pattern++;
915
916         switch (ch)
917         {
918             case '*':  
919                 retryPat = pattern;
920                 retryText = text;
921                 break;
922
923             case '[':  
924                 found = FALSE;
925
926                 while ((ch = *pattern++) != ']')
927                 {
928                     if (ch == '\\')
929                         ch = *pattern++;
930
931                     if (ch == '\0')
932                         return FALSE;
933
934                     if (*text == ch)
935                         found = TRUE;
936                 }
937
938                 //if (!found)
939                 if (found==TRUE)
940                 {
941                     pattern = retryPat;
942                     text = ++retryText;
943                 }
944
945                 /* fall into next case */
946
947             case '?':  
948                 if (*text++ == '\0')
949                     return FALSE;
950
951                 break;
952
953             case '\\':  
954                 ch = *pattern++;
955
956                 if (ch == '\0')
957                         return FALSE;
958
959                 /* fall into next case */
960
961             default:        
962                 if (*text == ch)
963                 {
964                     if (*text)
965                         text++;
966                     break;
967                 }
968
969                 if (*text)
970                 {
971                     pattern = retryPat;
972                     text = ++retryText;
973                     break;
974                 }
975
976                 return FALSE;
977         }
978
979         if (pattern == NULL)
980                 return FALSE;
981     }
982
983     return TRUE;
984 }
985 #endif
986
987
988
989
990 #if defined BB_DF || defined BB_MTAB
991 /*
992  * Given a block device, find the mount table entry if that block device
993  * is mounted.
994  *
995  * Given any other file (or directory), find the mount table entry for its
996  * filesystem.
997  */
998 extern struct mntent *findMountPoint(const char *name, const char *table)
999 {
1000     struct stat s;
1001     dev_t mountDevice;
1002     FILE *mountTable;
1003     struct mntent *mountEntry;
1004
1005     if (stat(name, &s) != 0)
1006         return 0;
1007
1008     if ((s.st_mode & S_IFMT) == S_IFBLK)
1009         mountDevice = s.st_rdev;
1010     else
1011         mountDevice = s.st_dev;
1012
1013
1014     if ((mountTable = setmntent(table, "r")) == 0)
1015         return 0;
1016
1017     while ((mountEntry = getmntent(mountTable)) != 0) {
1018         if (strcmp(name, mountEntry->mnt_dir) == 0
1019             || strcmp(name, mountEntry->mnt_fsname) == 0)       /* String match. */
1020             break;
1021         if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == mountDevice)  /* Match the device. */
1022             break;
1023         if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == mountDevice)      /* Match the directory's mount point. */
1024             break;
1025     }
1026     endmntent(mountTable);
1027     return mountEntry;
1028 }
1029 #endif
1030
1031
1032
1033 #if defined BB_DD || defined BB_TAIL
1034 /*
1035  * Read a number with a possible multiplier.
1036  * Returns -1 if the number format is illegal.
1037  */
1038 extern long getNum (const char *cp)
1039 {
1040     long value;
1041
1042     if (!isDecimal (*cp))
1043         return -1;
1044
1045     value = 0;
1046
1047     while (isDecimal (*cp))
1048         value = value * 10 + *cp++ - '0';
1049
1050     switch (*cp++) {
1051     case 'm':
1052         value *= 1048576;
1053         break;
1054
1055     case 'k':
1056         value *= 1024;
1057         break;
1058
1059     case 'b':
1060         value *= 512;
1061         break;
1062
1063     case 'w':
1064         value *= 2;
1065         break;
1066
1067     case '\0':
1068         return value;
1069
1070     default:
1071         return -1;
1072     }
1073
1074     if (*cp)
1075         return -1;
1076
1077     return value;
1078 }
1079 #endif
1080
1081
1082 #if defined BB_INIT || defined BB_HALT || defined BB_REBOOT 
1083
1084 #if ! defined BB_FEATURE_USE_PROCFS
1085 #error Sorry, I depend on the /proc filesystem right now.
1086 #endif
1087 /* findInitPid()
1088  *  
1089  *  This finds the pid of init (which is not always 1).
1090  *  Currently, it's implemented by rummaging through the proc filesystem.
1091  *
1092  *  [return]
1093  *  0       failure
1094  *  pid     when init's pid is found.
1095  */
1096 extern pid_t
1097 findInitPid()
1098 {
1099     pid_t   init_pid;
1100     char    filename[256];
1101     char    buffer[256];
1102
1103     /* no need to opendir ;) */
1104     for (init_pid = 1; init_pid < 65536; init_pid++) {
1105         FILE    *status;
1106
1107         sprintf(filename, "/proc/%d/status", init_pid);
1108         status = fopen(filename, "r");
1109         if (!status) { continue; }
1110         fgets(buffer, 256, status);
1111         fclose(status);
1112
1113         if ( (strstr(buffer, "init\n") != NULL )) {
1114             return init_pid;
1115         }
1116     }
1117     return 0;
1118 }
1119 #endif
1120
1121 #if (__GLIBC__ < 2) && (defined BB_SYSLOGD || defined BB_INIT)
1122 extern int vdprintf(int d, const char *format, va_list ap)
1123 {
1124     char buf[BUF_SIZE];
1125     int len;
1126
1127     len = vsprintf(buf, format, ap);
1128     return write(d, buf, len);
1129 }
1130 #endif
1131
1132 /* END CODE */