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