liyujie
2025-08-28 786ff4f4ca2374bdd9177f2e24b503d43e7a3b93
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
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include "selinux_internal.h"
#include "policy.h"
 
#ifndef SO_PEERSEC
#define SO_PEERSEC 31
#endif
 
int getpeercon_raw(int fd, char ** context)
{
   char *buf;
   socklen_t size;
   ssize_t ret;
 
   size = INITCONTEXTLEN + 1;
   buf = malloc(size);
   if (!buf)
       return -1;
   memset(buf, 0, size);
 
   ret = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &size);
   if (ret < 0 && errno == ERANGE) {
       char *newbuf;
 
       newbuf = realloc(buf, size);
       if (!newbuf)
           goto out;
 
       buf = newbuf;
       memset(buf, 0, size);
       ret = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &size);
   }
      out:
   if (ret < 0)
       free(buf);
   else
       *context = buf;
   return ret;
}
 
hidden_def(getpeercon_raw)
 
int getpeercon(int fd, char ** context)
{
   int ret;
   char * rcontext;
 
   ret = getpeercon_raw(fd, &rcontext);
 
   if (!ret) {
       ret = selinux_raw_to_trans_context(rcontext, context);
       freecon(rcontext);
   }
 
   return ret;
}