check_smtp.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /*****************************************************************************
  2. *
  3. * Monitoring check_smtp plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 2000-2007 Monitoring 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 = "devel@monitoring-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 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. #define EHLO_SUPPORTS_STARTTLS 1
  57. int process_arguments (int, char **);
  58. int validate_arguments (void);
  59. void print_help (void);
  60. void print_usage (void);
  61. void smtp_quit(void);
  62. int recvline(char *, size_t);
  63. int recvlines(char *, size_t);
  64. int my_close(void);
  65. #include "regex.h"
  66. char regex_expect[MAX_INPUT_BUFFER] = "";
  67. regex_t preg;
  68. regmatch_t pmatch[10];
  69. char timestamp[20] = "";
  70. char errbuf[MAX_INPUT_BUFFER];
  71. int cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
  72. int eflags = 0;
  73. int errcode, excode;
  74. int server_port = SMTP_PORT;
  75. char *server_address = NULL;
  76. char *server_expect = NULL;
  77. char *mail_command = NULL;
  78. char *from_arg = NULL;
  79. int send_mail_from=0;
  80. int ncommands=0;
  81. int command_size=0;
  82. int nresponses=0;
  83. int response_size=0;
  84. char **commands = NULL;
  85. char **responses = NULL;
  86. char *authtype = NULL;
  87. char *authuser = NULL;
  88. char *authpass = NULL;
  89. double warning_time = 0;
  90. int check_warning_time = FALSE;
  91. double critical_time = 0;
  92. int check_critical_time = FALSE;
  93. int verbose = 0;
  94. int use_ssl = FALSE;
  95. short use_ehlo = FALSE;
  96. short ssl_established = 0;
  97. char *localhostname = NULL;
  98. int sd;
  99. char buffer[MAX_INPUT_BUFFER];
  100. enum {
  101. TCP_PROTOCOL = 1,
  102. UDP_PROTOCOL = 2,
  103. };
  104. int ignore_send_quit_failure = FALSE;
  105. int
  106. main (int argc, char **argv)
  107. {
  108. short supports_tls=FALSE;
  109. int n = 0;
  110. double elapsed_time;
  111. long microsec;
  112. int result = STATE_UNKNOWN;
  113. char *cmd_str = NULL;
  114. char *helocmd = NULL;
  115. char *error_msg = "";
  116. struct timeval tv;
  117. /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */
  118. (void) signal (SIGPIPE, SIG_IGN);
  119. setlocale (LC_ALL, "");
  120. bindtextdomain (PACKAGE, LOCALEDIR);
  121. textdomain (PACKAGE);
  122. /* Parse extra opts if any */
  123. argv=np_extra_opts (&argc, argv, progname);
  124. if (process_arguments (argc, argv) == ERROR)
  125. usage4 (_("Could not parse arguments"));
  126. /* If localhostname not set on command line, use gethostname to set */
  127. if(! localhostname){
  128. localhostname = malloc (HOST_MAX_BYTES);
  129. if(!localhostname){
  130. printf(_("malloc() failed!\n"));
  131. return STATE_CRITICAL;
  132. }
  133. if(gethostname(localhostname, HOST_MAX_BYTES)){
  134. printf(_("gethostname() failed!\n"));
  135. return STATE_CRITICAL;
  136. }
  137. }
  138. if(use_ehlo)
  139. xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n");
  140. else
  141. xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n");
  142. if (verbose)
  143. printf("HELOCMD: %s", helocmd);
  144. /* initialize the MAIL command with optional FROM command */
  145. xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n");
  146. if (verbose && send_mail_from)
  147. printf ("FROM CMD: %s", cmd_str);
  148. /* initialize alarm signal handling */
  149. (void) signal (SIGALRM, socket_timeout_alarm_handler);
  150. /* set socket timeout */
  151. (void) alarm (socket_timeout);
  152. /* start timer */
  153. gettimeofday (&tv, NULL);
  154. /* try to connect to the host at the given port number */
  155. result = my_tcp_connect (server_address, server_port, &sd);
  156. if (result == STATE_OK) { /* we connected */
  157. /* watch for the SMTP connection string and */
  158. /* return a WARNING status if we couldn't read any data */
  159. if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
  160. printf (_("recv() failed\n"));
  161. return STATE_WARNING;
  162. }
  163. else {
  164. if (verbose)
  165. printf ("%s", buffer);
  166. /* strip the buffer of carriage returns */
  167. strip (buffer);
  168. /* make sure we find the response we are looking for */
  169. if (!strstr (buffer, server_expect)) {
  170. if (server_port == SMTP_PORT)
  171. printf (_("Invalid SMTP response received from host: %s\n"), buffer);
  172. else
  173. printf (_("Invalid SMTP response received from host on port %d: %s\n"),
  174. server_port, buffer);
  175. return STATE_WARNING;
  176. }
  177. }
  178. /* send the HELO/EHLO command */
  179. send(sd, helocmd, strlen(helocmd), 0);
  180. /* allow for response to helo command to reach us */
  181. if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) {
  182. printf (_("recv() failed\n"));
  183. return STATE_WARNING;
  184. } else if(use_ehlo){
  185. if(strstr(buffer, "250 STARTTLS") != NULL ||
  186. strstr(buffer, "250-STARTTLS") != NULL){
  187. supports_tls=TRUE;
  188. }
  189. }
  190. if(use_ssl && ! supports_tls){
  191. printf(_("WARNING - TLS not supported by server\n"));
  192. smtp_quit();
  193. return STATE_WARNING;
  194. }
  195. #ifdef HAVE_SSL
  196. if(use_ssl) {
  197. /* send the STARTTLS command */
  198. send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0);
  199. recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */
  200. if (!strstr (buffer, SMTP_EXPECT)) {
  201. printf (_("Server does not support STARTTLS\n"));
  202. smtp_quit();
  203. return STATE_UNKNOWN;
  204. }
  205. result = np_net_ssl_init(sd);
  206. if(result != STATE_OK) {
  207. printf (_("CRITICAL - Cannot create SSL context.\n"));
  208. close(sd);
  209. np_net_ssl_cleanup();
  210. return STATE_CRITICAL;
  211. } else {
  212. ssl_established = 1;
  213. }
  214. /*
  215. * Resend the EHLO command.
  216. *
  217. * RFC 3207 (4.2) says: ``The client MUST discard any knowledge
  218. * obtained from the server, such as the list of SMTP service
  219. * extensions, which was not obtained from the TLS negotiation
  220. * itself. The client SHOULD send an EHLO command as the first
  221. * command after a successful TLS negotiation.'' For this
  222. * reason, some MTAs will not allow an AUTH LOGIN command before
  223. * we resent EHLO via TLS.
  224. */
  225. if (my_send(helocmd, strlen(helocmd)) <= 0) {
  226. printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS."));
  227. my_close();
  228. return STATE_UNKNOWN;
  229. }
  230. if (verbose)
  231. printf(_("sent %s"), helocmd);
  232. if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) {
  233. printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS."));
  234. my_close();
  235. return STATE_UNKNOWN;
  236. }
  237. if (verbose) {
  238. printf("%s", buffer);
  239. }
  240. # ifdef USE_OPENSSL
  241. if ( check_cert ) {
  242. result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit);
  243. smtp_quit();
  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 > critical_time)
  373. result = STATE_CRITICAL;
  374. else if (check_warning_time && elapsed_time > 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_nonnegative (optarg))
  497. usage4 (_("Critical time must be a positive"));
  498. else {
  499. critical_time = strtod (optarg, NULL);
  500. check_critical_time = TRUE;
  501. }
  502. break;
  503. case 'w': /* warning time threshold */
  504. if (!is_nonnegative (optarg))
  505. usage4 (_("Warning time must be a positive"));
  506. else {
  507. warning_time = strtod (optarg, NULL);
  508. check_warning_time = TRUE;
  509. }
  510. break;
  511. case 'v': /* verbose */
  512. verbose++;
  513. break;
  514. case 'q':
  515. ignore_send_quit_failure++; /* ignore problem sending QUIT */
  516. break;
  517. case 't': /* timeout */
  518. if (is_intnonneg (optarg)) {
  519. socket_timeout = atoi (optarg);
  520. }
  521. else {
  522. usage4 (_("Timeout interval must be a positive integer"));
  523. }
  524. break;
  525. case 'D':
  526. /* Check SSL cert validity */
  527. #ifdef USE_OPENSSL
  528. if ((temp=strchr(optarg,','))!=NULL) {
  529. *temp='\0';
  530. if (!is_intnonneg (optarg))
  531. usage2 ("Invalid certificate expiration period", optarg);
  532. days_till_exp_warn = atoi(optarg);
  533. *temp=',';
  534. temp++;
  535. if (!is_intnonneg (temp))
  536. usage2 (_("Invalid certificate expiration period"), temp);
  537. days_till_exp_crit = atoi (temp);
  538. }
  539. else {
  540. days_till_exp_crit=0;
  541. if (!is_intnonneg (optarg))
  542. usage2 ("Invalid certificate expiration period", optarg);
  543. days_till_exp_warn = atoi (optarg);
  544. }
  545. check_cert = TRUE;
  546. ignore_send_quit_failure = TRUE;
  547. #else
  548. usage (_("SSL support not available - install OpenSSL and recompile"));
  549. #endif
  550. case 'S':
  551. /* starttls */
  552. use_ssl = TRUE;
  553. use_ehlo = TRUE;
  554. break;
  555. case '4':
  556. address_family = AF_INET;
  557. break;
  558. case '6':
  559. #ifdef USE_IPV6
  560. address_family = AF_INET6;
  561. #else
  562. usage4 (_("IPv6 support not available"));
  563. #endif
  564. break;
  565. case 'V': /* version */
  566. print_revision (progname, NP_VERSION);
  567. exit (STATE_UNKNOWN);
  568. case 'h': /* help */
  569. print_help ();
  570. exit (STATE_UNKNOWN);
  571. case '?': /* help */
  572. usage5 ();
  573. }
  574. }
  575. c = optind;
  576. if (server_address == NULL) {
  577. if (argv[c]) {
  578. if (is_host (argv[c]))
  579. server_address = argv[c];
  580. else
  581. usage2 (_("Invalid hostname/address"), argv[c]);
  582. }
  583. else {
  584. xasprintf (&server_address, "127.0.0.1");
  585. }
  586. }
  587. if (server_expect == NULL)
  588. server_expect = strdup (SMTP_EXPECT);
  589. if (mail_command == NULL)
  590. mail_command = strdup("MAIL ");
  591. if (from_arg==NULL)
  592. from_arg = strdup(" ");
  593. return validate_arguments ();
  594. }
  595. int
  596. validate_arguments (void)
  597. {
  598. return OK;
  599. }
  600. void
  601. smtp_quit(void)
  602. {
  603. int bytes;
  604. int n;
  605. n = my_send(SMTP_QUIT, strlen(SMTP_QUIT));
  606. if(n < 0) {
  607. if(ignore_send_quit_failure) {
  608. if(verbose) {
  609. printf(_("Connection closed by server before sending QUIT command\n"));
  610. }
  611. return;
  612. }
  613. die (STATE_UNKNOWN,
  614. _("Connection closed by server before sending QUIT command\n"));
  615. }
  616. if (verbose)
  617. printf(_("sent %s\n"), "QUIT");
  618. /* read the response but don't care about problems */
  619. bytes = recvlines(buffer, MAX_INPUT_BUFFER);
  620. if (verbose) {
  621. if (bytes < 0)
  622. printf(_("recv() failed after QUIT."));
  623. else if (bytes == 0)
  624. printf(_("Connection reset by peer."));
  625. else {
  626. buffer[bytes] = '\0';
  627. printf(_("received %s\n"), buffer);
  628. }
  629. }
  630. }
  631. /*
  632. * Receive one line, copy it into buf and nul-terminate it. Returns the
  633. * number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
  634. * error.
  635. *
  636. * TODO: Reading one byte at a time is very inefficient. Replace this by a
  637. * function which buffers the data, move that to netutils.c and change
  638. * check_smtp and other plugins to use that. Also, remove (\r)\n.
  639. */
  640. int
  641. recvline(char *buf, size_t bufsize)
  642. {
  643. int result;
  644. unsigned i;
  645. for (i = result = 0; i < bufsize - 1; i++) {
  646. if ((result = my_recv(&buf[i], 1)) != 1)
  647. break;
  648. if (buf[i] == '\n') {
  649. buf[++i] = '\0';
  650. return i;
  651. }
  652. }
  653. return (result == 1 || i == 0) ? -2 : result; /* -2 if out of space */
  654. }
  655. /*
  656. * Receive one or more lines, copy them into buf and nul-terminate it. Returns
  657. * the number of bytes written to buf (excluding the '\0') or 0 on EOF or <0 on
  658. * error. Works for all protocols which format multiline replies as follows:
  659. *
  660. * ``The format for multiline replies requires that every line, except the last,
  661. * begin with the reply code, followed immediately by a hyphen, `-' (also known
  662. * as minus), followed by text. The last line will begin with the reply code,
  663. * followed immediately by <SP>, optionally some text, and <CRLF>. As noted
  664. * above, servers SHOULD send the <SP> if subsequent text is not sent, but
  665. * clients MUST be prepared for it to be omitted.'' (RFC 2821, 4.2.1)
  666. *
  667. * TODO: Move this to netutils.c. Also, remove \r and possibly the final \n.
  668. */
  669. int
  670. recvlines(char *buf, size_t bufsize)
  671. {
  672. int result, i;
  673. for (i = 0; /* forever */; i += result)
  674. if (!((result = recvline(buf + i, bufsize - i)) > 3 &&
  675. isdigit((int)buf[i]) &&
  676. isdigit((int)buf[i + 1]) &&
  677. isdigit((int)buf[i + 2]) &&
  678. buf[i + 3] == '-'))
  679. break;
  680. return (result <= 0) ? result : result + i;
  681. }
  682. int
  683. my_close (void)
  684. {
  685. int result;
  686. result = close(sd);
  687. #ifdef HAVE_SSL
  688. np_net_ssl_cleanup();
  689. #endif
  690. return result;
  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_CONN_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. }