check_icmp: set rtmin initially
[monitoring-plugins.git] / plugins / check_smtp.c
blobe6369e632128ee480b958d4f19453741639c8d99
1 /*****************************************************************************
2 *
3 * Monitoring check_smtp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2000-2024 Monitoring Plugins Development Team
7 *
8 * Description:
9 *
10 * This file contains the check_smtp plugin
12 * This plugin will attempt to open an SMTP connection with the host.
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
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
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/>.
29 *****************************************************************************/
31 const char *progname = "check_smtp";
32 const char *copyright = "2000-2024";
33 const char *email = "devel@monitoring-plugins.org";
35 #include "common.h"
36 #include "netutils.h"
37 #include "utils.h"
38 #include "base64.h"
40 #include <ctype.h>
42 #ifdef HAVE_SSL
43 static bool check_cert = false;
44 static int days_till_exp_warn, days_till_exp_crit;
45 # define my_recv(buf, len) (((use_starttls || use_ssl) && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
46 # define my_send(buf, len) (((use_starttls || use_ssl) && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
47 #else /* ifndef HAVE_SSL */
48 # define my_recv(buf, len) read(sd, buf, len)
49 # define my_send(buf, len) send(sd, buf, len, 0)
50 #endif
52 enum {
53 SMTP_PORT = 25,
54 SMTPS_PORT = 465
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"
65 #define EHLO_SUPPORTS_STARTTLS 1
67 static int process_arguments (int, char **);
68 static int validate_arguments (void);
69 static void print_help (void);
70 void print_usage (void);
71 static void smtp_quit(void);
72 static int recvline(char *, size_t);
73 static int recvlines(char *, size_t);
74 static int my_close(void);
76 #include "regex.h"
77 static regex_t preg;
78 static regmatch_t pmatch[10];
79 static char errbuf[MAX_INPUT_BUFFER];
80 static int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
81 static int eflags = 0;
82 static int errcode, excode;
84 static int server_port = SMTP_PORT;
85 static int server_port_option = 0;
86 static char *server_address = NULL;
87 static char *server_expect = NULL;
88 static char *mail_command = NULL;
89 static char *from_arg = NULL;
90 static int send_mail_from=0;
91 static int ncommands=0;
92 static int command_size=0;
93 static int nresponses=0;
94 static int response_size=0;
95 static char **commands = NULL;
96 static char **responses = NULL;
97 static char *authtype = NULL;
98 static char *authuser = NULL;
99 static char *authpass = NULL;
100 static double warning_time = 0;
101 static bool check_warning_time = false;
102 static double critical_time = 0;
103 static bool check_critical_time = false;
104 static int verbose = 0;
105 static bool use_ssl = false;
106 static bool use_starttls = false;
107 static bool use_sni = false;
108 static bool use_proxy_prefix = false;
109 static bool use_ehlo = false;
110 static bool use_lhlo = false;
111 static bool ssl_established = false;
112 static char *localhostname = NULL;
113 static int sd;
114 static char buffer[MAX_INPUT_BUFFER];
115 enum {
116 TCP_PROTOCOL = 1,
117 UDP_PROTOCOL = 2,
119 static bool ignore_send_quit_failure = false;
123 main (int argc, char **argv)
125 bool supports_tls = false;
126 int n = 0;
127 double elapsed_time;
128 long microsec;
129 int result = STATE_UNKNOWN;
130 char *cmd_str = NULL;
131 char *helocmd = NULL;
132 char *error_msg = "";
133 char *server_response = NULL;
134 struct timeval tv;
136 /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
137 (void) signal (SIGPIPE, SIG_IGN);
139 setlocale (LC_ALL, "");
140 bindtextdomain (PACKAGE, LOCALEDIR);
141 textdomain (PACKAGE);
143 /* Parse extra opts if any */
144 argv=np_extra_opts (&argc, argv, progname);
146 if (process_arguments (argc, argv) == ERROR)
147 usage4 (_("Could not parse arguments"));
149 /* If localhostname not set on command line, use gethostname to set */
150 if(! localhostname){
151 localhostname = malloc (HOST_MAX_BYTES);
152 if(!localhostname){
153 printf(_("malloc() failed!\n"));
154 return STATE_CRITICAL;
156 if(gethostname(localhostname, HOST_MAX_BYTES)){
157 printf(_("gethostname() failed!\n"));
158 return STATE_CRITICAL;
161 if(use_lhlo)
162 xasprintf (&helocmd, "%s%s%s", SMTP_LHLO, localhostname, "\r\n");
163 else if(use_ehlo)
164 xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
165 else
166 xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
168 if (verbose)
169 printf("HELOCMD: %s", helocmd);
171 /* initialize the MAIL command with optional FROM command */
172 xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n");
174 if (verbose && send_mail_from)
175 printf ("FROM CMD: %s", cmd_str);
177 /* initialize alarm signal handling */
178 (void) signal (SIGALRM, socket_timeout_alarm_handler);
180 /* set socket timeout */
181 (void) alarm (socket_timeout);
183 /* start timer */
184 gettimeofday (&tv, NULL);
186 /* try to connect to the host at the given port number */
187 result = my_tcp_connect (server_address, server_port, &sd);
189 if (result == STATE_OK) { /* we connected */
190 /* If requested, send PROXY header */
191 if (use_proxy_prefix) {
192 if (verbose)
193 printf ("Sending header %s\n", PROXY_PREFIX);
194 my_send(PROXY_PREFIX, strlen(PROXY_PREFIX));
197 #ifdef HAVE_SSL
198 if (use_ssl) {
199 result = np_net_ssl_init_with_hostname(sd, (use_sni ? server_address : NULL));
200 if (result != STATE_OK) {
201 printf (_("CRITICAL - Cannot create SSL context.\n"));
202 close(sd);
203 np_net_ssl_cleanup();
204 return STATE_CRITICAL;
205 } else {
206 ssl_established = 1;
209 #endif
211 /* watch for the SMTP connection string and */
212 /* return a WARNING status if we couldn't read any data */
213 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
214 printf (_("recv() failed\n"));
215 return STATE_WARNING;
218 /* save connect return (220 hostname ..) for later use */
219 xasprintf(&server_response, "%s", buffer);
221 /* send the HELO/EHLO command */
222 my_send(helocmd, strlen(helocmd));
224 /* allow for response to helo command to reach us */
225 if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
226 printf (_("recv() failed\n"));
227 return STATE_WARNING;
228 } else if(use_ehlo || use_lhlo){
229 if(strstr(buffer, "250 STARTTLS") != NULL ||
230 strstr(buffer, "250-STARTTLS") != NULL){
231 supports_tls=true;
235 if(use_starttls && ! supports_tls){
236 printf(_("WARNING - TLS not supported by server\n"));
237 smtp_quit();
238 return STATE_WARNING;
241 #ifdef HAVE_SSL
242 if(use_starttls) {
243 /* send the STARTTLS command */
244 send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
246 recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
247 if (!strstr (buffer, SMTP_EXPECT)) {
248 printf (_("Server does not support STARTTLS\n"));
249 smtp_quit();
250 return STATE_UNKNOWN;
252 result = np_net_ssl_init_with_hostname(sd, (use_sni ? server_address : NULL));
253 if(result != STATE_OK) {
254 printf (_("CRITICAL - Cannot create SSL context.\n"));
255 close(sd);
256 np_net_ssl_cleanup();
257 return STATE_CRITICAL;
258 } else {
259 ssl_established = 1;
263 * Resend the EHLO command.
265 * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
266 * obtained from the server, such as the list of SMTP service
267 * extensions, which was not obtained from the TLS negotiation
268 * itself. The client SHOULD send an EHLO command as the first
269 * command after a successful TLS negotiation.'' For this
270 * reason, some MTAs will not allow an AUTH LOGIN command before
271 * we resent EHLO via TLS.
273 if (my_send(helocmd, strlen(helocmd)) <= 0) {
274 printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
275 my_close();
276 return STATE_UNKNOWN;
278 if (verbose)
279 printf(_("sent %s"), helocmd);
280 if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
281 printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
282 my_close();
283 return STATE_UNKNOWN;
285 if (verbose) {
286 printf("%s", buffer);
289 # ifdef USE_OPENSSL
290 if ( check_cert ) {
291 result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
292 smtp_quit();
293 my_close();
294 return result;
296 # endif /* USE_OPENSSL */
298 #endif
300 if (verbose)
301 printf ("%s", buffer);
303 /* save buffer for later use */
304 xasprintf(&server_response, "%s%s", server_response, buffer);
305 /* strip the buffer of carriage returns */
306 strip (server_response);
308 /* make sure we find the droids we are looking for */
309 if (!strstr (server_response, server_expect)) {
310 if (server_port == SMTP_PORT)
311 printf (_("Invalid SMTP response received from host: %s\n"), server_response);
312 else
313 printf (_("Invalid SMTP response received from host on port %d: %s\n"),
314 server_port, server_response);
315 return STATE_WARNING;
318 if (send_mail_from) {
319 my_send(cmd_str, strlen(cmd_str));
320 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
321 printf("%s", buffer);
324 n = 0;
325 while (n < ncommands) {
326 xasprintf (&cmd_str, "%s%s", commands[n], "\r\n");
327 my_send(cmd_str, strlen(cmd_str));
328 if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
329 printf("%s", buffer);
330 strip (buffer);
331 if (n < nresponses) {
332 cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
333 errcode = regcomp (&preg, responses[n], cflags);
334 if (errcode != 0) {
335 regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
336 printf (_("Could Not Compile Regular Expression"));
337 return ERROR;
339 excode = regexec (&preg, buffer, 10, pmatch, eflags);
340 if (excode == 0) {
341 result = STATE_OK;
343 else if (excode == REG_NOMATCH) {
344 result = STATE_WARNING;
345 printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
347 else {
348 regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
349 printf (_("Execute Error: %s\n"), errbuf);
350 result = STATE_UNKNOWN;
353 n++;
356 if (authtype != NULL) {
357 if (strcmp (authtype, "LOGIN") == 0) {
358 char *abuf;
359 int ret;
360 do {
361 if (authuser == NULL) {
362 result = STATE_CRITICAL;
363 xasprintf(&error_msg, _("no authuser specified, "));
364 break;
366 if (authpass == NULL) {
367 result = STATE_CRITICAL;
368 xasprintf(&error_msg, _("no authpass specified, "));
369 break;
372 /* send AUTH LOGIN */
373 my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
374 if (verbose)
375 printf (_("sent %s\n"), "AUTH LOGIN");
377 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
378 xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
379 result = STATE_WARNING;
380 break;
382 if (verbose)
383 printf (_("received %s\n"), buffer);
385 if (strncmp (buffer, "334", 3) != 0) {
386 result = STATE_CRITICAL;
387 xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
388 break;
391 /* encode authuser with base64 */
392 base64_encode_alloc (authuser, strlen(authuser), &abuf);
393 xasprintf(&abuf, "%s\r\n", abuf);
394 my_send(abuf, strlen(abuf));
395 if (verbose)
396 printf (_("sent %s\n"), abuf);
398 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
399 result = STATE_CRITICAL;
400 xasprintf(&error_msg, _("recv() failed after sending authuser, "));
401 break;
403 if (verbose) {
404 printf (_("received %s\n"), buffer);
406 if (strncmp (buffer, "334", 3) != 0) {
407 result = STATE_CRITICAL;
408 xasprintf(&error_msg, _("invalid response received after authuser, "));
409 break;
411 /* encode authpass with base64 */
412 base64_encode_alloc (authpass, strlen(authpass), &abuf);
413 xasprintf(&abuf, "%s\r\n", abuf);
414 my_send(abuf, strlen(abuf));
415 if (verbose) {
416 printf (_("sent %s\n"), abuf);
418 if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
419 result = STATE_CRITICAL;
420 xasprintf(&error_msg, _("recv() failed after sending authpass, "));
421 break;
423 if (verbose) {
424 printf (_("received %s\n"), buffer);
426 if (strncmp (buffer, "235", 3) != 0) {
427 result = STATE_CRITICAL;
428 xasprintf(&error_msg, _("invalid response received after authpass, "));
429 break;
431 break;
432 } while (0);
433 } else {
434 result = STATE_CRITICAL;
435 xasprintf(&error_msg, _("only authtype LOGIN is supported, "));
439 /* tell the server we're done */
440 smtp_quit();
442 /* finally close the connection */
443 close (sd);
446 /* reset the alarm */
447 alarm (0);
449 microsec = deltime (tv);
450 elapsed_time = (double)microsec / 1.0e6;
452 if (result == STATE_OK) {
453 if (check_critical_time && elapsed_time > critical_time)
454 result = STATE_CRITICAL;
455 else if (check_warning_time && elapsed_time > warning_time)
456 result = STATE_WARNING;
459 printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
460 state_text (result),
461 error_msg,
462 elapsed_time,
463 verbose?", ":"", verbose?buffer:"",
464 fperfdata ("time", elapsed_time, "s",
465 (int)check_warning_time, warning_time,
466 (int)check_critical_time, critical_time,
467 true, 0, false, 0));
469 return result;
474 /* process command-line arguments */
476 process_arguments (int argc, char **argv)
478 int c;
479 char* temp;
481 bool implicit_tls = false;
483 enum {
484 SNI_OPTION
487 int option = 0;
488 static struct option longopts[] = {
489 {"hostname", required_argument, 0, 'H'},
490 {"expect", required_argument, 0, 'e'},
491 {"critical", required_argument, 0, 'c'},
492 {"warning", required_argument, 0, 'w'},
493 {"timeout", required_argument, 0, 't'},
494 {"port", required_argument, 0, 'p'},
495 {"from", required_argument, 0, 'f'},
496 {"fqdn", required_argument, 0, 'F'},
497 {"authtype", required_argument, 0, 'A'},
498 {"authuser", required_argument, 0, 'U'},
499 {"authpass", required_argument, 0, 'P'},
500 {"command", required_argument, 0, 'C'},
501 {"response", required_argument, 0, 'R'},
502 {"verbose", no_argument, 0, 'v'},
503 {"version", no_argument, 0, 'V'},
504 {"use-ipv4", no_argument, 0, '4'},
505 {"use-ipv6", no_argument, 0, '6'},
506 {"help", no_argument, 0, 'h'},
507 {"lmtp", no_argument, 0, 'L'},
508 {"ssl", no_argument, 0, 's'},
509 {"tls", no_argument, 0, 's'},
510 {"starttls",no_argument,0,'S'},
511 {"sni", no_argument, 0, SNI_OPTION},
512 {"certificate",required_argument,0,'D'},
513 {"ignore-quit-failure",no_argument,0,'q'},
514 {"proxy",no_argument,0,'r'},
515 {0, 0, 0, 0}
518 if (argc < 2)
519 return ERROR;
521 for (c = 1; c < argc; c++) {
522 if (strcmp ("-to", argv[c]) == 0)
523 strcpy (argv[c], "-t");
524 else if (strcmp ("-wt", argv[c]) == 0)
525 strcpy (argv[c], "-w");
526 else if (strcmp ("-ct", argv[c]) == 0)
527 strcpy (argv[c], "-c");
530 while (1) {
531 c = getopt_long (argc, argv, "+hVv46Lrt:p:f:e:c:w:H:C:R:sSD:F:A:U:P:q",
532 longopts, &option);
534 if (c == -1 || c == EOF)
535 break;
537 switch (c) {
538 case 'H': /* hostname */
539 if (is_host (optarg)) {
540 server_address = optarg;
542 else {
543 usage2 (_("Invalid hostname/address"), optarg);
545 break;
546 case 'p': /* port */
547 if (is_intpos (optarg))
548 server_port_option = atoi (optarg);
549 else
550 usage4 (_("Port must be a positive integer"));
551 break;
552 case 'F':
553 /* localhostname */
554 localhostname = strdup(optarg);
555 break;
556 case 'f': /* from argument */
557 from_arg = optarg + strspn(optarg, "<");
558 from_arg = strndup(from_arg, strcspn(from_arg, ">"));
559 send_mail_from = 1;
560 break;
561 case 'A':
562 authtype = optarg;
563 use_ehlo = true;
564 break;
565 case 'U':
566 authuser = optarg;
567 break;
568 case 'P':
569 authpass = optarg;
570 break;
571 case 'e': /* server expect string on 220 */
572 server_expect = optarg;
573 break;
574 case 'C': /* commands */
575 if (ncommands >= command_size) {
576 command_size+=8;
577 commands = realloc (commands, sizeof(char *) * command_size);
578 if (commands == NULL)
579 die (STATE_UNKNOWN,
580 _("Could not realloc() units [%d]\n"), ncommands);
582 commands[ncommands] = (char *) malloc (sizeof(char) * 255);
583 strncpy (commands[ncommands], optarg, 255);
584 ncommands++;
585 break;
586 case 'R': /* server responses */
587 if (nresponses >= response_size) {
588 response_size += 8;
589 responses = realloc (responses, sizeof(char *) * response_size);
590 if (responses == NULL)
591 die (STATE_UNKNOWN,
592 _("Could not realloc() units [%d]\n"), nresponses);
594 responses[nresponses] = (char *) malloc (sizeof(char) * 255);
595 strncpy (responses[nresponses], optarg, 255);
596 nresponses++;
597 break;
598 case 'c': /* critical time threshold */
599 if (!is_nonnegative (optarg))
600 usage4 (_("Critical time must be a positive"));
601 else {
602 critical_time = strtod (optarg, NULL);
603 check_critical_time = true;
605 break;
606 case 'w': /* warning time threshold */
607 if (!is_nonnegative (optarg))
608 usage4 (_("Warning time must be a positive"));
609 else {
610 warning_time = strtod (optarg, NULL);
611 check_warning_time = true;
613 break;
614 case 'v': /* verbose */
615 verbose++;
616 break;
617 case 'q':
618 ignore_send_quit_failure = true; /* ignore problem sending QUIT */
619 break;
620 case 't': /* timeout */
621 if (is_intnonneg (optarg)) {
622 socket_timeout = atoi (optarg);
624 else {
625 usage4 (_("Timeout interval must be a positive integer"));
627 break;
628 case 'D':
629 /* Check SSL cert validity */
630 #ifdef USE_OPENSSL
631 if ((temp=strchr(optarg,','))!=NULL) {
632 *temp='\0';
633 if (!is_intnonneg (optarg))
634 usage2 ("Invalid certificate expiration period", optarg);
635 days_till_exp_warn = atoi(optarg);
636 *temp=',';
637 temp++;
638 if (!is_intnonneg (temp))
639 usage2 (_("Invalid certificate expiration period"), temp);
640 days_till_exp_crit = atoi (temp);
642 else {
643 days_till_exp_crit=0;
644 if (!is_intnonneg (optarg))
645 usage2 ("Invalid certificate expiration period", optarg);
646 days_till_exp_warn = atoi (optarg);
648 check_cert = true;
649 ignore_send_quit_failure = true;
650 #else
651 usage (_("SSL support not available - install OpenSSL and recompile"));
652 #endif
653 implicit_tls = true;
654 // fallthrough
655 case 's':
656 /* ssl */
657 use_ssl = true;
658 server_port = SMTPS_PORT;
659 break;
660 case 'S':
661 /* starttls */
662 use_starttls = true;
663 use_ehlo = true;
664 break;
665 case SNI_OPTION:
666 #ifdef HAVE_SSL
667 use_sni = true;
668 #else
669 usage (_("SSL support not available - install OpenSSL and recompile"));
670 #endif
671 break;
672 case 'r':
673 use_proxy_prefix = true;
674 break;
675 case 'L':
676 use_lhlo = true;
677 break;
678 case '4':
679 address_family = AF_INET;
680 break;
681 case '6':
682 #ifdef USE_IPV6
683 address_family = AF_INET6;
684 #else
685 usage4 (_("IPv6 support not available"));
686 #endif
687 break;
688 case 'V': /* version */
689 print_revision (progname, NP_VERSION);
690 exit (STATE_UNKNOWN);
691 case 'h': /* help */
692 print_help ();
693 exit (STATE_UNKNOWN);
694 case '?': /* help */
695 usage5 ();
699 c = optind;
700 if (server_address == NULL) {
701 if (argv[c]) {
702 if (is_host (argv[c]))
703 server_address = argv[c];
704 else
705 usage2 (_("Invalid hostname/address"), argv[c]);
707 else {
708 xasprintf (&server_address, "127.0.0.1");
712 if (server_expect == NULL)
713 server_expect = strdup (SMTP_EXPECT);
715 if (mail_command == NULL)
716 mail_command = strdup("MAIL ");
718 if (from_arg==NULL)
719 from_arg = strdup(" ");
721 if (use_starttls && use_ssl) {
722 if (implicit_tls) {
723 use_ssl = false;
724 server_port = SMTP_PORT;
725 } else {
726 usage4 (_("Set either -s/--ssl/--tls or -S/--starttls"));
730 if (server_port_option != 0) {
731 server_port = server_port_option;
734 return validate_arguments ();
740 validate_arguments (void)
742 return OK;
746 void
747 smtp_quit(void)
749 int bytes;
750 int n;
752 n = my_send(SMTP_QUIT, strlen(SMTP_QUIT));
753 if(n < 0) {
754 if(ignore_send_quit_failure) {
755 if(verbose) {
756 printf(_("Connection closed by server before sending QUIT command\n"));
758 return;
760 die (STATE_UNKNOWN,
761 _("Connection closed by server before sending QUIT command\n"));
764 if (verbose)
765 printf(_("sent %s\n"), "QUIT");
767 /* read the response but don't care about problems */
768 bytes = recvlines(buffer, MAX_INPUT_BUFFER);
769 if (verbose) {
770 if (bytes < 0)
771 printf(_("recv() failed after QUIT."));
772 else if (bytes == 0)
773 printf(_("Connection reset by peer."));
774 else {
775 buffer[bytes] = '\0';
776 printf(_("received %s\n"), buffer);
783 * Receive one line, copy it into buf and nul-terminate it. Returns the
784 * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
785 * error.
787 * TODO: Reading one byte at a time is very inefficient. Replace this by a
788 * function which buffers the data, move that to netutils.c and change
789 * check_smtp and other plugins to use that. Also, remove (\r)\n.
792 recvline(char *buf, size_t bufsize)
794 int result;
795 unsigned i;
797 for (i = result = 0; i < bufsize - 1; i++) {
798 if ((result = my_recv(&buf[i], 1)) != 1)
799 break;
800 if (buf[i] == '\n') {
801 buf[++i] = '\0';
802 return i;
805 return (result == 1 || i == 0) ? -2 : result; /* -2 if out of space */
810 * Receive one or more lines, copy them into buf and nul-terminate it. Returns
811 * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
812 * error. Works for all protocols which format multiline replies as follows:
814 * ``The format for multiline replies requires that every line, except the last,
815 * begin with the reply code, followed immediately by a hyphen, `-' (also known
816 * as minus), followed by text. The last line will begin with the reply code,
817 * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
818 * above, servers SHOULD send the <SP> if subsequent text is not sent, but
819 * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
821 * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
824 recvlines(char *buf, size_t bufsize)
826 int result, i;
828 for (i = 0; /* forever */; i += result)
829 if (!((result = recvline(buf + i, bufsize - i)) > 3 &&
830 isdigit((int)buf[i]) &&
831 isdigit((int)buf[i + 1]) &&
832 isdigit((int)buf[i + 2]) &&
833 buf[i + 3] == '-'))
834 break;
836 return (result <= 0) ? result : result + i;
841 my_close (void)
843 int result;
844 result = close(sd);
845 #ifdef HAVE_SSL
846 np_net_ssl_cleanup();
847 #endif
848 return result;
852 void
853 print_help (void)
855 char *myport;
856 xasprintf (&myport, "%d", SMTP_PORT);
858 print_revision (progname, NP_VERSION);
860 printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
861 printf (COPYRIGHT, copyright, email);
863 printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
865 printf ("\n\n");
867 print_usage ();
869 printf (UT_HELP_VRSN);
870 printf (UT_EXTRA_OPTS);
872 printf (UT_HOST_PORT, 'p', myport);
874 printf (UT_IPv46);
876 printf (" %s\n", "-e, --expect=STRING");
877 printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT);
878 printf (" %s\n", "-C, --command=STRING");
879 printf (" %s\n", _("SMTP command (may be used repeatedly)"));
880 printf (" %s\n", "-R, --response=STRING");
881 printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
882 printf (" %s\n", "-f, --from=STRING");
883 printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
884 printf (" %s\n", "-F, --fqdn=STRING");
885 printf (" %s\n", _("FQDN used for HELO"));
886 printf (" %s\n", "-r, --proxy");
887 printf (" %s\n", _("Use PROXY protocol prefix for the connection."));
888 #ifdef HAVE_SSL
889 printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
890 printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
891 printf (" %s\n", "-s, --ssl, --tls");
892 printf (" %s\n", _("Use SSL/TLS for the connection."));
893 printf (_(" Sets default port to %d.\n"), SMTPS_PORT);
894 printf (" %s\n", "-S, --starttls");
895 printf (" %s\n", _("Use STARTTLS for the connection."));
896 printf (" %s\n", "--sni");
897 printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
898 #endif
900 printf (" %s\n", "-A, --authtype=STRING");
901 printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
902 printf (" %s\n", "-U, --authuser=STRING");
903 printf (" %s\n", _("SMTP AUTH username"));
904 printf (" %s\n", "-P, --authpass=STRING");
905 printf (" %s\n", _("SMTP AUTH password"));
906 printf (" %s\n", "-L, --lmtp");
907 printf (" %s\n", _("Send LHLO instead of HELO/EHLO"));
908 printf (" %s\n", "-q, --ignore-quit-failure");
909 printf (" %s\n", _("Ignore failure when sending QUIT command to server"));
911 printf (UT_WARN_CRIT);
913 printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
915 printf (UT_VERBOSE);
917 printf("\n");
918 printf ("%s\n", _("Successful connects return STATE_OK, refusals and timeouts return"));
919 printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
920 printf ("%s\n", _("connects, but incorrect response messages from the host result in"));
921 printf ("%s\n", _("STATE_WARNING return values."));
923 printf (UT_SUPPORT);
928 void
929 print_usage (void)
931 printf ("%s\n", _("Usage:"));
932 printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname);
933 printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
934 printf ("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-r] [--sni] [-v] \n");