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