blob: 7182102c71962feb894511cf126f7761f6211ff5 [file] [log] [blame]
Eric Andersenaad1a882001-03-16 22:47:14 +00001/* vi: set sw=4 ts=4: */
2/*
Eric Andersenbdfd0d72001-10-24 05:00:29 +00003 * Utility routines.
Eric Andersenaad1a882001-03-16 22:47:14 +00004 *
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersenaad1a882001-03-16 22:47:14 +00006 *
"Robert P. J. Day"5d8843e2006-07-10 11:41:19 +00007 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
Eric Andersenaad1a882001-03-16 22:47:14 +00008 */
9
Eric Andersenaad1a882001-03-16 22:47:14 +000010#include "libbb.h"
11
Denis Vlasenko16abcd92007-04-13 23:59:52 +000012/* Find block device /dev/XXX which contains specified file
13 * We handle /dev/dir/dir/dir too, at a cost of ~80 more bytes code */
14
15/* Do not reallocate all this stuff on each recursion */
16enum { DEVNAME_MAX = 256 };
17struct arena {
18 struct stat st;
19 dev_t dev;
20 /* Was PATH_MAX, but we recurse _/dev_. We can assume
21 * people are not crazy enough to have mega-deep tree there */
22 char devpath[DEVNAME_MAX];
23};
24
25static char *find_block_device_in_dir(struct arena *ap)
Eric Andersenaad1a882001-03-16 22:47:14 +000026{
27 DIR *dir;
28 struct dirent *entry;
Denis Vlasenko16abcd92007-04-13 23:59:52 +000029 char *retpath = NULL;
30 int len, rem;
Eric Andersenaad1a882001-03-16 22:47:14 +000031
Denis Vlasenko16abcd92007-04-13 23:59:52 +000032 dir = opendir(ap->devpath);
33 if (!dir)
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000034 return NULL;
Denis Vlasenko16abcd92007-04-13 23:59:52 +000035
36 len = strlen(ap->devpath);
37 rem = DEVNAME_MAX-2 - len;
38 if (rem <= 0)
39 return NULL;
40 ap->devpath[len++] = '/';
41
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000042 while ((entry = readdir(dir)) != NULL) {
Denis Vlasenko16abcd92007-04-13 23:59:52 +000043 safe_strncpy(ap->devpath + len, entry->d_name, rem);
44 if (stat(ap->devpath, &ap->st) != 0)
45 continue;
46 if (S_ISBLK(ap->st.st_mode) && ap->st.st_rdev == ap->dev) {
47 retpath = xstrdup(ap->devpath);
Rob Landley6a6798b2005-08-10 20:35:54 +000048 break;
Eric Andersenaad1a882001-03-16 22:47:14 +000049 }
Denis Vlasenko16abcd92007-04-13 23:59:52 +000050 if (S_ISDIR(ap->st.st_mode)) {
51 /* Do not recurse for '.' and '..' */
52 if (DOT_OR_DOTDOT(entry->d_name))
53 continue;
54 retpath = find_block_device_in_dir(ap);
55 if (retpath)
56 break;
57 }
Eric Andersenaad1a882001-03-16 22:47:14 +000058 }
Rob Landley6a6798b2005-08-10 20:35:54 +000059 closedir(dir);
60
61 return retpath;
Eric Andersenaad1a882001-03-16 22:47:14 +000062}
Denis Vlasenko16abcd92007-04-13 23:59:52 +000063
64char *find_block_device(const char *path)
65{
66 struct arena a;
67
68 if (stat(path, &a.st) != 0)
69 return NULL;
70 a.dev = S_ISBLK(a.st.st_mode) ? a.st.st_rdev : a.st.st_dev;
71 strcpy(a.devpath, "/dev");
72 return find_block_device_in_dir(&a);
73}