More stuff.
[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 #ifdef BB_MTAB
40 const char mtab_file[] = "/etc/mtab";
41 #else
42 #if defined BB_MOUNT || defined BB_UMOUNT || defined BB_DF
43 const char mtab_file[] = "/proc/mounts";
44 #endif
45 #endif
46
47
48 /* volatile so gcc knows this is the enod of the line */
49 volatile void usage(const char *usage)
50 {
51     fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n", BB_VER, BB_BT);
52     fprintf(stderr, "Usage: %s\n", usage);
53     exit(FALSE);
54 }
55
56
57 #if defined (BB_INIT) || defined (BB_PS)
58
59 /* Returns kernel version encoded as major*65536 + minor*256 + patch,
60  * so, for example,  to check if the kernel is greater than 2.2.11:
61  *      if (get_kernel_revision() <= 2*65536+2*256+11) { <stuff> }
62  */
63 int
64 get_kernel_revision()
65 {
66   FILE *file;
67   int major=0, minor=0, patch=0;
68   char* filename="/proc/sys/kernel/osrelease";
69
70   file = fopen(filename,"r");
71   if (file == NULL) {
72     /* bummer, /proc must not be mounted... */
73     return( 0);
74   }
75   fscanf(file,"%d.%d.%d",&major,&minor,&patch);
76   fclose(file);
77   return major*65536 + minor*256 + patch;
78 }
79
80 #endif
81
82
83
84 #if defined (BB_CP) || defined (BB_MV)
85 /*
86  * Return TRUE if a fileName is a directory.
87  * Nonexistant files return FALSE.
88  */
89 int isDirectory(const char *name)
90 {
91     struct stat statBuf;
92
93     if (stat(name, &statBuf) < 0)
94         return FALSE;
95     if (S_ISDIR(statBuf.st_mode))
96         return TRUE;
97     return(FALSE);
98 }
99
100
101 /*
102  * Copy one file to another, while possibly preserving its modes, times,
103  * and modes.  Returns TRUE if successful, or FALSE on a failure with an
104  * error message output.  (Failure is not indicted if the attributes cannot
105  * be set.)
106  *  -Erik Andersen
107  */
108 int
109 copyFile( const char *srcName, const char *destName, 
110          int setModes, int followLinks)
111 {
112     int rfd;
113     int wfd;
114     int rcc;
115     int result;
116     char buf[BUF_SIZE];
117     struct stat srcStatBuf;
118     struct stat dstStatBuf;
119     struct utimbuf times;
120
121     if (followLinks == FALSE)
122         result = stat(srcName, &srcStatBuf);
123     else 
124         result = lstat(srcName, &srcStatBuf);
125     if (result < 0) {
126         perror(srcName);
127         return FALSE;
128     }
129
130     if (followLinks == FALSE)
131         result = stat(destName, &dstStatBuf);
132     else 
133         result = lstat(destName, &dstStatBuf);
134     if (result < 0) {
135         dstStatBuf.st_ino = -1;
136         dstStatBuf.st_dev = -1;
137     }
138
139     if ((srcStatBuf.st_dev == dstStatBuf.st_dev) &&
140         (srcStatBuf.st_ino == dstStatBuf.st_ino)) {
141         fprintf(stderr, "Copying file \"%s\" to itself\n", srcName);
142         return FALSE;
143     }
144
145     if (S_ISDIR(srcStatBuf.st_mode)) {
146         //fprintf(stderr, "copying directory %s to %s\n", srcName, destName);
147         /* Make sure the directory is writable */
148         if (mkdir(destName, 0777777 ^ umask(0))) {
149             perror(destName);
150             return (FALSE);
151         }
152     } else if (S_ISLNK(srcStatBuf.st_mode)) {
153         char *link_val;
154         int link_size;
155
156         //fprintf(stderr, "copying link %s to %s\n", srcName, destName);
157         link_val = (char *) alloca(PATH_MAX + 2);
158         link_size = readlink(srcName, link_val, PATH_MAX + 1);
159         if (link_size < 0) {
160             perror(srcName);
161             return (FALSE);
162         }
163         link_val[link_size] = '\0';
164         link_size = symlink(link_val, destName);
165         if (link_size != 0) {
166             perror(destName);
167             return (FALSE);
168         }
169     } else if (S_ISFIFO(srcStatBuf.st_mode)) {
170         //fprintf(stderr, "copying fifo %s to %s\n", srcName, destName);
171         if (mkfifo(destName, 644)) {
172             perror(destName);
173             return (FALSE);
174         }
175     } else if (S_ISBLK(srcStatBuf.st_mode) || S_ISCHR(srcStatBuf.st_mode) 
176             || S_ISSOCK (srcStatBuf.st_mode)) {
177         //fprintf(stderr, "copying soc, blk, or chr %s to %s\n", srcName, destName);
178         if (mknod(destName, srcStatBuf.st_mode, srcStatBuf.st_rdev)) {
179             perror(destName);
180             return (FALSE);
181         }
182     } else if (S_ISREG(srcStatBuf.st_mode)) {
183         //fprintf(stderr, "copying regular file %s to %s\n", srcName, destName);
184         rfd = open(srcName, O_RDONLY);
185         if (rfd < 0) {
186             perror(srcName);
187             return FALSE;
188         }
189
190         wfd = creat(destName, srcStatBuf.st_mode);
191         if (wfd < 0) {
192             perror(destName);
193             close(rfd);
194             return FALSE;
195         }
196
197         while ((rcc = read(rfd, buf, sizeof(buf))) > 0) {
198             if (fullWrite(wfd, buf, rcc) < 0)
199                 goto error_exit;
200         }
201         if (rcc < 0) {
202             goto error_exit;
203         }
204
205         close(rfd);
206         if (close(wfd) < 0) {
207             return FALSE;
208         }
209     }
210
211     if (setModes == TRUE) {
212         //fprintf(stderr, "Setting permissions for %s\n", destName);
213         chmod(destName, srcStatBuf.st_mode);
214         if (followLinks == TRUE)
215             chown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
216         else
217             lchown(destName, srcStatBuf.st_uid, srcStatBuf.st_gid);
218
219         times.actime = srcStatBuf.st_atime;
220         times.modtime = srcStatBuf.st_mtime;
221
222         utime(destName, &times);
223     }
224
225     return TRUE;
226
227
228   error_exit:
229     perror(destName);
230     close(rfd);
231     close(wfd);
232
233     return FALSE;
234 }
235 #endif
236
237
238
239 #ifdef BB_TAR
240 /*
241  * Return the standard ls-like mode string from a file mode.
242  * This is static and so is overwritten on each call.
243  */
244 const char *modeString(int mode)
245 {
246     static char buf[12];
247
248     strcpy(buf, "----------");
249
250     /*
251      * Fill in the file type.
252      */
253     if (S_ISDIR(mode))
254         buf[0] = 'd';
255     if (S_ISCHR(mode))
256         buf[0] = 'c';
257     if (S_ISBLK(mode))
258         buf[0] = 'b';
259     if (S_ISFIFO(mode))
260         buf[0] = 'p';
261     if (S_ISLNK(mode))
262         buf[0] = 'l';
263     if (S_ISSOCK(mode))
264         buf[0] = 's';
265     /*
266      * Now fill in the normal file permissions.
267      */
268     if (mode & S_IRUSR)
269         buf[1] = 'r';
270     if (mode & S_IWUSR)
271         buf[2] = 'w';
272     if (mode & S_IXUSR)
273         buf[3] = 'x';
274     if (mode & S_IRGRP)
275         buf[4] = 'r';
276     if (mode & S_IWGRP)
277         buf[5] = 'w';
278     if (mode & S_IXGRP)
279         buf[6] = 'x';
280     if (mode & S_IROTH)
281         buf[7] = 'r';
282     if (mode & S_IWOTH)
283         buf[8] = 'w';
284     if (mode & S_IXOTH)
285         buf[9] = 'x';
286
287     /*
288      * Finally fill in magic stuff like suid and sticky text.
289      */
290     if (mode & S_ISUID)
291         buf[3] = ((mode & S_IXUSR) ? 's' : 'S');
292     if (mode & S_ISGID)
293         buf[6] = ((mode & S_IXGRP) ? 's' : 'S');
294     if (mode & S_ISVTX)
295         buf[9] = ((mode & S_IXOTH) ? 't' : 'T');
296
297     return buf;
298 }
299
300
301 /*
302  * Get the time string to be used for a file.
303  * This is down to the minute for new files, but only the date for old files.
304  * The string is returned from a static buffer, and so is overwritten for
305  * 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
328
329 /*
330  * Write all of the supplied buffer out to a file.
331  * This does multiple writes as necessary.
332  * Returns the amount written, or -1 on an error.
333  */
334 int fullWrite(int fd, const char *buf, int len)
335 {
336     int cc;
337     int total;
338
339     total = 0;
340
341     while (len > 0) {
342         cc = write(fd, buf, len);
343
344         if (cc < 0)
345             return -1;
346
347         buf += cc;
348         total += cc;
349         len -= cc;
350     }
351
352     return total;
353 }
354
355
356 /*
357  * Read all of the supplied buffer from a file.
358  * This does multiple reads as necessary.
359  * Returns the amount read, or -1 on an error.
360  * A short read is returned on an end of file.
361  */
362 int fullRead(int fd, char *buf, int len)
363 {
364     int cc;
365     int total;
366
367     total = 0;
368
369     while (len > 0) {
370         cc = read(fd, buf, len);
371
372         if (cc < 0)
373             return -1;
374
375         if (cc == 0)
376             break;
377
378         buf += cc;
379         total += cc;
380         len -= cc;
381     }
382
383     return total;
384 }
385 #endif
386
387
388 #if defined (BB_CHOWN) || defined (BB_CP) || defined (BB_FIND) || defined (BB_LS)
389 /*
390  * Walk down all the directories under the specified 
391  * location, and do something (something specified
392  * by the fileAction and dirAction function pointers).
393  *
394  * Unfortunatly, while nftw(3) could replace this and reduce 
395  * code size a bit, nftw() wasn't supported before GNU libc 2.1, 
396  * and so isn't sufficiently portable to take over...
397  */
398 int
399 recursiveAction(const char *fileName, int recurse, int followLinks, int depthFirst,
400                 int (*fileAction) (const char *fileName, struct stat* statbuf),
401                 int (*dirAction) (const char *fileName, struct stat* statbuf))
402 {
403     int status;
404     struct stat statbuf;
405     struct dirent *next;
406
407     if (followLinks == FALSE)
408         status = stat(fileName, &statbuf);
409     else
410         status = lstat(fileName, &statbuf);
411
412     if (status < 0) {
413         perror(fileName);
414         return (FALSE);
415     }
416
417     if (recurse == FALSE) {
418         if (S_ISDIR(statbuf.st_mode)) {
419             if (dirAction != NULL)
420                 return (dirAction(fileName, &statbuf));
421             else
422                 return (TRUE);
423         } 
424     }
425
426     if (S_ISDIR(statbuf.st_mode)) {
427         DIR *dir;
428         dir = opendir(fileName);
429         if (!dir) {
430             perror(fileName);
431             return (FALSE);
432         }
433         if (dirAction != NULL && depthFirst == FALSE) {
434             status = dirAction(fileName, &statbuf);
435             if (status == FALSE) {
436                 perror(fileName);
437                 return (FALSE);
438             }
439         }
440         while ((next = readdir(dir)) != NULL) {
441             char nextFile[NAME_MAX];
442             if ((strcmp(next->d_name, "..") == 0)
443                 || (strcmp(next->d_name, ".") == 0)) {
444                 continue;
445             }
446             sprintf(nextFile, "%s/%s", fileName, next->d_name);
447             status =
448                 recursiveAction(nextFile, TRUE, followLinks, depthFirst, 
449                         fileAction, dirAction);
450             if (status < 0) {
451                 closedir(dir);
452                 return (FALSE);
453             }
454         }
455         status = closedir(dir);
456         if (status < 0) {
457             perror(fileName);
458             return (FALSE);
459         }
460         if (dirAction != NULL && depthFirst == TRUE) {
461             status = dirAction(fileName, &statbuf);
462             if (status == FALSE) {
463                 perror(fileName);
464                 return (FALSE);
465             }
466         }
467     } else {
468         if (fileAction == NULL)
469             return (TRUE);
470         else
471             return (fileAction(fileName, &statbuf));
472     }
473     return (TRUE);
474 }
475
476 #endif
477
478
479
480 #if defined (BB_TAR) || defined (BB_MKDIR)
481 /*
482  * Attempt to create the directories along the specified path, except for
483  * the final component.  The mode is given for the final directory only,
484  * while all previous ones get default protections.  Errors are not reported
485  * here, as failures to restore files can be reported later.
486  */
487 extern void createPath (const char *name, int mode)
488 {
489     char *cp;
490     char *cpOld;
491     char buf[NAME_MAX];
492
493     strcpy (buf, name);
494
495     cp = strchr (buf, '/');
496
497     while (cp) {
498         cpOld = cp;
499         cp = strchr (cp + 1, '/');
500
501         *cpOld = '\0';
502
503         if (mkdir (buf, cp ? 0777 : mode) == 0)
504             printf ("Directory \"%s\" created\n", buf);
505
506         *cpOld = '/';
507     }
508 }
509 #endif
510
511
512
513 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_MKDIR)
514 /* [ugoa]{+|-|=}[rwxst] */
515
516
517
518 extern int 
519 parse_mode( const char* s, mode_t* theMode)
520 {
521         mode_t andMode = S_ISVTX|S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
522         mode_t orMode = 0;
523         mode_t  mode = 0;
524         mode_t  groups = 0;
525         char    type;
526         char    c;
527
528         do {
529                 for ( ; ; ) {
530                         switch ( c = *s++ ) {
531                         case '\0':
532                                 return -1;
533                         case 'u':
534                                 groups |= S_ISUID|S_IRWXU;
535                                 continue;
536                         case 'g':
537                                 groups |= S_ISGID|S_IRWXG;
538                                 continue;
539                         case 'o':
540                                 groups |= S_IRWXO;
541                                 continue;
542                         case 'a':
543                                 groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
544                                 continue;
545                         case '+':
546                         case '=':
547                         case '-':
548                                 type = c;
549                                 if ( groups == 0 ) /* The default is "all" */
550                                         groups |= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
551                                 break;
552                         default:
553                                 if ( isdigit(c) && c >= '0' && c <= '7' && 
554                                                 mode == 0 && groups == 0 ) {
555                                         *theMode = strtol(--s, NULL, 8);
556                                         return (TRUE);
557                                 }
558                                 else
559                                         return (FALSE);
560                         }
561                         break;
562                 }
563
564                 while ( (c = *s++) != '\0' ) {
565                         switch ( c ) {
566                         case ',':
567                                 break;
568                         case 'r':
569                                 mode |= S_IRUSR|S_IRGRP|S_IROTH;
570                                 continue;
571                         case 'w':
572                                 mode |= S_IWUSR|S_IWGRP|S_IWOTH;
573                                 continue;
574                         case 'x':
575                                 mode |= S_IXUSR|S_IXGRP|S_IXOTH;
576                                 continue;
577                         case 's':
578                                 mode |= S_IXGRP|S_ISUID|S_ISGID;
579                                 continue;
580                         case 't':
581                                 mode |= 0;
582                                 continue;
583                         default:
584                                 *theMode &= andMode;
585                                 *theMode |= orMode;
586                                 return( TRUE);
587                         }
588                         break;
589                 }
590                 switch ( type ) {
591                 case '=':
592                         andMode &= ~(groups);
593                         /* fall through */
594                 case '+':
595                         orMode |= mode & groups;
596                         break;
597                 case '-':
598                         andMode &= ~(mode & groups);
599                         orMode &= andMode;
600                         break;
601                 }
602         } while ( c == ',' );
603         *theMode &= andMode;
604         *theMode |= orMode;
605         return (TRUE);
606 }
607
608
609 #endif
610
611
612
613
614
615
616
617 #if defined (BB_CHMOD_CHOWN_CHGRP) || defined (BB_PS)
618
619 /* Use this to avoid needing the glibc NSS stuff 
620  * This uses storage buf to hold things.
621  * */
622 uid_t 
623 my_getid(const char *filename, char *name, uid_t id) 
624 {
625         FILE *file;
626         char *rname, *start, *end, buf[128];
627         uid_t rid;
628
629         file=fopen(filename,"r");
630         if (file == NULL) {
631             perror(filename);
632             return (-1);
633         }
634
635         while (fgets (buf, 128, file) != NULL) {
636                 if (buf[0] == '#')
637                         continue;
638
639                 start = buf;
640                 end = strchr (start, ':');
641                 if (end == NULL)
642                         continue;
643                 *end = '\0';
644                 rname = start;
645
646                 start = end + 1;
647                 end = strchr (start, ':');
648                 if (end == NULL)
649                         continue;
650
651                 start = end + 1;
652                 rid = (uid_t) strtol (start, &end, 10);
653                 if (end == start)
654                         continue;
655
656                 if (name) {
657                     if (0 == strcmp(rname, name))
658                         return( rid);
659                 }
660                 if ( id != -1 && id == rid ) {
661                     strncpy(name, rname, 8);
662                     return( TRUE);
663                 }
664         }
665         fclose(file);
666         return (-1);
667 }
668
669 uid_t 
670 my_getpwnam(char *name) 
671 {
672     return my_getid("/etc/passwd", name, -1);
673 }
674
675 gid_t 
676 my_getgrnam(char *name) 
677 {
678     return my_getid("/etc/group", name, -1);
679 }
680
681 void
682 my_getpwuid(char* name, uid_t uid) 
683 {
684     my_getid("/etc/passwd", name, uid);
685 }
686
687 void
688 my_getgrgid(char* group, gid_t gid) 
689 {
690     my_getid("/etc/group", group, gid);
691 }
692
693
694 #endif
695
696
697
698
699 #if (defined BB_CHVT) || (defined BB_DEALLOCVT)
700
701
702 #include <linux/kd.h>
703 #include <sys/ioctl.h>
704
705 int is_a_console(int fd) 
706 {
707   char arg;
708   
709   arg = 0;
710   return (ioctl(fd, KDGKBTYPE, &arg) == 0
711           && ((arg == KB_101) || (arg == KB_84)));
712 }
713
714 static int open_a_console(char *fnam) 
715 {
716   int fd;
717   
718   /* try read-only */
719   fd = open(fnam, O_RDWR);
720   
721   /* if failed, try read-only */
722   if (fd < 0 && errno == EACCES)
723       fd = open(fnam, O_RDONLY);
724   
725   /* if failed, try write-only */
726   if (fd < 0 && errno == EACCES)
727       fd = open(fnam, O_WRONLY);
728   
729   /* if failed, fail */
730   if (fd < 0)
731       return -1;
732   
733   /* if not a console, fail */
734   if (! is_a_console(fd))
735     {
736       close(fd);
737       return -1;
738     }
739   
740   /* success */
741   return fd;
742 }
743
744 /*
745  * Get an fd for use with kbd/console ioctls.
746  * We try several things because opening /dev/console will fail
747  * if someone else used X (which does a chown on /dev/console).
748  *
749  * if tty_name is non-NULL, try this one instead.
750  */
751
752 int get_console_fd(char* tty_name) 
753 {
754   int fd;
755
756   if (tty_name)
757     {
758       if (-1 == (fd = open_a_console(tty_name)))
759         return -1;
760       else
761         return fd;
762     }
763   
764   fd = open_a_console("/dev/tty");
765   if (fd >= 0)
766     return fd;
767   
768   fd = open_a_console("/dev/tty0");
769   if (fd >= 0)
770     return fd;
771   
772   fd = open_a_console("/dev/console");
773   if (fd >= 0)
774     return fd;
775   
776   for (fd = 0; fd < 3; fd++)
777     if (is_a_console(fd))
778       return fd;
779   
780   fprintf(stderr,
781           "Couldnt get a file descriptor referring to the console\n");
782   return -1;            /* total failure */
783 }
784
785
786 #endif
787
788
789 #if !defined BB_REGEXP && (defined BB_GREP || defined BB_FIND || defined BB_SED)  
790
791 /* Do a case insensitive strstr() */
792 char* stristr(char *haystack, const char *needle)
793 {
794     int len = strlen( needle );
795     while( *haystack ) {
796         if( !strncasecmp( haystack, needle, len ) )
797             break;
798         haystack++;
799     }
800
801     if( !(*haystack) )
802             haystack = NULL;
803
804     return haystack;
805 }
806
807 /* This tries to find a needle in a haystack, but does so by
808  * only trying to match literal strings (look 'ma, no regexps!)
809  * This is short, sweet, and carries _very_ little baggage,
810  * unlike its beefier cousin in regexp.c
811  *  -Erik Andersen
812  */
813 extern int find_match(char *haystack, char *needle, int ignoreCase)
814 {
815
816     if (ignoreCase == FALSE)
817         haystack = strstr (haystack, needle);
818     else
819         haystack = stristr (haystack, needle);
820     if (haystack == NULL)
821         return FALSE;
822     return TRUE;
823 }
824
825
826 /* This performs substitutions after a string match has been found.  */
827 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
828 {
829     int foundOne=0;
830     char *where, *slider, *slider1, *oldhayStack;
831
832     if (ignoreCase == FALSE)
833         where = strstr (haystack, needle);
834     else
835         where = stristr (haystack, needle);
836
837     if (strcmp(needle, newNeedle)==0)
838         return FALSE;
839
840     oldhayStack = (char*)malloc((unsigned)(strlen(haystack)));
841     while(where!=NULL) {
842         foundOne++;
843         strcpy(oldhayStack, haystack);
844 #if 0
845         if ( strlen(newNeedle) > strlen(needle)) {
846             haystack = (char *)realloc(haystack, (unsigned)(strlen(haystack) - 
847                 strlen(needle) + strlen(newNeedle)));
848         }
849 #endif
850         for(slider=haystack,slider1=oldhayStack;slider!=where;slider++,slider1++);
851         *slider=0;
852         haystack=strcat(haystack, newNeedle);
853         slider1+=strlen(needle);
854         haystack = strcat(haystack, slider1);
855         where = strstr (slider, needle);
856     }
857     free( oldhayStack);
858
859     if (foundOne > 0)
860         return TRUE;
861     else
862         return FALSE;
863 }
864
865
866 #endif
867 /* END CODE */
868