1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <ctype.h>
5#include "get_default_type_internal.h"
6#include <errno.h>
7
8static int find_default_type(FILE * fp, const char *role, char **type);
9
10int get_default_type(const char *role, char **type)
11{
12	FILE *fp = NULL;
13
14	fp = fopen(selinux_default_type_path(), "r");
15	if (!fp)
16		return -1;
17
18	if (find_default_type(fp, role, type) < 0) {
19		fclose(fp);
20		return -1;
21	}
22
23	fclose(fp);
24	return 0;
25}
26
27static int find_default_type(FILE * fp, const char *role, char **type)
28{
29	char buf[250];
30	const char *ptr = "", *end;
31	char *t;
32	size_t len;
33	int found = 0;
34
35	len = strlen(role);
36	while (!feof_unlocked(fp)) {
37		if (!fgets_unlocked(buf, sizeof buf, fp)) {
38			errno = EINVAL;
39			return -1;
40		}
41		if (buf[strlen(buf) - 1])
42			buf[strlen(buf) - 1] = 0;
43
44		ptr = buf;
45		while (*ptr && isspace(*ptr))
46			ptr++;
47		if (!(*ptr))
48			continue;
49
50		if (!strncmp(role, ptr, len)) {
51			end = ptr + len;
52			if (*end == ':') {
53				found = 1;
54				ptr = ++end;
55				break;
56			}
57		}
58	}
59
60	if (!found) {
61		errno = EINVAL;
62		return -1;
63	}
64
65	t = malloc(strlen(buf) - len);
66	if (!t)
67		return -1;
68	strcpy(t, ptr);
69	*type = t;
70	return 0;
71}
72