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