1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <grp.h>
17 #include <malloc.h>
18 #include <pwd.h>
19 #include <stdio.h>
20 #include "test.h"
21
22 static int server_ngroups;
23 static gid_t *server_groups;
24
25 /*
26 * @tc.name : getgrouplist_0100
27 * @tc.desc : Get list of groups to which a user belongs
28 * @tc.level : Level 0
29 */
getgrouplist_0100()30 void getgrouplist_0100()
31 {
32 int result;
33 struct group *gr;
34 const char *server_user = "root";
35
36 struct passwd *pwd = getpwnam(server_user);
37 if (!pwd) {
38 t_error("%s getpwnam failed\n", __func__);
39 }
40
41 gid_t server_gid = pwd->pw_gid;
42
43 result = getgrouplist(server_user, server_gid, NULL, &server_ngroups);
44 if (result == 0) {
45 t_error("%s getgrouplist should be failed\n", __func__);
46 }
47
48 server_groups = (gid_t *)malloc(server_ngroups * sizeof(gid_t));
49 result = getgrouplist(server_user, server_gid, server_groups, &server_ngroups);
50 if (result == -1) {
51 t_error("%s getgrouplist failed\n", __func__);
52 }
53
54 for (int i = 0; i < server_ngroups; i++) {
55 printf("%d", server_groups[i]);
56 gr = getgrgid(server_groups[i]);
57 if (gr != NULL) {
58 printf(" (%s)", gr->gr_name);
59 }
60 printf("\n");
61 }
62 }
63
main(int argc,char * argv[])64 int main(int argc, char *argv[])
65 {
66 getgrouplist_0100();
67 return t_status;
68 }