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