summaryrefslogtreecommitdiffstats
path: root/plugins/check_smtp.c
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/check_smtp.c')
-rw-r--r--plugins/check_smtp.c1434
1 files changed, 783 insertions, 651 deletions
diff --git a/plugins/check_smtp.c b/plugins/check_smtp.c
index e6369e63..e806ad29 100644
--- a/plugins/check_smtp.c
+++ b/plugins/check_smtp.c
@@ -1,263 +1,302 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2 *
3* Monitoring check_smtp plugin 3 * Monitoring check_smtp plugin
4* 4 *
5* License: GPL 5 * License: GPL
6* Copyright (c) 2000-2024 Monitoring Plugins Development Team 6 * Copyright (c) 2000-2024 Monitoring Plugins Development Team
7* 7 *
8* Description: 8 * Description:
9* 9 *
10* This file contains the check_smtp plugin 10 * This file contains the check_smtp plugin
11* 11 *
12* This plugin will attempt to open an SMTP connection with the host. 12 * This plugin will attempt to open an SMTP connection with the host.
13* 13 *
14* 14 *
15* This program is free software: you can redistribute it and/or modify 15 * This program is free software: you can redistribute it and/or modify
16* it under the terms of the GNU General Public License as published by 16 * it under the terms of the GNU General Public License as published by
17* the Free Software Foundation, either version 3 of the License, or 17 * the Free Software Foundation, either version 3 of the License, or
18* (at your option) any later version. 18 * (at your option) any later version.
19* 19 *
20* This program is distributed in the hope that it will be useful, 20 * This program is distributed in the hope that it will be useful,
21* but WITHOUT ANY WARRANTY; without even the implied warranty of 21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23* GNU General Public License for more details. 23 * GNU General Public License for more details.
24* 24 *
25* You should have received a copy of the GNU General Public License 25 * You should have received a copy of the GNU General Public License
26* along with this program. If not, see <http://www.gnu.org/licenses/>. 26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27* 27 *
28* 28 *
29*****************************************************************************/ 29 *****************************************************************************/
30
31const char *progname = "check_smtp";
32const char *copyright = "2000-2024";
33const char *email = "devel@monitoring-plugins.org";
34 30
35#include "common.h" 31#include "common.h"
36#include "netutils.h" 32#include "netutils.h"
33#include "output.h"
34#include "perfdata.h"
35#include "thresholds.h"
37#include "utils.h" 36#include "utils.h"
38#include "base64.h" 37#include "base64.h"
38#include "regex.h"
39 39
40#include <bits/getopt_ext.h>
40#include <ctype.h> 41#include <ctype.h>
42#include <string.h>
43#include "check_smtp.d/config.h"
44#include "../lib/states.h"
41 45
46const char *progname = "check_smtp";
47const char *copyright = "2000-2024";
48const char *email = "devel@monitoring-plugins.org";
49
50#define PROXY_PREFIX "PROXY TCP4 0.0.0.0 0.0.0.0 25 25\r\n"
51#define SMTP_HELO "HELO "
52#define SMTP_EHLO "EHLO "
53#define SMTP_LHLO "LHLO "
54#define SMTP_QUIT "QUIT\r\n"
55#define SMTP_STARTTLS "STARTTLS\r\n"
56#define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
57
58#define EHLO_SUPPORTS_STARTTLS 1
59
60typedef struct {
61 int errorcode;
62 check_smtp_config config;
63} check_smtp_config_wrapper;
64static check_smtp_config_wrapper process_arguments(int /*argc*/, char ** /*argv*/);
65
66int my_recv(check_smtp_config config, void *buf, int num, int socket_descriptor,
67 bool ssl_established) {
42#ifdef HAVE_SSL 68#ifdef HAVE_SSL
43static bool check_cert = false; 69 if ((config.use_starttls || config.use_ssl) && ssl_established) {
44static int days_till_exp_warn, days_till_exp_crit; 70 return np_net_ssl_read(buf, num);
45# define my_recv(buf, len) (((use_starttls || use_ssl) && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len)) 71 }
46# define my_send(buf, len) (((use_starttls || use_ssl) && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0)) 72 return (int)read(socket_descriptor, buf, (size_t)num);
47#else /* ifndef HAVE_SSL */ 73#else /* ifndef HAVE_SSL */
48# define my_recv(buf, len) read(sd, buf, len) 74 return read(socket_descriptor, buf, len)
49# define my_send(buf, len) send(sd, buf, len, 0)
50#endif 75#endif
76}
51 77
52enum { 78int my_send(check_smtp_config config, void *buf, int num, int socket_descriptor,
53 SMTP_PORT = 25, 79 bool ssl_established) {
54 SMTPS_PORT = 465 80#ifdef HAVE_SSL
55}; 81 if ((config.use_starttls || config.use_ssl) && ssl_established) {
56#define PROXY_PREFIX "PROXY TCP4 0.0.0.0 0.0.0.0 25 25\r\n"
57#define SMTP_EXPECT "220"
58#define SMTP_HELO "HELO "
59#define SMTP_EHLO "EHLO "
60#define SMTP_LHLO "LHLO "
61#define SMTP_QUIT "QUIT\r\n"
62#define SMTP_STARTTLS "STARTTLS\r\n"
63#define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
64 82
65#define EHLO_SUPPORTS_STARTTLS 1 83 return np_net_ssl_write(buf, num);
84 }
85 return (int)send(socket_descriptor, buf, (size_t)num, 0);
86#else /* ifndef HAVE_SSL */
87 return send(socket_descriptor, buf, len, 0);
88#endif
89}
66 90
67static int process_arguments (int, char **); 91static void print_help(void);
68static int validate_arguments (void); 92void print_usage(void);
69static void print_help (void); 93static char *smtp_quit(check_smtp_config /*config*/, char /*buffer*/[MAX_INPUT_BUFFER],
70void print_usage (void); 94 int /*socket_descriptor*/, bool /*ssl_established*/);
71static void smtp_quit(void); 95static int recvline(char * /*buf*/, size_t /*bufsize*/, check_smtp_config /*config*/,
72static int recvline(char *, size_t); 96 int /*socket_descriptor*/, bool /*ssl_established*/);
73static int recvlines(char *, size_t); 97static int recvlines(check_smtp_config /*config*/, char * /*buf*/, size_t /*bufsize*/,
74static int my_close(void); 98 int /*socket_descriptor*/, bool /*ssl_established*/);
99static int my_close(int /*socket_descriptor*/);
75 100
76#include "regex.h"
77static regex_t preg;
78static regmatch_t pmatch[10];
79static char errbuf[MAX_INPUT_BUFFER];
80static int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
81static int eflags = 0;
82static int errcode, excode;
83
84static int server_port = SMTP_PORT;
85static int server_port_option = 0;
86static char *server_address = NULL;
87static char *server_expect = NULL;
88static char *mail_command = NULL;
89static char *from_arg = NULL;
90static int send_mail_from=0;
91static int ncommands=0;
92static int command_size=0;
93static int nresponses=0;
94static int response_size=0;
95static char **commands = NULL;
96static char **responses = NULL;
97static char *authtype = NULL;
98static char *authuser = NULL;
99static char *authpass = NULL;
100static double warning_time = 0;
101static bool check_warning_time = false;
102static double critical_time = 0;
103static bool check_critical_time = false;
104static int verbose = 0; 101static int verbose = 0;
105static bool use_ssl = false;
106static bool use_starttls = false;
107static bool use_sni = false;
108static bool use_proxy_prefix = false;
109static bool use_ehlo = false;
110static bool use_lhlo = false;
111static bool ssl_established = false;
112static char *localhostname = NULL;
113static int sd;
114static char buffer[MAX_INPUT_BUFFER];
115enum {
116 TCP_PROTOCOL = 1,
117 UDP_PROTOCOL = 2,
118};
119static bool ignore_send_quit_failure = false;
120
121
122int
123main (int argc, char **argv)
124{
125 bool supports_tls = false;
126 int n = 0;
127 double elapsed_time;
128 long microsec;
129 int result = STATE_UNKNOWN;
130 char *cmd_str = NULL;
131 char *helocmd = NULL;
132 char *error_msg = "";
133 char *server_response = NULL;
134 struct timeval tv;
135
136 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
137 (void) signal (SIGPIPE, SIG_IGN);
138 102
139 setlocale (LC_ALL, ""); 103int main(int argc, char **argv) {
140 bindtextdomain (PACKAGE, LOCALEDIR); 104 setlocale(LC_ALL, "");
141 textdomain (PACKAGE); 105 bindtextdomain(PACKAGE, LOCALEDIR);
106 textdomain(PACKAGE);
142 107
143 /* Parse extra opts if any */ 108 /* Parse extra opts if any */
144 argv=np_extra_opts (&argc, argv, progname); 109 argv = np_extra_opts(&argc, argv, progname);
145 110
146 if (process_arguments (argc, argv) == ERROR) 111 check_smtp_config_wrapper tmp_config = process_arguments(argc, argv);
147 usage4 (_("Could not parse arguments")); 112
113 if (tmp_config.errorcode == ERROR) {
114 usage4(_("Could not parse arguments"));
115 }
116
117 const check_smtp_config config = tmp_config.config;
118
119 if (config.output_format_is_set) {
120 mp_set_format(config.output_format);
121 }
148 122
149 /* If localhostname not set on command line, use gethostname to set */ 123 /* If localhostname not set on command line, use gethostname to set */
150 if(! localhostname){ 124 char *localhostname = config.localhostname;
151 localhostname = malloc (HOST_MAX_BYTES); 125 if (!localhostname) {
152 if(!localhostname){ 126 localhostname = malloc(HOST_MAX_BYTES);
127 if (!localhostname) {
153 printf(_("malloc() failed!\n")); 128 printf(_("malloc() failed!\n"));
154 return STATE_CRITICAL; 129 exit(STATE_CRITICAL);
155 } 130 }
156 if(gethostname(localhostname, HOST_MAX_BYTES)){ 131 if (gethostname(localhostname, HOST_MAX_BYTES)) {
157 printf(_("gethostname() failed!\n")); 132 printf(_("gethostname() failed!\n"));
158 return STATE_CRITICAL; 133 exit(STATE_CRITICAL);
159 } 134 }
160 } 135 }
161 if(use_lhlo)
162 xasprintf (&helocmd, "%s%s%s", SMTP_LHLO, localhostname, "\r\n");
163 else if(use_ehlo)
164 xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
165 else
166 xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
167 136
168 if (verbose) 137 char *helocmd = NULL;
138 if (config.use_lhlo) {
139 xasprintf(&helocmd, "%s%s%s", SMTP_LHLO, localhostname, "\r\n");
140 } else if (config.use_ehlo) {
141 xasprintf(&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
142 } else {
143 xasprintf(&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
144 }
145
146 if (verbose) {
169 printf("HELOCMD: %s", helocmd); 147 printf("HELOCMD: %s", helocmd);
148 }
170 149
150 char *mail_command = strdup("MAIL ");
151 char *cmd_str = NULL;
171 /* initialize the MAIL command with optional FROM command */ 152 /* initialize the MAIL command with optional FROM command */
172 xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n"); 153 xasprintf(&cmd_str, "%sFROM:<%s>%s", mail_command, config.from_arg, "\r\n");
154
155 if (verbose && config.send_mail_from) {
156 printf("FROM CMD: %s", cmd_str);
157 }
173 158
174 if (verbose && send_mail_from) 159 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
175 printf ("FROM CMD: %s", cmd_str); 160 (void)signal(SIGPIPE, SIG_IGN);
176 161
177 /* initialize alarm signal handling */ 162 /* initialize alarm signal handling */
178 (void) signal (SIGALRM, socket_timeout_alarm_handler); 163 (void)signal(SIGALRM, socket_timeout_alarm_handler);
179 164
180 /* set socket timeout */ 165 /* set socket timeout */
181 (void) alarm (socket_timeout); 166 (void)alarm(socket_timeout);
182 167
168 struct timeval start_time;
183 /* start timer */ 169 /* start timer */
184 gettimeofday (&tv, NULL); 170 gettimeofday(&start_time, NULL);
171
172 int socket_descriptor = 0;
185 173
186 /* try to connect to the host at the given port number */ 174 /* try to connect to the host at the given port number */
187 result = my_tcp_connect (server_address, server_port, &sd); 175 mp_state_enum tcp_result =
188 176 my_tcp_connect(config.server_address, config.server_port, &socket_descriptor);
189 if (result == STATE_OK) { /* we connected */ 177
190 /* If requested, send PROXY header */ 178 mp_check overall = mp_check_init();
191 if (use_proxy_prefix) { 179 mp_subcheck sc_tcp_connect = mp_subcheck_init();
192 if (verbose) 180 char buffer[MAX_INPUT_BUFFER];
193 printf ("Sending header %s\n", PROXY_PREFIX); 181 bool ssl_established = false;
194 my_send(PROXY_PREFIX, strlen(PROXY_PREFIX)); 182
183 if (tcp_result != STATE_OK) {
184 // Connect failed
185 sc_tcp_connect = mp_set_subcheck_state(sc_tcp_connect, STATE_CRITICAL);
186 xasprintf(&sc_tcp_connect.output, "TCP connect to '%s' failed", config.server_address);
187 mp_add_subcheck_to_check(&overall, sc_tcp_connect);
188 mp_exit(overall);
189 }
190
191 /* we connected */
192 /* If requested, send PROXY header */
193 if (config.use_proxy_prefix) {
194 if (verbose) {
195 printf("Sending header %s\n", PROXY_PREFIX);
195 } 196 }
197 my_send(config, PROXY_PREFIX, strlen(PROXY_PREFIX), socket_descriptor, ssl_established);
198 }
196 199
197#ifdef HAVE_SSL 200#ifdef HAVE_SSL
198 if (use_ssl) { 201 if (config.use_ssl) {
199 result = np_net_ssl_init_with_hostname(sd, (use_sni ? server_address : NULL)); 202 int tls_result = np_net_ssl_init_with_hostname(
200 if (result != STATE_OK) { 203 socket_descriptor, (config.use_sni ? config.server_address : NULL));
201 printf (_("CRITICAL - Cannot create SSL context.\n")); 204
202 close(sd); 205 mp_subcheck sc_tls_connection = mp_subcheck_init();
203 np_net_ssl_cleanup(); 206
204 return STATE_CRITICAL; 207 if (tls_result != STATE_OK) {
205 } else { 208 close(socket_descriptor);
206 ssl_established = 1; 209 np_net_ssl_cleanup();
207 } 210
211 sc_tls_connection = mp_set_subcheck_state(sc_tls_connection, STATE_CRITICAL);
212 xasprintf(&sc_tls_connection.output, "cannot create TLS context");
213 mp_add_subcheck_to_check(&overall, sc_tls_connection);
214 mp_exit(overall);
208 } 215 }
216
217 sc_tls_connection = mp_set_subcheck_state(sc_tls_connection, STATE_OK);
218 xasprintf(&sc_tls_connection.output, "TLS context established");
219 mp_add_subcheck_to_check(&overall, sc_tls_connection);
220 ssl_established = true;
221 }
209#endif 222#endif
210 223
211 /* watch for the SMTP connection string and */ 224 /* watch for the SMTP connection string and */
212 /* return a WARNING status if we couldn't read any data */ 225 /* return a WARNING status if we couldn't read any data */
213 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { 226 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <= 0) {
214 printf (_("recv() failed\n")); 227 mp_subcheck sc_read_data = mp_subcheck_init();
215 return STATE_WARNING; 228 sc_read_data = mp_set_subcheck_state(sc_read_data, STATE_WARNING);
229 xasprintf(&sc_read_data.output, "recv() failed");
230 mp_add_subcheck_to_check(&overall, sc_read_data);
231 mp_exit(overall);
232 }
233
234 char *server_response = NULL;
235 /* save connect return (220 hostname ..) for later use */
236 xasprintf(&server_response, "%s", buffer);
237
238 /* send the HELO/EHLO command */
239 my_send(config, helocmd, (int)strlen(helocmd), socket_descriptor, ssl_established);
240
241 /* allow for response to helo command to reach us */
242 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <= 0) {
243 mp_subcheck sc_read_data = mp_subcheck_init();
244 sc_read_data = mp_set_subcheck_state(sc_read_data, STATE_WARNING);
245 xasprintf(&sc_read_data.output, "recv() failed");
246 mp_add_subcheck_to_check(&overall, sc_read_data);
247 mp_exit(overall);
248 }
249
250 bool supports_tls = false;
251 if (config.use_ehlo || config.use_lhlo) {
252 if (strstr(buffer, "250 STARTTLS") != NULL || strstr(buffer, "250-STARTTLS") != NULL) {
253 supports_tls = true;
216 } 254 }
255 }
217 256
218 /* save connect return (220 hostname ..) for later use */ 257 if (config.use_starttls && !supports_tls) {
219 xasprintf(&server_response, "%s", buffer); 258 smtp_quit(config, buffer, socket_descriptor, ssl_established);
220 259
221 /* send the HELO/EHLO command */ 260 mp_subcheck sc_read_data = mp_subcheck_init();
222 my_send(helocmd, strlen(helocmd)); 261 sc_read_data = mp_set_subcheck_state(sc_read_data, STATE_WARNING);
262 xasprintf(&sc_read_data.output, "StartTLS not supported by server");
263 mp_add_subcheck_to_check(&overall, sc_read_data);
264 mp_exit(overall);
265 }
223 266
224 /* allow for response to helo command to reach us */ 267#ifdef HAVE_SSL
225 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { 268 if (config.use_starttls) {
226 printf (_("recv() failed\n")); 269 /* send the STARTTLS command */
227 return STATE_WARNING; 270 send(socket_descriptor, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
228 } else if(use_ehlo || use_lhlo){ 271
229 if(strstr(buffer, "250 STARTTLS") != NULL || 272 mp_subcheck sc_starttls_init = mp_subcheck_init();
230 strstr(buffer, "250-STARTTLS") != NULL){ 273 recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
231 supports_tls=true; 274 ssl_established); /* wait for it */
232 } 275 if (!strstr(buffer, SMTP_EXPECT)) {
276 smtp_quit(config, buffer, socket_descriptor, ssl_established);
277
278 xasprintf(&sc_starttls_init.output, "StartTLS not supported by server");
279 sc_starttls_init = mp_set_subcheck_state(sc_starttls_init, STATE_UNKNOWN);
280 mp_add_subcheck_to_check(&overall, sc_starttls_init);
281 mp_exit(overall);
233 } 282 }
234 283
235 if(use_starttls && ! supports_tls){ 284 mp_state_enum starttls_result = np_net_ssl_init_with_hostname(
236 printf(_("WARNING - TLS not supported by server\n")); 285 socket_descriptor, (config.use_sni ? config.server_address : NULL));
237 smtp_quit(); 286 if (starttls_result != STATE_OK) {
238 return STATE_WARNING; 287 close(socket_descriptor);
288 np_net_ssl_cleanup();
289
290 sc_starttls_init = mp_set_subcheck_state(sc_starttls_init, STATE_CRITICAL);
291 xasprintf(&sc_starttls_init.output, "failed to create StartTLS context");
292 mp_add_subcheck_to_check(&overall, sc_starttls_init);
293 mp_exit(overall);
239 } 294 }
295 sc_starttls_init = mp_set_subcheck_state(sc_starttls_init, STATE_OK);
296 xasprintf(&sc_starttls_init.output, "created StartTLS context");
297 mp_add_subcheck_to_check(&overall, sc_starttls_init);
240 298
241#ifdef HAVE_SSL 299 ssl_established = true;
242 if(use_starttls) {
243 /* send the STARTTLS command */
244 send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
245
246 recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
247 if (!strstr (buffer, SMTP_EXPECT)) {
248 printf (_("Server does not support STARTTLS\n"));
249 smtp_quit();
250 return STATE_UNKNOWN;
251 }
252 result = np_net_ssl_init_with_hostname(sd, (use_sni ? server_address : NULL));
253 if(result != STATE_OK) {
254 printf (_("CRITICAL - Cannot create SSL context.\n"));
255 close(sd);
256 np_net_ssl_cleanup();
257 return STATE_CRITICAL;
258 } else {
259 ssl_established = 1;
260 }
261 300
262 /* 301 /*
263 * Resend the EHLO command. 302 * Resend the EHLO command.
@@ -270,218 +309,287 @@ main (int argc, char **argv)
270 * reason, some MTAs will not allow an AUTH LOGIN command before 309 * reason, some MTAs will not allow an AUTH LOGIN command before
271 * we resent EHLO via TLS. 310 * we resent EHLO via TLS.
272 */ 311 */
273 if (my_send(helocmd, strlen(helocmd)) <= 0) { 312 if (my_send(config, helocmd, (int)strlen(helocmd), socket_descriptor, ssl_established) <=
274 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS.")); 313 0) {
275 my_close(); 314 my_close(socket_descriptor);
276 return STATE_UNKNOWN; 315
316 mp_subcheck sc_ehlo = mp_subcheck_init();
317 sc_ehlo = mp_set_subcheck_state(sc_ehlo, STATE_UNKNOWN);
318 xasprintf(&sc_ehlo.output, "cannot send EHLO command via StartTLS");
319 mp_add_subcheck_to_check(&overall, sc_ehlo);
320 mp_exit(overall);
277 } 321 }
278 if (verbose) 322
323 if (verbose) {
279 printf(_("sent %s"), helocmd); 324 printf(_("sent %s"), helocmd);
280 if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
281 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
282 my_close();
283 return STATE_UNKNOWN;
284 } 325 }
326
327 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) <= 0) {
328 my_close(socket_descriptor);
329
330 mp_subcheck sc_ehlo = mp_subcheck_init();
331 sc_ehlo = mp_set_subcheck_state(sc_ehlo, STATE_UNKNOWN);
332 xasprintf(&sc_ehlo.output, "cannot read EHLO response via StartTLS");
333 mp_add_subcheck_to_check(&overall, sc_ehlo);
334 mp_exit(overall);
335 }
336
285 if (verbose) { 337 if (verbose) {
286 printf("%s", buffer); 338 printf("%s", buffer);
287 } 339 }
340 }
341
342# ifdef USE_OPENSSL
343 if (ssl_established) {
344 net_ssl_check_cert_result cert_check_result =
345 np_net_ssl_check_cert2(config.days_till_exp_warn, config.days_till_exp_crit);
346
347 mp_subcheck sc_cert_check = mp_subcheck_init();
348
349 switch (cert_check_result.errors) {
350 case ALL_OK: {
351
352 if (cert_check_result.result_state != STATE_OK &&
353 config.ignore_certificate_expiration) {
354 xasprintf(&sc_cert_check.output,
355 "Remaining certificate lifetime: %d days. Expiration will be ignored",
356 (int)(cert_check_result.remaining_seconds / 86400));
357 sc_cert_check = mp_set_subcheck_state(sc_cert_check, STATE_OK);
358 } else {
359 xasprintf(&sc_cert_check.output, "Remaining certificate lifetime: %d days",
360 (int)(cert_check_result.remaining_seconds / 86400));
361 sc_cert_check =
362 mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
363 }
364 } break;
365 case NO_SERVER_CERTIFICATE_PRESENT: {
366 xasprintf(&sc_cert_check.output, "no server certificate present");
367 sc_cert_check = mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
368 } break;
369 case UNABLE_TO_RETRIEVE_CERTIFICATE_SUBJECT: {
370 xasprintf(&sc_cert_check.output, "can not retrieve certificate subject");
371 sc_cert_check = mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
372 } break;
373 case WRONG_TIME_FORMAT_IN_CERTIFICATE: {
374 xasprintf(&sc_cert_check.output, "wrong time format in certificate");
375 sc_cert_check = mp_set_subcheck_state(sc_cert_check, cert_check_result.result_state);
376 } break;
377 };
378
379 mp_add_subcheck_to_check(&overall, sc_cert_check);
380 }
381# endif /* USE_OPENSSL */
288 382
289# ifdef USE_OPENSSL
290 if ( check_cert ) {
291 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
292 smtp_quit();
293 my_close();
294 return result;
295 }
296# endif /* USE_OPENSSL */
297 }
298#endif 383#endif
299 384
300 if (verbose) 385 if (verbose) {
301 printf ("%s", buffer); 386 printf("%s", buffer);
302 387 }
303 /* save buffer for later use */ 388
304 xasprintf(&server_response, "%s%s", server_response, buffer); 389 /* save buffer for later use */
305 /* strip the buffer of carriage returns */ 390 xasprintf(&server_response, "%s%s", server_response, buffer);
306 strip (server_response); 391 /* strip the buffer of carriage returns */
307 392 strip(server_response);
308 /* make sure we find the droids we are looking for */ 393
309 if (!strstr (server_response, server_expect)) { 394 /* make sure we find the droids we are looking for */
310 if (server_port == SMTP_PORT) 395 mp_subcheck sc_expect_response = mp_subcheck_init();
311 printf (_("Invalid SMTP response received from host: %s\n"), server_response); 396
312 else 397 if (!strstr(server_response, config.server_expect)) {
313 printf (_("Invalid SMTP response received from host on port %d: %s\n"), 398 sc_expect_response = mp_set_subcheck_state(sc_expect_response, STATE_WARNING);
314 server_port, server_response); 399 if (config.server_port == SMTP_PORT) {
315 return STATE_WARNING; 400 xasprintf(&sc_expect_response.output, _("invalid SMTP response received from host: %s"),
401 server_response);
402 } else {
403 xasprintf(&sc_expect_response.output,
404 _("invalid SMTP response received from host on port %d: %s"),
405 config.server_port, server_response);
316 } 406 }
407 exit(STATE_WARNING);
408 } else {
409 xasprintf(&sc_expect_response.output, "received valid SMTP response '%s' from host: '%s'",
410 config.server_expect, server_response);
411 sc_expect_response = mp_set_subcheck_state(sc_expect_response, STATE_OK);
412 }
413
414 mp_add_subcheck_to_check(&overall, sc_expect_response);
317 415
318 if (send_mail_from) { 416 if (config.send_mail_from) {
319 my_send(cmd_str, strlen(cmd_str)); 417 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established);
320 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) 418 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >= 1 &&
321 printf("%s", buffer); 419 verbose) {
420 printf("%s", buffer);
421 }
422 }
423
424 size_t counter = 0;
425 while (counter < config.ncommands) {
426 xasprintf(&cmd_str, "%s%s", config.commands[counter], "\r\n");
427 my_send(config, cmd_str, (int)strlen(cmd_str), socket_descriptor, ssl_established);
428 if (recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established) >= 1 &&
429 verbose) {
430 printf("%s", buffer);
322 } 431 }
323 432
324 n = 0; 433 strip(buffer);
325 while (n < ncommands) { 434
326 xasprintf (&cmd_str, "%s%s", commands[n], "\r\n"); 435 if (counter < config.nresponses) {
327 my_send(cmd_str, strlen(cmd_str)); 436 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
328 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) 437 regex_t preg;
329 printf("%s", buffer); 438 int errcode = regcomp(&preg, config.responses[counter], cflags);
330 strip (buffer); 439 char errbuf[MAX_INPUT_BUFFER];
331 if (n < nresponses) { 440 if (errcode != 0) {
332 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; 441 regerror(errcode, &preg, errbuf, MAX_INPUT_BUFFER);
333 errcode = regcomp (&preg, responses[n], cflags); 442 printf(_("Could Not Compile Regular Expression"));
334 if (errcode != 0) { 443 exit(STATE_UNKNOWN);
335 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); 444 }
336 printf (_("Could Not Compile Regular Expression")); 445
337 return ERROR; 446 regmatch_t pmatch[10];
447 int eflags = 0;
448 int excode = regexec(&preg, buffer, 10, pmatch, eflags);
449 mp_subcheck sc_expected_responses = mp_subcheck_init();
450 if (excode == 0) {
451 xasprintf(&sc_expected_responses.output, "valid response '%s' to command '%s'",
452 buffer, config.commands[counter]);
453 sc_expected_responses = mp_set_subcheck_state(sc_expected_responses, STATE_OK);
454 } else if (excode == REG_NOMATCH) {
455 sc_expected_responses = mp_set_subcheck_state(sc_expected_responses, STATE_WARNING);
456 xasprintf(&sc_expected_responses.output, "invalid response '%s' to command '%s'",
457 buffer, config.commands[counter]);
458 } else {
459 regerror(excode, &preg, errbuf, MAX_INPUT_BUFFER);
460 xasprintf(&sc_expected_responses.output, "regexec execute error: %s", errbuf);
461 sc_expected_responses = mp_set_subcheck_state(sc_expected_responses, STATE_UNKNOWN);
462 }
463 }
464 counter++;
465 }
466
467 if (config.authtype != NULL) {
468 mp_subcheck sc_auth = mp_subcheck_init();
469
470 if (strcmp(config.authtype, "LOGIN") == 0) {
471 char *abuf;
472 int ret;
473 do {
474 /* send AUTH LOGIN */
475 my_send(config, SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN), socket_descriptor,
476 ssl_established);
477
478 if (verbose) {
479 printf(_("sent %s\n"), "AUTH LOGIN");
338 } 480 }
339 excode = regexec (&preg, buffer, 10, pmatch, eflags); 481
340 if (excode == 0) { 482 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
341 result = STATE_OK; 483 ssl_established)) <= 0) {
484 xasprintf(&sc_auth.output, _("recv() failed after AUTH LOGIN"));
485 sc_auth = mp_set_subcheck_state(sc_auth, STATE_WARNING);
486 break;
342 } 487 }
343 else if (excode == REG_NOMATCH) { 488
344 result = STATE_WARNING; 489 if (verbose) {
345 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]); 490 printf(_("received %s\n"), buffer);
346 } 491 }
347 else { 492
348 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER); 493 if (strncmp(buffer, "334", 3) != 0) {
349 printf (_("Execute Error: %s\n"), errbuf); 494 xasprintf(&sc_auth.output, "invalid response received after AUTH LOGIN");
350 result = STATE_UNKNOWN; 495 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
496 break;
497 }
498
499 /* encode authuser with base64 */
500 base64_encode_alloc(config.authuser, strlen(config.authuser), &abuf);
501 xasprintf(&abuf, "%s\r\n", abuf);
502 my_send(config, abuf, (int)strlen(abuf), socket_descriptor, ssl_established);
503 if (verbose) {
504 printf(_("sent %s\n"), abuf);
351 } 505 }
352 }
353 n++;
354 }
355 506
356 if (authtype != NULL) { 507 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
357 if (strcmp (authtype, "LOGIN") == 0) { 508 ssl_established)) <= 0) {
358 char *abuf; 509 xasprintf(&sc_auth.output, "recv() failed after sending authuser");
359 int ret; 510 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
360 do {
361 if (authuser == NULL) {
362 result = STATE_CRITICAL;
363 xasprintf(&error_msg, _("no authuser specified, "));
364 break;
365 }
366 if (authpass == NULL) {
367 result = STATE_CRITICAL;
368 xasprintf(&error_msg, _("no authpass specified, "));
369 break;
370 }
371
372 /* send AUTH LOGIN */
373 my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
374 if (verbose)
375 printf (_("sent %s\n"), "AUTH LOGIN");
376
377 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
378 xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
379 result = STATE_WARNING;
380 break;
381 }
382 if (verbose)
383 printf (_("received %s\n"), buffer);
384
385 if (strncmp (buffer, "334", 3) != 0) {
386 result = STATE_CRITICAL;
387 xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
388 break;
389 }
390
391 /* encode authuser with base64 */
392 base64_encode_alloc (authuser, strlen(authuser), &abuf);
393 xasprintf(&abuf, "%s\r\n", abuf);
394 my_send(abuf, strlen(abuf));
395 if (verbose)
396 printf (_("sent %s\n"), abuf);
397
398 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
399 result = STATE_CRITICAL;
400 xasprintf(&error_msg, _("recv() failed after sending authuser, "));
401 break;
402 }
403 if (verbose) {
404 printf (_("received %s\n"), buffer);
405 }
406 if (strncmp (buffer, "334", 3) != 0) {
407 result = STATE_CRITICAL;
408 xasprintf(&error_msg, _("invalid response received after authuser, "));
409 break;
410 }
411 /* encode authpass with base64 */
412 base64_encode_alloc (authpass, strlen(authpass), &abuf);
413 xasprintf(&abuf, "%s\r\n", abuf);
414 my_send(abuf, strlen(abuf));
415 if (verbose) {
416 printf (_("sent %s\n"), abuf);
417 }
418 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
419 result = STATE_CRITICAL;
420 xasprintf(&error_msg, _("recv() failed after sending authpass, "));
421 break;
422 }
423 if (verbose) {
424 printf (_("received %s\n"), buffer);
425 }
426 if (strncmp (buffer, "235", 3) != 0) {
427 result = STATE_CRITICAL;
428 xasprintf(&error_msg, _("invalid response received after authpass, "));
429 break;
430 }
431 break; 511 break;
432 } while (0); 512 }
433 } else {
434 result = STATE_CRITICAL;
435 xasprintf(&error_msg, _("only authtype LOGIN is supported, "));
436 }
437 }
438 513
439 /* tell the server we're done */ 514 if (verbose) {
440 smtp_quit(); 515 printf(_("received %s\n"), buffer);
516 }
441 517
442 /* finally close the connection */ 518 if (strncmp(buffer, "334", 3) != 0) {
443 close (sd); 519 xasprintf(&sc_auth.output, "invalid response received after authuser");
444 } 520 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
521 break;
522 }
445 523
446 /* reset the alarm */ 524 /* encode authpass with base64 */
447 alarm (0); 525 base64_encode_alloc(config.authpass, strlen(config.authpass), &abuf);
526 xasprintf(&abuf, "%s\r\n", abuf);
527 my_send(config, abuf, (int)strlen(abuf), socket_descriptor, ssl_established);
528
529 if (verbose) {
530 printf(_("sent %s\n"), abuf);
531 }
532
533 if ((ret = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor,
534 ssl_established)) <= 0) {
535 xasprintf(&sc_auth.output, "recv() failed after sending authpass");
536 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
537 break;
538 }
448 539
449 microsec = deltime (tv); 540 if (verbose) {
450 elapsed_time = (double)microsec / 1.0e6; 541 printf(_("received %s\n"), buffer);
542 }
543
544 if (strncmp(buffer, "235", 3) != 0) {
545 xasprintf(&sc_auth.output, "invalid response received after authpass");
546 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
547 break;
548 }
549 break;
550 } while (false);
551 } else {
552 sc_auth = mp_set_subcheck_state(sc_auth, STATE_CRITICAL);
553 xasprintf(&sc_auth.output, "only authtype LOGIN is supported");
554 }
451 555
452 if (result == STATE_OK) { 556 mp_add_subcheck_to_check(&overall, sc_auth);
453 if (check_critical_time && elapsed_time > critical_time)
454 result = STATE_CRITICAL;
455 else if (check_warning_time && elapsed_time > warning_time)
456 result = STATE_WARNING;
457 } 557 }
458 558
459 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), 559 /* tell the server we're done */
460 state_text (result), 560 smtp_quit(config, buffer, socket_descriptor, ssl_established);
461 error_msg,
462 elapsed_time,
463 verbose?", ":"", verbose?buffer:"",
464 fperfdata ("time", elapsed_time, "s",
465 (int)check_warning_time, warning_time,
466 (int)check_critical_time, critical_time,
467 true, 0, false, 0));
468 561
469 return result; 562 /* finally close the connection */
470} 563 close(socket_descriptor);
471 564
565 /* reset the alarm */
566 alarm(0);
472 567
568 long microsec = deltime(start_time);
569 double elapsed_time = (double)microsec / 1.0e6;
473 570
474/* process command-line arguments */ 571 mp_perfdata pd_elapsed_time = perfdata_init();
475int 572 pd_elapsed_time = mp_set_pd_value(pd_elapsed_time, elapsed_time);
476process_arguments (int argc, char **argv) 573 pd_elapsed_time.label = "time";
477{ 574 pd_elapsed_time.uom = "s";
478 int c;
479 char* temp;
480 575
481 bool implicit_tls = false; 576 pd_elapsed_time = mp_pd_set_thresholds(pd_elapsed_time, config.connection_time);
577
578 mp_subcheck sc_connection_time = mp_subcheck_init();
579 xasprintf(&sc_connection_time.output, "connection time: %.3gs", elapsed_time);
580 sc_connection_time =
581 mp_set_subcheck_state(sc_connection_time, mp_get_pd_status(pd_elapsed_time));
582 mp_add_subcheck_to_check(&overall, sc_connection_time);
583
584 mp_exit(overall);
585}
482 586
587/* process command-line arguments */
588check_smtp_config_wrapper process_arguments(int argc, char **argv) {
483 enum { 589 enum {
484 SNI_OPTION 590 SNI_OPTION = CHAR_MAX + 1,
591 output_format_index,
592 ignore_certificate_expiration_index,
485 }; 593 };
486 594
487 int option = 0; 595 int option = 0;
@@ -507,173 +615,194 @@ process_arguments (int argc, char **argv)
507 {"lmtp", no_argument, 0, 'L'}, 615 {"lmtp", no_argument, 0, 'L'},
508 {"ssl", no_argument, 0, 's'}, 616 {"ssl", no_argument, 0, 's'},
509 {"tls", no_argument, 0, 's'}, 617 {"tls", no_argument, 0, 's'},
510 {"starttls",no_argument,0,'S'}, 618 {"starttls", no_argument, 0, 'S'},
511 {"sni", no_argument, 0, SNI_OPTION}, 619 {"sni", no_argument, 0, SNI_OPTION},
512 {"certificate",required_argument,0,'D'}, 620 {"certificate", required_argument, 0, 'D'},
513 {"ignore-quit-failure",no_argument,0,'q'}, 621 {"ignore-quit-failure", no_argument, 0, 'q'},
514 {"proxy",no_argument,0,'r'}, 622 {"proxy", no_argument, 0, 'r'},
515 {0, 0, 0, 0} 623 {"ignore-certificate-expiration", no_argument, 0, ignore_certificate_expiration_index},
624 {"output-format", required_argument, 0, output_format_index},
625 {0, 0, 0, 0}};
626
627 check_smtp_config_wrapper result = {
628 .config = check_smtp_config_init(),
629 .errorcode = OK,
516 }; 630 };
517 631
518 if (argc < 2) 632 if (argc < 2) {
519 return ERROR; 633 result.errorcode = ERROR;
634 return result;
635 }
520 636
521 for (c = 1; c < argc; c++) { 637 for (int index = 1; index < argc; index++) {
522 if (strcmp ("-to", argv[c]) == 0) 638 if (strcmp("-to", argv[index]) == 0) {
523 strcpy (argv[c], "-t"); 639 strcpy(argv[index], "-t");
524 else if (strcmp ("-wt", argv[c]) == 0) 640 } else if (strcmp("-wt", argv[index]) == 0) {
525 strcpy (argv[c], "-w"); 641 strcpy(argv[index], "-w");
526 else if (strcmp ("-ct", argv[c]) == 0) 642 } else if (strcmp("-ct", argv[index]) == 0) {
527 strcpy (argv[c], "-c"); 643 strcpy(argv[index], "-c");
644 }
528 } 645 }
529 646
530 while (1) { 647 unsigned long command_size = 0;
531 c = getopt_long (argc, argv, "+hVv46Lrt:p:f:e:c:w:H:C:R:sSD:F:A:U:P:q", 648 unsigned long response_size = 0;
532 longopts, &option); 649 bool implicit_tls = false;
650 int server_port_option = 0;
651 while (true) {
652 int opt_index =
653 getopt_long(argc, argv, "+hVv46Lrt:p:f:e:c:w:H:C:R:sSD:F:A:U:P:q", longopts, &option);
533 654
534 if (c == -1 || c == EOF) 655 if (opt_index == -1 || opt_index == EOF) {
535 break; 656 break;
657 }
536 658
537 switch (c) { 659 switch (opt_index) {
538 case 'H': /* hostname */ 660 case 'H': /* hostname */
539 if (is_host (optarg)) { 661 if (is_host(optarg)) {
540 server_address = optarg; 662 result.config.server_address = optarg;
541 } 663 } else {
542 else { 664 usage2(_("Invalid hostname/address"), optarg);
543 usage2 (_("Invalid hostname/address"), optarg);
544 } 665 }
545 break; 666 break;
546 case 'p': /* port */ 667 case 'p': /* port */
547 if (is_intpos (optarg)) 668 if (is_intpos(optarg)) {
548 server_port_option = atoi (optarg); 669 server_port_option = atoi(optarg);
549 else 670 } else {
550 usage4 (_("Port must be a positive integer")); 671 usage4(_("Port must be a positive integer"));
672 }
551 break; 673 break;
552 case 'F': 674 case 'F':
553 /* localhostname */ 675 /* localhostname */
554 localhostname = strdup(optarg); 676 result.config.localhostname = strdup(optarg);
555 break; 677 break;
556 case 'f': /* from argument */ 678 case 'f': /* from argument */
557 from_arg = optarg + strspn(optarg, "<"); 679 result.config.from_arg = optarg + strspn(optarg, "<");
558 from_arg = strndup(from_arg, strcspn(from_arg, ">")); 680 result.config.from_arg =
559 send_mail_from = 1; 681 strndup(result.config.from_arg, strcspn(result.config.from_arg, ">"));
682 result.config.send_mail_from = true;
560 break; 683 break;
561 case 'A': 684 case 'A':
562 authtype = optarg; 685 result.config.authtype = optarg;
563 use_ehlo = true; 686 result.config.use_ehlo = true;
564 break; 687 break;
565 case 'U': 688 case 'U':
566 authuser = optarg; 689 result.config.authuser = optarg;
567 break; 690 break;
568 case 'P': 691 case 'P':
569 authpass = optarg; 692 result.config.authpass = optarg;
570 break; 693 break;
571 case 'e': /* server expect string on 220 */ 694 case 'e': /* server expect string on 220 */
572 server_expect = optarg; 695 result.config.server_expect = optarg;
573 break; 696 break;
574 case 'C': /* commands */ 697 case 'C': /* commands */
575 if (ncommands >= command_size) { 698 if (result.config.ncommands >= command_size) {
576 command_size+=8; 699 command_size += 8;
577 commands = realloc (commands, sizeof(char *) * command_size); 700 result.config.commands =
578 if (commands == NULL) 701 realloc(result.config.commands, sizeof(char *) * command_size);
579 die (STATE_UNKNOWN, 702 if (result.config.commands == NULL) {
580 _("Could not realloc() units [%d]\n"), ncommands); 703 die(STATE_UNKNOWN, _("Could not realloc() units [%lu]\n"),
704 result.config.ncommands);
705 }
581 } 706 }
582 commands[ncommands] = (char *) malloc (sizeof(char) * 255); 707 result.config.commands[result.config.ncommands] = (char *)malloc(sizeof(char) * 255);
583 strncpy (commands[ncommands], optarg, 255); 708 strncpy(result.config.commands[result.config.ncommands], optarg, 255);
584 ncommands++; 709 result.config.ncommands++;
585 break; 710 break;
586 case 'R': /* server responses */ 711 case 'R': /* server responses */
587 if (nresponses >= response_size) { 712 if (result.config.nresponses >= response_size) {
588 response_size += 8; 713 response_size += 8;
589 responses = realloc (responses, sizeof(char *) * response_size); 714 result.config.responses =
590 if (responses == NULL) 715 realloc(result.config.responses, sizeof(char *) * response_size);
591 die (STATE_UNKNOWN, 716 if (result.config.responses == NULL) {
592 _("Could not realloc() units [%d]\n"), nresponses); 717 die(STATE_UNKNOWN, _("Could not realloc() units [%lu]\n"),
718 result.config.nresponses);
719 }
593 } 720 }
594 responses[nresponses] = (char *) malloc (sizeof(char) * 255); 721 result.config.responses[result.config.nresponses] = (char *)malloc(sizeof(char) * 255);
595 strncpy (responses[nresponses], optarg, 255); 722 strncpy(result.config.responses[result.config.nresponses], optarg, 255);
596 nresponses++; 723 result.config.nresponses++;
597 break; 724 break;
598 case 'c': /* critical time threshold */ 725 case 'c': /* critical time threshold */ {
599 if (!is_nonnegative (optarg)) 726 mp_range_parsed tmp = mp_parse_range_string(optarg);
600 usage4 (_("Critical time must be a positive")); 727 if (tmp.error != MP_PARSING_SUCCES) {
601 else { 728 die(STATE_UNKNOWN, "failed to parse critical time threshold");
602 critical_time = strtod (optarg, NULL);
603 check_critical_time = true;
604 } 729 }
605 break; 730 result.config.connection_time =
606 case 'w': /* warning time threshold */ 731 mp_thresholds_set_warn(result.config.connection_time, tmp.range);
607 if (!is_nonnegative (optarg)) 732 } break;
608 usage4 (_("Warning time must be a positive")); 733 case 'w': /* warning time threshold */ {
609 else { 734 mp_range_parsed tmp = mp_parse_range_string(optarg);
610 warning_time = strtod (optarg, NULL); 735 if (tmp.error != MP_PARSING_SUCCES) {
611 check_warning_time = true; 736 die(STATE_UNKNOWN, "failed to parse warning time threshold");
612 } 737 }
613 break; 738 result.config.connection_time =
614 case 'v': /* verbose */ 739 mp_thresholds_set_crit(result.config.connection_time, tmp.range);
740 } break;
741 case 'v': /* verbose */
615 verbose++; 742 verbose++;
616 break; 743 break;
617 case 'q': 744 case 'q':
618 ignore_send_quit_failure = true; /* ignore problem sending QUIT */ 745 result.config.ignore_send_quit_failure = true; /* ignore problem sending QUIT */
619 break; 746 break;
620 case 't': /* timeout */ 747 case 't': /* timeout */
621 if (is_intnonneg (optarg)) { 748 if (is_intnonneg(optarg)) {
622 socket_timeout = atoi (optarg); 749 socket_timeout = atoi(optarg);
623 } 750 } else {
624 else { 751 usage4(_("Timeout interval must be a positive integer"));
625 usage4 (_("Timeout interval must be a positive integer"));
626 } 752 }
627 break; 753 break;
628 case 'D': 754 case 'D': {
629 /* Check SSL cert validity */ 755 /* Check SSL cert validity */
630#ifdef USE_OPENSSL 756#ifdef USE_OPENSSL
631 if ((temp=strchr(optarg,','))!=NULL) { 757 char *temp;
632 *temp='\0'; 758 if ((temp = strchr(optarg, ',')) != NULL) {
633 if (!is_intnonneg (optarg)) 759 *temp = '\0';
634 usage2 ("Invalid certificate expiration period", optarg); 760 if (!is_intnonneg(optarg)) {
635 days_till_exp_warn = atoi(optarg); 761 usage2("Invalid certificate expiration period", optarg);
636 *temp=','; 762 }
637 temp++; 763 result.config.days_till_exp_warn = atoi(optarg);
638 if (!is_intnonneg (temp)) 764 *temp = ',';
639 usage2 (_("Invalid certificate expiration period"), temp); 765 temp++;
640 days_till_exp_crit = atoi (temp); 766 if (!is_intnonneg(temp)) {
641 } 767 usage2(_("Invalid certificate expiration period"), temp);
642 else { 768 }
643 days_till_exp_crit=0; 769 result.config.days_till_exp_crit = atoi(temp);
644 if (!is_intnonneg (optarg)) 770 } else {
645 usage2 ("Invalid certificate expiration period", optarg); 771 result.config.days_till_exp_crit = 0;
646 days_till_exp_warn = atoi (optarg); 772 if (!is_intnonneg(optarg)) {
647 } 773 usage2("Invalid certificate expiration period", optarg);
648 check_cert = true; 774 }
649 ignore_send_quit_failure = true; 775 result.config.days_till_exp_warn = atoi(optarg);
776 }
777 result.config.ignore_send_quit_failure = true;
650#else 778#else
651 usage (_("SSL support not available - install OpenSSL and recompile")); 779 usage(_("SSL support not available - install OpenSSL and recompile"));
652#endif 780#endif
653 implicit_tls = true; 781 implicit_tls = true;
654 // fallthrough 782 // fallthrough
655 case 's': 783 case 's':
656 /* ssl */ 784 /* ssl */
657 use_ssl = true; 785 result.config.use_ssl = true;
658 server_port = SMTPS_PORT; 786 result.config.server_port = SMTPS_PORT;
659 break; 787 break;
660 case 'S': 788 case 'S':
661 /* starttls */ 789 /* starttls */
662 use_starttls = true; 790 result.config.use_starttls = true;
663 use_ehlo = true; 791 result.config.use_ehlo = true;
664 break; 792 break;
793 }
665 case SNI_OPTION: 794 case SNI_OPTION:
666#ifdef HAVE_SSL 795#ifdef HAVE_SSL
667 use_sni = true; 796 result.config.use_sni = true;
668#else 797#else
669 usage (_("SSL support not available - install OpenSSL and recompile")); 798 usage(_("SSL support not available - install OpenSSL and recompile"));
670#endif 799#endif
671 break; 800 break;
672 case 'r': 801 case 'r':
673 use_proxy_prefix = true; 802 result.config.use_proxy_prefix = true;
674 break; 803 break;
675 case 'L': 804 case 'L':
676 use_lhlo = true; 805 result.config.use_lhlo = true;
677 break; 806 break;
678 case '4': 807 case '4':
679 address_family = AF_INET; 808 address_family = AF_INET;
@@ -682,102 +811,109 @@ process_arguments (int argc, char **argv)
682#ifdef USE_IPV6 811#ifdef USE_IPV6
683 address_family = AF_INET6; 812 address_family = AF_INET6;
684#else 813#else
685 usage4 (_("IPv6 support not available")); 814 usage4(_("IPv6 support not available"));
686#endif 815#endif
687 break; 816 break;
688 case 'V': /* version */ 817 case 'V': /* version */
689 print_revision (progname, NP_VERSION); 818 print_revision(progname, NP_VERSION);
690 exit (STATE_UNKNOWN); 819 exit(STATE_UNKNOWN);
691 case 'h': /* help */ 820 case 'h': /* help */
692 print_help (); 821 print_help();
693 exit (STATE_UNKNOWN); 822 exit(STATE_UNKNOWN);
694 case '?': /* help */ 823 case '?': /* help */
695 usage5 (); 824 usage5();
825 case output_format_index: {
826 parsed_output_format parser = mp_parse_output_format(optarg);
827 if (!parser.parsing_success) {
828 // TODO List all available formats here, maybe add anothoer usage function
829 printf("Invalid output format: %s\n", optarg);
830 exit(STATE_UNKNOWN);
831 }
832
833 result.config.output_format_is_set = true;
834 result.config.output_format = parser.output_format;
835 break;
836 }
837 case ignore_certificate_expiration_index: {
838 result.config.ignore_certificate_expiration = true;
839 }
696 } 840 }
697 } 841 }
698 842
699 c = optind; 843 int c = optind;
700 if (server_address == NULL) { 844 if (result.config.server_address == NULL) {
701 if (argv[c]) { 845 if (argv[c]) {
702 if (is_host (argv[c])) 846 if (is_host(argv[c])) {
703 server_address = argv[c]; 847 result.config.server_address = argv[c];
704 else 848 } else {
705 usage2 (_("Invalid hostname/address"), argv[c]); 849 usage2(_("Invalid hostname/address"), argv[c]);
706 } 850 }
707 else { 851 } else {
708 xasprintf (&server_address, "127.0.0.1"); 852 result.config.server_address = strdup("localhost");
709 } 853 }
710 } 854 }
711 855
712 if (server_expect == NULL) 856 if (result.config.use_starttls && result.config.use_ssl) {
713 server_expect = strdup (SMTP_EXPECT);
714
715 if (mail_command == NULL)
716 mail_command = strdup("MAIL ");
717
718 if (from_arg==NULL)
719 from_arg = strdup(" ");
720
721 if (use_starttls && use_ssl) {
722 if (implicit_tls) { 857 if (implicit_tls) {
723 use_ssl = false; 858 result.config.use_ssl = false;
724 server_port = SMTP_PORT;
725 } else { 859 } else {
726 usage4 (_("Set either -s/--ssl/--tls or -S/--starttls")); 860 usage4(_("Set either -s/--ssl/--tls or -S/--starttls"));
727 } 861 }
728 } 862 }
729 863
730 if (server_port_option != 0) { 864 if (server_port_option != 0) {
731 server_port = server_port_option; 865 result.config.server_port = server_port_option;
732 } 866 }
733 867
734 return validate_arguments (); 868 if (result.config.authtype) {
735} 869 if (strcmp(result.config.authtype, "LOGIN") == 0) {
736 870 if (result.config.authuser == NULL) {
737 871 usage4("no authuser specified");
872 }
873 if (result.config.authpass == NULL) {
874 usage4("no authpass specified");
875 }
876 } else {
877 usage4("only authtype LOGIN is supported");
878 }
879 }
738 880
739int 881 return result;
740validate_arguments (void)
741{
742 return OK;
743} 882}
744 883
745 884char *smtp_quit(check_smtp_config config, char buffer[MAX_INPUT_BUFFER], int socket_descriptor,
746void 885 bool ssl_established) {
747smtp_quit(void) 886 int sent_bytes =
748{ 887 my_send(config, SMTP_QUIT, strlen(SMTP_QUIT), socket_descriptor, ssl_established);
749 int bytes; 888 if (sent_bytes < 0) {
750 int n; 889 if (config.ignore_send_quit_failure) {
751 890 if (verbose) {
752 n = my_send(SMTP_QUIT, strlen(SMTP_QUIT));
753 if(n < 0) {
754 if(ignore_send_quit_failure) {
755 if(verbose) {
756 printf(_("Connection closed by server before sending QUIT command\n")); 891 printf(_("Connection closed by server before sending QUIT command\n"));
757 } 892 }
758 return; 893 return buffer;
759 } 894 }
760 die (STATE_UNKNOWN, 895 die(STATE_UNKNOWN, _("Connection closed by server before sending QUIT command\n"));
761 _("Connection closed by server before sending QUIT command\n"));
762 } 896 }
763 897
764 if (verbose) 898 if (verbose) {
765 printf(_("sent %s\n"), "QUIT"); 899 printf(_("sent %s\n"), "QUIT");
900 }
766 901
767 /* read the response but don't care about problems */ 902 /* read the response but don't care about problems */
768 bytes = recvlines(buffer, MAX_INPUT_BUFFER); 903 int bytes = recvlines(config, buffer, MAX_INPUT_BUFFER, socket_descriptor, ssl_established);
769 if (verbose) { 904 if (verbose) {
770 if (bytes < 0) 905 if (bytes < 0) {
771 printf(_("recv() failed after QUIT.")); 906 printf(_("recv() failed after QUIT."));
772 else if (bytes == 0) 907 } else if (bytes == 0) {
773 printf(_("Connection reset by peer.")); 908 printf(_("Connection reset by peer."));
774 else { 909 } else {
775 buffer[bytes] = '\0'; 910 buffer[bytes] = '\0';
776 printf(_("received %s\n"), buffer); 911 printf(_("received %s\n"), buffer);
777 } 912 }
778 } 913 }
779}
780 914
915 return buffer;
916}
781 917
782/* 918/*
783 * Receive one line, copy it into buf and nul-terminate it. Returns the 919 * Receive one line, copy it into buf and nul-terminate it. Returns the
@@ -788,24 +924,23 @@ smtp_quit(void)
788 * function which buffers the data, move that to netutils.c and change 924 * function which buffers the data, move that to netutils.c and change
789 * check_smtp and other plugins to use that. Also, remove (\r)\n. 925 * check_smtp and other plugins to use that. Also, remove (\r)\n.
790 */ 926 */
791int 927int recvline(char *buf, size_t bufsize, check_smtp_config config, int socket_descriptor,
792recvline(char *buf, size_t bufsize) 928 bool ssl_established) {
793{
794 int result; 929 int result;
795 unsigned i; 930 size_t counter;
796 931
797 for (i = result = 0; i < bufsize - 1; i++) { 932 for (counter = result = 0; counter < bufsize - 1; counter++) {
798 if ((result = my_recv(&buf[i], 1)) != 1) 933 if ((result = my_recv(config, &buf[counter], 1, socket_descriptor, ssl_established)) != 1) {
799 break; 934 break;
800 if (buf[i] == '\n') { 935 }
801 buf[++i] = '\0'; 936 if (buf[counter] == '\n') {
802 return i; 937 buf[++counter] = '\0';
938 return (int)counter;
803 } 939 }
804 } 940 }
805 return (result == 1 || i == 0) ? -2 : result; /* -2 if out of space */ 941 return (result == 1 || counter == 0) ? -2 : result; /* -2 if out of space */
806} 942}
807 943
808
809/* 944/*
810 * Receive one or more lines, copy them into buf and nul-terminate it. Returns 945 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
811 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on 946 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
@@ -820,117 +955,114 @@ recvline(char *buf, size_t bufsize)
820 * 955 *
821 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n. 956 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
822 */ 957 */
823int 958int recvlines(check_smtp_config config, char *buf, size_t bufsize, int socket_descriptor,
824recvlines(char *buf, size_t bufsize) 959 bool ssl_established) {
825{ 960 int result;
826 int result, i; 961 int counter;
827 962
828 for (i = 0; /* forever */; i += result) 963 for (counter = 0; /* forever */; counter += result) {
829 if (!((result = recvline(buf + i, bufsize - i)) > 3 && 964 if (!((result = recvline(buf + counter, bufsize - counter, config, socket_descriptor,
830 isdigit((int)buf[i]) && 965 ssl_established)) > 3 &&
831 isdigit((int)buf[i + 1]) && 966 isdigit((int)buf[counter]) && isdigit((int)buf[counter + 1]) &&
832 isdigit((int)buf[i + 2]) && 967 isdigit((int)buf[counter + 2]) && buf[counter + 3] == '-')) {
833 buf[i + 3] == '-'))
834 break; 968 break;
969 }
970 }
835 971
836 return (result <= 0) ? result : result + i; 972 return (result <= 0) ? result : result + counter;
837} 973}
838 974
839 975int my_close(int socket_descriptor) {
840int
841my_close (void)
842{
843 int result; 976 int result;
844 result = close(sd); 977 result = close(socket_descriptor);
845#ifdef HAVE_SSL 978#ifdef HAVE_SSL
846 np_net_ssl_cleanup(); 979 np_net_ssl_cleanup();
847#endif 980#endif
848 return result; 981 return result;
849} 982}
850 983
851 984void print_help(void) {
852void
853print_help (void)
854{
855 char *myport; 985 char *myport;
856 xasprintf (&myport, "%d", SMTP_PORT); 986 xasprintf(&myport, "%d", SMTP_PORT);
857 987
858 print_revision (progname, NP_VERSION); 988 print_revision(progname, NP_VERSION);
859 989
860 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n"); 990 printf("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
861 printf (COPYRIGHT, copyright, email); 991 printf(COPYRIGHT, copyright, email);
862 992
863 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host.")); 993 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
864 994
865 printf ("\n\n"); 995 printf("\n\n");
866 996
867 print_usage (); 997 print_usage();
868 998
869 printf (UT_HELP_VRSN); 999 printf(UT_HELP_VRSN);
870 printf (UT_EXTRA_OPTS); 1000 printf(UT_EXTRA_OPTS);
871 1001
872 printf (UT_HOST_PORT, 'p', myport); 1002 printf(UT_HOST_PORT, 'p', myport);
873 1003
874 printf (UT_IPv46); 1004 printf(UT_IPv46);
875 1005
876 printf (" %s\n", "-e, --expect=STRING"); 1006 printf(" %s\n", "-e, --expect=STRING");
877 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT); 1007 printf(_(" String to expect in first line of server response (default: '%s')\n"),
878 printf (" %s\n", "-C, --command=STRING"); 1008 SMTP_EXPECT);
879 printf (" %s\n", _("SMTP command (may be used repeatedly)")); 1009 printf(" %s\n", "-C, --command=STRING");
880 printf (" %s\n", "-R, --response=STRING"); 1010 printf(" %s\n", _("SMTP command (may be used repeatedly)"));
881 printf (" %s\n", _("Expected response to command (may be used repeatedly)")); 1011 printf(" %s\n", "-R, --response=STRING");
882 printf (" %s\n", "-f, --from=STRING"); 1012 printf(" %s\n", _("Expected response to command (may be used repeatedly)"));
883 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")), 1013 printf(" %s\n", "-f, --from=STRING");
884 printf (" %s\n", "-F, --fqdn=STRING"); 1014 printf(" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
885 printf (" %s\n", _("FQDN used for HELO")); 1015 printf(" %s\n", "-F, --fqdn=STRING");
886 printf (" %s\n", "-r, --proxy"); 1016 printf(" %s\n", _("FQDN used for HELO"));
887 printf (" %s\n", _("Use PROXY protocol prefix for the connection.")); 1017 printf(" %s\n", "-r, --proxy");
1018 printf(" %s\n", _("Use PROXY protocol prefix for the connection."));
888#ifdef HAVE_SSL 1019#ifdef HAVE_SSL
889 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]"); 1020 printf(" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
890 printf (" %s\n", _("Minimum number of days a certificate has to be valid.")); 1021 printf(" %s\n", _("Minimum number of days a certificate has to be valid."));
891 printf (" %s\n", "-s, --ssl, --tls"); 1022 printf(" %s\n", "-s, --ssl, --tls");
892 printf (" %s\n", _("Use SSL/TLS for the connection.")); 1023 printf(" %s\n", _("Use SSL/TLS for the connection."));
893 printf (_(" Sets default port to %d.\n"), SMTPS_PORT); 1024 printf(_(" Sets default port to %d.\n"), SMTPS_PORT);
894 printf (" %s\n", "-S, --starttls"); 1025 printf(" %s\n", "-S, --starttls");
895 printf (" %s\n", _("Use STARTTLS for the connection.")); 1026 printf(" %s\n", _("Use STARTTLS for the connection."));
896 printf (" %s\n", "--sni"); 1027 printf(" %s\n", "--sni");
897 printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)")); 1028 printf(" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
898#endif 1029#endif
899 1030
900 printf (" %s\n", "-A, --authtype=STRING"); 1031 printf(" %s\n", "-A, --authtype=STRING");
901 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)")); 1032 printf(" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
902 printf (" %s\n", "-U, --authuser=STRING"); 1033 printf(" %s\n", "-U, --authuser=STRING");
903 printf (" %s\n", _("SMTP AUTH username")); 1034 printf(" %s\n", _("SMTP AUTH username"));
904 printf (" %s\n", "-P, --authpass=STRING"); 1035 printf(" %s\n", "-P, --authpass=STRING");
905 printf (" %s\n", _("SMTP AUTH password")); 1036 printf(" %s\n", _("SMTP AUTH password"));
906 printf (" %s\n", "-L, --lmtp"); 1037 printf(" %s\n", "-L, --lmtp");
907 printf (" %s\n", _("Send LHLO instead of HELO/EHLO")); 1038 printf(" %s\n", _("Send LHLO instead of HELO/EHLO"));
908 printf (" %s\n", "-q, --ignore-quit-failure"); 1039 printf(" %s\n", "-q, --ignore-quit-failure");
909 printf (" %s\n", _("Ignore failure when sending QUIT command to server")); 1040 printf(" %s\n", _("Ignore failure when sending QUIT command to server"));
910 1041 printf(" %s\n", "--ignore-certificate-expiration");
911 printf (UT_WARN_CRIT); 1042 printf(" %s\n", _("Ignore certificate expiration"));
912
913 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
914 1043
915 printf (UT_VERBOSE); 1044 printf(UT_WARN_CRIT);
916 1045
917 printf("\n"); 1046 printf(UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
918 printf ("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return"));
919 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
920 printf ("%s\n", _("connects, but incorrect response messages from the host result in"));
921 printf ("%s\n", _("STATE_WARNING return values."));
922 1047
923 printf (UT_SUPPORT); 1048 printf(UT_OUTPUT_FORMAT);
924}
925 1049
1050 printf(UT_VERBOSE);
926 1051
1052 printf("\n");
1053 printf("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return"));
1054 printf("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
1055 printf("%s\n", _("connects, but incorrect response messages from the host result in"));
1056 printf("%s\n", _("STATE_WARNING return values."));
927 1057
928void 1058 printf(UT_SUPPORT);
929print_usage (void)
930{
931 printf ("%s\n", _("Usage:"));
932 printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname);
933 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
934 printf ("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-r] [--sni] [-v] \n");
935} 1059}
936 1060
1061void print_usage(void) {
1062 printf("%s\n", _("Usage:"));
1063 printf("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n",
1064 progname);
1065 printf("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
1066 printf("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-r] [--sni] "
1067 "[-v] \n");
1068}