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