110 lines
2.1 KiB
C++
110 lines
2.1 KiB
C++
|
#include <pwd.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
static struct passwd pwd;
|
||
|
static FILE* f { nullptr };
|
||
|
static char buf[4096];
|
||
|
|
||
|
extern "C"
|
||
|
{
|
||
|
struct passwd* getpwent()
|
||
|
{
|
||
|
if (!f)
|
||
|
{
|
||
|
f = fopen("/etc/passwd", "r");
|
||
|
if (!f) return nullptr;
|
||
|
}
|
||
|
|
||
|
while (true)
|
||
|
{
|
||
|
char* rc = fgets(buf, sizeof(buf), f);
|
||
|
if (!rc) return nullptr;
|
||
|
|
||
|
char* name = strtok(rc, ":\n");
|
||
|
if (!name) continue;
|
||
|
|
||
|
char* passwd = strtok(nullptr, ":\n");
|
||
|
if (!passwd) continue;
|
||
|
|
||
|
char* uid = strtok(nullptr, ":\n");
|
||
|
if (!uid) continue;
|
||
|
|
||
|
char* gid = strtok(nullptr, ":\n");
|
||
|
if (!gid) continue;
|
||
|
|
||
|
char* gecos = strtok(nullptr, ":\n");
|
||
|
if (!gecos) continue;
|
||
|
|
||
|
char* dir = strtok(nullptr, ":\n");
|
||
|
if (!dir) continue;
|
||
|
|
||
|
char* shell = strtok(nullptr, ":\n");
|
||
|
if (!shell) continue;
|
||
|
|
||
|
pwd.pw_name = name;
|
||
|
pwd.pw_passwd = passwd;
|
||
|
pwd.pw_uid = (uid_t)strtoul(uid, NULL, 10);
|
||
|
pwd.pw_gid = (gid_t)strtoul(gid, NULL, 10);
|
||
|
pwd.pw_gecos = gecos;
|
||
|
pwd.pw_dir = dir;
|
||
|
pwd.pw_shell = shell;
|
||
|
|
||
|
return &pwd;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
struct passwd* getpwnam(const char* name)
|
||
|
{
|
||
|
setpwent();
|
||
|
|
||
|
struct passwd* entry;
|
||
|
|
||
|
while ((entry = getpwent()))
|
||
|
{
|
||
|
if (!strcmp(entry->pw_name, name))
|
||
|
{
|
||
|
endpwent();
|
||
|
return entry;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
endpwent();
|
||
|
return entry;
|
||
|
}
|
||
|
|
||
|
struct passwd* getpwuid(uid_t uid)
|
||
|
{
|
||
|
setpwent();
|
||
|
|
||
|
struct passwd* entry;
|
||
|
|
||
|
while ((entry = getpwent()))
|
||
|
{
|
||
|
if (entry->pw_uid == uid)
|
||
|
{
|
||
|
endpwent();
|
||
|
return entry;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
endpwent();
|
||
|
return entry;
|
||
|
}
|
||
|
|
||
|
void setpwent()
|
||
|
{
|
||
|
if (f) rewind(f);
|
||
|
}
|
||
|
|
||
|
void endpwent()
|
||
|
{
|
||
|
if (f)
|
||
|
{
|
||
|
fclose(f);
|
||
|
f = nullptr;
|
||
|
}
|
||
|
}
|
||
|
}
|