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