xref: /aosp_15_r20/external/e2fsprogs/lib/support/devname.c (revision 6a54128f25917bfc36a8a6e9d722c04a0b4641b6)
1 /*
2  * devname.c --- Support function to translate a user provided string
3  * identifying a device to an actual device path
4  *
5  * Copyright (C) 2022 Red Hat, Inc., Lukas Czerner <[email protected]>
6  *
7  * %Begin-Header%
8  * This file may be redistributed under the terms of the GNU Public
9  * License.
10  * %End-Header%
11  */
12 
13 #include <unistd.h>
14 #include <string.h>
15 #include <stdio.h>
16 
17 #include "config.h"
18 #include "devname.h"
19 #include "nls-enable.h"
20 
21 /*
22  *  blkid_get_devname() is primarily intended for parsing "NAME=value"
23  *  tokens. It will return the device matching the specified token, NULL if
24  *  nothing is found, or copy of the string if it's not in "NAME=value"
25  *  format.
26  *  get_devname() takes the same parameters and works the same way as
27  *  blkid_get_devname() except it can handle '=' in the file name.
28  */
get_devname(blkid_cache cache,const char * token,const char * value)29 char *get_devname(blkid_cache cache, const char *token, const char *value)
30 {
31 	int is_file = 0;
32 	char *ret = NULL;
33 
34 	if (!token)
35 		goto out;
36 
37 	if (value) {
38 		ret = blkid_get_devname(cache, token, value);
39 		goto out;
40 	}
41 
42 	if (access(token, F_OK) == 0)
43 		is_file = 1;
44 
45 	ret = blkid_get_devname(cache, token, NULL);
46 	if (ret) {
47 		/*
48 		 * In case of collision prefer the result from
49 		 * blkid_get_devname() to avoid a file masking file system with
50 		 * existing tag.
51 		 */
52 		if (is_file && (strcmp(ret, token) != 0)) {
53 			fprintf(stderr,
54 				_("Collision found: '%s' refers to both '%s' "
55 				  "and a file '%s'. Using '%s'!\n"),
56 				token, ret, token, ret);
57 		}
58 		goto out;
59 	}
60 
61 	if (is_file)
62 		ret = strdup(token);
63 out:
64 	return ret;
65 }
66