Code

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