summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLorenz Kästle <12514511+RincewindsHat@users.noreply.github.com>2025-08-11 23:22:54 +0200
committerGitHub <noreply@github.com>2025-08-11 23:22:54 +0200
commit723e0d3466d85a6ed9811d0661db289e7d9406d9 (patch)
tree4b26f57d9f62c3cb084e063011910efa42fea0f4
parent2046ae85574c32370facab3c01f2152e56e1e981 (diff)
parent7382fa90f84d38cd2ae08c880e9ed6a4ad644d35 (diff)
downloadmonitoring-plugins-723e0d34.tar.gz
Merge pull request #2107 from RincewindsHat/refactor/check_users
Refactor/check users
-rw-r--r--.gitignore2
-rw-r--r--plugins/Makefile.am2
-rw-r--r--plugins/check_users.c253
-rw-r--r--plugins/check_users.d/config.h20
-rw-r--r--plugins/check_users.d/users.c167
-rw-r--r--plugins/check_users.d/users.h18
-rw-r--r--plugins/t/check_users.t4
7 files changed, 343 insertions, 123 deletions
diff --git a/.gitignore b/.gitignore
index 8b14f429..f1fe8b9a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -197,6 +197,8 @@ plugins/check_disk.d/.dirstamp
197/plugins/check_udp 197/plugins/check_udp
198/plugins/check_ups 198/plugins/check_ups
199/plugins/check_users 199/plugins/check_users
200/plugins/check_users.d/.deps
201/plugins/check_users.d/.dirstamp
200/plugins/check_vsz 202/plugins/check_vsz
201/plugins/config.h 203/plugins/config.h
202/plugins/config.h.in 204/plugins/config.h.in
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index 192a2549..5994b405 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -59,6 +59,7 @@ EXTRA_DIST = t \
59 check_radius.d \ 59 check_radius.d \
60 check_disk.d \ 60 check_disk.d \
61 check_time.d \ 61 check_time.d \
62 check_users.d \
62 check_load.d \ 63 check_load.d \
63 check_nagios.d \ 64 check_nagios.d \
64 check_dbi.d \ 65 check_dbi.d \
@@ -159,6 +160,7 @@ check_tcp_LDADD = $(SSLOBJS)
159check_time_LDADD = $(NETLIBS) 160check_time_LDADD = $(NETLIBS)
160check_ntp_time_LDADD = $(NETLIBS) $(MATHLIBS) 161check_ntp_time_LDADD = $(NETLIBS) $(MATHLIBS)
161check_ups_LDADD = $(NETLIBS) 162check_ups_LDADD = $(NETLIBS)
163check_users_SOURCES = check_users.c check_users.d/users.c
162check_users_LDADD = $(BASEOBJS) $(WTSAPI32LIBS) $(SYSTEMDLIBS) 164check_users_LDADD = $(BASEOBJS) $(WTSAPI32LIBS) $(SYSTEMDLIBS)
163check_by_ssh_LDADD = $(NETLIBS) 165check_by_ssh_LDADD = $(NETLIBS)
164check_ide_smart_LDADD = $(BASEOBJS) 166check_ide_smart_LDADD = $(BASEOBJS)
diff --git a/plugins/check_users.c b/plugins/check_users.c
index f1e1c39d..cd3bd181 100644
--- a/plugins/check_users.c
+++ b/plugins/check_users.c
@@ -34,8 +34,15 @@ const char *progname = "check_users";
34const char *copyright = "2000-2024"; 34const char *copyright = "2000-2024";
35const char *email = "devel@monitoring-plugins.org"; 35const char *email = "devel@monitoring-plugins.org";
36 36
37#include "common.h" 37#include "check_users.d/users.h"
38#include "utils.h" 38#include "output.h"
39#include "perfdata.h"
40#include "states.h"
41#include "utils_base.h"
42#include "./common.h"
43#include "./utils.h"
44#include "check_users.d/config.h"
45#include "thresholds.h"
39 46
40#if HAVE_WTSAPI32_H 47#if HAVE_WTSAPI32_H
41# include <windows.h> 48# include <windows.h>
@@ -53,29 +60,16 @@ const char *email = "devel@monitoring-plugins.org";
53# include <systemd/sd-login.h> 60# include <systemd/sd-login.h>
54#endif 61#endif
55 62
56#define possibly_set(a, b) ((a) == 0 ? (b) : 0) 63typedef struct process_argument_wrapper {
64 int errorcode;
65 check_users_config config;
66} check_users_config_wrapper;
67check_users_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
57 68
58static int process_arguments(int, char **); 69void print_help(void);
59static void print_help(void);
60void print_usage(void); 70void print_usage(void);
61 71
62static char *warning_range = NULL;
63static char *critical_range = NULL;
64static thresholds *thlds = NULL;
65
66int main(int argc, char **argv) { 72int main(int argc, char **argv) {
67 int users = -1;
68 int result = STATE_UNKNOWN;
69#if HAVE_WTSAPI32_H
70 WTS_SESSION_INFO *wtsinfo;
71 DWORD wtscount;
72 DWORD index;
73#elif HAVE_UTMPX_H
74 struct utmpx *putmpx;
75#else
76 char input_buffer[MAX_INPUT_BUFFER];
77#endif
78
79 setlocale(LC_ALL, ""); 73 setlocale(LC_ALL, "");
80 bindtextdomain(PACKAGE, LOCALEDIR); 74 bindtextdomain(PACKAGE, LOCALEDIR);
81 textdomain(PACKAGE); 75 textdomain(PACKAGE);
@@ -83,121 +77,100 @@ int main(int argc, char **argv) {
83 /* Parse extra opts if any */ 77 /* Parse extra opts if any */
84 argv = np_extra_opts(&argc, argv, progname); 78 argv = np_extra_opts(&argc, argv, progname);
85 79
86 if (process_arguments(argc, argv) == ERROR) 80 check_users_config_wrapper tmp_config = process_arguments(argc, argv);
87 usage4(_("Could not parse arguments"));
88
89 users = 0;
90
91#ifdef HAVE_LIBSYSTEMD
92 if (sd_booted() > 0)
93 users = sd_get_sessions(NULL);
94 else {
95#endif
96#if HAVE_WTSAPI32_H
97 if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) {
98 printf(_("Could not enumerate RD sessions: %d\n"), GetLastError());
99 return STATE_UNKNOWN;
100 }
101
102 for (index = 0; index < wtscount; index++) {
103 LPTSTR username;
104 DWORD size;
105 int len;
106
107 if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size))
108 continue;
109
110 len = lstrlen(username);
111
112 WTSFreeMemory(username);
113
114 if (len == 0)
115 continue;
116 81
117 if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected) 82 if (tmp_config.errorcode == ERROR) {
118 users++; 83 usage4(_("Could not parse arguments"));
119 }
120
121 WTSFreeMemory(wtsinfo);
122#elif HAVE_UTMPX_H
123 /* get currently logged users from utmpx */
124 setutxent();
125
126 while ((putmpx = getutxent()) != NULL)
127 if (putmpx->ut_type == USER_PROCESS)
128 users++;
129
130 endutxent();
131#else
132 /* run the command */
133 child_process = spopen(WHO_COMMAND);
134 if (child_process == NULL) {
135 printf(_("Could not open pipe: %s\n"), WHO_COMMAND);
136 return STATE_UNKNOWN;
137 } 84 }
138 85
139 child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r"); 86 check_users_config config = tmp_config.config;
140 if (child_stderr == NULL)
141 printf(_("Could not open stderr for %s\n"), WHO_COMMAND);
142
143 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
144 /* increment 'users' on all lines except total user count */
145 if (input_buffer[0] != '#') {
146 users++;
147 continue;
148 }
149 87
150 /* get total logged in users */ 88#ifdef _WIN32
151 if (sscanf(input_buffer, _("# users=%d"), &users) == 1) 89# if HAVE_WTSAPI32_H
152 break; 90 get_num_of_users_wrapper user_wrapper = get_num_of_users_windows();
91# else
92# error Did not find WTSAPI32
93# endif // HAVE_WTSAPI32_H
94#else
95# ifdef HAVE_LIBSYSTEMD
96 get_num_of_users_wrapper user_wrapper = get_num_of_users_systemd();
97# elif HAVE_UTMPX_H
98 get_num_of_users_wrapper user_wrapper = get_num_of_users_utmp();
99# else // !HAVE_LIBSYSTEMD && !HAVE_UTMPX_H
100 get_num_of_users_wrapper user_wrapper = get_num_of_users_who_command();
101# endif // HAVE_LIBSYSTEMD
102#endif // _WIN32
103
104 mp_check overall = mp_check_init();
105 if (config.output_format_is_set) {
106 mp_set_format(config.output_format);
153 } 107 }
108 mp_subcheck sc_users = mp_subcheck_init();
154 109
155 /* check STDERR */ 110 if (user_wrapper.errorcode != 0) {
156 if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) 111 sc_users = mp_set_subcheck_state(sc_users, STATE_UNKNOWN);
157 result = possibly_set(result, STATE_UNKNOWN); 112 sc_users.output = "Failed to retrieve number of users";
158 (void)fclose(child_stderr); 113 mp_add_subcheck_to_check(&overall, sc_users);
159 114 mp_exit(overall);
160 /* close the pipe */
161 if (spclose(child_process))
162 result = possibly_set(result, STATE_UNKNOWN);
163#endif
164#ifdef HAVE_LIBSYSTEMD
165 } 115 }
166#endif
167
168 /* check the user count against warning and critical thresholds */ 116 /* check the user count against warning and critical thresholds */
169 result = get_status((double)users, thlds);
170 117
171 if (result == STATE_UNKNOWN) 118 mp_perfdata users_pd = {
172 printf("%s\n", _("Unable to read output")); 119 .label = "users",
173 else { 120 .value = mp_create_pd_value(user_wrapper.users),
174 printf(_("USERS %s - %d users currently logged in |%s\n"), state_text(result), users, 121 };
175 sperfdata_int("users", users, "", warning_range, critical_range, true, 0, false, 0)); 122
123 users_pd = mp_pd_set_thresholds(users_pd, config.thresholds);
124 mp_add_perfdata_to_subcheck(&sc_users, users_pd);
125
126 int tmp_status = mp_get_pd_status(users_pd);
127 sc_users = mp_set_subcheck_state(sc_users, tmp_status);
128
129 switch (tmp_status) {
130 case STATE_WARNING:
131 xasprintf(&sc_users.output, "%d users currently logged in. This violates the warning threshold", user_wrapper.users);
132 break;
133 case STATE_CRITICAL:
134 xasprintf(&sc_users.output, "%d users currently logged in. This violates the critical threshold", user_wrapper.users);
135 break;
136 default:
137 xasprintf(&sc_users.output, "%d users currently logged in", user_wrapper.users);
176 } 138 }
177 139
178 return result; 140 mp_add_subcheck_to_check(&overall, sc_users);
141 mp_exit(overall);
179} 142}
180 143
144#define output_format_index CHAR_MAX + 1
145
181/* process command-line arguments */ 146/* process command-line arguments */
182int process_arguments(int argc, char **argv) { 147check_users_config_wrapper process_arguments(int argc, char **argv) {
183 static struct option longopts[] = {{"critical", required_argument, 0, 'c'}, 148 static struct option longopts[] = {{"critical", required_argument, 0, 'c'},
184 {"warning", required_argument, 0, 'w'}, 149 {"warning", required_argument, 0, 'w'},
185 {"version", no_argument, 0, 'V'}, 150 {"version", no_argument, 0, 'V'},
186 {"help", no_argument, 0, 'h'}, 151 {"help", no_argument, 0, 'h'},
152 {"output-format", required_argument, 0, output_format_index},
187 {0, 0, 0, 0}}; 153 {0, 0, 0, 0}};
188 154
189 if (argc < 2) 155 if (argc < 2) {
190 usage("\n"); 156 usage(progname);
157 }
158
159 char *warning_range = NULL;
160 char *critical_range = NULL;
161 check_users_config_wrapper result = {
162 .config = check_users_config_init(),
163 .errorcode = OK,
164 };
191 165
192 int option_char;
193 while (true) { 166 while (true) {
194 int option = 0; 167 int counter = getopt_long(argc, argv, "+hVvc:w:", longopts, NULL);
195 option_char = getopt_long(argc, argv, "+hVvc:w:", longopts, &option);
196 168
197 if (option_char == -1 || option_char == EOF || option_char == 1) 169 if (counter == -1 || counter == EOF || counter == 1) {
198 break; 170 break;
171 }
199 172
200 switch (option_char) { 173 switch (counter) {
201 case '?': /* print short usage statement if args not parsable */ 174 case '?': /* print short usage statement if args not parsable */
202 usage5(); 175 usage5();
203 case 'h': /* help */ 176 case 'h': /* help */
@@ -212,29 +185,66 @@ int process_arguments(int argc, char **argv) {
212 case 'w': /* warning */ 185 case 'w': /* warning */
213 warning_range = optarg; 186 warning_range = optarg;
214 break; 187 break;
188 case output_format_index: {
189 parsed_output_format parser = mp_parse_output_format(optarg);
190 if (!parser.parsing_success) {
191 // TODO List all available formats here, maybe add anothoer usage function
192 printf("Invalid output format: %s\n", optarg);
193 exit(STATE_UNKNOWN);
194 }
195
196 result.config.output_format_is_set = true;
197 result.config.output_format = parser.output_format;
198 break;
199 }
215 } 200 }
216 } 201 }
217 202
218 option_char = optind; 203 int option_char = optind;
219 204
220 if (warning_range == NULL && argc > option_char) 205 if (warning_range == NULL && argc > option_char) {
221 warning_range = argv[option_char++]; 206 warning_range = argv[option_char++];
207 }
222 208
223 if (critical_range == NULL && argc > option_char) 209 if (critical_range == NULL && argc > option_char) {
224 critical_range = argv[option_char++]; 210 critical_range = argv[option_char++];
211 }
225 212
226 /* this will abort in case of invalid ranges */ 213 // TODO add proper verification for ranges here!
227 set_thresholds(&thlds, warning_range, critical_range); 214 mp_range_parsed tmp;
215 if (warning_range) {
216 tmp = mp_parse_range_string(warning_range);
217 } else {
218 printf("Warning threshold missing\n");
219 print_usage();
220 exit(STATE_UNKNOWN);
221 }
228 222
229 if (!thlds->warning) { 223 if (tmp.error == MP_PARSING_SUCCES) {
230 usage4(_("Warning threshold must be a valid range expression")); 224 result.config.thresholds.warning = tmp.range;
225 result.config.thresholds.warning_is_set = true;
226 } else {
227 printf("Failed to parse warning range: %s", warning_range);
228 exit(STATE_UNKNOWN);
231 } 229 }
232 230
233 if (!thlds->critical) { 231 if (critical_range) {
234 usage4(_("Critical threshold must be a valid range expression")); 232 tmp = mp_parse_range_string(critical_range);
233 } else {
234 printf("Critical threshold missing\n");
235 print_usage();
236 exit(STATE_UNKNOWN);
235 } 237 }
236 238
237 return OK; 239 if (tmp.error == MP_PARSING_SUCCES) {
240 result.config.thresholds.critical = tmp.range;
241 result.config.thresholds.critical_is_set = true;
242 } else {
243 printf("Failed to parse critical range: %s", critical_range);
244 exit(STATE_UNKNOWN);
245 }
246
247 return result;
238} 248}
239 249
240void print_help(void) { 250void print_help(void) {
@@ -257,6 +267,7 @@ void print_help(void) {
257 printf(" %s\n", _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION")); 267 printf(" %s\n", _("Set WARNING status if number of logged in users violates RANGE_EXPRESSION"));
258 printf(" %s\n", "-c, --critical=RANGE_EXPRESSION"); 268 printf(" %s\n", "-c, --critical=RANGE_EXPRESSION");
259 printf(" %s\n", _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION")); 269 printf(" %s\n", _("Set CRITICAL status if number of logged in users violates RANGE_EXPRESSION"));
270 printf(UT_OUTPUT_FORMAT);
260 271
261 printf(UT_SUPPORT); 272 printf(UT_SUPPORT);
262} 273}
diff --git a/plugins/check_users.d/config.h b/plugins/check_users.d/config.h
new file mode 100644
index 00000000..26d3ee70
--- /dev/null
+++ b/plugins/check_users.d/config.h
@@ -0,0 +1,20 @@
1#pragma once
2
3#include "output.h"
4#include "thresholds.h"
5
6typedef struct check_users_config {
7 mp_thresholds thresholds;
8
9 bool output_format_is_set;
10 mp_output_format output_format;
11} check_users_config;
12
13check_users_config check_users_config_init() {
14 check_users_config tmp = {
15 .thresholds = mp_thresholds_init(),
16
17 .output_format_is_set = false,
18 };
19 return tmp;
20}
diff --git a/plugins/check_users.d/users.c b/plugins/check_users.d/users.c
new file mode 100644
index 00000000..a8b168a0
--- /dev/null
+++ b/plugins/check_users.d/users.c
@@ -0,0 +1,167 @@
1#include "./users.h"
2
3#ifdef _WIN32
4# ifdef HAVE_WTSAPI32_H
5# include <windows.h>
6# include <wtsapi32.h>
7# undef ERROR
8# define ERROR -1
9
10get_num_of_users_wrapper get_num_of_users_windows() {
11 WTS_SESSION_INFO *wtsinfo;
12 DWORD wtscount;
13
14 get_num_of_users_wrapper result = {};
15
16 if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &wtsinfo, &wtscount)) {
17 // printf(_("Could not enumerate RD sessions: %d\n"), GetLastError());
18 result.error = WINDOWS_COULD_NOT_ENUMERATE_SESSIONS;
19 return result;
20 }
21
22 for (DWORD index = 0; index < wtscount; index++) {
23 LPTSTR username;
24 DWORD size;
25
26 if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, wtsinfo[index].SessionId, WTSUserName, &username, &size)) {
27 continue;
28 }
29
30 int len = lstrlen(username);
31
32 WTSFreeMemory(username);
33
34 if (len == 0) {
35 continue;
36 }
37
38 if (wtsinfo[index].State == WTSActive || wtsinfo[index].State == WTSDisconnected) {
39 result.users++;
40 }
41 }
42
43 WTSFreeMemory(wtsinfo);
44 return result;
45}
46# else // HAVE_WTSAPI32_H
47# error On windows but without the WTSAPI32 lib
48# endif // HAVE_WTSAPI32_H
49
50#else // _WIN32
51
52# include "../../config.h"
53# include <stddef.h>
54
55# ifdef HAVE_LIBSYSTEMD
56# include <systemd/sd-daemon.h>
57# include <systemd/sd-login.h>
58
59get_num_of_users_wrapper get_num_of_users_systemd() {
60 get_num_of_users_wrapper result = {};
61
62 // Test whether we booted with systemd
63 if (sd_booted() > 0) {
64 int users = sd_get_uids(NULL);
65 if (users >= 0) {
66 // Success
67 result.users = users;
68 return result;
69 }
70
71 // Failure! return the error code
72 result.errorcode = users;
73 return result;
74 }
75
76 // Looks like we are not running systemd,
77 // return with error here
78 result.errorcode = NO_SYSTEMD_ERROR;
79 return result;
80}
81# endif
82
83# ifdef HAVE_UTMPX_H
84# include <utmpx.h>
85
86get_num_of_users_wrapper get_num_of_users_utmp() {
87 int users = 0;
88
89 /* get currently logged users from utmpx */
90 setutxent();
91
92 struct utmpx *putmpx;
93 while ((putmpx = getutxent()) != NULL) {
94 if (putmpx->ut_type == USER_PROCESS) {
95 users++;
96 }
97 }
98
99 endutxent();
100
101 get_num_of_users_wrapper result = {
102 .errorcode = 0,
103 .users = users,
104 };
105
106 return result;
107}
108# endif
109
110# ifndef HAVE_WTSAPI32_H
111# ifndef HAVE_LIBSYSTEMD
112# ifndef HAVE_UTMPX_H
113// Fall back option here for the others (probably still not on windows)
114
115# include "../popen.h"
116# include "../common.h"
117# include "../utils.h"
118
119get_num_of_users_wrapper get_num_of_users_who_command() {
120 /* run the command */
121 child_process = spopen(WHO_COMMAND);
122 if (child_process == NULL) {
123 // printf(_("Could not open pipe: %s\n"), WHO_COMMAND);
124 get_num_of_users_wrapper result = {
125 .errorcode = COULD_NOT_OPEN_PIPE,
126 };
127 return result;
128 }
129
130 child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r");
131 if (child_stderr == NULL) {
132 // printf(_("Could not open stderr for %s\n"), WHO_COMMAND);
133 // TODO this error should probably be reported
134 }
135
136 get_num_of_users_wrapper result = {};
137 char input_buffer[MAX_INPUT_BUFFER];
138 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
139 /* increment 'users' on all lines except total user count */
140 if (input_buffer[0] != '#') {
141 result.users++;
142 continue;
143 }
144
145 /* get total logged in users */
146 if (sscanf(input_buffer, _("# users=%d"), &result.users) == 1) {
147 break;
148 }
149 }
150
151 /* check STDERR */
152 if (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
153 // if this fails, something broke and the result can not be relied upon or so is the theorie here
154 result.errorcode = STDERR_COULD_NOT_BE_READ;
155 }
156 (void)fclose(child_stderr);
157
158 /* close the pipe */
159 spclose(child_process);
160
161 return result;
162}
163
164# endif
165# endif
166# endif
167#endif
diff --git a/plugins/check_users.d/users.h b/plugins/check_users.d/users.h
new file mode 100644
index 00000000..aacba775
--- /dev/null
+++ b/plugins/check_users.d/users.h
@@ -0,0 +1,18 @@
1#pragma once
2
3typedef struct get_num_of_users_wrapper {
4 int errorcode;
5 int users;
6} get_num_of_users_wrapper;
7
8enum {
9 NO_SYSTEMD_ERROR = 64,
10 WINDOWS_COULD_NOT_ENUMERATE_SESSIONS,
11 COULD_NOT_OPEN_PIPE,
12 STDERR_COULD_NOT_BE_READ,
13};
14
15get_num_of_users_wrapper get_num_of_users_systemd();
16get_num_of_users_wrapper get_num_of_users_utmp();
17get_num_of_users_wrapper get_num_of_users_windows();
18get_num_of_users_wrapper get_num_of_users_who_command();
diff --git a/plugins/t/check_users.t b/plugins/t/check_users.t
index 21c3e53d..446e0476 100644
--- a/plugins/t/check_users.t
+++ b/plugins/t/check_users.t
@@ -15,8 +15,8 @@ use NPTest;
15use vars qw($tests); 15use vars qw($tests);
16BEGIN {$tests = 12; plan tests => $tests} 16BEGIN {$tests = 12; plan tests => $tests}
17 17
18my $successOutput = '/^USERS OK - [0-9]+ users currently logged in/'; 18my $successOutput = '/[0-9]+ users currently logged in/';
19my $failureOutput = '/^USERS CRITICAL - [0-9]+ users currently logged in/'; 19my $failureOutput = '/[0-9]+ users currently logged in/';
20my $wrongOptionOutput = '/Usage:/'; 20my $wrongOptionOutput = '/Usage:/';
21 21
22my $t; 22my $t;