Code

Making messages more consistent
[nagiosplug.git] / plugins / check_smtp.c
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 ******************************************************************************/
19 const char *progname = "check_smtp";
20 const char *revision = "$Revision$";
21 const char *copyright = "2000-2003";
22 const char *email = "nagiosplug-devel@lists.sourceforge.net";
24 #include "common.h"
25 #include "netutils.h"
26 #include "utils.h"
28 enum {
29         SMTP_PORT       = 25
30 };
31 const char *SMTP_EXPECT = "220";
32 const char *SMTP_HELO = "HELO ";
33 const char *SMTP_QUIT   = "QUIT\r\n";
35 int process_arguments (int, char **);
36 int validate_arguments (void);
37 void print_help (void);
38 void print_usage (void);
40 #ifdef HAVE_REGEX_H
41 #include <regex.h>
42 char regex_expect[MAX_INPUT_BUFFER] = "";
43 regex_t preg;
44 regmatch_t pmatch[10];
45 char timestamp[10] = "";
46 char errbuf[MAX_INPUT_BUFFER];
47 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
48 int eflags = 0;
49 int errcode, excode;
50 #endif
52 int server_port = SMTP_PORT;
53 char *server_address = NULL;
54 char *server_expect = NULL;
55 int smtp_use_dummycmd = 0;
56 char *mail_command = NULL;
57 char *from_arg = NULL;
58 int ncommands=0;
59 int command_size=0;
60 int nresponses=0;
61 int response_size=0;
62 char **commands = NULL;
63 char **responses = NULL;
64 int warning_time = 0;
65 int check_warning_time = FALSE;
66 int critical_time = 0;
67 int check_critical_time = FALSE;
68 int verbose = 0;
74 \f
75 int
76 main (int argc, char **argv)
77 {
78         int sd;
79         int n = 0;
80         double elapsed_time;
81         long microsec;
82         int result = STATE_UNKNOWN;
83         char buffer[MAX_INPUT_BUFFER];
84         char *cmd_str = NULL;
85         char *helocmd = NULL;
86         struct timeval tv;
88         setlocale (LC_ALL, "");
89         bindtextdomain (PACKAGE, LOCALEDIR);
90         textdomain (PACKAGE);
92         if (process_arguments (argc, argv) != OK)
93                 usage (_("Incorrect arguments supplied\n"));
95         /* initialize the HELO command with the localhostname */
96 #ifndef HOST_MAX_BYTES
97 #define HOST_MAX_BYTES 255
98 #endif
99         helocmd = malloc (HOST_MAX_BYTES);
100         gethostname(helocmd, HOST_MAX_BYTES);
101         asprintf (&helocmd, "%s%s%s", SMTP_HELO, helocmd, "\r\n");
103         /* initialize the MAIL command with optional FROM command  */
104         asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
106         if (verbose && smtp_use_dummycmd)
107                 printf ("FROM CMD: %s", cmd_str);
108         
109         /* initialize alarm signal handling */
110         (void) signal (SIGALRM, socket_timeout_alarm_handler);
112         /* set socket timeout */
113         (void) alarm (socket_timeout);
115         /* start timer */
116         gettimeofday (&tv, NULL);
118         /* try to connect to the host at the given port number */
119         result = my_tcp_connect (server_address, server_port, &sd);
121         if (result == STATE_OK) { /* we connected */
123                 /* watch for the SMTP connection string and */
124                 /* return a WARNING status if we couldn't read any data */
125                 if (recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0) == -1) {
126                         printf (_("recv() failed\n"));
127                         result = STATE_WARNING;
128                 }
129                 else {
130                         if (verbose)
131                                 printf ("%s", buffer);
132                         /* strip the buffer of carriage returns */
133                         strip (buffer);
134                         /* make sure we find the response we are looking for */
135                         if (!strstr (buffer, server_expect)) {
136                                 if (server_port == SMTP_PORT)
137                                         printf (_("Invalid SMTP response received from host\n"));
138                                 else
139                                         printf (_("Invalid SMTP response received from host on port %d\n"),
140                                                                         server_port);
141                                 result = STATE_WARNING;
142                         }
143                 }
145                 /* send the HELO command */
146                 send(sd, helocmd, strlen(helocmd), 0);
148                 /* allow for response to helo command to reach us */
149                 recv(sd, buffer, MAX_INPUT_BUFFER-1, 0);
150                                 
151                 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
152                  * to do something useful. This can be prevented by giving a command
153                  * even if syntax is illegal (MAIL requires a FROM:<...> argument)
154                  *
155                  * According to rfc821 you can include a null reversepath in the from command
156                  * - but a log message is generated on the smtp server.
157                  *
158                  * You can disable sending mail_command with '--nocommand'
159                  * Use the -f option to provide a FROM address
160                  */
161                 if (smtp_use_dummycmd) {
162                         send(sd, cmd_str, strlen(cmd_str), 0);
163                         recv(sd, buffer, MAX_INPUT_BUFFER-1, 0);
164                         if (verbose) 
165                                 printf("%s", buffer);
166                 }
168                 while (n < ncommands) {
169                         asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
170                         send(sd, cmd_str, strlen(cmd_str), 0);
171                         recv(sd, buffer, MAX_INPUT_BUFFER-1, 0);
172                         if (verbose) 
173                                 printf("%s", buffer);
174                         strip (buffer);
175                         if (n < nresponses) {
176 #ifdef HAVE_REGEX_H
177                                 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
178                                 //strncpy (regex_expect, responses[n], sizeof (regex_expect) - 1);
179                                 //regex_expect[sizeof (regex_expect) - 1] = '\0';
180                                 errcode = regcomp (&preg, responses[n], cflags);
181                                 if (errcode != 0) {
182                                         regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
183                                         printf (_("Could Not Compile Regular Expression"));
184                                         return ERROR;
185                                 }
186                                 excode = regexec (&preg, buffer, 10, pmatch, eflags);
187                                 if (excode == 0) {
188                                         result = STATE_OK;
189                                 }
190                                 else if (excode == REG_NOMATCH) {
191                                         result = STATE_WARNING;
192                                         printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
193                                 }
194                                 else {
195                                         regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
196                                         printf (_("Execute Error: %s\n"), errbuf);
197                                         result = STATE_UNKNOWN;
198                                 }
199 #else
200                                 if (strstr(buffer, responses[n])!=buffer) {
201                                         result = STATE_WARNING;
202                                         printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
203                                 }
204 #endif
205                         }
206                         n++;
207                 }
209                 /* tell the server we're done */
210                 send (sd, SMTP_QUIT, strlen (SMTP_QUIT), 0);
212                 /* finally close the connection */
213                 close (sd);
214         }
216         /* reset the alarm */
217         alarm (0);
219         microsec = deltime (tv);
220         elapsed_time = (double)microsec / 1.0e6;
222         if (result == STATE_OK)
223                 if (check_critical_time && elapsed_time > (double) critical_time)
224                         result = STATE_CRITICAL;
225                 else if (check_warning_time && elapsed_time > (double) warning_time)
226                         result = STATE_WARNING;
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;
243 \f
244 /* process command-line arguments */
245 int
246 process_arguments (int argc, char **argv)
248         int c;
250         int option = 0;
251         static struct option longopts[] = {
252                 {"hostname", required_argument, 0, 'H'},
253                 {"expect", required_argument, 0, 'e'},
254                 {"critical", required_argument, 0, 'c'},
255                 {"warning", required_argument, 0, 'w'},
256                 {"timeout", required_argument, 0, 't'},
257                 {"port", required_argument, 0, 'p'},
258                 {"from", required_argument, 0, 'f'},
259                 {"command", required_argument, 0, 'C'},
260                 {"response", required_argument, 0, 'R'},
261                 {"nocommand", required_argument, 0, 'n'},
262                 {"verbose", no_argument, 0, 'v'},
263                 {"version", no_argument, 0, 'V'},
264                 {"use-ipv4", no_argument, 0, '4'},
265                 {"use-ipv6", no_argument, 0, '6'},
266                 {"help", no_argument, 0, 'h'},
267                 {0, 0, 0, 0}
268         };
270         if (argc < 2)
271                 return ERROR;
273         for (c = 1; c < argc; c++) {
274                 if (strcmp ("-to", argv[c]) == 0)
275                         strcpy (argv[c], "-t");
276                 else if (strcmp ("-wt", argv[c]) == 0)
277                         strcpy (argv[c], "-w");
278                 else if (strcmp ("-ct", argv[c]) == 0)
279                         strcpy (argv[c], "-c");
280         }
282         while (1) {
283                 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:",
284                                  longopts, &option);
286                 if (c == -1 || c == EOF)
287                         break;
289                 switch (c) {
290                 case 'H':                                                                       /* hostname */
291                         if (is_host (optarg)) {
292                                 server_address = optarg;
293                         }
294                         else {
295                                 usage2 (_("Invalid host name"), optarg);
296                         }
297                         break;
298                 case 'p':                                                                       /* port */
299                         if (is_intpos (optarg))
300                                 server_port = atoi (optarg);
301                         else
302                                 usage (_("Server port must be a positive integer\n"));
303                         break;
304                 case 'f':                                                                       /* from argument */
305                         from_arg = optarg;
306                         smtp_use_dummycmd = 1;
307                         break;
308                 case 'e':                                                                       /* server expect string on 220  */
309                         server_expect = optarg;
310                         break;
311                 case 'C':                                                                       /* commands  */
312                         if (ncommands >= command_size) {
313                                 commands = realloc (commands, command_size+8);
314                                 if (commands == NULL)
315                                         die (STATE_UNKNOWN,
316                                              _("Could not realloc() units [%d]\n"), ncommands);
317                         }
318                         commands[ncommands] = optarg;
319                         ncommands++;
320                         break;
321                 case 'R':                                                                       /* server responses */
322                         if (nresponses >= response_size) {
323                                 responses = realloc (responses, response_size+8);
324                                 if (responses == NULL)
325                                         die (STATE_UNKNOWN,
326                                              _("Could not realloc() units [%d]\n"), nresponses);
327                         }
328                         responses[nresponses] = optarg;
329                         nresponses++;
330                         break;
331                 case 'c':                                                                       /* critical time threshold */
332                         if (is_intnonneg (optarg)) {
333                                 critical_time = atoi (optarg);
334                                 check_critical_time = TRUE;
335                         }
336                         else {
337                                 usage (_("Critical time must be a nonnegative integer\n"));
338                         }
339                         break;
340                 case 'w':                                                                       /* warning time threshold */
341                         if (is_intnonneg (optarg)) {
342                                 warning_time = atoi (optarg);
343                                 check_warning_time = TRUE;
344                         }
345                         else {
346                                 usage (_("Warning time must be a nonnegative integer\n"));
347                         }
348                         break;
349                 case 'v':                                                                       /* verbose */
350                         verbose++;
351                         break;
352                 case 't':                                                                       /* timeout */
353                         if (is_intnonneg (optarg)) {
354                                 socket_timeout = atoi (optarg);
355                         }
356                         else {
357                                 usage (_("Time interval must be a nonnegative integer\n"));
358                         }
359                         break;
360                 case '4':
361                         address_family = AF_INET;
362                         break;
363                 case '6':
364 #ifdef USE_IPV6
365                         address_family = AF_INET6;
366 #else
367                         usage (_("IPv6 support not available\n"));
368 #endif
369                         break;
370                 case 'V':                                                                       /* version */
371                         print_revision (progname, revision);
372                         exit (STATE_OK);
373                 case 'h':                                                                       /* help */
374                         print_help ();
375                         exit (STATE_OK);
376                 case '?':                                                                       /* help */
377                         usage (_("Invalid argument\n"));
378                 }
379         }
381         c = optind;
382         if (server_address == NULL) {
383                 if (argv[c]) {
384                         if (is_host (argv[c]))
385                                 server_address = argv[c];
386                         else
387                                 usage2 (_("Invalid host name"), argv[c]);
388                 }
389                 else {
390                         asprintf (&server_address, "127.0.0.1");
391                 }
392         }
394         if (server_expect == NULL)
395                 server_expect = strdup (SMTP_EXPECT);
397         if (mail_command == NULL)
398                 mail_command = strdup("MAIL ");
400         if (from_arg==NULL)
401                 from_arg = strdup(" ");
403         return validate_arguments ();
410 int
411 validate_arguments (void)
413         return OK;
420 \f
421 void
422 print_help (void)
424         char *myport;
425         asprintf (&myport, "%d", SMTP_PORT);
427         print_revision (progname, revision);
429         printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
430         printf (COPYRIGHT, copyright, email);
432         printf(_("\
433 This plugin will attempt to open an SMTP connection with the host.\n\n"));
435         print_usage ();
437         printf (_(UT_HELP_VRSN));
439         printf (_(UT_HOST_PORT), 'p', myport);
441         printf (_(UT_IPv46));
443         printf (_("\
444  -e, --expect=STRING\n\
445    String to expect in first line of server response (default: '%s')\n\
446  -n, nocommand\n\
447    Suppress SMTP command\n\
448  -C, --command=STRING\n\
449    SMTP command (may be used repeatedly)\n\
450  -R, --command=STRING\n\
451    Expected response to command (may be used repeatedly)\n\
452  -f, --from=STRING\n\
453    FROM-address to include in MAIL command, required by Exchange 2000\n"),
454                 SMTP_EXPECT);
456         printf (_(UT_WARN_CRIT));
458         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
460         printf (_(UT_VERBOSE));
462         printf(_("\n\
463 Successul connects return STATE_OK, refusals and timeouts return\n\
464 STATE_CRITICAL, other errors return STATE_UNKNOWN.  Successful\n\
465 connects, but incorrect reponse messages from the host result in\n\
466 STATE_WARNING return values.\n"));
468         printf (_(UT_SUPPORT));
475 void
476 print_usage (void)
478         printf ("\
479 Usage: %s -H host [-p port] [-e expect] [-C command] [-f from addr]\n\
480   [-w warn] [-c crit] [-t timeout] [-n] [-v] [-4|-6]\n", progname);
481         printf (_(UT_HLP_VRS), progname, progname);
484