check_smtp.c 23 KB

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