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