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