summaryrefslogtreecommitdiffstats
path: root/src/libsystemd/sd-device/device-util.c
blob: b192914b1d09eeaf5aa5c48a567e621e14494c55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include "device-private.h"
#include "device-util.h"
#include "devnum-util.h"
#include "fd-util.h"
#include "string-util.h"

int devname_from_devnum(mode_t mode, dev_t devnum, char **ret) {
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
        _cleanup_free_ char *s = NULL;
        const char *devname;
        int r;

        assert(ret);

        if (major(devnum) == 0 && minor(devnum) == 0)
                return device_path_make_inaccessible(mode, ret);

        r = device_new_from_mode_and_devnum(&dev, mode, devnum);
        if (r < 0)
                return r;

        r = sd_device_get_devname(dev, &devname);
        if (r < 0)
                return r;

        s = strdup(devname);
        if (!s)
                return -ENOMEM;

        *ret = TAKE_PTR(s);
        return 0;
}

int device_open_from_devnum(mode_t mode, dev_t devnum, int flags, char **ret) {
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
        _cleanup_close_ int fd = -1;
        int r;

        r = device_new_from_mode_and_devnum(&dev, mode, devnum);
        if (r < 0)
                return r;

        fd = sd_device_open(dev, flags);
        if (fd < 0)
                return fd;

        if (ret) {
                const char *devname;
                char *s;

                r = sd_device_get_devname(dev, &devname);
                if (r < 0)
                        return r;

                s = strdup(devname);
                if (!s)
                        return -ENOMEM;

                *ret = s;
        }

        return TAKE_FD(fd);
}