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