1 /*
2  * devname.c - get a dev by its device inode name
3  *
4  * Copyright (C) Andries Brouwer
5  * Copyright (C) 1999, 2000, 2001, 2002, 2003 Theodore Ts'o
6  * Copyright (C) 2001 Andreas Dilger
7  *
8  * %Begin-Header%
9  * This file may be redistributed under the terms of the
10  * GNU Lesser General Public License.
11  * %End-Header%
12  */
13 
14 #define _GNU_SOURCE 1
15 
16 #include "config.h"
17 #include <stdio.h>
18 #include <string.h>
19 #include <limits.h>
20 #if HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #if HAVE_SYS_TYPES_H
27 #include <sys/types.h>
28 #endif
29 #include <dirent.h>
30 #if HAVE_SYS_STAT_H
31 #include <sys/stat.h>
32 #endif
33 #if HAVE_ERRNO_H
34 #include <errno.h>
35 #endif
36 #if HAVE_SYS_MKDEV_H
37 #include <sys/mkdev.h>
38 #endif
39 #ifdef HAVE_SYS_SYSMACROS_H
40 #include <sys/sysmacros.h>
41 #endif
42 #include <time.h>
43 #ifdef __FreeBSD__
44 #include <sys/sysctl.h>
45 #endif
46 
47 #include "blkidP.h"
48 
49 /*
50  * Find a dev struct in the cache by device name, if available.
51  *
52  * If there is no entry with the specified device name, and the create
53  * flag is set, then create an empty device entry.
54  */
blkid_get_dev(blkid_cache cache,const char * devname,int flags)55 blkid_dev blkid_get_dev(blkid_cache cache, const char *devname, int flags)
56 {
57 	blkid_dev dev = NULL, tmp;
58 	struct list_head *p, *pnext;
59 
60 	if (!cache || !devname)
61 		return NULL;
62 
63 	list_for_each(p, &cache->bic_devs) {
64 		tmp = list_entry(p, struct blkid_struct_dev, bid_devs);
65 		if (strcmp(tmp->bid_name, devname))
66 			continue;
67 
68 		DBG(DEBUG_DEVNAME,
69 		    printf("found devname %s in cache\n", tmp->bid_name));
70 		dev = tmp;
71 		break;
72 	}
73 
74 	if (!dev && (flags & BLKID_DEV_CREATE)) {
75 		if (access(devname, F_OK) < 0)
76 			return NULL;
77 		dev = blkid_new_dev();
78 		if (!dev)
79 			return NULL;
80 		dev->bid_time = INT_MIN;
81 		dev->bid_name = blkid_strdup(devname);
82 		dev->bid_cache = cache;
83 		list_add_tail(&dev->bid_devs, &cache->bic_devs);
84 		cache->bic_flags |= BLKID_BIC_FL_CHANGED;
85 	}
86 
87 	if (flags & BLKID_DEV_VERIFY) {
88 		dev = blkid_verify(cache, dev);
89 		if (!dev || !(dev->bid_flags & BLKID_BID_FL_VERIFIED))
90 			return dev;
91 		/*
92 		 * If the device is verified, then search the blkid
93 		 * cache for any entries that match on the type, uuid,
94 		 * and label, and verify them; if a cache entry can
95 		 * not be verified, then it's stale and so we remove
96 		 * it.
97 		 */
98 		list_for_each_safe(p, pnext, &cache->bic_devs) {
99 			blkid_dev dev2;
100 			dev2 = list_entry(p, struct blkid_struct_dev, bid_devs);
101 			if (dev2->bid_flags & BLKID_BID_FL_VERIFIED)
102 				continue;
103 			if (!dev->bid_type || !dev2->bid_type ||
104 			    strcmp(dev->bid_type, dev2->bid_type))
105 				continue;
106 			if (dev->bid_label && dev2->bid_label &&
107 			    strcmp(dev->bid_label, dev2->bid_label))
108 				continue;
109 			if (dev->bid_uuid && dev2->bid_uuid &&
110 			    strcmp(dev->bid_uuid, dev2->bid_uuid))
111 				continue;
112 			if ((dev->bid_label && !dev2->bid_label) ||
113 			    (!dev->bid_label && dev2->bid_label) ||
114 			    (dev->bid_uuid && !dev2->bid_uuid) ||
115 			    (!dev->bid_uuid && dev2->bid_uuid))
116 				continue;
117 			dev2 = blkid_verify(cache, dev2);
118 			if (dev2 && !(dev2->bid_flags & BLKID_BID_FL_VERIFIED))
119 				blkid_free_dev(dev2);
120 		}
121 	}
122 	return dev;
123 }
124 
125 /* Directories where we will try to search for device names */
126 static const char *dirlist[] = { "/dev", "/devfs", "/devices", NULL };
127 
is_dm_leaf(const char * devname)128 static int is_dm_leaf(const char *devname)
129 {
130 	struct dirent	*de, *d_de;
131 	DIR		*dir, *d_dir;
132 	char		path[300];
133 	int		ret = 1;
134 
135 	if ((dir = opendir("/sys/block")) == NULL)
136 		return 0;
137 	while ((de = readdir(dir)) != NULL) {
138 		if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..") ||
139 		    !strcmp(de->d_name, devname) ||
140 		    strncmp(de->d_name, "dm-", 3) ||
141 		    strlen(de->d_name) > sizeof(path)-32)
142 			continue;
143 		sprintf(path, "/sys/block/%s/slaves", de->d_name);
144 		if ((d_dir = opendir(path)) == NULL)
145 			continue;
146 		while ((d_de = readdir(d_dir)) != NULL) {
147 			if (!strcmp(d_de->d_name, devname)) {
148 				ret = 0;
149 				break;
150 			}
151 		}
152 		closedir(d_dir);
153 		if (!ret)
154 			break;
155 	}
156 	closedir(dir);
157 	return ret;
158 }
159 
160 /*
161  * Since 2.6.29 (patch 784aae735d9b0bba3f8b9faef4c8b30df3bf0128) kernel sysfs
162  * provides the real DM device names in /sys/block/<ptname>/dm/name
163  */
get_dm_name(const char * ptname)164 static char *get_dm_name(const char *ptname)
165 {
166 	FILE	*f;
167 	size_t	sz;
168 	char	path[300], name[256], *res = NULL;
169 
170 	snprintf(path, sizeof(path), "/sys/block/%s/dm/name", ptname);
171 	if ((f = fopen(path, "r")) == NULL)
172 		return NULL;
173 
174 	/* read "<name>\n" from sysfs */
175 	if (fgets(name, sizeof(name), f) && (sz = strlen(name)) > 1) {
176 		name[sz - 1] = '\0';
177 		snprintf(path, sizeof(path), "/dev/mapper/%s", name);
178 		res = blkid_strdup(path);
179 	}
180 	fclose(f);
181 	return res;
182 }
183 
184 /*
185  * Probe a single block device to add to the device cache.
186  */
probe_one(blkid_cache cache,const char * ptname,dev_t devno,int pri,int only_if_new)187 static void probe_one(blkid_cache cache, const char *ptname,
188 		      dev_t devno, int pri, int only_if_new)
189 {
190 	blkid_dev dev = NULL;
191 	struct list_head *p, *pnext;
192 	const char **dir;
193 	char *devname = NULL;
194 
195 	/* See if we already have this device number in the cache. */
196 	list_for_each_safe(p, pnext, &cache->bic_devs) {
197 		blkid_dev tmp = list_entry(p, struct blkid_struct_dev,
198 					   bid_devs);
199 		if (tmp->bid_devno == devno) {
200 			if (only_if_new && !access(tmp->bid_name, F_OK))
201 				return;
202 			dev = blkid_verify(cache, tmp);
203 			if (dev && (dev->bid_flags & BLKID_BID_FL_VERIFIED))
204 				break;
205 			dev = 0;
206 		}
207 	}
208 	if (dev && dev->bid_devno == devno)
209 		goto set_pri;
210 
211 	/* Try to translate private device-mapper dm-<N> names
212 	 * to standard /dev/mapper/<name>.
213 	 */
214 	if (!strncmp(ptname, "dm-", 3) && isdigit(ptname[3])) {
215 		devname = get_dm_name(ptname);
216 		if (!devname)
217 			blkid__scan_dir("/dev/mapper", devno, 0, &devname);
218 		if (devname)
219 			goto get_dev;
220 	}
221 
222 	/*
223 	 * Take a quick look at /dev/ptname for the device number.  We check
224 	 * all of the likely device directories.  If we don't find it, or if
225 	 * the stat information doesn't check out, use blkid_devno_to_devname()
226 	 * to find it via an exhaustive search for the device major/minor.
227 	 */
228 	for (dir = dirlist; *dir; dir++) {
229 		struct stat st;
230 		char device[256];
231 
232 		sprintf(device, "%s/%s", *dir, ptname);
233 		if ((dev = blkid_get_dev(cache, device, BLKID_DEV_FIND)) &&
234 		    dev->bid_devno == devno)
235 			goto set_pri;
236 
237 		if (stat(device, &st) == 0 &&
238 		    blkidP_is_disk_device(st.st_mode) &&
239 		    st.st_rdev == devno) {
240 			devname = blkid_strdup(device);
241 			goto get_dev;
242 		}
243 	}
244 	/* Do a short-cut scan of /dev/mapper first */
245 	if (!devname)
246 		devname = get_dm_name(ptname);
247 	if (!devname)
248 		blkid__scan_dir("/dev/mapper", devno, 0, &devname);
249 	if (!devname) {
250 		devname = blkid_devno_to_devname(devno);
251 		if (!devname)
252 			return;
253 	}
254 get_dev:
255 	dev = blkid_get_dev(cache, devname, BLKID_DEV_NORMAL);
256 	free(devname);
257 set_pri:
258 	if (dev) {
259 		if (pri)
260 			dev->bid_pri = pri;
261 		else if (!strncmp(dev->bid_name, "/dev/mapper/", 11)) {
262 			dev->bid_pri = BLKID_PRI_DM;
263 			if (is_dm_leaf(ptname))
264 				dev->bid_pri += 5;
265 		} else if (!strncmp(ptname, "md", 2))
266 			dev->bid_pri = BLKID_PRI_MD;
267  	}
268 	return;
269 }
270 
271 #define PROC_PARTITIONS "/proc/partitions"
272 #define VG_DIR		"/proc/lvm/VGs"
273 
274 /*
275  * This function initializes the UUID cache with devices from the LVM
276  * proc hierarchy.  We currently depend on the names of the LVM
277  * hierarchy giving us the device structure in /dev.  (XXX is this a
278  * safe thing to do?)
279  */
280 #ifdef VG_DIR
lvm_get_devno(const char * lvm_device)281 static dev_t lvm_get_devno(const char *lvm_device)
282 {
283 	FILE *lvf;
284 	char buf[1024];
285 	int ma, mi;
286 	dev_t ret = 0;
287 
288 	DBG(DEBUG_DEVNAME, printf("opening %s\n", lvm_device));
289 	if ((lvf = fopen(lvm_device, "r")) == NULL) {
290 		DBG(DEBUG_DEVNAME, printf("%s: (%d) %s\n", lvm_device, errno,
291 					  strerror(errno)));
292 		return 0;
293 	}
294 
295 	while (fgets(buf, sizeof(buf), lvf)) {
296 		if (sscanf(buf, "device: %d:%d", &ma, &mi) == 2) {
297 			ret = makedev(ma, mi);
298 			break;
299 		}
300 	}
301 	fclose(lvf);
302 
303 	return ret;
304 }
305 
lvm_probe_all(blkid_cache cache,int only_if_new)306 static void lvm_probe_all(blkid_cache cache, int only_if_new)
307 {
308 	DIR		*vg_list;
309 	struct dirent	*vg_iter;
310 	int		vg_len = strlen(VG_DIR);
311 	dev_t		dev;
312 
313 	if ((vg_list = opendir(VG_DIR)) == NULL)
314 		return;
315 
316 	DBG(DEBUG_DEVNAME, printf("probing LVM devices under %s\n", VG_DIR));
317 
318 	while ((vg_iter = readdir(vg_list)) != NULL) {
319 		DIR		*lv_list;
320 		char		*vdirname;
321 		char		*vg_name;
322 		struct dirent	*lv_iter;
323 
324 		vg_name = vg_iter->d_name;
325 		if (!strcmp(vg_name, ".") || !strcmp(vg_name, ".."))
326 			continue;
327 		vdirname = malloc(vg_len + strlen(vg_name) + 8);
328 		if (!vdirname)
329 			goto exit;
330 		sprintf(vdirname, "%s/%s/LVs", VG_DIR, vg_name);
331 
332 		lv_list = opendir(vdirname);
333 		free(vdirname);
334 		if (lv_list == NULL)
335 			continue;
336 
337 		while ((lv_iter = readdir(lv_list)) != NULL) {
338 			char		*lv_name, *lvm_device;
339 
340 			lv_name = lv_iter->d_name;
341 			if (!strcmp(lv_name, ".") || !strcmp(lv_name, ".."))
342 				continue;
343 
344 			lvm_device = malloc(vg_len + strlen(vg_name) +
345 					    strlen(lv_name) + 8);
346 			if (!lvm_device) {
347 				closedir(lv_list);
348 				goto exit;
349 			}
350 			sprintf(lvm_device, "%s/%s/LVs/%s", VG_DIR, vg_name,
351 				lv_name);
352 			dev = lvm_get_devno(lvm_device);
353 			sprintf(lvm_device, "%s/%s", vg_name, lv_name);
354 			DBG(DEBUG_DEVNAME, printf("LVM dev %s: devno 0x%04X\n",
355 						  lvm_device,
356 						  (unsigned int) dev));
357 			probe_one(cache, lvm_device, dev, BLKID_PRI_LVM,
358 				  only_if_new);
359 			free(lvm_device);
360 		}
361 		closedir(lv_list);
362 	}
363 exit:
364 	closedir(vg_list);
365 }
366 #endif
367 
368 #define PROC_EVMS_VOLUMES "/proc/evms/volumes"
369 
370 static int
evms_probe_all(blkid_cache cache,int only_if_new)371 evms_probe_all(blkid_cache cache, int only_if_new)
372 {
373 	char line[100];
374 	int ma, mi, sz, num = 0;
375 	FILE *procpt;
376 	char device[110];
377 
378 	procpt = fopen(PROC_EVMS_VOLUMES, "r");
379 	if (!procpt)
380 		return 0;
381 	while (fgets(line, sizeof(line), procpt)) {
382 		if (sscanf (line, " %d %d %d %*s %*s %[^\n ]",
383 			    &ma, &mi, &sz, device) != 4)
384 			continue;
385 
386 		DBG(DEBUG_DEVNAME, printf("Checking partition %s (%d, %d)\n",
387 					  device, ma, mi));
388 
389 		probe_one(cache, device, makedev(ma, mi), BLKID_PRI_EVMS,
390 			  only_if_new);
391 		num++;
392 	}
393 	fclose(procpt);
394 	return num;
395 }
396 
397 /*
398  * Read the device data for all available block devices in the system.
399  */
probe_all(blkid_cache cache,int only_if_new)400 static int probe_all(blkid_cache cache, int only_if_new)
401 {
402 	FILE *proc;
403 #ifndef __FreeBSD__
404 	char line[1024];
405 	int ma, mi;
406 #else
407 	char *line;
408 #endif /* __FreeBSD__ */
409 	char ptname0[129], ptname1[129], *ptname = 0;
410 	char *ptnames[2];
411 	dev_t devs[2];
412 	unsigned long long sz;
413 	int lens[2] = { 0, 0 };
414 	int which = 0, last = 0;
415 	struct list_head *p, *pnext;
416 
417 	ptnames[0] = ptname0;
418 	ptnames[1] = ptname1;
419 
420 	if (!cache)
421 		return -BLKID_ERR_PARAM;
422 
423 	if (cache->bic_flags & BLKID_BIC_FL_PROBED &&
424 	    time(0) - cache->bic_time < BLKID_PROBE_INTERVAL)
425 		return 0;
426 
427 	blkid_read_cache(cache);
428 	evms_probe_all(cache, only_if_new);
429 #ifdef VG_DIR
430 	lvm_probe_all(cache, only_if_new);
431 #endif
432 
433 #ifndef __FreeBSD__
434 	proc = fopen(PROC_PARTITIONS, "r");
435 	if (!proc)
436 		return -BLKID_ERR_PROC;
437 
438 	while (fgets(line, sizeof(line), proc)) {
439 #else
440 	size_t len, bufsiz = 4096;
441 	char *buf = NULL;
442 
443 	for(;;) {
444 		buf = realloc(buf, bufsiz);
445 		if (!buf) return -BLKID_ERR_MEM;
446 		len = bufsiz - 1;
447 		if (sysctlbyname("kern.geom.conftxt", buf, &len, NULL, 0)) {
448 			if (ENOMEM != errno) {
449 				free(buf);
450 				return -BLKID_ERR_IO;
451 			}
452 			bufsiz <<= 1;
453 		} else {
454 			if (len < bufsiz) buf[len] = '\0';
455 			else              buf[bufsiz - 1] = '\0';
456 			break;
457 		}
458 	}
459 	char *str = buf;
460 	while (line = strsep(&str, "\n")) {
461 #endif /* __FreeBSD__ */
462 		last = which;
463 		which ^= 1;
464 		ptname = ptnames[which];
465 
466 #ifndef __FreeBSD__
467 		if (sscanf(line, " %d %d %llu %128[^\n ]",
468 			   &ma, &mi, &sz, ptname) != 4)
469 			continue;
470 		devs[which] = makedev(ma, mi);
471 #else
472 		char type[5];
473 		int dummy;
474 
475 		if (sscanf(line, "%*d %5s %128[^ ] %lld %d",
476 			   type, ptname, &sz, &dummy) != 4)
477 			continue;
478 		sz /= 1024;
479 
480 		if (strcmp("PART", type) && strcmp("DISK", type))
481 			continue;
482 		{
483 			struct stat st;
484 			char dn[128];
485 			if (snprintf(dn, sizeof dn, "/dev/%s", ptname) >= sizeof dn)
486 				continue;
487 
488 			if (stat(dn, &st))
489 				continue;
490 
491 			devs[which] = st.st_rdev;
492 		}
493 #endif /* __FreeBSD__ */
494 
495 		DBG(DEBUG_DEVNAME, printf("read partition name %s\n", ptname));
496 
497 		/* Skip whole disk devs unless they have no partitions.
498 		 * If base name of device has changed, also
499 		 * check previous dev to see if it didn't have a partn.
500 		 * heuristic: partition name ends in a digit, & partition
501 		 * names contain whole device name as substring.
502 		 *
503 		 * Skip extended partitions.
504 		 * heuristic: size is 1
505 		 *
506 		 * FIXME: skip /dev/{ida,cciss,rd} whole-disk devs
507 		 */
508 
509 		lens[which] = strlen(ptname);
510 
511 		/* ends in a digit, clearly a partition, so check */
512 		if (isdigit(ptname[lens[which] - 1])) {
513 			DBG(DEBUG_DEVNAME,
514 			    printf("partition dev %s, devno 0x%04X\n",
515 				   ptname, (unsigned int) devs[which]));
516 
517 			if (sz > 1)
518 				probe_one(cache, ptname, devs[which], 0,
519 					  only_if_new);
520 			lens[which] = 0;	/* mark as checked */
521 		}
522 
523 		/*
524 		 * If last was a whole disk and we just found a partition
525 		 * on it, remove the whole-disk dev from the cache if
526 		 * it exists.
527 		 */
528 		if (lens[last] && !strncmp(ptnames[last], ptname, lens[last])) {
529 			list_for_each_safe(p, pnext, &cache->bic_devs) {
530 				blkid_dev tmp;
531 
532 				/* find blkid dev for the whole-disk devno */
533 				tmp = list_entry(p, struct blkid_struct_dev,
534 						 bid_devs);
535 				if (tmp->bid_devno == devs[last]) {
536 					DBG(DEBUG_DEVNAME,
537 						printf("freeing %s\n",
538 						       tmp->bid_name));
539 					blkid_free_dev(tmp);
540 					cache->bic_flags |= BLKID_BIC_FL_CHANGED;
541 					break;
542 				}
543 			}
544 			lens[last] = 0;
545 		}
546 		/*
547 		 * If last was not checked because it looked like a whole-disk
548 		 * dev, and the device's base name has changed,
549 		 * check last as well.
550 		 */
551 		if (lens[last] && strncmp(ptnames[last], ptname, lens[last])) {
552 			DBG(DEBUG_DEVNAME,
553 			    printf("whole dev %s, devno 0x%04X\n",
554 				   ptnames[last], (unsigned int) devs[last]));
555 			probe_one(cache, ptnames[last], devs[last], 0,
556 				  only_if_new);
557 			lens[last] = 0;
558 		}
559 	}
560 
561 	/* Handle the last device if it wasn't partitioned */
562 	if (lens[which])
563 		probe_one(cache, ptname, devs[which], 0, only_if_new);
564 
565 #ifndef __FreeBSD__
566 	fclose(proc);
567 #else
568 	free(buf);
569 #endif /* __FreeBSD__ */
570 	blkid_flush_cache(cache);
571 	return 0;
572 }
573 
574 int blkid_probe_all(blkid_cache cache)
575 {
576 	int ret;
577 
578 	DBG(DEBUG_PROBE, printf("Begin blkid_probe_all()\n"));
579 	ret = probe_all(cache, 0);
580 	cache->bic_time = time(0);
581 	cache->bic_flags |= BLKID_BIC_FL_PROBED;
582 	DBG(DEBUG_PROBE, printf("End blkid_probe_all()\n"));
583 	return ret;
584 }
585 
586 int blkid_probe_all_new(blkid_cache cache)
587 {
588 	int ret;
589 
590 	DBG(DEBUG_PROBE, printf("Begin blkid_probe_all_new()\n"));
591 	ret = probe_all(cache, 1);
592 	DBG(DEBUG_PROBE, printf("End blkid_probe_all_new()\n"));
593 	return ret;
594 }
595 
596 
597 #ifdef TEST_PROGRAM
598 int main(int argc, char **argv)
599 {
600 	blkid_cache cache = NULL;
601 	int ret;
602 
603 	blkid_debug_mask = DEBUG_ALL;
604 	if (argc != 1) {
605 		fprintf(stderr, "Usage: %s\n"
606 			"Probe all devices and exit\n", argv[0]);
607 		exit(1);
608 	}
609 	if ((ret = blkid_get_cache(&cache, "/dev/null")) != 0) {
610 		fprintf(stderr, "%s: error creating cache (%d)\n",
611 			argv[0], ret);
612 		exit(1);
613 	}
614 	if (blkid_probe_all(cache) < 0)
615 		printf("%s: error probing devices\n", argv[0]);
616 
617 	blkid_put_cache(cache);
618 	return (0);
619 }
620 #endif
621