forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetpwuid.cpp
More file actions
67 lines (57 loc) · 1.28 KB
/
getpwuid.cpp
File metadata and controls
67 lines (57 loc) · 1.28 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//! @brief returns the username for a uid
#include "getpwuid.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include <string.h>
#include <unistd.h>
//! @brief GetPwUid returns the username for a uid
//!
//! GetPwUid
//!
//! @param[in] uid
//! @parblock
//! The user identifier to lookup.
//! @endparblock
//!
//! @retval username as UTF-8 string, or NULL if unsuccessful
//!
char* GetPwUid(uid_t uid)
{
int32_t ret = 0;
struct passwd pwd;
struct passwd* result = NULL;
char* buf;
int buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
if (buflen < 1)
{
buflen = 2048;
}
allocate:
buf = (char*)calloc(buflen, sizeof(char));
errno = 0;
ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
if (ret != 0)
{
if (errno == ERANGE)
{
free(buf);
buflen *= 2;
goto allocate;
}
return NULL;
}
// no result
if (result == NULL)
{
return NULL;
}
// allocate copy on heap so CLR can free it
size_t userlen = strnlen(pwd.pw_name, buflen);
char* username = strndup(pwd.pw_name, userlen);
free(buf);
return username;
}