4
0

check_smtp.c 24 KB

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