summaryrefslogtreecommitdiffstats
path: root/usb.c
blob: c41ca00349edc482854f3e8b5afb3c2c28673e4a (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <unistd.h>
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libldetect.h"
#include "libldetect-private.h"
#include "common.h"

char *proc_usb_path = "/proc/bus/usb/devices";


extern struct pciusb_entries usb_probe(void) {
	FILE *f;
	char buf[BUF_SIZE];
	int line;
	struct pciusb_entry t[MAX_DEVICES];
	struct pciusb_entries r;
	struct pciusb_entry *e = NULL;

	if (access(proc_pci_path, R_OK) != 0) {
		printf( "TOTO\n");
		exit(1);
	}

	if (!(f = fopen(proc_usb_path, "r"))) {
		char *err_msg;
		if (proc_usb_path==NULL || strcmp(proc_usb_path, "/proc/bus/usb/devices")) {
			asprintf(&err_msg, "unable to open \"%s\"\n"
				    "You may have passed a wrong argument to the \"-u\" option.\n"
				    "fopen() sets errno to", proc_usb_path);
			perror(err_msg);
		} /*else {
			asprintf(&err_msg, "unable to open \"%s\"\n"
				    "You should enable the usb service (as root, type 'service usb start'.\n"
				    "fopen() sets errno to", proc_usb_path);
			perror(err_msg);
		} */
		exit(1);
	}
  
	for(r.nb = line = 0; fgets(buf, sizeof(buf) - 1, f) && r.nb < psizeof(t); line++) {
		if (buf[0] == 'P') {
			e = &t[r.nb++];
			pciusb_initialize(e);

			if (sscanf(buf, "P:  Vendor=%hx ProdID=%hx", &e->vendor, &e->device) != 2) {
				fprintf(stderr, "%s %d: unknown ``P'' line\n", proc_usb_path, line);
				pciusb_initialize(e);
			}
		} else if (e && buf[0] == 'I' && e->class_ == 0) {
			int class_, sub, prot = 0;
			if (sscanf(buf, "I:  If#=%*2d Alt=%*2d #EPs=%*2d Cls=%02x(%*5c) Sub=%02x Prot=%02x", &class_, &sub, &prot) == 3) {
				e->class_ = (class_ * 0x100 + sub) * 0x100 + prot;
			} else {
				fprintf(stderr, "%s %d: unknown ``I'' line\n", proc_usb_path, line);
			}
		} else if (e && buf[0] == 'S') {
			int offset;
			char dummy;
			size_t length = strlen(buf) -1;
			if (sscanf(buf, "S:  Manufacturer=%n%c", &offset, &dummy) == 1) {
				buf[length] = '|'; /* replacing '\n' by '|' */
				e->text = strdup(buf + offset);
			} else if (sscanf(buf, "S:  Product=%n%c", &offset, &dummy) == 1) {
				if (!e->text) 
					e->text = strdup("Unknown|");
				buf[length - 1] = 0; /* removing '\n' */
				e->text = realloc(e->text, strlen(e->text) + length-offset + 2);
				strcat(e->text, buf + offset);
			}
		}
	}
	fclose(f);
	r.entries = memdup(t, sizeof(struct pciusb_entry) * r.nb);

	pciusb_find_modules(&r, "usbtable", 1 /* no_subid */);
	return r;
}