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