File: names.c

package info (click to toggle)
libtypec 0.6.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 432 kB
  • sloc: ansic: 4,991; makefile: 4
file content (100 lines) | stat: -rw-r--r-- 2,375 bytes parent folder | download
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
    Copyright (c) 2021-2022 by Rajaram Regupathy, rajaram.regupathy@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; version 2 of the License.

    This program is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty MERCHANTABILITY or FITNESS
    FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
    details.

    (See the full license text in the LICENSES directory)
*/
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Code based on usbutils: https://github.com/gregkh/usbutils
 */

#include <libudev.h>
#include <string.h>
#include <stdio.h>

static struct udev *udev = NULL;
static struct udev_hwdb *hwdb = NULL;

int names_init(void)
{
    udev = udev_new();
    if (udev == NULL)
    {
        return -1;
    }
    hwdb = udev_hwdb_new(udev);
    if (hwdb == NULL)
    {
        return -1;
    }

    return 0;
}

void names_exit(void)
{
    hwdb = udev_hwdb_unref(hwdb);
    udev = udev_unref(udev);
}

static const char *hwdb_get(const char *modalias, const char *key)
{
    struct udev_list_entry *entry;
    udev_list_entry_foreach(entry, udev_hwdb_get_properties_list_entry(hwdb, modalias, 0))
    {
        if (strcmp(udev_list_entry_get_name(entry), key) == 0)
        {
            return udev_list_entry_get_value(entry);
        }
    }
    return NULL;
}

const char *names_vendor(u_int16_t vendorid)
{
    char modalias[64];
    sprintf(modalias, "usb:v%04X*", vendorid);
    return hwdb_get(modalias, "ID_VENDOR_FROM_DATABASE");
}

const char *names_product(u_int16_t vendorid, u_int16_t productid)
{
    char modalias[64];

    sprintf(modalias, "usb:v%04Xp%04X*", vendorid, productid);

    return hwdb_get(modalias, "ID_MODEL_FROM_DATABASE");
}

int get_vendor_string(char *buf, size_t size, u_int16_t vid)
{
    const char *cp;

    if (size < 1)
        return 0;
    *buf = 0;
    if (!(cp = names_vendor(vid)))
        return 0;
    return snprintf(buf, size, "%s", cp);
}

int get_product_string(char *buf, size_t size, u_int16_t vid, u_int16_t pid)
{
    const char *cp;

    if (size < 1)
        return 0;
    *buf = 0;
    if (!(cp = names_product(vid, pid)))
        return 0;
    return snprintf(buf, size, "%s", cp);
}