-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchkgrp.c
More file actions
75 lines (62 loc) · 1.73 KB
/
Copy pathchkgrp.c
File metadata and controls
75 lines (62 loc) · 1.73 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
68
69
70
71
72
73
74
/**
* chkgrp is a program that checks if a user is a member of a group.
*
* Author: Johannes Findeisen <you@hanez.org> - 2025
* Homepage: https://git.xw3.org/hanez/chkusr
* License: Apache-2.0 (see LICENSE)
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Usage: %s <username> <groupname>\n", argv[0]);
return 2;
}
const char *username = argv[1];
const char *groupname = argv[2];
// Runtime check for max name length
long max_name_len = sysconf(_SC_LOGIN_NAME_MAX);
if (max_name_len <= 0 || max_name_len > 1024) {
max_name_len = MAX_NAME;
}
if (strlen(username) > (size_t)max_name_len) {
fprintf(stderr, "Error: Username too long (max %ld characters).\n",
max_name_len);
return 2;
}
if (strlen(groupname) > (size_t)max_name_len) {
fprintf(stderr, "Error: Group name too long (max %ld characters).\n",
max_name_len);
return 2;
}
struct passwd *pw = getpwnam(username);
if (!pw) {
fprintf(stderr, "Error: User '%s' not found.\n", username);
return 2;
}
struct group *gr = getgrnam(groupname);
if (!gr) {
fprintf(stderr, "Error: Group '%s' not found.\n", groupname);
return 2;
}
if (pw->pw_gid == gr->gr_gid) {
puts("Yes");
return 0;
}
for (char **members = gr->gr_mem; *members != NULL; members++) {
if (strcmp(*members, username) == 0) {
puts("Yes");
return 0;
}
}
puts("No");
return 1;
}