check_tcp.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /*****************************************************************************
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation; either version 2 of the License, or
  5. (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program; if not, write to the Free Software
  12. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  13. $Id$
  14. *****************************************************************************/
  15. /* progname "check_tcp" changes depending on symlink called */
  16. char *progname;
  17. const char *revision = "$Revision$";
  18. const char *copyright = "1999-2004";
  19. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  20. #include "common.h"
  21. #include "netutils.h"
  22. #include "utils.h"
  23. #ifdef HAVE_SSL
  24. static int check_cert = FALSE;
  25. static int days_till_exp;
  26. static char *randbuff = "";
  27. # define my_recv(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
  28. # define my_send(buf, len) ((flags & FLAG_SSL) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
  29. #else
  30. # define my_recv(buf, len) read(sd, buf, len)
  31. # define my_send(buf, len) send(sd, buf, len, 0)
  32. #endif
  33. /* int my_recv(char *, size_t); */
  34. static int process_arguments (int, char **);
  35. void print_help (void);
  36. void print_usage (void);
  37. #define EXPECT server_expect[0]
  38. static char *SERVICE = "TCP";
  39. static char *SEND = NULL;
  40. static char *QUIT = NULL;
  41. static int PROTOCOL = IPPROTO_TCP; /* most common is default */
  42. static int PORT = 0;
  43. static char timestamp[17] = "";
  44. static int server_port = 0;
  45. static char *server_address = NULL;
  46. static char *server_send = NULL;
  47. static char *server_quit = NULL;
  48. static char **server_expect;
  49. static size_t server_expect_count = 0;
  50. static size_t maxbytes = 0;
  51. static char **warn_codes = NULL;
  52. static size_t warn_codes_count = 0;
  53. static char **crit_codes = NULL;
  54. static size_t crit_codes_count = 0;
  55. static unsigned int delay = 0;
  56. static double warning_time = 0;
  57. static double critical_time = 0;
  58. static double elapsed_time = 0;
  59. static long microsec;
  60. static int sd = 0;
  61. #define MAXBUF 1024
  62. static char buffer[MAXBUF];
  63. static int expect_mismatch_state = STATE_WARNING;
  64. #define FLAG_SSL 0x01
  65. #define FLAG_VERBOSE 0x02
  66. #define FLAG_EXACT_MATCH 0x04
  67. #define FLAG_TIME_WARN 0x08
  68. #define FLAG_TIME_CRIT 0x10
  69. #define FLAG_HIDE_OUTPUT 0x20
  70. static size_t flags = FLAG_EXACT_MATCH;
  71. int
  72. main (int argc, char **argv)
  73. {
  74. int result = STATE_UNKNOWN;
  75. int i;
  76. char *status = NULL;
  77. struct timeval tv;
  78. size_t len, match = -1;
  79. setlocale (LC_ALL, "");
  80. bindtextdomain (PACKAGE, LOCALEDIR);
  81. textdomain (PACKAGE);
  82. /* determine program- and service-name quickly */
  83. progname = strrchr(argv[0], '/');
  84. if(progname != NULL) progname++;
  85. else progname = argv[0];
  86. len = strlen(progname);
  87. if(len > 6 && !memcmp(progname, "check_", 6)) {
  88. SERVICE = progname + 6;
  89. for(i = 0; i < len - 6; i++)
  90. SERVICE[i] = toupper(SERVICE[i]);
  91. }
  92. /* set up a resonable buffer at first (will be realloc()'ed if
  93. * user specifies other options) */
  94. server_expect = calloc(sizeof(char *), 2);
  95. /* determine defaults for this service's protocol */
  96. if (!strncmp(SERVICE, "UDP", 3)) {
  97. PROTOCOL = IPPROTO_UDP;
  98. }
  99. else if (!strncmp(SERVICE, "FTP", 3)) {
  100. EXPECT = "220";
  101. QUIT = "QUIT\r\n";
  102. PORT = 21;
  103. }
  104. else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) {
  105. EXPECT = "+OK";
  106. QUIT = "QUIT\r\n";
  107. PORT = 110;
  108. }
  109. else if (!strncmp(SERVICE, "SMTP", 4)) {
  110. EXPECT = "220";
  111. QUIT = "QUIT\r\n";
  112. PORT = 25;
  113. }
  114. else if (!strncmp(SERVICE, "IMAP", 4)) {
  115. EXPECT = "* OK";
  116. QUIT = "a1 LOGOUT\r\n";
  117. PORT = 143;
  118. }
  119. #ifdef HAVE_SSL
  120. else if (!strncmp(SERVICE, "SIMAP", 5)) {
  121. EXPECT = "* OK";
  122. QUIT = "a1 LOGOUT\r\n";
  123. flags |= FLAG_SSL;
  124. PORT = 993;
  125. }
  126. else if (!strncmp(SERVICE, "SPOP", 4)) {
  127. EXPECT = "+OK";
  128. QUIT = "QUIT\r\n";
  129. flags |= FLAG_SSL;
  130. PORT = 995;
  131. }
  132. else if (!strncmp(SERVICE, "SSMTP", 5)) {
  133. EXPECT = "220";
  134. QUIT = "QUIT\r\n";
  135. flags |= FLAG_SSL;
  136. PORT = 465;
  137. }
  138. else if (!strncmp(SERVICE, "JABBER", 6)) {
  139. SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n";
  140. EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns:stream=\'http://etherx.jabber.org/streams\'";
  141. QUIT = "</stream:stream>\n";
  142. flags |= FLAG_SSL | FLAG_HIDE_OUTPUT;
  143. PORT = 5222;
  144. }
  145. else if (!strncmp (SERVICE, "NNTPS", 5)) {
  146. server_expect_count = 2;
  147. server_expect[0] = "200";
  148. server_expect[1] = "201";
  149. QUIT = "QUIT\r\n";
  150. flags |= FLAG_SSL;
  151. PORT = 563;
  152. }
  153. #endif
  154. else if (!strncmp (SERVICE, "NNTP", 4)) {
  155. server_expect_count = 2;
  156. server_expect = malloc(sizeof(char *) * server_expect_count);
  157. server_expect[0] = strdup("200");
  158. server_expect[1] = strdup("201");
  159. QUIT = "QUIT\r\n";
  160. PORT = 119;
  161. }
  162. /* fallthrough check, so it's supposed to use reverse matching */
  163. else if (strcmp (SERVICE, "TCP"))
  164. usage (_("CRITICAL - Generic check_tcp called with unknown service\n"));
  165. server_address = "127.0.0.1";
  166. server_port = PORT;
  167. server_send = SEND;
  168. server_quit = QUIT;
  169. status = NULL;
  170. if (process_arguments (argc, argv) == ERROR)
  171. usage4 (_("Could not parse arguments"));
  172. if(flags & FLAG_VERBOSE) {
  173. printf("Using service %s\n", SERVICE);
  174. printf("Port: %d\n", PORT);
  175. printf("flags: 0x%x\n", flags);
  176. }
  177. if(EXPECT && !server_expect_count)
  178. server_expect_count++;
  179. /* set up the timer */
  180. signal (SIGALRM, socket_timeout_alarm_handler);
  181. alarm (socket_timeout);
  182. /* try to connect to the host at the given port number */
  183. gettimeofday (&tv, NULL);
  184. result = np_net_connect (server_address, server_port, &sd, PROTOCOL);
  185. if (result == STATE_CRITICAL) return STATE_CRITICAL;
  186. #ifdef HAVE_SSL
  187. if (flags & FLAG_SSL){
  188. result = np_net_ssl_init(sd);
  189. if (result == STATE_OK && check_cert == TRUE) {
  190. result = np_net_ssl_check_cert(days_till_exp);
  191. if(result != STATE_OK) {
  192. printf(_("CRITICAL - Cannot retrieve server certificate.\n"));
  193. }
  194. }
  195. }
  196. if(result != STATE_OK){
  197. np_net_ssl_cleanup();
  198. if(sd) close(sd);
  199. return result;
  200. }
  201. #endif /* HAVE_SSL */
  202. if (server_send != NULL) { /* Something to send? */
  203. my_send(server_send, strlen(server_send));
  204. }
  205. if (delay > 0) {
  206. tv.tv_sec += delay;
  207. sleep (delay);
  208. }
  209. if(flags & FLAG_VERBOSE) {
  210. printf("server_expect_count: %d\n", server_expect_count);
  211. for(i = 0; i < server_expect_count; i++)
  212. printf("\t%d: %s\n", i, server_expect[i]);
  213. }
  214. /* if(len) later on, we know we have a non-NULL response */
  215. len = 0;
  216. if (server_expect_count) {
  217. /* watch for the expect string */
  218. while ((i = my_recv(buffer, sizeof(buffer))) > 0) {
  219. status = realloc(status, len + i + 1);
  220. memcpy(&status[len], buffer, i);
  221. len += i;
  222. /* stop reading if user-forced or data-starved */
  223. if(i < sizeof(buffer) || (maxbytes && len >= maxbytes))
  224. break;
  225. if (maxbytes && len >= maxbytes)
  226. break;
  227. }
  228. /* no data when expected, so return critical */
  229. if (len == 0)
  230. die (STATE_CRITICAL, _("No data received from host\n"));
  231. /* force null-termination and strip whitespace from end of output */
  232. status[len--] = '\0';
  233. /* print raw output if we're debugging */
  234. if(flags & FLAG_VERBOSE)
  235. printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n",
  236. len + 1, status);
  237. while(isspace(status[len])) status[len--] = '\0';
  238. for (i = 0; i < server_expect_count; i++) {
  239. match = -2; /* tag it so we know if we tried and failed */
  240. if (flags & FLAG_VERBOSE)
  241. printf ("looking for [%s] %s [%s]\n", server_expect[i],
  242. (flags & FLAG_EXACT_MATCH) ? "in beginning of" : "anywhere in",
  243. status);
  244. /* match it. math first in short-circuit */
  245. if ((flags & FLAG_EXACT_MATCH && !strncmp(status, server_expect[i], strlen(server_expect[i]))) ||
  246. (!(flags & FLAG_EXACT_MATCH) && strstr(status, server_expect[i])))
  247. {
  248. if(flags & FLAG_VERBOSE) puts("found it");
  249. match = i;
  250. break;
  251. }
  252. }
  253. }
  254. if (server_quit != NULL) {
  255. my_send(server_quit, strlen(server_quit));
  256. }
  257. #ifdef HAVE_SSL
  258. np_net_ssl_cleanup();
  259. #endif
  260. if (sd) close (sd);
  261. microsec = deltime (tv);
  262. elapsed_time = (double)microsec / 1.0e6;
  263. if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time)
  264. result = STATE_CRITICAL;
  265. else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time)
  266. result = STATE_WARNING;
  267. /* did we get the response we hoped? */
  268. if(match == -2 && result != STATE_CRITICAL)
  269. result = STATE_WARNING;
  270. /* reset the alarm */
  271. alarm (0);
  272. /* this is a bit stupid, because we don't want to print the
  273. * response time (which can look ok to the user) if we didn't get
  274. * the response we were looking for. if-else */
  275. printf(_("%s %s - "), SERVICE, state_text(result));
  276. if(match == -2 && len && !(flags & FLAG_HIDE_OUTPUT))
  277. printf("Unexpected response from host: %s", status);
  278. else
  279. printf("%.3f second response time on port %d",
  280. elapsed_time, server_port);
  281. if (match != -2 && !(flags & FLAG_HIDE_OUTPUT) && len)
  282. printf (" [%s]", status);
  283. /* perf-data doesn't apply when server doesn't talk properly,
  284. * so print all zeroes on warn and crit */
  285. if(match == -2)
  286. printf ("|time=%fs;0.0;0.0;0.0;0.0", elapsed_time);
  287. else
  288. printf("|%s",
  289. fperfdata ("time", elapsed_time, "s",
  290. TRUE, warning_time,
  291. TRUE, critical_time,
  292. TRUE, 0,
  293. TRUE, socket_timeout)
  294. );
  295. putchar('\n');
  296. return result;
  297. }
  298. /* process command-line arguments */
  299. static int
  300. process_arguments (int argc, char **argv)
  301. {
  302. int c;
  303. int option = 0;
  304. static struct option longopts[] = {
  305. {"hostname", required_argument, 0, 'H'},
  306. {"critical-time", required_argument, 0, 'c'},
  307. {"warning-time", required_argument, 0, 'w'},
  308. {"critical-codes", required_argument, 0, 'C'},
  309. {"warning-codes", required_argument, 0, 'W'},
  310. {"timeout", required_argument, 0, 't'},
  311. {"protocol", required_argument, 0, 'P'},
  312. {"port", required_argument, 0, 'p'},
  313. {"send", required_argument, 0, 's'},
  314. {"expect", required_argument, 0, 'e'},
  315. {"maxbytes", required_argument, 0, 'm'},
  316. {"quit", required_argument, 0, 'q'},
  317. {"jail", required_argument, 0, 'j'},
  318. {"delay", required_argument, 0, 'd'},
  319. {"refuse", required_argument, 0, 'r'},
  320. {"mismatch", required_argument, 0, 'M'},
  321. {"use-ipv4", no_argument, 0, '4'},
  322. {"use-ipv6", no_argument, 0, '6'},
  323. {"verbose", no_argument, 0, 'v'},
  324. {"version", no_argument, 0, 'V'},
  325. {"help", no_argument, 0, 'h'},
  326. #ifdef HAVE_SSL
  327. {"ssl", no_argument, 0, 'S'},
  328. {"certificate", required_argument, 0, 'D'},
  329. #endif
  330. {0, 0, 0, 0}
  331. };
  332. if (argc < 2)
  333. usage4 (_("No arguments found"));
  334. /* backwards compatibility */
  335. for (c = 1; c < argc; c++) {
  336. if (strcmp ("-to", argv[c]) == 0)
  337. strcpy (argv[c], "-t");
  338. else if (strcmp ("-wt", argv[c]) == 0)
  339. strcpy (argv[c], "-w");
  340. else if (strcmp ("-ct", argv[c]) == 0)
  341. strcpy (argv[c], "-c");
  342. }
  343. if (!is_option (argv[1])) {
  344. server_address = argv[1];
  345. argv[1] = argv[0];
  346. argv = &argv[1];
  347. argc--;
  348. }
  349. while (1) {
  350. c = getopt_long (argc, argv, "+hVv46H:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
  351. longopts, &option);
  352. if (c == -1 || c == EOF || c == 1)
  353. break;
  354. switch (c) {
  355. case '?': /* print short usage statement if args not parsable */
  356. usage2 (_("Unknown argument"), optarg);
  357. case 'h': /* help */
  358. print_help ();
  359. exit (STATE_OK);
  360. case 'V': /* version */
  361. print_revision (progname, revision);
  362. exit (STATE_OK);
  363. case 'v': /* verbose mode */
  364. flags |= FLAG_VERBOSE;
  365. break;
  366. case '4':
  367. address_family = AF_INET;
  368. break;
  369. case '6':
  370. #ifdef USE_IPV6
  371. address_family = AF_INET6;
  372. #else
  373. usage4 (_("IPv6 support not available"));
  374. #endif
  375. break;
  376. case 'H': /* hostname */
  377. if (is_host (optarg) == FALSE)
  378. usage2 (_("Invalid hostname/address"), optarg);
  379. server_address = optarg;
  380. break;
  381. case 'c': /* critical */
  382. if (!is_intnonneg (optarg))
  383. usage4 (_("Critical threshold must be a positive integer"));
  384. else
  385. critical_time = strtod (optarg, NULL);
  386. flags |= FLAG_TIME_CRIT;
  387. break;
  388. case 'j': /* hide output */
  389. flags |= FLAG_HIDE_OUTPUT;
  390. break;
  391. case 'w': /* warning */
  392. if (!is_intnonneg (optarg))
  393. usage4 (_("Warning threshold must be a positive integer"));
  394. else
  395. warning_time = strtod (optarg, NULL);
  396. flags |= FLAG_TIME_WARN;
  397. break;
  398. case 'C':
  399. crit_codes = realloc (crit_codes, ++crit_codes_count);
  400. crit_codes[crit_codes_count - 1] = optarg;
  401. break;
  402. case 'W':
  403. warn_codes = realloc (warn_codes, ++warn_codes_count);
  404. warn_codes[warn_codes_count - 1] = optarg;
  405. break;
  406. case 't': /* timeout */
  407. if (!is_intpos (optarg))
  408. usage4 (_("Timeout interval must be a positive integer"));
  409. else
  410. socket_timeout = atoi (optarg);
  411. break;
  412. case 'p': /* port */
  413. if (!is_intpos (optarg))
  414. usage4 (_("Port must be a positive integer"));
  415. else
  416. server_port = atoi (optarg);
  417. break;
  418. case 's':
  419. server_send = optarg;
  420. break;
  421. case 'e': /* expect string (may be repeated) */
  422. EXPECT = NULL;
  423. flags &= ~FLAG_EXACT_MATCH;
  424. if (server_expect_count == 0)
  425. server_expect = malloc (sizeof (char *) * (++server_expect_count));
  426. else
  427. server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
  428. server_expect[server_expect_count - 1] = optarg;
  429. break;
  430. case 'm':
  431. if (!is_intpos (optarg))
  432. usage4 (_("Maxbytes must be a positive integer"));
  433. else
  434. maxbytes = strtol (optarg, NULL, 0);
  435. case 'q':
  436. asprintf(&server_quit, "%s\r\n", optarg);
  437. break;
  438. case 'r':
  439. if (!strncmp(optarg,"ok",2))
  440. econn_refuse_state = STATE_OK;
  441. else if (!strncmp(optarg,"warn",4))
  442. econn_refuse_state = STATE_WARNING;
  443. else if (!strncmp(optarg,"crit",4))
  444. econn_refuse_state = STATE_CRITICAL;
  445. else
  446. usage4 (_("Refuse must be one of ok, warn, crit"));
  447. break;
  448. case 'M':
  449. if (!strncmp(optarg,"ok",2))
  450. expect_mismatch_state = STATE_OK;
  451. else if (!strncmp(optarg,"warn",4))
  452. expect_mismatch_state = STATE_WARNING;
  453. else if (!strncmp(optarg,"crit",4))
  454. expect_mismatch_state = STATE_CRITICAL;
  455. else
  456. usage4 (_("Mismatch must be one of ok, warn, crit"));
  457. break;
  458. case 'd':
  459. if (is_intpos (optarg))
  460. delay = atoi (optarg);
  461. else
  462. usage4 (_("Delay must be a positive integer"));
  463. break;
  464. case 'D': /* Check SSL cert validity - days 'til certificate expiration */
  465. #ifdef HAVE_SSL
  466. # ifdef USE_OPENSSL /* XXX */
  467. if (!is_intnonneg (optarg))
  468. usage2 (_("Invalid certificate expiration period"), optarg);
  469. days_till_exp = atoi (optarg);
  470. check_cert = TRUE;
  471. flags |= FLAG_SSL;
  472. break;
  473. # endif /* USE_OPENSSL */
  474. #endif
  475. /* fallthrough if we don't have ssl */
  476. case 'S':
  477. #ifdef HAVE_SSL
  478. flags |= FLAG_SSL;
  479. #else
  480. die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
  481. #endif
  482. break;
  483. }
  484. }
  485. if (server_address == NULL)
  486. usage4 (_("You must provide a server address"));
  487. return TRUE;
  488. }
  489. void
  490. print_help (void)
  491. {
  492. print_revision (progname, revision);
  493. printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
  494. printf (COPYRIGHT, copyright, email);
  495. printf (_("This plugin tests %s connections with the specified host.\n\n"),
  496. SERVICE);
  497. print_usage ();
  498. printf (_(UT_HELP_VRSN));
  499. printf (_(UT_HOST_PORT), 'p', "none");
  500. printf (_(UT_IPv46));
  501. printf (_("\
  502. -s, --send=STRING\n\
  503. String to send to the server\n\
  504. -e, --expect=STRING\n\
  505. String to expect in server response\n\
  506. -q, --quit=STRING\n\
  507. String to send server to initiate a clean close of the connection\n"));
  508. printf (_("\
  509. -r, --refuse=ok|warn|crit\n\
  510. Accept tcp refusals with states ok, warn, crit (default: crit)\n\
  511. -M, --mismatch=ok|warn|crit\n\
  512. Accept expected string mismatches with states ok, warn, crit (default: warn)\n\
  513. -j, --jail\n\
  514. Hide output from TCP socket\n\
  515. -m, --maxbytes=INTEGER\n\
  516. Close connection once more than this number of bytes are received\n\
  517. -d, --delay=INTEGER\n\
  518. Seconds to wait between sending string and polling for response\n"));
  519. #ifdef HAVE_SSL
  520. printf (_("\
  521. -D, --certificate=INTEGER\n\
  522. Minimum number of days a certificate has to be valid.\n\
  523. -S, --ssl\n\
  524. Use SSL for the connection.\n"));
  525. #endif
  526. printf (_(UT_WARN_CRIT));
  527. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  528. printf (_(UT_VERBOSE));
  529. printf (_(UT_SUPPORT));
  530. }
  531. void
  532. print_usage (void)
  533. {
  534. printf ("\
  535. Usage: %s -H host -p port [-w <warning time>] [-c <critical time>]\n\
  536. [-s <send string>] [-e <expect string>] [-q <quit string>]\n\
  537. [-m <maximum bytes>] [-d <delay>] [-t <timeout seconds>]\n\
  538. [-r <refuse state>] [-M <mismatch state>] [-v] [-4|-6] [-j]\n\
  539. [-D <days to cert expiry>] [-S <use SSL>]\n", progname);
  540. }