check_smtp.c 23 KB

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