GVM User Suite
User tools for the GVM open source project.
device.c
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2022 2666680 Ontario Inc.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  */
19 #include <utils/device.h>
20 
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 
30 uint8_t device_exists(const char* device_name)
31 {
32  char new_device[1024] = "/dev/";
33  uint8_t ret = 0;
34  strcat(new_device, device_name);
35  ret = (access(device_name, F_OK) == 0) || (access(new_device, F_OK) == 0);
36  return ret;
37 }
38 
42 int32_t get_major(const char* device)
43 {
44  int32_t major = -1;
45  FILE *in_file = fopen("/proc/devices", "r");
46 
47  struct stat sb;
48  stat("/proc/devices", &sb);
49 
50  char file_contents[1024] = "";
51 
52  while (fscanf(in_file, "%[^\n] ", file_contents) != EOF) {
53  char name[1024] = "";
54 
55  int correct_format = sscanf(file_contents, "%d %s", &major, name);
56  int compare = strcmp(name, device);
57 
58  if (correct_format == 2 && compare == 0)
59  break;
60 
61  major = -1;
62  }
63 
64  fclose(in_file);
65 
66  return major;
67 }
68 
71 int32_t get_param(const char* filename, const char* parameter)
72 {
73  int32_t ret = -1;
74  FILE *in_file = fopen(filename, "r");
75 
76  struct stat sb;
77  stat(filename, &sb);
78 
79  char file_contents[1024] = "";
80  char name[1024] = "";
81  sprintf(name, "%s: %%d", parameter);
82 
83  while (fscanf(in_file, "%[^\n] ", file_contents) != EOF) {
84  int correct_format = sscanf(file_contents, name, &ret);
85 
86  if (correct_format == 1)
87  break;
88 
89  ret = -1;
90  }
91 
92  fclose(in_file);
93 
94  return ret;
95 }
uint8_t device_exists(const char *device_name)
Does a device file exist?
Definition: device.c:30
int32_t get_major(const char *device)
Gets the device major id from /proc/devices.
Definition: device.c:42
int32_t get_param(const char *filename, const char *parameter)
Gets a parameter from a driver param file.
Definition: device.c:71