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