blob: e1e981901e113fdbf7c76b3811cb736de1668af8 (
plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
<?php
namespace gipfl\Socket;
use RuntimeException;
use React\Socket\ConnectionInterface;
use function array_shift;
use function file_exists;
use function is_int;
use function posix_getgrgid;
use function posix_getpwuid;
use function preg_split;
use function socket_get_option;
use function socket_import_stream;
use function stat;
use function strlen;
use function trim;
class UnixSocketInspection
{
/**
* @param ConnectionInterface $connection
* @return UnixSocketPeer
*/
public static function getPeer(ConnectionInterface $connection)
{
$socket = socket_import_stream($connection->stream);
$remotePid = static::getRemotePidFromSocket($socket);
$stat = static::statProcFile($remotePid);
$uid = $stat['uid'];
$gid = $stat['gid'];
$userInfo = static::getUserInfo($uid);
$gecosParts = preg_split('/,/', $userInfo['gecos']);
$fullName = trim(array_shift($gecosParts));
$groupInfo = static::getGroupInfo($gid);
return new UnixSocketPeer(
$remotePid,
$uid,
$gid,
$userInfo['name'],
strlen($fullName) ? $fullName : null,
$groupInfo['name']
);
}
protected static function getRemotePidFromSocket($socket)
{
// SO_PEERCRED = 17
$remotePid = socket_get_option($socket, SOL_SOCKET, 17);
if (! is_int($remotePid) || ! $remotePid > 0) {
throw new RuntimeException("Remote PID expected, got " . var_export($remotePid));
}
return $remotePid;
}
protected static function statProcFile($pid)
{
$procDir = "/proc/$pid";
if (file_exists($procDir)) {
return stat($procDir);
} else {
throw new RuntimeException("Got no proc dir ($procDir) for remote node");
}
}
protected static function getUserInfo($uid)
{
$userInfo = posix_getpwuid($uid);
if ($userInfo === false) {
throw new RuntimeException("Unable to resolve remote UID '$uid'");
}
return $userInfo;
}
protected static function getGroupInfo($gid)
{
$groupInfo = posix_getgrgid($gid);
if ($groupInfo === false) {
throw new RuntimeException("Unable to resolve remote GID '$gid'");
}
return $groupInfo;
}
}
|