1#include <unistd.h>
2#include <sys/types.h>
3#include <fcntl.h>
4#include <stdlib.h>
5#include <stdio.h>
6#include <errno.h>
7#include <string.h>
8#include "selinux_internal.h"
9#include "policy.h"
10#include <limits.h>
11
12#define SELINUX_INITCON_DIR "/initial_contexts/"
13
14int security_get_initial_context_raw(const char * name, char ** con)
15{
16	char path[PATH_MAX];
17	char *buf;
18	size_t size;
19	int fd, ret;
20
21	if (!selinux_mnt) {
22		errno = ENOENT;
23		return -1;
24	}
25
26	if (strchr(name, '/')) {
27		errno = EINVAL;
28		return -1;
29	}
30
31	ret = snprintf(path, sizeof path, "%s%s%s", selinux_mnt, SELINUX_INITCON_DIR, name);
32	if (ret < 0 || (size_t)ret >= sizeof path) {
33		errno = EOVERFLOW;
34		return -1;
35	}
36
37	fd = open(path, O_RDONLY | O_CLOEXEC);
38	if (fd < 0)
39		return -1;
40
41	size = selinux_page_size;
42	buf = malloc(size);
43	if (!buf) {
44		ret = -1;
45		goto out;
46	}
47	memset(buf, 0, size);
48	ret = read(fd, buf, size - 1);
49	if (ret < 0)
50		goto out2;
51
52	*con = strdup(buf);
53	if (!(*con)) {
54		ret = -1;
55		goto out2;
56	}
57	ret = 0;
58      out2:
59	free(buf);
60      out:
61	close(fd);
62	return ret;
63}
64
65
66int security_get_initial_context(const char * name, char ** con)
67{
68	int ret;
69	char * rcon;
70
71	ret = security_get_initial_context_raw(name, &rcon);
72	if (!ret) {
73		ret = selinux_raw_to_trans_context(rcon, con);
74		freecon(rcon);
75	}
76
77	return ret;
78}
79
80