#include <sys/cdefs.h>
__RCSID("$NetBSD: getfsspecname.c,v 1.8 2018/12/27 21:35:48 alnsn Exp $");
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>
#include <sys/disk.h>
#include <stdio.h>
#include <vis.h>
#include <string.h>
#include <fstab.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <util.h>
#define COMPAT_DKWEDGE
const char *
getfsspecname(char *buf, size_t bufsiz, const char *name)
{
static const int mib[] = { CTL_HW, HW_DISKNAMES };
static const unsigned int miblen = __arraycount(mib);
char *drives, *dk, *p;
size_t len;
int fd, savee = errno;
char *vname;
p = drives = vname = NULL;
if (strncasecmp(name, "ROOT.", 5) == 0 && strchr(name, ':') == NULL) {
static const int mib_root[] = { CTL_KERN, KERN_ROOT_DEVICE };
static const unsigned int mib_rootlen = __arraycount(mib_root);
strlcpy(buf, "/dev/", bufsiz);
len = bufsiz - 5;
if (sysctl(mib_root, mib_rootlen, buf + 5, &len, NULL, 0) == -1) {
savee = errno;
strlcpy(buf, "sysctl kern.root_device failed", bufsiz);
goto out;
}
strlcat(buf, name + 5, bufsiz);
return buf;
}
if (strncasecmp(name, "NAME=", 5) != 0) {
#ifdef COMPAT_DKWEDGE
char rbuf[MAXPATHLEN];
if (name[0] == '/') {
if (getdiskrawname(rbuf, sizeof(rbuf), name) != NULL) {
if ((fd = open(rbuf, O_RDONLY)) == -1) {
if (errno == EBUSY) {
name = strrchr(name, '/') + 1;
goto search;
}
} else
close(fd);
}
}
#endif
strlcpy(buf, name, bufsiz);
return buf;
} else
name += 5;
#ifdef COMPAT_DKWEDGE
search:
#endif
vname = malloc(strlen(name) + 1);
if (vname == NULL) {
savee = errno;
strlcpy(buf, "malloc failed", bufsiz);
goto out;
}
strunvis(vname, name);
if (sysctl(mib, miblen, NULL, &len, NULL, 0) == -1) {
savee = errno;
strlcpy(buf, "sysctl hw.disknames failed", bufsiz);
goto out;
}
drives = malloc(len);
if (drives == NULL) {
savee = errno;
strlcpy(buf, "malloc failed", bufsiz);
goto out;
}
if (sysctl(mib, miblen, drives, &len, NULL, 0) == -1) {
savee = errno;
strlcpy(buf, "sysctl hw.disknames failed", bufsiz);
goto out;
}
for (dk = strtok(drives, " "); dk != NULL; dk = strtok(NULL, " ")) {
struct dkwedge_info dkw;
if (strncmp(dk, "dk", 2) != 0)
continue;
fd = opendisk(dk, O_RDONLY, buf, bufsiz, 0);
if (fd == -1)
continue;
if (ioctl(fd, DIOCGWEDGEINFO, &dkw) == -1) {
savee = errno;
snprintf(buf, bufsiz, "%s: getwedgeinfo", dk);
(void)close(fd);
goto out;
}
(void)close(fd);
if (strcmp(vname, (char *)dkw.dkw_wname) == 0) {
p = strstr(buf, "/rdk");
goto good;
}
}
#ifdef COMPAT_DKWEDGE
fd = opendisk(name, O_RDONLY, buf, bufsiz, 0);
if (fd != -1) {
close(fd);
p = strstr(buf, "/r");
goto good;
}
#endif
savee = ESRCH;
snprintf(buf, bufsiz, "no match for `%s'", vname);
out:
buf = NULL;
good:
if (p++ != NULL)
strcpy(p, p + 1);
free(drives);
free(vname);
errno = savee;
return buf;
}