check_smtp.c 23 KB

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