1 /*
2  * SNOOPY LOGGER
3  *
4  * File: snoopy/datasource/egroup.c
5  *
6  * Copyright (c) 2014-2015 Bostjan Skufca <bostjan@a2o.si>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2, or (at your option)
11  * any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21  */
22 
23 
24 
25 /*
26  * Includes order: from local to global
27  */
28 #include "egroup.h"
29 
30 #include "snoopy.h"
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <sys/types.h>
36 #include <grp.h>
37 
38 
39 
40 /*
41  * SNOOPY DATA SOURCE: egroup
42  *
43  * Description:
44  *     Returns literal effective group name (Group ID) of current process
45  *
46  * Params:
47  *     result: pointer to string, to write result into
48  *     arg:    (ignored)
49  *
50  * Return:
51  *     number of characters in the returned string, or SNOOPY_DATASOURCE_FAILURE
52  */
snoopy_datasource_egroup(char * const result,char const * const arg)53 int snoopy_datasource_egroup (char * const result, char const * const arg)
54 {
55     struct group   gr;
56     struct group  *gr_gid         = NULL;
57     char          *buffgr_gid     = NULL;
58     long           buffgrsize_gid = 0;
59     int            messageLength  = 0;
60 
61     /* Allocate memory */
62     buffgrsize_gid = sysconf(_SC_GETGR_R_SIZE_MAX);
63     if (-1 == buffgrsize_gid) {
64         buffgrsize_gid = 16384;
65     }
66     buffgr_gid = malloc(buffgrsize_gid);
67     if (NULL == buffgr_gid) {
68         return snprintf(result, SNOOPY_DATASOURCE_MESSAGE_MAX_SIZE, "ERROR(malloc)");
69     }
70 
71     /* Try to get data */
72     if (0 != getgrgid_r(getegid(), &gr, buffgr_gid, buffgrsize_gid, &gr_gid)) {
73         messageLength  = snprintf(result, SNOOPY_DATASOURCE_MESSAGE_MAX_SIZE, "ERROR(getgrgid_r)");
74     } else {
75         if (NULL == gr_gid) {
76             messageLength = snprintf(result, SNOOPY_DATASOURCE_MESSAGE_MAX_SIZE, "(undefined)");
77         } else {
78             messageLength = snprintf(result, SNOOPY_DATASOURCE_MESSAGE_MAX_SIZE, "%s", gr_gid->gr_name);
79         }
80     }
81 
82     /* Cleanup and return */
83     free(buffgr_gid);
84     return messageLength;
85 }
86