blob: 3bd29dc4906f172ec4995d70a1a0b1f241f3e96c [file] [log] [blame]
Stephen Smalleyf0740362012-01-04 12:30:47 -05001#include <unistd.h>
2#include <fcntl.h>
3#include <string.h>
4#include <stdlib.h>
5#include <errno.h>
6#include <sys/socket.h>
7#include "selinux_internal.h"
8#include "policy.h"
9
10#ifndef SO_PEERSEC
11#define SO_PEERSEC 31
12#endif
13
Stephen Smalleyab40ea92014-02-19 09:16:17 -050014int getpeercon(int fd, char ** context)
Stephen Smalleyf0740362012-01-04 12:30:47 -050015{
16 char *buf;
17 socklen_t size;
18 ssize_t ret;
19
20 size = INITCONTEXTLEN + 1;
21 buf = malloc(size);
22 if (!buf)
23 return -1;
24 memset(buf, 0, size);
25
26 ret = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &size);
27 if (ret < 0 && errno == ERANGE) {
28 char *newbuf;
29
30 newbuf = realloc(buf, size);
31 if (!newbuf)
32 goto out;
33
34 buf = newbuf;
35 memset(buf, 0, size);
36 ret = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &size);
37 }
38 out:
39 if (ret < 0)
40 free(buf);
41 else
42 *context = buf;
43 return ret;
44}
45