summaryrefslogtreecommitdiffstats
path: root/common.c
blob: 01ebae9c39e7fab74347603ad1a1aa23da337109 (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

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "common.h"

static char *table_name_to_file(const char *name) {

	char *share_path = getenv("SHARE_PATH");
	char *fname;
	if (!share_path || !*share_path) share_path = "/usr/share";

	asprintf(&fname, "%s/ldetect-lst/%s", share_path, name);
	return fname;
}

fh fh_open(const char *name) {
	fh ret;
	char *fname = table_name_to_file(name);
	int length = strlen(fname);

	if (access(fname, R_OK) == 0) {
		ret.f = fopen(fname, "r");
		ret.pid = 0;
	} else {
		int fdno[2];
		char *fname_gz = alloca(length + sizeof(".gz"));
		sprintf(fname_gz, "%s.gz", fname);
		if (access(fname_gz, R_OK) != 0) {
			fprintf(stderr, "Missing %s (should be %s)\n", name, fname);
			exit(1);
		}
		if (pipe(fdno)) {
			perror("pciusb");
			exit(1);
		}

		if ((ret.pid = fork()) != 0) {
			ret.f = fdopen(fdno[0], "r");
			close(fdno[1]);
		} else {
			char* cmd[5];
			int ip = 0;
			char *ld_loader = getenv("LD_LOADER");

			if (ld_loader && *ld_loader)
				cmd[ip++] = ld_loader;

			cmd[ip++] = "gzip";
			cmd[ip++] = "-cd";
			cmd[ip++] = fname_gz;
			cmd[ip++] = NULL;

			dup2(fdno[1], STDOUT_FILENO);
			close(fdno[0]);
			close(fdno[1]);
			execvp(cmd[0], cmd);
			perror("pciusb"); 
			exit(2);
		}
	}
	free(fname);
	return ret;
}

void fh_close(fh *f) {
	fclose(f->f);
	if (f->pid > 0)
		waitpid(f->pid, NULL, 0);
}