1/* vi: set sw=4 ts=4: */
2/*
3 * Utility routines.
4 *
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6 *
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8 */
9
10#include "libbb.h"
11
12
13/* Do not reallocate all this stuff on each recursion */
14enum { DEVNAME_MAX = 256 };
15struct arena {
16	struct stat st;
17	dev_t dev;
18	/* Was PATH_MAX, but we recurse _/dev_. We can assume
19	 * people are not crazy enough to have mega-deep tree there */
20	char devpath[DEVNAME_MAX];
21};
22
23static char *find_block_device_in_dir(struct arena *ap)
24{
25	DIR *dir;
26	struct dirent *entry;
27	char *retpath = NULL;
28	int len, rem;
29
30	dir = opendir(ap->devpath);
31	if (!dir)
32		return NULL;
33
34	len = strlen(ap->devpath);
35	rem = DEVNAME_MAX-2 - len;
36	if (rem <= 0)
37		return NULL;
38	ap->devpath[len++] = '/';
39
40	while ((entry = readdir(dir)) != NULL) {
41		safe_strncpy(ap->devpath + len, entry->d_name, rem);
42		/* lstat: do not follow links */
43		if (lstat(ap->devpath, &ap->st) != 0)
44			continue;
45		if (S_ISBLK(ap->st.st_mode) && ap->st.st_rdev == ap->dev) {
46			retpath = xstrdup(ap->devpath);
47			break;
48		}
49		if (S_ISDIR(ap->st.st_mode)) {
50			/* Do not recurse for '.' and '..' */
51			if (DOT_OR_DOTDOT(entry->d_name))
52				continue;
53			retpath = find_block_device_in_dir(ap);
54			if (retpath)
55				break;
56		}
57	}
58	closedir(dir);
59
60	return retpath;
61}
62
63char *find_block_device(const char *path)
64{
65	struct arena a;
66
67	if (stat(path, &a.st) != 0)
68		return NULL;
69	a.dev = S_ISBLK(a.st.st_mode) ? a.st.st_rdev : a.st.st_dev;
70	strcpy(a.devpath, "/dev");
71	return find_block_device_in_dir(&a);
72}
73