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