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