1 /******************************************************************************
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2 of the License, or
6 (at your option) any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 $Id$
19 ******************************************************************************/
21 const char *progname = "check_smtp";
22 const char *revision = "$Revision$";
23 const char *copyright = "2000-2004";
24 const char *email = "nagiosplug-devel@lists.sourceforge.net";
26 #include "common.h"
27 #include "netutils.h"
28 #include "utils.h"
30 enum {
31 SMTP_PORT = 25
32 };
33 const char *SMTP_EXPECT = "220";
34 const char *SMTP_HELO = "HELO ";
35 const char *SMTP_QUIT = "QUIT\r\n";
37 int process_arguments (int, char **);
38 int validate_arguments (void);
39 void print_help (void);
40 void print_usage (void);
42 #ifdef HAVE_REGEX_H
43 #include <regex.h>
44 char regex_expect[MAX_INPUT_BUFFER] = "";
45 regex_t preg;
46 regmatch_t pmatch[10];
47 char timestamp[10] = "";
48 char errbuf[MAX_INPUT_BUFFER];
49 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
50 int eflags = 0;
51 int errcode, excode;
52 #endif
54 int server_port = SMTP_PORT;
55 char *server_address = NULL;
56 char *server_expect = NULL;
57 int smtp_use_dummycmd = 0;
58 char *mail_command = NULL;
59 char *from_arg = NULL;
60 int ncommands=0;
61 int command_size=0;
62 int nresponses=0;
63 int response_size=0;
64 char **commands = NULL;
65 char **responses = NULL;
66 int warning_time = 0;
67 int check_warning_time = FALSE;
68 int critical_time = 0;
69 int check_critical_time = FALSE;
70 int verbose = 0;
74 int
75 main (int argc, char **argv)
76 {
77 int sd;
78 int n = 0;
79 double elapsed_time;
80 long microsec;
81 int result = STATE_UNKNOWN;
82 char buffer[MAX_INPUT_BUFFER];
83 char *cmd_str = NULL;
84 char *helocmd = NULL;
85 struct timeval tv;
87 setlocale (LC_ALL, "");
88 bindtextdomain (PACKAGE, LOCALEDIR);
89 textdomain (PACKAGE);
91 if (process_arguments (argc, argv) == ERROR)
92 usage4 (_("Could not parse arguments"));
94 /* initialize the HELO command with the localhostname */
95 #ifndef HOST_MAX_BYTES
96 #define HOST_MAX_BYTES 255
97 #endif
98 helocmd = malloc (HOST_MAX_BYTES);
99 gethostname(helocmd, HOST_MAX_BYTES);
100 asprintf (&helocmd, "%s%s%s", SMTP_HELO, helocmd, "\r\n");
102 /* initialize the MAIL command with optional FROM command */
103 asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
105 if (verbose && smtp_use_dummycmd)
106 printf ("FROM CMD: %s", cmd_str);
108 /* initialize alarm signal handling */
109 (void) signal (SIGALRM, socket_timeout_alarm_handler);
111 /* set socket timeout */
112 (void) alarm (socket_timeout);
114 /* start timer */
115 gettimeofday (&tv, NULL);
117 /* try to connect to the host at the given port number */
118 result = my_tcp_connect (server_address, server_port, &sd);
120 if (result == STATE_OK) { /* we connected */
122 /* watch for the SMTP connection string and */
123 /* return a WARNING status if we couldn't read any data */
124 if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) == -1) {
125 printf (_("recv() failed\n"));
126 result = STATE_WARNING;
127 }
128 else {
129 if (verbose)
130 printf ("%s", buffer);
131 /* strip the buffer of carriage returns */
132 strip (buffer);
133 /* make sure we find the response we are looking for */
134 if (!strstr (buffer, server_expect)) {
135 if (server_port == SMTP_PORT)
136 printf (_("Invalid SMTP response received from host\n"));
137 else
138 printf (_("Invalid SMTP response received from host on port %d\n"),
139 server_port);
140 result = STATE_WARNING;
141 }
142 }
144 /* send the HELO command */
145 send(sd, helocmd, strlen(helocmd), 0);
147 /* allow for response to helo command to reach us */
148 recv(sd, buffer, MAX_INPUT_BUFFER-1, 0);
150 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
151 * to do something useful. This can be prevented by giving a command
152 * even if syntax is illegal (MAIL requires a FROM:<...> argument)
153 *
154 * According to rfc821 you can include a null reversepath in the from command
155 * - but a log message is generated on the smtp server.
156 *
157 * You can disable sending mail_command with '--nocommand'
158 * Use the -f option to provide a FROM address
159 */
160 if (smtp_use_dummycmd) {
161 send(sd, cmd_str, strlen(cmd_str), 0);
162 recv(sd, buffer, MAX_INPUT_BUFFER-1, 0);
163 if (verbose)
164 printf("%s", buffer);
165 }
167 while (n < ncommands) {
168 asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
169 send(sd, cmd_str, strlen(cmd_str), 0);
170 recv(sd, buffer, MAX_INPUT_BUFFER-1, 0);
171 if (verbose)
172 printf("%s", buffer);
173 strip (buffer);
174 if (n < nresponses) {
175 #ifdef HAVE_REGEX_H
176 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
177 //strncpy (regex_expect, responses[n], sizeof (regex_expect) - 1);
178 //regex_expect[sizeof (regex_expect) - 1] = '\0';
179 errcode = regcomp (&preg, responses[n], cflags);
180 if (errcode != 0) {
181 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
182 printf (_("Could Not Compile Regular Expression"));
183 return ERROR;
184 }
185 excode = regexec (&preg, buffer, 10, pmatch, eflags);
186 if (excode == 0) {
187 result = STATE_OK;
188 }
189 else if (excode == REG_NOMATCH) {
190 result = STATE_WARNING;
191 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
192 }
193 else {
194 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
195 printf (_("Execute Error: %s\n"), errbuf);
196 result = STATE_UNKNOWN;
197 }
198 #else
199 if (strstr(buffer, responses[n])!=buffer) {
200 result = STATE_WARNING;
201 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
202 }
203 #endif
204 }
205 n++;
206 }
208 /* tell the server we're done */
209 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
211 /* finally close the connection */
212 close (sd);
213 }
215 /* reset the alarm */
216 alarm (0);
218 microsec = deltime (tv);
219 elapsed_time = (double)microsec / 1.0e6;
221 if (result == STATE_OK) {
222 if (check_critical_time && elapsed_time > (double) critical_time)
223 result = STATE_CRITICAL;
224 else if (check_warning_time && elapsed_time > (double) warning_time)
225 result = STATE_WARNING;
226 }
228 printf (_("SMTP %s - %.3f sec. response time%s%s|%s\n"),
229 state_text (result), elapsed_time,
230 verbose?", ":"", verbose?buffer:"",
231 fperfdata ("time", elapsed_time, "s",
232 (int)check_warning_time, warning_time,
233 (int)check_critical_time, critical_time,
234 TRUE, 0, FALSE, 0));
236 return result;
237 }
241 /* process command-line arguments */
242 int
243 process_arguments (int argc, char **argv)
244 {
245 int c;
247 int option = 0;
248 static struct option longopts[] = {
249 {"hostname", required_argument, 0, 'H'},
250 {"expect", required_argument, 0, 'e'},
251 {"critical", required_argument, 0, 'c'},
252 {"warning", required_argument, 0, 'w'},
253 {"timeout", required_argument, 0, 't'},
254 {"port", required_argument, 0, 'p'},
255 {"from", required_argument, 0, 'f'},
256 {"command", required_argument, 0, 'C'},
257 {"response", required_argument, 0, 'R'},
258 {"nocommand", required_argument, 0, 'n'},
259 {"verbose", no_argument, 0, 'v'},
260 {"version", no_argument, 0, 'V'},
261 {"use-ipv4", no_argument, 0, '4'},
262 {"use-ipv6", no_argument, 0, '6'},
263 {"help", no_argument, 0, 'h'},
264 {0, 0, 0, 0}
265 };
267 if (argc < 2)
268 return ERROR;
270 for (c = 1; c < argc; c++) {
271 if (strcmp ("-to", argv[c]) == 0)
272 strcpy (argv[c], "-t");
273 else if (strcmp ("-wt", argv[c]) == 0)
274 strcpy (argv[c], "-w");
275 else if (strcmp ("-ct", argv[c]) == 0)
276 strcpy (argv[c], "-c");
277 }
279 while (1) {
280 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:",
281 longopts, &option);
283 if (c == -1 || c == EOF)
284 break;
286 switch (c) {
287 case 'H': /* hostname */
288 if (is_host (optarg)) {
289 server_address = optarg;
290 }
291 else {
292 usage2 (_("Invalid hostname/address"), optarg);
293 }
294 break;
295 case 'p': /* port */
296 if (is_intpos (optarg))
297 server_port = atoi (optarg);
298 else
299 usage4 (_("Port must be a positive integer"));
300 break;
301 case 'f': /* from argument */
302 from_arg = optarg;
303 smtp_use_dummycmd = 1;
304 break;
305 case 'e': /* server expect string on 220 */
306 server_expect = optarg;
307 break;
308 case 'C': /* commands */
309 if (ncommands >= command_size) {
310 commands = realloc (commands, command_size+8);
311 if (commands == NULL)
312 die (STATE_UNKNOWN,
313 _("Could not realloc() units [%d]\n"), ncommands);
314 }
315 commands[ncommands] = optarg;
316 ncommands++;
317 break;
318 case 'R': /* server responses */
319 if (nresponses >= response_size) {
320 responses = realloc (responses, response_size+8);
321 if (responses == NULL)
322 die (STATE_UNKNOWN,
323 _("Could not realloc() units [%d]\n"), nresponses);
324 }
325 responses[nresponses] = optarg;
326 nresponses++;
327 break;
328 case 'c': /* critical time threshold */
329 if (is_intnonneg (optarg)) {
330 critical_time = atoi (optarg);
331 check_critical_time = TRUE;
332 }
333 else {
334 usage4 (_("Critical time must be a positive integer"));
335 }
336 break;
337 case 'w': /* warning time threshold */
338 if (is_intnonneg (optarg)) {
339 warning_time = atoi (optarg);
340 check_warning_time = TRUE;
341 }
342 else {
343 usage4 (_("Warning time must be a positive integer"));
344 }
345 break;
346 case 'v': /* verbose */
347 verbose++;
348 break;
349 case 't': /* timeout */
350 if (is_intnonneg (optarg)) {
351 socket_timeout = atoi (optarg);
352 }
353 else {
354 usage4 (_("Time interval must be a positive integer"));
355 }
356 break;
357 case '4':
358 address_family = AF_INET;
359 break;
360 case '6':
361 #ifdef USE_IPV6
362 address_family = AF_INET6;
363 #else
364 usage4 (_("IPv6 support not available"));
365 #endif
366 break;
367 case 'V': /* version */
368 print_revision (progname, revision);
369 exit (STATE_OK);
370 case 'h': /* help */
371 print_help ();
372 exit (STATE_OK);
373 case '?': /* help */
374 printf (_("%s: Unknown argument: %s\n\n"), progname, optarg);
375 print_usage ();
376 exit (STATE_UNKNOWN);
377 }
378 }
380 c = optind;
381 if (server_address == NULL) {
382 if (argv[c]) {
383 if (is_host (argv[c]))
384 server_address = argv[c];
385 else
386 usage2 (_("Invalid hostname/address"), argv[c]);
387 }
388 else {
389 asprintf (&server_address, "127.0.0.1");
390 }
391 }
393 if (server_expect == NULL)
394 server_expect = strdup (SMTP_EXPECT);
396 if (mail_command == NULL)
397 mail_command = strdup("MAIL ");
399 if (from_arg==NULL)
400 from_arg = strdup(" ");
402 return validate_arguments ();
403 }
407 int
408 validate_arguments (void)
409 {
410 return OK;
411 }
415 void
416 print_help (void)
417 {
418 char *myport;
419 asprintf (&myport, "%d", SMTP_PORT);
421 print_revision (progname, revision);
423 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
424 printf (COPYRIGHT, copyright, email);
426 printf(_("This plugin will attempt to open an SMTP connection with the host.\n\n"));
428 print_usage ();
430 printf (_(UT_HELP_VRSN));
432 printf (_(UT_HOST_PORT), 'p', myport);
434 printf (_(UT_IPv46));
436 printf (_("\
437 -e, --expect=STRING\n\
438 String to expect in first line of server response (default: '%s')\n\
439 -n, nocommand\n\
440 Suppress SMTP command\n\
441 -C, --command=STRING\n\
442 SMTP command (may be used repeatedly)\n\
443 -R, --command=STRING\n\
444 Expected response to command (may be used repeatedly)\n\
445 -f, --from=STRING\n\
446 FROM-address to include in MAIL command, required by Exchange 2000\n"),
447 SMTP_EXPECT);
449 printf (_(UT_WARN_CRIT));
451 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
453 printf (_(UT_VERBOSE));
455 printf(_("\n\
456 Successul connects return STATE_OK, refusals and timeouts return\n\
457 STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful\n\
458 connects, but incorrect reponse messages from the host result in\n\
459 STATE_WARNING return values.\n"));
461 printf (_(UT_SUPPORT));
462 }
466 void
467 print_usage (void)
468 {
469 printf ("\
470 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
471 [-w warn] [-c crit] [-t timeout] [-n] [-v] [-4|-6]\n", progname);
472 }