check_smtp.c 25 KB

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