check_smtp.c 24 KB

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