Code

Properly handle SMTP server responses which are split into multiple
[nagiosplug.git] / plugins / check_smtp.c
1 /******************************************************************************
2 *
3 * Nagios check_smtp plugin
4 *
5 * License: GPL
6 * Copyright (c) 1999-2006 nagios-plugins team
7 *
8 * Last Modified: $Date$
9 *
10 * Description:
11 *
12 * This file contains the check_smtp plugin
13 *
14 *  This plugin will attempt to open an SMTP connection with the host.
15 *
16 *
17 * License Information:
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 *
33 *
34 * $Id$
35
36 ******************************************************************************/
38 const char *progname = "check_smtp";
39 const char *revision = "$Revision$";
40 const char *copyright = "2000-2006";
41 const char *email = "nagiosplug-devel@lists.sourceforge.net";
43 #include <ctype.h>
45 #include "common.h"
46 #include "netutils.h"
47 #include "utils.h"
49 #ifdef HAVE_SSL
50 int check_cert = FALSE;
51 int days_till_exp;
52 #  define my_recv(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
53 #  define my_send(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
54 #else /* ifndef HAVE_SSL */
55 #  define my_recv(buf, len) read(sd, buf, len)
56 #  define my_send(buf, len) send(sd, buf, len, 0)
57 #endif
59 enum {
60         SMTP_PORT       = 25
61 };
62 #define SMTP_EXPECT "220"
63 #define SMTP_HELO "HELO "
64 #define SMTP_EHLO "EHLO "
65 #define SMTP_QUIT "QUIT\r\n"
66 #define SMTP_STARTTLS "STARTTLS\r\n"
67 #define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
69 #ifndef HOST_MAX_BYTES
70 #define HOST_MAX_BYTES 255
71 #endif
73 #define EHLO_SUPPORTS_STARTTLS 1
75 int process_arguments (int, char **);
76 int validate_arguments (void);
77 void print_help (void);
78 void print_usage (void);
79 void smtp_quit(void);
80 int recvline(char *, size_t);
81 int recvlines(char *, size_t);
82 int my_close(void);
84 #include "regex.h"
85 char regex_expect[MAX_INPUT_BUFFER] = "";
86 regex_t preg;
87 regmatch_t pmatch[10];
88 char timestamp[20] = "";
89 char errbuf[MAX_INPUT_BUFFER];
90 int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
91 int eflags = 0;
92 int errcode, excode;
94 int server_port = SMTP_PORT;
95 char *server_address = NULL;
96 char *server_expect = NULL;
97 int smtp_use_dummycmd = 0;
98 char *mail_command = NULL;
99 char *from_arg = NULL;
100 int ncommands=0;
101 int command_size=0;
102 int nresponses=0;
103 int response_size=0;
104 char **commands = NULL;
105 char **responses = NULL;
106 char *authtype = NULL;
107 char *authuser = NULL;
108 char *authpass = NULL;
109 int warning_time = 0;
110 int check_warning_time = FALSE;
111 int critical_time = 0;
112 int check_critical_time = FALSE;
113 int verbose = 0;
114 int use_ssl = FALSE;
115 short use_ehlo = FALSE;
116 short ssl_established = 0;
117 char *localhostname = NULL;
118 int sd;
119 char buffer[MAX_INPUT_BUFFER];
120 enum {
121   TCP_PROTOCOL = 1,
122   UDP_PROTOCOL = 2,
123 };
125 /* written by lauri alanko */
126 static char *
127 base64 (const char *bin, size_t len)
130         char *buf = (char *) malloc ((len + 2) / 3 * 4 + 1);
131         size_t i = 0, j = 0;
133         char BASE64_END = '=';
134         char base64_table[64];
135         strncpy (base64_table, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 64);
137         while (j < len - 2) {
138                 buf[i++] = base64_table[bin[j] >> 2];
139                 buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
140                 buf[i++] = base64_table[((bin[j + 1] & 15) << 2) | (bin[j + 2] >> 6)];
141                 buf[i++] = base64_table[bin[j + 2] & 63];
142                 j += 3;
143         }
145         switch (len - j) {
146         case 1:
147                 buf[i++] = base64_table[bin[j] >> 2];
148                 buf[i++] = base64_table[(bin[j] & 3) << 4];
149                 buf[i++] = BASE64_END;
150                 buf[i++] = BASE64_END;
151                 break;
152         case 2:
153                 buf[i++] = base64_table[bin[j] >> 2];
154                 buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
155                 buf[i++] = base64_table[(bin[j + 1] & 15) << 2];
156                 buf[i++] = BASE64_END;
157                 break;
158         case 0:
159                 break;
160         }
162         buf[i] = '\0';
163         return buf;
166 int
167 main (int argc, char **argv)
169         short supports_tls=FALSE;
170         int n = 0;
171         double elapsed_time;
172         long microsec;
173         int result = STATE_UNKNOWN;
174         char *cmd_str = NULL;
175         char *helocmd = NULL;
176         char *error_msg = "";
177         struct timeval tv;
179         setlocale (LC_ALL, "");
180         bindtextdomain (PACKAGE, LOCALEDIR);
181         textdomain (PACKAGE);
183         if (process_arguments (argc, argv) == ERROR)
184                 usage4 (_("Could not parse arguments"));
186         /* If localhostname not set on command line, use gethostname to set */
187         if(! localhostname){
188                 localhostname = malloc (HOST_MAX_BYTES);
189                 if(!localhostname){
190                         printf(_("malloc() failed!\n"));
191                         return STATE_CRITICAL;
192                 }
193                 if(gethostname(localhostname, HOST_MAX_BYTES)){
194                         printf(_("gethostname() failed!\n"));
195                         return STATE_CRITICAL;
196                 }
197         }
198         if(use_ehlo)
199                 asprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
200         else
201                 asprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
203         if (verbose)
204                 printf("HELOCMD: %s", helocmd);
206         /* initialize the MAIL command with optional FROM command  */
207         asprintf (&cmd_str, "%sFROM: %s%s", mail_command, from_arg, "\r\n");
209         if (verbose && smtp_use_dummycmd)
210                 printf ("FROM CMD: %s", cmd_str);
211         
212         /* initialize alarm signal handling */
213         (void) signal (SIGALRM, socket_timeout_alarm_handler);
215         /* set socket timeout */
216         (void) alarm (socket_timeout);
218         /* start timer */
219         gettimeofday (&tv, NULL);
221         /* try to connect to the host at the given port number */
222         result = my_tcp_connect (server_address, server_port, &sd);
224         if (result == STATE_OK) { /* we connected */
226                 /* watch for the SMTP connection string and */
227                 /* return a WARNING status if we couldn't read any data */
228                 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
229                         printf (_("recv() failed\n"));
230                         result = STATE_WARNING;
231                 }
232                 else {
233                         if (verbose)
234                                 printf ("%s", buffer);
235                         /* strip the buffer of carriage returns */
236                         strip (buffer);
237                         /* make sure we find the response we are looking for */
238                         if (!strstr (buffer, server_expect)) {
239                                 if (server_port == SMTP_PORT)
240                                         printf (_("Invalid SMTP response received from host\n"));
241                                 else
242                                         printf (_("Invalid SMTP response received from host on port %d\n"),
243                                                                         server_port);
244                                 result = STATE_WARNING;
245                         }
246                 }
248                 /* send the HELO/EHLO command */
249                 send(sd, helocmd, strlen(helocmd), 0);
251                 /* allow for response to helo command to reach us */
252                 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
253                         printf (_("recv() failed\n"));
254                         return STATE_WARNING;
255                 } else if(use_ehlo){
256                         if(strstr(buffer, "250 STARTTLS") != NULL ||
257                            strstr(buffer, "250-STARTTLS") != NULL){
258                                 supports_tls=TRUE;
259                         }
260                 }
262                 if(use_ssl && ! supports_tls){
263                         printf(_("WARNING - TLS not supported by server\n"));
264                         smtp_quit();
265                         return STATE_WARNING;
266                 }
268 #ifdef HAVE_SSL
269                 if(use_ssl) {
270                   /* send the STARTTLS command */
271                   send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
273                   recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
274                   if (!strstr (buffer, server_expect)) {
275                     printf (_("Server does not support STARTTLS\n"));
276                     smtp_quit();
277                     return STATE_UNKNOWN;
278                   }
279                   result = np_net_ssl_init(sd);
280                   if(result != STATE_OK) {
281                     printf (_("CRITICAL - Cannot create SSL context.\n"));
282                     np_net_ssl_cleanup();
283                     close(sd);
284                     return STATE_CRITICAL;
285                   } else {
286                         ssl_established = 1;
287                   }
289                 /*
290                  * Resend the EHLO command.
291                  *
292                  * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
293                  * obtained from the server, such as the list of SMTP service
294                  * extensions, which was not obtained from the TLS negotiation
295                  * itself.  The client SHOULD send an EHLO command as the first
296                  * command after a successful TLS negotiation.''  For this
297                  * reason, some MTAs will not allow an AUTH LOGIN command before
298                  * we resent EHLO via TLS.
299                  */
300                 if (my_send(helocmd, strlen(helocmd)) <= 0) {
301                         printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
302                         my_close();
303                         return STATE_UNKNOWN;
304                 }
305                 if (verbose)
306                         printf(_("sent %s"), helocmd);
307                 if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
308                         printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
309                         my_close();
310                         return STATE_UNKNOWN;
311                 }
312                 if (verbose) {
313                         printf("%s", buffer);
314                 }
316 #  ifdef USE_OPENSSL
317                   if ( check_cert ) {
318                     result = np_net_ssl_check_cert(days_till_exp);
319                     if(result != STATE_OK){
320                       printf ("%s\n", _("CRITICAL - Cannot retrieve server certificate."));
321                     }
322                     my_close();
323                     return result;
324                   }
325 #  endif /* USE_OPENSSL */
326                 }
327 #endif
328                                 
329                 /* sendmail will syslog a "NOQUEUE" error if session does not attempt
330                  * to do something useful. This can be prevented by giving a command
331                  * even if syntax is illegal (MAIL requires a FROM:<...> argument)
332                  *
333                  * According to rfc821 you can include a null reversepath in the from command
334                  * - but a log message is generated on the smtp server.
335                  *
336                  * You can disable sending mail_command with '--nocommand'
337                  * Use the -f option to provide a FROM address
338                  */
339                 if (smtp_use_dummycmd) {
340                   my_send(cmd_str, strlen(cmd_str));
341                   if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
342                     printf("%s", buffer);
343                 }
345                 while (n < ncommands) {
346                         asprintf (&cmd_str, "%s%s", commands[n], "\r\n");
347                         my_send(cmd_str, strlen(cmd_str));
348                         if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
349                                 printf("%s", buffer);
350                         strip (buffer);
351                         if (n < nresponses) {
352                                 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
353                                 errcode = regcomp (&preg, responses[n], cflags);
354                                 if (errcode != 0) {
355                                         regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
356                                         printf (_("Could Not Compile Regular Expression"));
357                                         return ERROR;
358                                 }
359                                 excode = regexec (&preg, buffer, 10, pmatch, eflags);
360                                 if (excode == 0) {
361                                         result = STATE_OK;
362                                 }
363                                 else if (excode == REG_NOMATCH) {
364                                         result = STATE_WARNING;
365                                         printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
366                                 }
367                                 else {
368                                         regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
369                                         printf (_("Execute Error: %s\n"), errbuf);
370                                         result = STATE_UNKNOWN;
371                                 }
372                         }
373                         n++;
374                 }
376                 if (authtype != NULL) {
377                         if (strcmp (authtype, "LOGIN") == 0) {
378                                 char *abuf;
379                                 int ret;
380                                 do {
381                                         if (authuser == NULL) {
382                                                 result = STATE_CRITICAL;
383                                                 asprintf(&error_msg, _("no authuser specified, "));
384                                                 break;
385                                         }
386                                         if (authpass == NULL) {
387                                                 result = STATE_CRITICAL;
388                                                 asprintf(&error_msg, _("no authpass specified, "));
389                                                 break;
390                                         }
392                                         /* send AUTH LOGIN */
393                                         my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
394                                         if (verbose)
395                                                 printf (_("sent %s\n"), "AUTH LOGIN");
397                                         if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
398                                                 asprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
399                                                 result = STATE_WARNING;
400                                                 break;
401                                         }
402                                         if (verbose)
403                                                 printf (_("received %s\n"), buffer);
405                                         if (strncmp (buffer, "334", 3) != 0) {
406                                                 result = STATE_CRITICAL;
407                                                 asprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
408                                                 break;
409                                         }
411                                         /* encode authuser with base64 */
412                                         abuf = base64 (authuser, strlen(authuser));
413                                         strcat (abuf, "\r\n");
414                                         my_send(abuf, strlen(abuf));
415                                         if (verbose)
416                                                 printf (_("sent %s\n"), abuf);
418                                         if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
419                                                 result = STATE_CRITICAL;
420                                                 asprintf(&error_msg, _("recv() failed after sending authuser, "));
421                                                 break;
422                                         }
423                                         if (verbose) {
424                                                 printf (_("received %s\n"), buffer);
425                                         }
426                                         if (strncmp (buffer, "334", 3) != 0) {
427                                                 result = STATE_CRITICAL;
428                                                 asprintf(&error_msg, _("invalid response received after authuser, "));
429                                                 break;
430                                         }
431                                         /* encode authpass with base64 */
432                                         abuf = base64 (authpass, strlen(authpass));
433                                         strcat (abuf, "\r\n");
434                                         my_send(abuf, strlen(abuf));
435                                         if (verbose) {
436                                                 printf (_("sent %s\n"), abuf);
437                                         }
438                                         if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
439                                                 result = STATE_CRITICAL;
440                                                 asprintf(&error_msg, _("recv() failed after sending authpass, "));
441                                                 break;
442                                         }
443                                         if (verbose) {
444                                                 printf (_("received %s\n"), buffer);
445                                         }
446                                         if (strncmp (buffer, "235", 3) != 0) {
447                                                 result = STATE_CRITICAL;
448                                                 asprintf(&error_msg, _("invalid response received after authpass, "));
449                                                 break;
450                                         }
451                                         break;
452                                 } while (0);
453                         } else {
454                                 result = STATE_CRITICAL;
455                                 asprintf(&error_msg, _("only authtype LOGIN is supported, "));
456                         }
457                 }
459                 /* tell the server we're done */
460                 smtp_quit();
462                 /* finally close the connection */
463                 close (sd);
464         }
466         /* reset the alarm */
467         alarm (0);
469         microsec = deltime (tv);
470         elapsed_time = (double)microsec / 1.0e6;
472         if (result == STATE_OK) {
473                 if (check_critical_time && elapsed_time > (double) critical_time)
474                         result = STATE_CRITICAL;
475                 else if (check_warning_time && elapsed_time > (double) warning_time)
476                         result = STATE_WARNING;
477         }
479         printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
480                         state_text (result),
481                         error_msg,
482                         elapsed_time,
483                         verbose?", ":"", verbose?buffer:"",
484                         fperfdata ("time", elapsed_time, "s",
485                                 (int)check_warning_time, warning_time,
486                                 (int)check_critical_time, critical_time,
487                                 TRUE, 0, FALSE, 0));
489         return result;
494 /* process command-line arguments */
495 int
496 process_arguments (int argc, char **argv)
498         int c;
500         int option = 0;
501         static struct option longopts[] = {
502                 {"hostname", required_argument, 0, 'H'},
503                 {"expect", required_argument, 0, 'e'},
504                 {"critical", required_argument, 0, 'c'},
505                 {"warning", required_argument, 0, 'w'},
506                 {"timeout", required_argument, 0, 't'},
507                 {"port", required_argument, 0, 'p'},
508                 {"from", required_argument, 0, 'f'},
509                 {"fqdn", required_argument, 0, 'F'},
510                 {"authtype", required_argument, 0, 'A'},
511                 {"authuser", required_argument, 0, 'U'},
512                 {"authpass", required_argument, 0, 'P'},
513                 {"command", required_argument, 0, 'C'},
514                 {"response", required_argument, 0, 'R'},
515                 {"nocommand", required_argument, 0, 'n'},
516                 {"verbose", no_argument, 0, 'v'},
517                 {"version", no_argument, 0, 'V'},
518                 {"use-ipv4", no_argument, 0, '4'},
519                 {"use-ipv6", no_argument, 0, '6'},
520                 {"help", no_argument, 0, 'h'},
521                 {"starttls",no_argument,0,'S'},
522                 {"certificate",required_argument,0,'D'},
523                 {0, 0, 0, 0}
524         };
526         if (argc < 2)
527                 return ERROR;
529         for (c = 1; c < argc; c++) {
530                 if (strcmp ("-to", argv[c]) == 0)
531                         strcpy (argv[c], "-t");
532                 else if (strcmp ("-wt", argv[c]) == 0)
533                         strcpy (argv[c], "-w");
534                 else if (strcmp ("-ct", argv[c]) == 0)
535                         strcpy (argv[c], "-c");
536         }
538         while (1) {
539                 c = getopt_long (argc, argv, "+hVv46t:p:f:e:c:w:H:C:R:SD:F:A:U:P:",
540                                  longopts, &option);
542                 if (c == -1 || c == EOF)
543                         break;
545                 switch (c) {
546                 case 'H':                                                                       /* hostname */
547                         if (is_host (optarg)) {
548                                 server_address = optarg;
549                         }
550                         else {
551                                 usage2 (_("Invalid hostname/address"), optarg);
552                         }
553                         break;
554                 case 'p':                                                                       /* port */
555                         if (is_intpos (optarg))
556                                 server_port = atoi (optarg);
557                         else
558                                 usage4 (_("Port must be a positive integer"));
559                         break;
560                 case 'F':
561                 /* localhostname */
562                         localhostname = strdup(optarg);
563                         break;
564                 case 'f':                                                                       /* from argument */
565                         from_arg = optarg;
566                         smtp_use_dummycmd = 1;
567                         break;
568                 case 'A':
569                         authtype = optarg;
570                         break;
571                 case 'U':
572                         authuser = optarg;
573                         break;
574                 case 'P':
575                         authpass = optarg;
576                         break;
577                 case 'e':                                                                       /* server expect string on 220  */
578                         server_expect = optarg;
579                         break;
580                 case 'C':                                                                       /* commands  */
581                         if (ncommands >= command_size) {
582                                 command_size+=8;
583                                 commands = realloc (commands, sizeof(char *) * command_size);
584                                 if (commands == NULL)
585                                         die (STATE_UNKNOWN,
586                                              _("Could not realloc() units [%d]\n"), ncommands);
587                         }
588                         commands[ncommands] = (char *) malloc (sizeof(char) * 255);
589                         strncpy (commands[ncommands], optarg, 255);
590                         ncommands++;
591                         break;
592                 case 'R':                                                                       /* server responses */
593                         if (nresponses >= response_size) {
594                                 response_size += 8;
595                                 responses = realloc (responses, sizeof(char *) * response_size);
596                                 if (responses == NULL)
597                                         die (STATE_UNKNOWN,
598                                              _("Could not realloc() units [%d]\n"), nresponses);
599                         }
600                         responses[nresponses] = (char *) malloc (sizeof(char) * 255);
601                         strncpy (responses[nresponses], optarg, 255);
602                         nresponses++;
603                         break;
604                 case 'c':                                                                       /* critical time threshold */
605                         if (is_intnonneg (optarg)) {
606                                 critical_time = atoi (optarg);
607                                 check_critical_time = TRUE;
608                         }
609                         else {
610                                 usage4 (_("Critical time must be a positive integer"));
611                         }
612                         break;
613                 case 'w':                                                                       /* warning time threshold */
614                         if (is_intnonneg (optarg)) {
615                                 warning_time = atoi (optarg);
616                                 check_warning_time = TRUE;
617                         }
618                         else {
619                                 usage4 (_("Warning time must be a positive integer"));
620                         }
621                         break;
622                 case 'v':                                                                       /* verbose */
623                         verbose++;
624                         break;
625                 case 't':                                                                       /* timeout */
626                         if (is_intnonneg (optarg)) {
627                                 socket_timeout = atoi (optarg);
628                         }
629                         else {
630                                 usage4 (_("Timeout interval must be a positive integer"));
631                         }
632                         break;
633                 case 'S':
634                 /* starttls */
635                         use_ssl = TRUE;
636                         use_ehlo = TRUE;
637                         break;
638                 case 'D':
639                 /* Check SSL cert validity */
640 #ifdef USE_OPENSSL
641                         if (!is_intnonneg (optarg))
642                                 usage2 ("Invalid certificate expiration period",optarg);
643                                 days_till_exp = atoi (optarg);
644                                 check_cert = TRUE;
645 #else
646                                 usage (_("SSL support not available - install OpenSSL and recompile"));
647 #endif
648                         break;
649                 case '4':
650                         address_family = AF_INET;
651                         break;
652                 case '6':
653 #ifdef USE_IPV6
654                         address_family = AF_INET6;
655 #else
656                         usage4 (_("IPv6 support not available"));
657 #endif
658                         break;
659                 case 'V':                                                                       /* version */
660                         print_revision (progname, revision);
661                         exit (STATE_OK);
662                 case 'h':                                                                       /* help */
663                         print_help ();
664                         exit (STATE_OK);
665                 case '?':                                                                       /* help */
666                         usage5 ();
667                 }
668         }
670         c = optind;
671         if (server_address == NULL) {
672                 if (argv[c]) {
673                         if (is_host (argv[c]))
674                                 server_address = argv[c];
675                         else
676                                 usage2 (_("Invalid hostname/address"), argv[c]);
677                 }
678                 else {
679                         asprintf (&server_address, "127.0.0.1");
680                 }
681         }
683         if (server_expect == NULL)
684                 server_expect = strdup (SMTP_EXPECT);
686         if (mail_command == NULL)
687                 mail_command = strdup("MAIL ");
689         if (from_arg==NULL)
690                 from_arg = strdup(" ");
692         return validate_arguments ();
697 int
698 validate_arguments (void)
700         return OK;
704 void
705 smtp_quit(void)
707         int bytes;
709         my_send(SMTP_QUIT, strlen(SMTP_QUIT));
710         if (verbose)
711                 printf(_("sent %s\n"), "QUIT");
713         /* read the response but don't care about problems */
714         bytes = recvlines(buffer, MAX_INPUT_BUFFER);
715         if (verbose) {
716                 if (bytes < 0)
717                         printf(_("recv() failed after QUIT."));
718                 else if (bytes == 0)
719                         printf(_("Connection reset by peer."));
720                 else {
721                         buffer[bytes] = '\0';
722                         printf(_("received %s\n"), buffer);
723                 }
724         }
728 /*
729  * Receive one line, copy it into buf and nul-terminate it.  Returns the
730  * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
731  * error.
732  *
733  * TODO: Reading one byte at a time is very inefficient.  Replace this by a
734  * function which buffers the data, move that to netutils.c and change
735  * check_smtp and other plugins to use that.  Also, remove (\r)\n.
736  */
737 int
738 recvline(char *buf, size_t bufsize)
740         int result;
741         unsigned i;
743         for (i = result = 0; i < bufsize - 1; i++) {
744                 if ((result = my_recv(&buf[i], 1)) != 1)
745                         break;
746                 if (buf[i] == '\n') {
747                         buf[++i] = '\0';
748                         return i;
749                 }
750         }
751         return (result == 1 || i == 0) ? -2 : result;   /* -2 if out of space */
755 /*
756  * Receive one or more lines, copy them into buf and nul-terminate it.  Returns
757  * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
758  * error.  Works for all protocols which format multiline replies as follows:
759  *
760  * ``The format for multiline replies requires that every line, except the last,
761  * begin with the reply code, followed immediately by a hyphen, `-' (also known
762  * as minus), followed by text.  The last line will begin with the reply code,
763  * followed immediately by <SP>, optionally some text, and <CRLF>.  As noted
764  * above, servers SHOULD send the <SP> if subsequent text is not sent, but
765  * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
766  *
767  * TODO: Move this to netutils.c.  Also, remove \r and possibly the final \n.
768  */
769 int
770 recvlines(char *buf, size_t bufsize)
772         int result, i;
774         for (i = 0; /* forever */; i += result)
775                 if (!((result = recvline(buf + i, bufsize - i)) > 3 &&
776                     isdigit((int)buf[i]) &&
777                     isdigit((int)buf[i + 1]) &&
778                     isdigit((int)buf[i + 2]) &&
779                     buf[i + 3] == '-'))
780                         break;
782         return (result <= 0) ? result : result + i;
786 int 
787 my_close (void)
789 #ifdef HAVE_SSL
790   np_net_ssl_cleanup();
791 #endif
792   return close(sd);
796 void
797 print_help (void)
799         char *myport;
800         asprintf (&myport, "%d", SMTP_PORT);
802         print_revision (progname, revision);
804         printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
805         printf (COPYRIGHT, copyright, email);
807         printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
809   printf ("\n\n");
811         print_usage ();
813         printf (_(UT_HELP_VRSN));
815         printf (_(UT_HOST_PORT), 'p', myport);
817         printf (_(UT_IPv46));
819         printf (" %s\n", "-e, --expect=STRING");
820   printf (_("    String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT);
821   printf (" %s\n", "-n, nocommand");
822   printf ("    %s\n", _("Suppress SMTP command"));
823   printf (" %s\n", "-C, --command=STRING");
824   printf ("    %s\n", _("SMTP command (may be used repeatedly)"));
825   printf (" %s\n", "-R, --command=STRING");
826   printf ("    %s\n", _("Expected response to command (may be used repeatedly)"));
827   printf (" %s\n", "-f, --from=STRING");
828   printf ("    %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
829 #ifdef HAVE_SSL
830   printf (" %s\n", "-D, --certificate=INTEGER");
831   printf ("    %s\n", _("Minimum number of days a certificate has to be valid."));
832   printf (" %s\n", "-S, --starttls");
833   printf ("    %s\n", _("Use STARTTLS for the connection."));
834 #endif
836         printf (" %s\n", "-A, --authtype=STRING");
837   printf ("    %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
838   printf (" %s\n", "-U, --authuser=STRING");
839   printf ("    %s\n", _("SMTP AUTH username"));
840   printf (" %s\n", "-P, --authpass=STRING");
841   printf ("    %s\n", _("SMTP AUTH password"));
843         printf (_(UT_WARN_CRIT));
845         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
847         printf (_(UT_VERBOSE));
849         printf("\n");
850         printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
851   printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN.  Successful"));
852   printf ("%s\n", _("connects, but incorrect reponse messages from the host result in"));
853   printf ("%s\n", _("STATE_WARNING return values."));
855         printf (_(UT_SUPPORT));
860 void
861 print_usage (void)
863   printf (_("Usage:"));
864         printf ("%s -H host [-p port] [-e expect] [-C command] [-f from addr]", progname);
865   printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout]\n");
866   printf ("[-S] [-D days] [-n] [-v] [-4|-6]\n");