matchmediacon.c revision 9eb9c9327563014ad6a807814e7975424642d5b9
1#include <unistd.h>
2#include <fcntl.h>
3#include <sys/stat.h>
4#include <string.h>
5#include "selinux_internal.h"
6#include <stdio.h>
7#include <stdlib.h>
8#include <ctype.h>
9#include <errno.h>
10#include <limits.h>
11#include <regex.h>
12#include <stdarg.h>
13
14int matchmediacon(const char *media, char ** con)
15{
16	const char *path = selinux_media_context_path();
17	FILE *infile;
18	char *ptr, *ptr2 = NULL;
19	int found = 0;
20	char current_line[PATH_MAX];
21	if ((infile = fopen(path, "r")) == NULL)
22		return -1;
23	while (!feof_unlocked(infile)) {
24		if (!fgets_unlocked(current_line, sizeof(current_line), infile)) {
25			return -1;
26		}
27		if (current_line[strlen(current_line) - 1])
28			current_line[strlen(current_line) - 1] = 0;
29		/* Skip leading whitespace before the partial context. */
30		ptr = current_line;
31		while (*ptr && isspace(*ptr))
32			ptr++;
33
34		if (!(*ptr))
35			continue;
36
37		/* Find the end of the media context. */
38		ptr2 = ptr;
39		while (*ptr2 && !isspace(*ptr2))
40			ptr2++;
41		if (!(*ptr2))
42			continue;
43
44		*ptr2++ = 0;
45		if (strcmp(media, ptr) == 0) {
46			found = 1;
47			break;
48		}
49	}
50	fclose(infile);
51	if (!found)
52		return -1;
53
54	/* Skip whitespace. */
55	while (*ptr2 && isspace(*ptr2))
56		ptr2++;
57	if (!(*ptr2)) {
58		return -1;
59	}
60
61	if (selinux_raw_to_trans_context(ptr2, con)) {
62		*con = NULL;
63		return -1;
64	}
65
66	return 0;
67}
68