check_smtp.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. /*****************************************************************************
  2. *
  3. * Nagios check_smtp plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 2000-2014 Nagios Plugins Development Team
  7. *
  8. * Description:
  9. *
  10. * This file contains the check_smtp plugin
  11. *
  12. * This plugin will attempt to open an SMTP connection with the host.
  13. *
  14. *
  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.
  19. *
  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.
  24. *
  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/>.
  27. *
  28. *
  29. *****************************************************************************/
  30. const char *progname = "check_smtp";
  31. const char *copyright = "2000-2014";
  32. const char *email = "devel@nagios-plugins.org";
  33. #include "common.h"
  34. #include "netutils.h"
  35. #include "utils.h"
  36. #include "base64.h"
  37. #include <ctype.h>
  38. #ifdef HAVE_SSL
  39. int check_cert = FALSE;
  40. int days_till_exp_warn, days_till_exp_crit;
  41. # define my_recv(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
  42. # define my_send(buf, len) ((use_ssl && ssl_established) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
  43. #else /* ifndef HAVE_SSL */
  44. # define my_recv(buf, len) read(sd, buf, len)
  45. # define my_send(buf, len) send(sd, buf, len, 0)
  46. #endif
  47. enum {
  48. SMTP_PORT = 25
  49. };
  50. #define SMTP_EXPECT "220"
  51. #define SMTP_HELO "HELO "
  52. #define SMTP_EHLO "EHLO "
  53. #define SMTP_LHLO "LHLO "
  54. #define SMTP_QUIT "QUIT\r\n"
  55. #define SMTP_STARTTLS "STARTTLS\r\n"
  56. #define SMTP_AUTH_LOGIN "AUTH LOGIN\r\n"
  57. #ifndef HOST_MAX_BYTES
  58. #define HOST_MAX_BYTES 255
  59. #endif
  60. #define EHLO_SUPPORTS_STARTTLS 1
  61. int process_arguments (int, char **);
  62. int validate_arguments (void);
  63. void print_help (void);
  64. void print_usage (void);
  65. void smtp_quit(void);
  66. int recvline(char *, size_t);
  67. int recvlines(char *, size_t);
  68. int my_close(void);
  69. #include "regex.h"
  70. char regex_expect[MAX_INPUT_BUFFER] = "";
  71. regex_t preg;
  72. regmatch_t pmatch[10];
  73. char timestamp[20] = "";
  74. char errbuf[MAX_INPUT_BUFFER];
  75. int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
  76. int eflags = 0;
  77. int errcode, excode;
  78. int server_port = SMTP_PORT;
  79. char *server_address = NULL;
  80. char *server_expect = NULL;
  81. char *mail_command = NULL;
  82. char *from_arg = NULL;
  83. int send_mail_from=0;
  84. int ncommands=0;
  85. int command_size=0;
  86. int nresponses=0;
  87. int response_size=0;
  88. char **commands = NULL;
  89. char **responses = NULL;
  90. char *authtype = NULL;
  91. char *authuser = NULL;
  92. char *authpass = NULL;
  93. double warning_time = 0;
  94. int check_warning_time = FALSE;
  95. double critical_time = 0;
  96. int check_critical_time = FALSE;
  97. int verbose = 0;
  98. int use_ssl = FALSE;
  99. short use_ehlo = FALSE;
  100. short use_lhlo = FALSE;
  101. short ssl_established = 0;
  102. char *localhostname = NULL;
  103. int sd;
  104. char buffer[MAX_INPUT_BUFFER];
  105. enum {
  106. TCP_PROTOCOL = 1,
  107. UDP_PROTOCOL = 2,
  108. };
  109. int ignore_send_quit_failure = FALSE;
  110. int
  111. main (int argc, char **argv)
  112. {
  113. short supports_tls=FALSE;
  114. int n = 0;
  115. double elapsed_time;
  116. long microsec;
  117. int result = STATE_UNKNOWN;
  118. char *cmd_str = NULL;
  119. char *helocmd = NULL;
  120. char *error_msg = "";
  121. struct timeval tv;
  122. /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
  123. #ifdef HAVE_SIGACTION
  124. struct sigaction sig_action;
  125. sig_action.sa_sigaction = NULL;
  126. sig_action.sa_handler = SIG_IGN;
  127. sigemptyset(&sig_action.sa_mask);
  128. sig_action.sa_flags = 0;
  129. sigaction(SIGPIPE, &sig_action, NULL);
  130. #else /* HAVE_SIGACTION */
  131. (void) signal (SIGPIPE, SIG_IGN);
  132. #endif /* HAVE_SIGACTION */
  133. setlocale (LC_ALL, "");
  134. bindtextdomain (PACKAGE, LOCALEDIR);
  135. textdomain (PACKAGE);
  136. /* Parse extra opts if any */
  137. argv=np_extra_opts (&argc, argv, progname);
  138. if (process_arguments (argc, argv) == ERROR)
  139. usage4 (_("Could not parse arguments"));
  140. /* If localhostname not set on command line, use gethostname to set */
  141. if(! localhostname){
  142. localhostname = malloc (HOST_MAX_BYTES);
  143. if(!localhostname){
  144. printf(_("malloc() failed!\n"));
  145. return STATE_CRITICAL;
  146. }
  147. if(gethostname(localhostname, HOST_MAX_BYTES)){
  148. printf(_("gethostname() failed!\n"));
  149. return STATE_CRITICAL;
  150. }
  151. }
  152. if(use_lhlo)
  153. xasprintf (&helocmd, "%s%s%s", SMTP_LHLO, localhostname, "\r\n");
  154. else if(use_ehlo)
  155. xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
  156. else
  157. xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
  158. if (verbose)
  159. printf("HELOCMD: %s", helocmd);
  160. /* initialize the MAIL command with optional FROM command */
  161. xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n");
  162. if (verbose && send_mail_from)
  163. printf ("FROM CMD: %s", cmd_str);
  164. /* initialize alarm signal handling */
  165. (void) signal (SIGALRM, socket_timeout_alarm_handler);
  166. /* set socket timeout */
  167. (void) alarm (timeout_interval);
  168. /* start timer */
  169. gettimeofday (&tv, NULL);
  170. /* try to connect to the host at the given port number */
  171. result = my_tcp_connect (server_address, server_port, &sd);
  172. if (result == STATE_OK) { /* we connected */
  173. /* watch for the SMTP connection string and */
  174. /* return a WARNING status if we couldn't read any data */
  175. if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
  176. printf (_("recv() failed\n"));
  177. return STATE_WARNING;
  178. }
  179. else {
  180. if (verbose)
  181. printf ("%s", buffer);
  182. /* strip the buffer of carriage returns */
  183. strip (buffer);
  184. /* make sure we find the response we are looking for */
  185. if (!strstr (buffer, server_expect)) {
  186. if (server_port == SMTP_PORT)
  187. printf (_("Invalid SMTP response received from host: %s\n"), buffer);
  188. else
  189. printf (_("Invalid SMTP response received from host on port %d: %s\n"),
  190. server_port, buffer);
  191. return STATE_WARNING;
  192. }
  193. }
  194. /* send the HELO/EHLO command */
  195. send(sd, helocmd, strlen(helocmd), 0);
  196. /* allow for response to helo command to reach us */
  197. if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
  198. printf (_("recv() failed\n"));
  199. return STATE_WARNING;
  200. } else if(use_ehlo || use_lhlo){
  201. if(strstr(buffer, "250 STARTTLS") != NULL ||
  202. strstr(buffer, "250-STARTTLS") != NULL){
  203. supports_tls=TRUE;
  204. }
  205. }
  206. if(use_ssl && ! supports_tls){
  207. printf(_("WARNING - TLS not supported by server\n"));
  208. smtp_quit();
  209. return STATE_WARNING;
  210. }
  211. #ifdef HAVE_SSL
  212. if(use_ssl) {
  213. /* send the STARTTLS command */
  214. send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
  215. recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
  216. if (!strstr (buffer, SMTP_EXPECT)) {
  217. printf (_("Server does not support STARTTLS\n"));
  218. smtp_quit();
  219. return STATE_UNKNOWN;
  220. }
  221. result = np_net_ssl_init(sd);
  222. if(result != STATE_OK) {
  223. printf (_("CRITICAL - Cannot create SSL context.\n"));
  224. np_net_ssl_cleanup();
  225. close(sd);
  226. return STATE_CRITICAL;
  227. } else {
  228. ssl_established = 1;
  229. }
  230. /*
  231. * Resend the EHLO command.
  232. *
  233. * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
  234. * obtained from the server, such as the list of SMTP service
  235. * extensions, which was not obtained from the TLS negotiation
  236. * itself. The client SHOULD send an EHLO command as the first
  237. * command after a successful TLS negotiation.'' For this
  238. * reason, some MTAs will not allow an AUTH LOGIN command before
  239. * we resent EHLO via TLS.
  240. */
  241. if (my_send(helocmd, strlen(helocmd)) <= 0) {
  242. printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
  243. my_close();
  244. return STATE_UNKNOWN;
  245. }
  246. if (verbose)
  247. printf(_("sent %s"), helocmd);
  248. if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
  249. printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
  250. my_close();
  251. return STATE_UNKNOWN;
  252. }
  253. if (verbose) {
  254. printf("%s", buffer);
  255. }
  256. # ifdef USE_OPENSSL
  257. if ( check_cert ) {
  258. result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
  259. smtp_quit();
  260. my_close();
  261. return result;
  262. }
  263. # endif /* USE_OPENSSL */
  264. }
  265. #endif
  266. if (send_mail_from) {
  267. my_send(cmd_str, strlen(cmd_str));
  268. if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
  269. printf("%s", buffer);
  270. }
  271. while (n < ncommands) {
  272. xasprintf (&cmd_str, "%s%s", commands[n], "\r\n");
  273. my_send(cmd_str, strlen(cmd_str));
  274. if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose)
  275. printf("%s", buffer);
  276. strip (buffer);
  277. if (n < nresponses) {
  278. cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
  279. errcode = regcomp (&preg, responses[n], cflags);
  280. if (errcode != 0) {
  281. regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  282. printf (_("Could Not Compile Regular Expression"));
  283. return ERROR;
  284. }
  285. excode = regexec (&preg, buffer, 10, pmatch, eflags);
  286. if (excode == 0) {
  287. result = STATE_OK;
  288. }
  289. else if (excode == REG_NOMATCH) {
  290. result = STATE_WARNING;
  291. printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]);
  292. }
  293. else {
  294. regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER);
  295. printf (_("Execute Error: %s\n"), errbuf);
  296. result = STATE_UNKNOWN;
  297. }
  298. }
  299. n++;
  300. }
  301. if (authtype != NULL) {
  302. if (strcmp (authtype, "LOGIN") == 0) {
  303. char *abuf;
  304. int ret;
  305. do {
  306. if (authuser == NULL) {
  307. result = STATE_CRITICAL;
  308. xasprintf(&error_msg, _("no authuser specified, "));
  309. break;
  310. }
  311. if (authpass == NULL) {
  312. result = STATE_CRITICAL;
  313. xasprintf(&error_msg, _("no authpass specified, "));
  314. break;
  315. }
  316. /* send AUTH LOGIN */
  317. my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN));
  318. if (verbose)
  319. printf (_("sent %s\n"), "AUTH LOGIN");
  320. if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
  321. xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, "));
  322. result = STATE_WARNING;
  323. break;
  324. }
  325. if (verbose)
  326. printf (_("received %s\n"), buffer);
  327. if (strncmp (buffer, "334", 3) != 0) {
  328. result = STATE_CRITICAL;
  329. xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, "));
  330. break;
  331. }
  332. /* encode authuser with base64 */
  333. base64_encode_alloc (authuser, strlen(authuser), &abuf);
  334. xasprintf(&abuf, "%s\r\n", abuf);
  335. my_send(abuf, strlen(abuf));
  336. if (verbose)
  337. printf (_("sent %s\n"), abuf);
  338. if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
  339. result = STATE_CRITICAL;
  340. xasprintf(&error_msg, _("recv() failed after sending authuser, "));
  341. break;
  342. }
  343. if (verbose) {
  344. printf (_("received %s\n"), buffer);
  345. }
  346. if (strncmp (buffer, "334", 3) != 0) {
  347. result = STATE_CRITICAL;
  348. xasprintf(&error_msg, _("invalid response received after authuser, "));
  349. break;
  350. }
  351. /* encode authpass with base64 */
  352. base64_encode_alloc (authpass, strlen(authpass), &abuf);
  353. xasprintf(&abuf, "%s\r\n", abuf);
  354. my_send(abuf, strlen(abuf));
  355. if (verbose) {
  356. printf (_("sent %s\n"), abuf);
  357. }
  358. if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
  359. result = STATE_CRITICAL;
  360. xasprintf(&error_msg, _("recv() failed after sending authpass, "));
  361. break;
  362. }
  363. if (verbose) {
  364. printf (_("received %s\n"), buffer);
  365. }
  366. if (strncmp (buffer, "235", 3) != 0) {
  367. result = STATE_CRITICAL;
  368. xasprintf(&error_msg, _("invalid response received after authpass, "));
  369. break;
  370. }
  371. break;
  372. } while (0);
  373. } else {
  374. result = STATE_CRITICAL;
  375. xasprintf(&error_msg, _("only authtype LOGIN is supported, "));
  376. }
  377. }
  378. /* tell the server we're done */
  379. smtp_quit();
  380. /* finally close the connection */
  381. close (sd);
  382. }
  383. /* reset the alarm */
  384. alarm (0);
  385. microsec = deltime (tv);
  386. elapsed_time = (double)microsec / 1.0e6;
  387. if (result == STATE_OK) {
  388. if (check_critical_time && elapsed_time > critical_time)
  389. result = STATE_CRITICAL;
  390. else if (check_warning_time && elapsed_time > warning_time)
  391. result = STATE_WARNING;
  392. }
  393. printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"),
  394. state_text (result),
  395. error_msg,
  396. elapsed_time,
  397. verbose?", ":"", verbose?buffer:"",
  398. fperfdata ("time", elapsed_time, "s",
  399. (int)check_warning_time, warning_time,
  400. (int)check_critical_time, critical_time,
  401. TRUE, 0, FALSE, 0));
  402. return result;
  403. }
  404. /* process command-line arguments */
  405. int
  406. process_arguments (int argc, char **argv)
  407. {
  408. int c;
  409. char* temp;
  410. int option = 0;
  411. static struct option longopts[] = {
  412. {"hostname", required_argument, 0, 'H'},
  413. {"expect", required_argument, 0, 'e'},
  414. {"critical", required_argument, 0, 'c'},
  415. {"warning", required_argument, 0, 'w'},
  416. {"timeout", required_argument, 0, 't'},
  417. {"port", required_argument, 0, 'p'},
  418. {"from", required_argument, 0, 'f'},
  419. {"fqdn", required_argument, 0, 'F'},
  420. {"authtype", required_argument, 0, 'A'},
  421. {"authuser", required_argument, 0, 'U'},
  422. {"authpass", required_argument, 0, 'P'},
  423. {"command", required_argument, 0, 'C'},
  424. {"response", required_argument, 0, 'R'},
  425. {"verbose", no_argument, 0, 'v'},
  426. {"version", no_argument, 0, 'V'},
  427. {"use-ipv4", no_argument, 0, '4'},
  428. {"use-ipv6", no_argument, 0, '6'},
  429. {"help", no_argument, 0, 'h'},
  430. {"lmtp", no_argument, 0, 'L'},
  431. {"starttls",no_argument,0,'S'},
  432. {"certificate",required_argument,0,'D'},
  433. {"ignore-quit-failure",no_argument,0,'q'},
  434. {0, 0, 0, 0}
  435. };
  436. if (argc < 2)
  437. return ERROR;
  438. for (c = 1; c < argc; c++) {
  439. if (strcmp ("-to", argv[c]) == 0)
  440. strcpy (argv[c], "-t");
  441. else if (strcmp ("-wt", argv[c]) == 0)
  442. strcpy (argv[c], "-w");
  443. else if (strcmp ("-ct", argv[c]) == 0)
  444. strcpy (argv[c], "-c");
  445. }
  446. while (1) {
  447. c = getopt_long (argc, argv, "+hVv46Lt:p:f:e:c:w:H:C:R:SD:F:A:U:P:q",
  448. longopts, &option);
  449. if (c == -1 || c == EOF)
  450. break;
  451. switch (c) {
  452. case 'H': /* hostname */
  453. if (is_host (optarg)) {
  454. server_address = optarg;
  455. }
  456. else {
  457. usage2 (_("Invalid hostname/address"), optarg);
  458. }
  459. break;
  460. case 'p': /* port */
  461. if (is_intpos (optarg))
  462. server_port = atoi (optarg);
  463. else
  464. usage4 (_("Port must be a positive integer"));
  465. break;
  466. case 'F':
  467. /* localhostname */
  468. localhostname = strdup(optarg);
  469. break;
  470. case 'f': /* from argument */
  471. from_arg = optarg + strspn(optarg, "<");
  472. from_arg = strndup(from_arg, strcspn(from_arg, ">"));
  473. send_mail_from = 1;
  474. break;
  475. case 'A':
  476. authtype = optarg;
  477. use_ehlo = TRUE;
  478. break;
  479. case 'U':
  480. authuser = optarg;
  481. break;
  482. case 'P':
  483. authpass = optarg;
  484. break;
  485. case 'e': /* server expect string on 220 */
  486. server_expect = optarg;
  487. break;
  488. case 'C': /* commands */
  489. if (ncommands >= command_size) {
  490. command_size+=8;
  491. commands = realloc (commands, sizeof(char *) * command_size);
  492. if (commands == NULL)
  493. die (STATE_UNKNOWN,
  494. _("Could not realloc() units [%d]\n"), ncommands);
  495. }
  496. commands[ncommands] = (char *) malloc (sizeof(char) * 255);
  497. strncpy (commands[ncommands], optarg, 255);
  498. ncommands++;
  499. break;
  500. case 'R': /* server responses */
  501. if (nresponses >= response_size) {
  502. response_size += 8;
  503. responses = realloc (responses, sizeof(char *) * response_size);
  504. if (responses == NULL)
  505. die (STATE_UNKNOWN,
  506. _("Could not realloc() units [%d]\n"), nresponses);
  507. }
  508. responses[nresponses] = (char *) malloc (sizeof(char) * 255);
  509. strncpy (responses[nresponses], optarg, 255);
  510. nresponses++;
  511. break;
  512. case 'c': /* critical time threshold */
  513. if (!is_nonnegative (optarg))
  514. usage4 (_("Critical time must be a positive"));
  515. else {
  516. critical_time = strtod (optarg, NULL);
  517. check_critical_time = TRUE;
  518. }
  519. break;
  520. case 'w': /* warning time threshold */
  521. if (!is_nonnegative (optarg))
  522. usage4 (_("Warning time must be a positive"));
  523. else {
  524. warning_time = strtod (optarg, NULL);
  525. check_warning_time = TRUE;
  526. }
  527. break;
  528. case 'v': /* verbose */
  529. verbose++;
  530. break;
  531. case 'q':
  532. ignore_send_quit_failure++; /* ignore problem sending QUIT */
  533. break;
  534. case 't': /* timeout */
  535. timeout_interval = parse_timeout_string (optarg);
  536. break;
  537. case 'D':
  538. /* Check SSL cert validity */
  539. #ifdef USE_OPENSSL
  540. if ((temp=strchr(optarg,','))!=NULL) {
  541. *temp='\0';
  542. if (!is_intnonneg (optarg))
  543. usage2 ("Invalid certificate expiration period", optarg);
  544. days_till_exp_warn = atoi(optarg);
  545. *temp=',';
  546. temp++;
  547. if (!is_intnonneg (temp))
  548. usage2 (_("Invalid certificate expiration period"), temp);
  549. days_till_exp_crit = atoi (temp);
  550. }
  551. else {
  552. days_till_exp_crit=0;
  553. if (!is_intnonneg (optarg))
  554. usage2 ("Invalid certificate expiration period", optarg);
  555. days_till_exp_warn = atoi (optarg);
  556. }
  557. check_cert = TRUE;
  558. ignore_send_quit_failure = TRUE;
  559. #else
  560. usage (_("SSL support not available - install OpenSSL and recompile"));
  561. #endif
  562. case 'S':
  563. /* starttls */
  564. use_ssl = TRUE;
  565. use_ehlo = TRUE;
  566. break;
  567. case 'L':
  568. use_lhlo = TRUE;
  569. break;
  570. case '4':
  571. address_family = AF_INET;
  572. break;
  573. case '6':
  574. #ifdef USE_IPV6
  575. address_family = AF_INET6;
  576. #else
  577. usage4 (_("IPv6 support not available"));
  578. #endif
  579. break;
  580. case 'V': /* version */
  581. print_revision (progname, NP_VERSION);
  582. exit (STATE_OK);
  583. case 'h': /* help */
  584. print_help ();
  585. exit (STATE_OK);
  586. case '?': /* help */
  587. usage5 ();
  588. }
  589. }
  590. c = optind;
  591. if (server_address == NULL) {
  592. if (argv[c]) {
  593. if (is_host (argv[c]))
  594. server_address = argv[c];
  595. else
  596. usage2 (_("Invalid hostname/address"), argv[c]);
  597. }
  598. else {
  599. xasprintf (&server_address, "127.0.0.1");
  600. }
  601. }
  602. if (server_expect == NULL)
  603. server_expect = strdup (SMTP_EXPECT);
  604. if (mail_command == NULL)
  605. mail_command = strdup("MAIL ");
  606. if (from_arg==NULL)
  607. from_arg = strdup(" ");
  608. return validate_arguments ();
  609. }
  610. int
  611. validate_arguments (void)
  612. {
  613. return OK;
  614. }
  615. void
  616. smtp_quit(void)
  617. {
  618. int bytes;
  619. int n;
  620. n = my_send(SMTP_QUIT, strlen(SMTP_QUIT));
  621. if(n < 0) {
  622. if(ignore_send_quit_failure) {
  623. if(verbose) {
  624. printf(_("Connection closed by server before sending QUIT command\n"));
  625. }
  626. return;
  627. }
  628. die (STATE_UNKNOWN,
  629. _("Connection closed by server before sending QUIT command\n"));
  630. }
  631. if (verbose)
  632. printf(_("sent %s\n"), "QUIT");
  633. /* read the response but don't care about problems */
  634. bytes = recvlines(buffer, MAX_INPUT_BUFFER);
  635. if (verbose) {
  636. if (bytes < 0)
  637. printf(_("recv() failed after QUIT."));
  638. else if (bytes == 0)
  639. printf(_("Connection reset by peer."));
  640. else {
  641. buffer[bytes] = '\0';
  642. printf(_("received %s\n"), buffer);
  643. }
  644. }
  645. }
  646. /*
  647. * Receive one line, copy it into buf and nul-terminate it. Returns the
  648. * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
  649. * error.
  650. *
  651. * TODO: Reading one byte at a time is very inefficient. Replace this by a
  652. * function which buffers the data, move that to netutils.c and change
  653. * check_smtp and other plugins to use that. Also, remove (\r)\n.
  654. */
  655. int
  656. recvline(char *buf, size_t bufsize)
  657. {
  658. int result;
  659. unsigned i;
  660. for (i = result = 0; i < bufsize - 1; i++) {
  661. if ((result = my_recv(&buf[i], 1)) != 1)
  662. break;
  663. if (buf[i] == '\n') {
  664. buf[++i] = '\0';
  665. return i;
  666. }
  667. }
  668. return (result == 1 || i == 0) ? -2 : result; /* -2 if out of space */
  669. }
  670. /*
  671. * Receive one or more lines, copy them into buf and nul-terminate it. Returns
  672. * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
  673. * error. Works for all protocols which format multiline replies as follows:
  674. *
  675. * ``The format for multiline replies requires that every line, except the last,
  676. * begin with the reply code, followed immediately by a hyphen, `-' (also known
  677. * as minus), followed by text. The last line will begin with the reply code,
  678. * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
  679. * above, servers SHOULD send the <SP> if subsequent text is not sent, but
  680. * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
  681. *
  682. * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
  683. */
  684. int
  685. recvlines(char *buf, size_t bufsize)
  686. {
  687. int result, i;
  688. for (i = 0; /* forever */; i += result)
  689. if (!((result = recvline(buf + i, bufsize - i)) > 3 &&
  690. isdigit((int)buf[i]) &&
  691. isdigit((int)buf[i + 1]) &&
  692. isdigit((int)buf[i + 2]) &&
  693. buf[i + 3] == '-'))
  694. break;
  695. return (result <= 0) ? result : result + i;
  696. }
  697. int
  698. my_close (void)
  699. {
  700. #ifdef HAVE_SSL
  701. np_net_ssl_cleanup();
  702. #endif
  703. return close(sd);
  704. }
  705. void
  706. print_help (void)
  707. {
  708. char *myport;
  709. xasprintf (&myport, "%d", SMTP_PORT);
  710. print_revision (progname, NP_VERSION);
  711. printf ("Copyright (c) 1999-2001 Ethan Galstad <nagios@nagios.org>\n");
  712. printf (COPYRIGHT, copyright, email);
  713. printf("%s\n", _("This plugin will attempt to open an SMTP connection with the host."));
  714. printf ("\n\n");
  715. print_usage ();
  716. printf (UT_HELP_VRSN);
  717. printf (UT_EXTRA_OPTS);
  718. printf (UT_HOST_PORT, 'p', myport);
  719. printf (UT_IPv46);
  720. printf (" %s\n", "-e, --expect=STRING");
  721. printf (_(" String to expect in first line of server response (default: '%s')\n"), SMTP_EXPECT);
  722. printf (" %s\n", "-C, --command=STRING");
  723. printf (" %s\n", _("SMTP command (may be used repeatedly)"));
  724. printf (" %s\n", "-R, --response=STRING");
  725. printf (" %s\n", _("Expected response to command (may be used repeatedly)"));
  726. printf (" %s\n", "-f, --from=STRING");
  727. printf (" %s\n", _("FROM-address to include in MAIL command, required by Exchange 2000")),
  728. printf (" %s\n", "-F, --fqdn=STRING");
  729. printf (" %s\n", _("FQDN used for HELO"));
  730. #ifdef HAVE_SSL
  731. printf (" %s\n", "-D, --certificate=INTEGER[,INTEGER]");
  732. printf (" %s\n", _("Minimum number of days a certificate has to be valid."));
  733. printf (" %s\n", "-S, --starttls");
  734. printf (" %s\n", _("Use STARTTLS for the connection."));
  735. #endif
  736. printf (" %s\n", "-A, --authtype=STRING");
  737. printf (" %s\n", _("SMTP AUTH type to check (default none, only LOGIN supported)"));
  738. printf (" %s\n", "-U, --authuser=STRING");
  739. printf (" %s\n", _("SMTP AUTH username"));
  740. printf (" %s\n", "-P, --authpass=STRING");
  741. printf (" %s\n", _("SMTP AUTH password"));
  742. printf (" %s\n", "-L, --lmtp");
  743. printf (" %s\n", _("Send LHLO instead of HELO/EHLO"));
  744. printf (" %s\n", "-q, --ignore-quit-failure");
  745. printf (" %s\n", _("Ignore failure when sending QUIT command to server"));
  746. printf (UT_WARN_CRIT);
  747. printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  748. printf (UT_VERBOSE);
  749. printf("\n");
  750. printf ("%s\n", _("Successul connects return STATE_OK, refusals and timeouts return"));
  751. printf ("%s\n", _("STATE_CRITICAL, other errors return STATE_UNKNOWN. Successful"));
  752. printf ("%s\n", _("connects, but incorrect reponse messages from the host result in"));
  753. printf ("%s\n", _("STATE_WARNING return values."));
  754. printf (UT_SUPPORT);
  755. }
  756. void
  757. print_usage (void)
  758. {
  759. printf ("%s\n", _("Usage:"));
  760. printf ("%s -H host [-p port] [-4|-6] [-e expect] [-C command] [-R response] [-f from addr]\n", progname);
  761. printf ("[-A authtype -U authuser -P authpass] [-w warn] [-c crit] [-t timeout] [-q]\n");
  762. printf ("[-F fqdn] [-S] [-L] [-D warn days cert expire[,crit days cert expire]] [-v] \n");
  763. }