check_http.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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. ******************************************************************************/
  14. /* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ ../../plugins/check_http.c */
  15. const char *progname = "check_http";
  16. const char *revision = "$Revision$";
  17. const char *copyright = "1999-2001";
  18. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  19. #include "common.h"
  20. #include "netutils.h"
  21. #include "utils.h"
  22. #define HTTP_EXPECT "HTTP/1."
  23. enum {
  24. MAX_IPV4_HOSTLENGTH = 255,
  25. HTTP_PORT = 80,
  26. HTTPS_PORT = 443
  27. };
  28. #ifdef HAVE_SSL_H
  29. #include <rsa.h>
  30. #include <crypto.h>
  31. #include <x509.h>
  32. #include <pem.h>
  33. #include <ssl.h>
  34. #include <err.h>
  35. #include <rand.h>
  36. #else
  37. # ifdef HAVE_OPENSSL_SSL_H
  38. # include <openssl/rsa.h>
  39. # include <openssl/crypto.h>
  40. # include <openssl/x509.h>
  41. # include <openssl/pem.h>
  42. # include <openssl/ssl.h>
  43. # include <openssl/err.h>
  44. # include <openssl/rand.h>
  45. # endif
  46. #endif
  47. #ifdef HAVE_SSL
  48. int check_cert = FALSE;
  49. int days_till_exp;
  50. char *randbuff;
  51. SSL_CTX *ctx;
  52. SSL *ssl;
  53. X509 *server_cert;
  54. int connect_SSL (void);
  55. int check_certificate (X509 **);
  56. #endif
  57. #ifdef HAVE_REGEX_H
  58. enum {
  59. REGS = 2,
  60. MAX_RE_SIZE = 256
  61. };
  62. #include <regex.h>
  63. regex_t preg;
  64. regmatch_t pmatch[REGS];
  65. char regexp[MAX_RE_SIZE];
  66. char errbuf[MAX_INPUT_BUFFER];
  67. int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE;
  68. int errcode;
  69. #endif
  70. struct timeval tv;
  71. #define HTTP_URL "/"
  72. #define CRLF "\r\n"
  73. char timestamp[17] = "";
  74. int specify_port = FALSE;
  75. int server_port = HTTP_PORT;
  76. char server_port_text[6] = "";
  77. char server_type[6] = "http";
  78. char *server_address;
  79. char *host_name;
  80. char *server_url;
  81. char *user_agent;
  82. int server_url_length;
  83. int server_expect_yn = 0;
  84. char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
  85. char string_expect[MAX_INPUT_BUFFER] = "";
  86. double warning_time = 0;
  87. int check_warning_time = FALSE;
  88. double critical_time = 0;
  89. int check_critical_time = FALSE;
  90. char user_auth[MAX_INPUT_BUFFER] = "";
  91. int display_html = FALSE;
  92. int onredirect = STATE_OK;
  93. int use_ssl = FALSE;
  94. int verbose = FALSE;
  95. int sd;
  96. int min_page_len = 0;
  97. int redir_depth = 0;
  98. int max_depth = 15;
  99. char *http_method;
  100. char *http_post_data;
  101. char *http_content_type;
  102. char buffer[MAX_INPUT_BUFFER];
  103. int process_arguments (int, char **);
  104. static char *base64 (const char *bin, size_t len);
  105. int check_http (void);
  106. void redir (char *pos, char *status_line);
  107. int server_type_check(const char *type);
  108. int server_port_check(int ssl_flag);
  109. char *perfd_time (long microsec);
  110. char *perfd_size (int page_len);
  111. int my_recv (void);
  112. int my_close (void);
  113. void print_help (void);
  114. void print_usage (void);
  115. int
  116. main (int argc, char **argv)
  117. {
  118. int result = STATE_UNKNOWN;
  119. /* Set default URL. Must be malloced for subsequent realloc if --onredirect=follow */
  120. server_url = strdup(HTTP_URL);
  121. server_url_length = strlen(server_url);
  122. asprintf (&user_agent, "User-Agent: check_http/%s (nagios-plugins %s)",
  123. clean_revstring (revision), VERSION);
  124. if (process_arguments (argc, argv) == ERROR)
  125. usage (_("check_http: could not parse arguments\n"));
  126. if (strstr (timestamp, ":")) {
  127. if (strstr (server_url, "?"))
  128. asprintf (&server_url, "%s&%s", server_url, timestamp);
  129. else
  130. asprintf (&server_url, "%s?%s", server_url, timestamp);
  131. }
  132. if (display_html == TRUE)
  133. printf ("<A HREF=\"http://%s:%d%s\" target=\"_blank\">",
  134. host_name, server_port, server_url);
  135. /* initialize alarm signal handling, set socket timeout, start timer */
  136. (void) signal (SIGALRM, socket_timeout_alarm_handler);
  137. (void) alarm (socket_timeout);
  138. gettimeofday (&tv, NULL);
  139. #ifdef HAVE_SSL
  140. if (use_ssl && check_cert == TRUE) {
  141. if (connect_SSL () != OK)
  142. die (STATE_CRITICAL, _("HTTP CRITICAL - Could not make SSL connection\n"));
  143. if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
  144. result = check_certificate (&server_cert);
  145. X509_free (server_cert);
  146. }
  147. else {
  148. printf (_("ERROR: Cannot retrieve server certificate.\n"));
  149. result = STATE_CRITICAL;
  150. }
  151. SSL_shutdown (ssl);
  152. SSL_free (ssl);
  153. SSL_CTX_free (ctx);
  154. close (sd);
  155. }
  156. else {
  157. result = check_http ();
  158. }
  159. #else
  160. result = check_http ();
  161. #endif
  162. return result;
  163. }
  164. /* process command-line arguments */
  165. int
  166. process_arguments (int argc, char **argv)
  167. {
  168. int c = 1;
  169. int option = 0;
  170. static struct option longopts[] = {
  171. STD_LONG_OPTS,
  172. {"file",required_argument,0,'F'},
  173. {"link", no_argument, 0, 'L'},
  174. {"nohtml", no_argument, 0, 'n'},
  175. {"ssl", no_argument, 0, 'S'},
  176. {"verbose", no_argument, 0, 'v'},
  177. {"post", required_argument, 0, 'P'},
  178. {"IP-address", required_argument, 0, 'I'},
  179. {"string", required_argument, 0, 's'},
  180. {"regex", required_argument, 0, 'r'},
  181. {"ereg", required_argument, 0, 'r'},
  182. {"eregi", required_argument, 0, 'R'},
  183. {"linespan", no_argument, 0, 'l'},
  184. {"onredirect", required_argument, 0, 'f'},
  185. {"certificate", required_argument, 0, 'C'},
  186. {"content-type", required_argument, 0, 'T'},
  187. {"min", required_argument, 0, 'm'},
  188. {"use-ipv4", no_argument, 0, '4'},
  189. {"use-ipv6", no_argument, 0, '6'},
  190. {0, 0, 0, 0}
  191. };
  192. if (argc < 2)
  193. return ERROR;
  194. for (c = 1; c < argc; c++) {
  195. if (strcmp ("-to", argv[c]) == 0)
  196. strcpy (argv[c], "-t");
  197. if (strcmp ("-hn", argv[c]) == 0)
  198. strcpy (argv[c], "-H");
  199. if (strcmp ("-wt", argv[c]) == 0)
  200. strcpy (argv[c], "-w");
  201. if (strcmp ("-ct", argv[c]) == 0)
  202. strcpy (argv[c], "-c");
  203. if (strcmp ("-nohtml", argv[c]) == 0)
  204. strcpy (argv[c], "-n");
  205. }
  206. while (1) {
  207. c = getopt_long (argc, argv, "Vvh46t:c:w:H:P:T:I:a:e:p:s:R:r:u:f:C:nlLSm:", longopts, &option);
  208. if (c == -1 || c == EOF)
  209. break;
  210. switch (c) {
  211. case '?': /* usage */
  212. usage3 (_("unknown argument"), optopt);
  213. break;
  214. case 'h': /* help */
  215. print_help ();
  216. exit (STATE_OK);
  217. break;
  218. case 'V': /* version */
  219. print_revision (progname, revision);
  220. exit (STATE_OK);
  221. break;
  222. case 't': /* timeout period */
  223. if (!is_intnonneg (optarg))
  224. usage2 (_("timeout interval must be a non-negative integer"), optarg);
  225. else
  226. socket_timeout = atoi (optarg);
  227. break;
  228. case 'c': /* critical time threshold */
  229. if (!is_nonnegative (optarg))
  230. usage2 (_("invalid critical threshold"), optarg);
  231. else {
  232. critical_time = strtod (optarg, NULL);
  233. check_critical_time = TRUE;
  234. }
  235. break;
  236. case 'w': /* warning time threshold */
  237. if (!is_nonnegative (optarg))
  238. usage2 (_("invalid warning threshold"), optarg);
  239. else {
  240. warning_time = strtod (optarg, NULL);
  241. check_warning_time = TRUE;
  242. }
  243. break;
  244. case 'L': /* show html link */
  245. display_html = TRUE;
  246. break;
  247. case 'n': /* do not show html link */
  248. display_html = FALSE;
  249. break;
  250. case 'S': /* use SSL */
  251. #ifndef HAVE_SSL
  252. usage (_("check_http: invalid option - SSL is not available\n"));
  253. #endif
  254. use_ssl = TRUE;
  255. if (specify_port == FALSE)
  256. server_port = HTTPS_PORT;
  257. break;
  258. case 'C': /* Check SSL cert validity */
  259. #ifdef HAVE_SSL
  260. if (!is_intnonneg (optarg))
  261. usage2 (_("invalid certificate expiration period"), optarg);
  262. else {
  263. days_till_exp = atoi (optarg);
  264. check_cert = TRUE;
  265. }
  266. #else
  267. usage (_("check_http: invalid option - SSL is not available\n"));
  268. #endif
  269. break;
  270. case 'f': /* onredirect */
  271. if (!strcmp (optarg, "follow"))
  272. onredirect = STATE_DEPENDENT;
  273. if (!strcmp (optarg, "unknown"))
  274. onredirect = STATE_UNKNOWN;
  275. if (!strcmp (optarg, "ok"))
  276. onredirect = STATE_OK;
  277. if (!strcmp (optarg, "warning"))
  278. onredirect = STATE_WARNING;
  279. if (!strcmp (optarg, "critical"))
  280. onredirect = STATE_CRITICAL;
  281. if (verbose)
  282. printf(_("option f:%d \n"), onredirect);
  283. break;
  284. /* Note: H, I, and u must be malloc'd or will fail on redirects */
  285. case 'H': /* Host Name (virtual host) */
  286. host_name = strdup (optarg);
  287. break;
  288. case 'I': /* Server IP-address */
  289. server_address = strdup (optarg);
  290. break;
  291. case 'u': /* URL path */
  292. server_url = strdup (optarg);
  293. server_url_length = strlen (server_url);
  294. break;
  295. case 'p': /* Server port */
  296. if (!is_intnonneg (optarg))
  297. usage2 (_("invalid port number"), optarg);
  298. else {
  299. server_port = atoi (optarg);
  300. specify_port = TRUE;
  301. }
  302. break;
  303. case 'a': /* authorization info */
  304. strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1);
  305. user_auth[MAX_INPUT_BUFFER - 1] = 0;
  306. break;
  307. case 'P': /* HTTP POST data in URL encoded format */
  308. if (http_method || http_post_data) break;
  309. http_method = strdup("POST");
  310. http_post_data = strdup (optarg);
  311. break;
  312. case 's': /* string or substring */
  313. strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1);
  314. string_expect[MAX_INPUT_BUFFER - 1] = 0;
  315. break;
  316. case 'e': /* string or substring */
  317. strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1);
  318. server_expect[MAX_INPUT_BUFFER - 1] = 0;
  319. server_expect_yn = 1;
  320. break;
  321. case 'T': /* Content-type */
  322. asprintf (&http_content_type, "%s", optarg);
  323. break;
  324. #ifndef HAVE_REGEX_H
  325. case 'l': /* linespan */
  326. case 'r': /* linespan */
  327. case 'R': /* linespan */
  328. usage (_("check_http: call for regex which was not a compiled option\n"));
  329. break;
  330. #else
  331. case 'l': /* linespan */
  332. cflags &= ~REG_NEWLINE;
  333. break;
  334. case 'R': /* regex */
  335. cflags |= REG_ICASE;
  336. case 'r': /* regex */
  337. strncpy (regexp, optarg, MAX_RE_SIZE - 1);
  338. regexp[MAX_RE_SIZE - 1] = 0;
  339. errcode = regcomp (&preg, regexp, cflags);
  340. if (errcode != 0) {
  341. (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  342. printf (_("Could Not Compile Regular Expression: %s"), errbuf);
  343. return ERROR;
  344. }
  345. break;
  346. #endif
  347. case '4':
  348. address_family = AF_INET;
  349. break;
  350. case '6':
  351. #ifdef USE_IPV6
  352. address_family = AF_INET6;
  353. #else
  354. usage (_("IPv6 support not available\n"));
  355. #endif
  356. break;
  357. case 'v': /* verbose */
  358. verbose = TRUE;
  359. break;
  360. case 'm': /* min_page_length */
  361. min_page_len = atoi (optarg);
  362. break;
  363. }
  364. }
  365. c = optind;
  366. if (server_address == NULL && c < argc)
  367. server_address = strdup (argv[c++]);
  368. if (host_name == NULL && c < argc)
  369. host_name = strdup (argv[c++]);
  370. if (server_address == NULL) {
  371. if (host_name == NULL)
  372. usage (_("check_http: you must specify a server address or host name\n"));
  373. else
  374. server_address = strdup (host_name);
  375. }
  376. if (check_critical_time && critical_time>(double)socket_timeout)
  377. socket_timeout = (int)critical_time + 1;
  378. if (http_method == NULL)
  379. http_method = strdup ("GET");
  380. return TRUE;
  381. }
  382. /* written by lauri alanko */
  383. static char *
  384. base64 (const char *bin, size_t len)
  385. {
  386. char *buf = (char *) malloc ((len + 2) / 3 * 4 + 1);
  387. size_t i = 0, j = 0;
  388. char BASE64_END = '=';
  389. char base64_table[64];
  390. strncpy (base64_table, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 64);
  391. while (j < len - 2) {
  392. buf[i++] = base64_table[bin[j] >> 2];
  393. buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
  394. buf[i++] = base64_table[((bin[j + 1] & 15) << 2) | (bin[j + 2] >> 6)];
  395. buf[i++] = base64_table[bin[j + 2] & 63];
  396. j += 3;
  397. }
  398. switch (len - j) {
  399. case 1:
  400. buf[i++] = base64_table[bin[j] >> 2];
  401. buf[i++] = base64_table[(bin[j] & 3) << 4];
  402. buf[i++] = BASE64_END;
  403. buf[i++] = BASE64_END;
  404. break;
  405. case 2:
  406. buf[i++] = base64_table[bin[j] >> 2];
  407. buf[i++] = base64_table[((bin[j] & 3) << 4) | (bin[j + 1] >> 4)];
  408. buf[i++] = base64_table[(bin[j + 1] & 15) << 2];
  409. buf[i++] = BASE64_END;
  410. break;
  411. case 0:
  412. break;
  413. }
  414. buf[i] = '\0';
  415. return buf;
  416. }
  417. int
  418. check_http (void)
  419. {
  420. char *msg;
  421. char *status_line;
  422. char *status_code;
  423. char *header;
  424. char *page;
  425. char *auth;
  426. int http_status;
  427. int i = 0;
  428. size_t pagesize = 0;
  429. char *full_page;
  430. char *buf;
  431. char *pos;
  432. long microsec;
  433. double elapsed_time;
  434. int page_len = 0;
  435. #ifdef HAVE_SSL
  436. int sslerr;
  437. #endif
  438. /* try to connect to the host at the given port number */
  439. #ifdef HAVE_SSL
  440. if (use_ssl == TRUE) {
  441. if (connect_SSL () != OK) {
  442. die (STATE_CRITICAL, _("Unable to open TCP socket\n"));
  443. }
  444. if ((server_cert = SSL_get_peer_certificate (ssl)) != NULL) {
  445. X509_free (server_cert);
  446. }
  447. else {
  448. printf (_("ERROR: Cannot retrieve server certificate.\n"));
  449. return STATE_CRITICAL;
  450. }
  451. }
  452. else {
  453. #endif
  454. if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK)
  455. die (STATE_CRITICAL, _("Unable to open TCP socket\n"));
  456. #ifdef HAVE_SSL
  457. }
  458. #endif
  459. asprintf (&buf, "%s %s HTTP/1.0\r\n%s\r\n", http_method, server_url, user_agent);
  460. /* optionally send the host header info */
  461. if (host_name)
  462. asprintf (&buf, "%sHost: %s\r\n", buf, host_name);
  463. /* optionally send the authentication info */
  464. if (strlen(user_auth)) {
  465. auth = base64 (user_auth, strlen (user_auth));
  466. asprintf (&buf, "%sAuthorization: Basic %s\r\n", buf, auth);
  467. }
  468. /* either send http POST data */
  469. if (http_post_data) {
  470. if (http_content_type) {
  471. asprintf (&buf, "%sContent-Type: %s\r\n", buf, http_content_type);
  472. } else {
  473. asprintf (&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", buf);
  474. }
  475. asprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, strlen (http_post_data));
  476. asprintf (&buf, "%s%s%s", buf, http_post_data, CRLF);
  477. }
  478. else {
  479. /* or just a newline so the server knows we're done with the request */
  480. asprintf (&buf, "%s%s", buf, CRLF);
  481. }
  482. if (verbose)
  483. printf ("%s\n", buf);
  484. #ifdef HAVE_SSL
  485. if (use_ssl == TRUE) {
  486. if (SSL_write (ssl, buf, (int)strlen(buf)) == -1) {
  487. ERR_print_errors_fp (stderr);
  488. return STATE_CRITICAL;
  489. }
  490. }
  491. else {
  492. #endif
  493. send (sd, buf, strlen (buf), 0);
  494. #ifdef HAVE_SSL
  495. }
  496. #endif
  497. /* fetch the page */
  498. full_page = strdup("");
  499. while ((i = my_recv ()) > 0) {
  500. buffer[i] = '\0';
  501. asprintf (&full_page, "%s%s", full_page, buffer);
  502. pagesize += i;
  503. }
  504. if (i < 0 && errno != ECONNRESET) {
  505. #ifdef HAVE_SSL
  506. if (use_ssl) {
  507. sslerr=SSL_get_error(ssl, i);
  508. if ( sslerr == SSL_ERROR_SSL ) {
  509. die (STATE_WARNING, _("Client Certificate Required\n"));
  510. } else {
  511. die (STATE_CRITICAL, _("Error in recv()\n"));
  512. }
  513. }
  514. else {
  515. #endif
  516. die (STATE_CRITICAL, _("Error in recv()\n"));
  517. #ifdef HAVE_SSL
  518. }
  519. #endif
  520. }
  521. /* return a CRITICAL status if we couldn't read any data */
  522. if (pagesize == (size_t) 0)
  523. die (STATE_CRITICAL, _("No data received %s\n"), timestamp);
  524. /* close the connection */
  525. my_close ();
  526. /* reset the alarm */
  527. alarm (0);
  528. /* leave full_page untouched so we can free it later */
  529. page = full_page;
  530. if (verbose)
  531. printf ("%s://%s:%d%s is %d characters\n", server_type, server_address, server_port, server_url, pagesize);
  532. /* find status line and null-terminate it */
  533. status_line = page;
  534. page += (size_t) strcspn (page, "\r\n");
  535. pos = page;
  536. page += (size_t) strspn (page, "\r\n");
  537. status_line[strcspn(status_line, "\r\n")] = 0;
  538. strip (status_line);
  539. if (verbose)
  540. printf ("STATUS: %s\n", status_line);
  541. /* find header info and null-terminate it */
  542. header = page;
  543. while (strcspn (page, "\r\n") > 0) {
  544. page += (size_t) strcspn (page, "\r\n");
  545. pos = page;
  546. if ((strspn (page, "\r") == 1 && strspn (page, "\r\n") >= 2) ||
  547. (strspn (page, "\n") == 1 && strspn (page, "\r\n") >= 2))
  548. page += (size_t) 2;
  549. else
  550. page += (size_t) 1;
  551. }
  552. page += (size_t) strspn (page, "\r\n");
  553. header[pos - header] = 0;
  554. if (verbose)
  555. printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header, page);
  556. /* make sure the status line matches the response we are looking for */
  557. if (!strstr (status_line, server_expect)) {
  558. if (server_port == HTTP_PORT)
  559. asprintf (&msg,
  560. _("Invalid HTTP response received from host\n"));
  561. else
  562. asprintf (&msg,
  563. _("Invalid HTTP response received from host on port %d\n"),
  564. server_port);
  565. die (STATE_CRITICAL, "%s", msg);
  566. }
  567. /* Exit here if server_expect was set by user and not default */
  568. if ( server_expect_yn ) {
  569. asprintf (&msg,
  570. _("HTTP OK: Status line output matched \"%s\"\n"),
  571. server_expect);
  572. if (verbose)
  573. printf ("%s\n",msg);
  574. }
  575. else {
  576. /* Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF */
  577. /* HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT */
  578. /* Status-Code = 3 DIGITS */
  579. status_code = strchr (status_line, ' ') + sizeof (char);
  580. if (strspn (status_code, "1234567890") != 3)
  581. die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status Line (%s)\n"), status_line);
  582. http_status = atoi (status_code);
  583. /* check the return code */
  584. if (http_status >= 600 || http_status < 100)
  585. die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%s)\n"), status_line);
  586. /* server errors result in a critical state */
  587. else if (http_status >= 500)
  588. die (STATE_CRITICAL, _("HTTP CRITICAL: %s\n"), status_line);
  589. /* client errors result in a warning state */
  590. else if (http_status >= 400)
  591. die (STATE_WARNING, _("HTTP WARNING: %s\n"), status_line);
  592. /* check redirected page if specified */
  593. else if (http_status >= 300) {
  594. if (onredirect == STATE_DEPENDENT)
  595. redir (header, status_line);
  596. else if (onredirect == STATE_UNKNOWN)
  597. printf (_("UNKNOWN"));
  598. else if (onredirect == STATE_OK)
  599. printf (_("OK"));
  600. else if (onredirect == STATE_WARNING)
  601. printf (_("WARNING"));
  602. else if (onredirect == STATE_CRITICAL)
  603. printf (_("CRITICAL"));
  604. microsec = deltime (tv);
  605. elapsed_time = (double)microsec / 1.0e6;
  606. die (onredirect,
  607. _(" - %s - %.3f second response time %s%s|%s %s\n"),
  608. status_line, elapsed_time, timestamp,
  609. (display_html ? "</A>" : ""),
  610. perfd_time (microsec), perfd_size (pagesize));
  611. } /* end if (http_status >= 300) */
  612. } /* end else (server_expect_yn) */
  613. /* check elapsed time */
  614. microsec = deltime (tv);
  615. elapsed_time = (double)microsec / 1.0e6;
  616. asprintf (&msg,
  617. _("HTTP problem: %s - %.3f second response time %s%s|%s %s\n"),
  618. status_line, elapsed_time, timestamp,
  619. (display_html ? "</A>" : ""),
  620. perfd_time (microsec), perfd_size (pagesize));
  621. if (check_critical_time == TRUE && elapsed_time > critical_time)
  622. die (STATE_CRITICAL, "%s", msg);
  623. if (check_warning_time == TRUE && elapsed_time > warning_time)
  624. die (STATE_WARNING, "%s", msg);
  625. /* Page and Header content checks go here */
  626. /* these checks should be last */
  627. if (strlen (string_expect)) {
  628. if (strstr (page, string_expect)) {
  629. printf (_("HTTP OK %s - %.3f second response time %s%s|%s %s\n"),
  630. status_line, elapsed_time,
  631. timestamp, (display_html ? "</A>" : ""),
  632. perfd_time (microsec), perfd_size (pagesize));
  633. exit (STATE_OK);
  634. }
  635. else {
  636. printf (_("CRITICAL - string not found%s|%s %s\n"),
  637. (display_html ? "</A>" : ""),
  638. perfd_time (microsec), perfd_size (pagesize));
  639. exit (STATE_CRITICAL);
  640. }
  641. }
  642. #ifdef HAVE_REGEX_H
  643. if (strlen (regexp)) {
  644. errcode = regexec (&preg, page, REGS, pmatch, 0);
  645. if (errcode == 0) {
  646. printf (_("HTTP OK %s - %.3f second response time %s%s|%s %s\n"),
  647. status_line, elapsed_time,
  648. timestamp, (display_html ? "</A>" : ""),
  649. perfd_time (microsec), perfd_size (pagesize));
  650. exit (STATE_OK);
  651. }
  652. else {
  653. if (errcode == REG_NOMATCH) {
  654. printf (_("CRITICAL - pattern not found%s|%s %s\n"),
  655. (display_html ? "</A>" : ""),
  656. perfd_time (microsec), perfd_size (pagesize));
  657. exit (STATE_CRITICAL);
  658. }
  659. else {
  660. regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  661. printf (_("CRITICAL - Execute Error: %s\n"), errbuf);
  662. exit (STATE_CRITICAL);
  663. }
  664. }
  665. }
  666. #endif
  667. /* make sure the page is of an appropriate size */
  668. page_len = strlen (page);
  669. if ((min_page_len > 0) && (page_len < min_page_len)) {
  670. printf (_("HTTP WARNING: page size %d too small%s|%s\n"),
  671. page_len, (display_html ? "</A>" : ""), perfd_size (page_len) );
  672. exit (STATE_WARNING);
  673. }
  674. /* We only get here if all tests have been passed */
  675. asprintf (&msg, _("HTTP OK %s - %d bytes in %.3f seconds %s%s|%s %s\n"),
  676. status_line, page_len, elapsed_time,
  677. timestamp, (display_html ? "</A>" : ""),
  678. perfd_time (microsec), perfd_size (page_len));
  679. die (STATE_OK, "%s", msg);
  680. return STATE_UNKNOWN;
  681. }
  682. /* per RFC 2396 */
  683. #define HDR_LOCATION "%*[Ll]%*[Oo]%*[Cc]%*[Aa]%*[Tt]%*[Ii]%*[Oo]%*[Nn]: "
  684. #define URI_HTTP "%[HTPShtps]://"
  685. #define URI_HOST "%[-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]"
  686. #define URI_PORT ":%[0123456789]"
  687. #define URI_PATH "%[-_.!~*'();/?:@&=+$,%#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]"
  688. #define HD1 URI_HTTP URI_HOST URI_PORT URI_PATH
  689. #define HD2 URI_HTTP URI_HOST URI_PATH
  690. #define HD3 URI_HTTP URI_HOST URI_PORT
  691. #define HD4 URI_HTTP URI_HOST
  692. #define HD5 URI_PATH
  693. void
  694. redir (char *pos, char *status_line)
  695. {
  696. int i = 0;
  697. char *x;
  698. char xx[2];
  699. char type[6];
  700. char *addr;
  701. char port[6];
  702. char *url;
  703. addr = malloc (MAX_IPV4_HOSTLENGTH + 1);
  704. if (addr == NULL)
  705. die (STATE_UNKNOWN, _("ERROR: could not allocate addr\n"));
  706. url = malloc (strcspn (pos, "\r\n"));
  707. if (url == NULL)
  708. die (STATE_UNKNOWN, _("ERROR: could not allocate url\n"));
  709. while (pos) {
  710. if (sscanf (pos, "%[Ll]%*[Oo]%*[Cc]%*[Aa]%*[Tt]%*[Ii]%*[Oo]%*[Nn]:%n", xx, &i) < 1) {
  711. pos += (size_t) strcspn (pos, "\r\n");
  712. pos += (size_t) strspn (pos, "\r\n");
  713. if (strlen(pos) == 0)
  714. die (STATE_UNKNOWN,
  715. _("UNKNOWN - Could not find redirect location - %s%s\n"),
  716. status_line, (display_html ? "</A>" : ""));
  717. continue;
  718. }
  719. pos += i;
  720. pos += strspn (pos, " \t\r\n");
  721. url = realloc (url, strcspn (pos, "\r\n"));
  722. if (url == NULL)
  723. die (STATE_UNKNOWN, _("ERROR: could not allocate url\n"));
  724. /* URI_HTTP, URI_HOST, URI_PORT, URI_PATH */
  725. if (sscanf (pos, HD1, type, addr, port, url) == 4) {
  726. use_ssl = server_type_check (type);
  727. i = atoi (port);
  728. }
  729. /* URI_HTTP URI_HOST URI_PATH */
  730. else if (sscanf (pos, HD2, type, addr, url) == 3 ) {
  731. use_ssl = server_type_check (type);
  732. i = server_port_check (use_ssl);
  733. }
  734. /* URI_HTTP URI_HOST URI_PORT */
  735. else if(sscanf (pos, HD3, type, addr, port) == 3) {
  736. strcpy (url, HTTP_URL);
  737. use_ssl = server_type_check (type);
  738. i = atoi (port);
  739. }
  740. /* URI_HTTP URI_HOST */
  741. else if(sscanf (pos, HD4, type, addr) == 2) {
  742. strcpy (url, HTTP_URL);
  743. use_ssl = server_type_check (type);
  744. i = server_port_check (use_ssl);
  745. }
  746. /* URI_PATH */
  747. else if (sscanf (pos, HD5, url) == 1) {
  748. /* relative url */
  749. if ((url[0] != '/')) {
  750. if ((x = strrchr(server_url, '/')))
  751. *x = '\0';
  752. asprintf (&url, "%s/%s", server_url, url);
  753. }
  754. i = server_port;
  755. strcpy (type, server_type);
  756. strcpy (addr, host_name);
  757. }
  758. else {
  759. die (STATE_UNKNOWN,
  760. _("UNKNOWN - Could not parse redirect location - %s%s\n"),
  761. pos, (display_html ? "</A>" : ""));
  762. }
  763. break;
  764. } /* end while (pos) */
  765. if (++redir_depth > max_depth)
  766. die (STATE_WARNING,
  767. _("WARNING - maximum redirection depth %d exceeded - %s://%s:%d%s%s\n"),
  768. max_depth, type, addr, i, url, (display_html ? "</A>" : ""));
  769. if (server_port==i &&
  770. !strcmp(server_address, addr) &&
  771. (host_name && !strcmp(host_name, addr)) &&
  772. !strcmp(server_url, url))
  773. die (STATE_WARNING,
  774. _("WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"),
  775. type, addr, i, url, (display_html ? "</A>" : ""));
  776. server_port = i;
  777. strcpy (server_type, type);
  778. free (host_name);
  779. host_name = strdup (addr);
  780. free (server_address);
  781. server_address = strdup (addr);
  782. free (server_url);
  783. server_url = strdup (url);
  784. check_http ();
  785. }
  786. int
  787. server_type_check (const char *type)
  788. {
  789. if (strcmp (type, "https"))
  790. return FALSE;
  791. else
  792. return TRUE;
  793. }
  794. int
  795. server_port_check (int ssl_flag)
  796. {
  797. if (ssl_flag)
  798. return HTTPS_PORT;
  799. else
  800. return HTTP_PORT;
  801. }
  802. #ifdef HAVE_SSL
  803. int connect_SSL (void)
  804. {
  805. SSL_METHOD *meth;
  806. asprintf (&randbuff, "%s", "qwertyuiopasdfghjklqwertyuiopasdfghjkl");
  807. RAND_seed (randbuff, (int)strlen(randbuff));
  808. if (verbose)
  809. printf(_("SSL seeding: %s\n"), (RAND_status()==1 ? _("OK") : _("Failed")) );
  810. /* Initialize SSL context */
  811. SSLeay_add_ssl_algorithms ();
  812. meth = SSLv23_client_method ();
  813. SSL_load_error_strings ();
  814. if ((ctx = SSL_CTX_new (meth)) == NULL) {
  815. printf (_("CRITICAL - Cannot create SSL context.\n"));
  816. return STATE_CRITICAL;
  817. }
  818. /* Initialize alarm signal handling */
  819. signal (SIGALRM, socket_timeout_alarm_handler);
  820. /* Set socket timeout */
  821. alarm (socket_timeout);
  822. /* Save start time */
  823. gettimeofday (&tv, NULL);
  824. /* Make TCP connection */
  825. if (my_tcp_connect (server_address, server_port, &sd) == STATE_OK) {
  826. /* Do the SSL handshake */
  827. if ((ssl = SSL_new (ctx)) != NULL) {
  828. SSL_set_cipher_list(ssl, "ALL");
  829. SSL_set_fd (ssl, sd);
  830. if (SSL_connect (ssl) != -1)
  831. return OK;
  832. ERR_print_errors_fp (stderr);
  833. }
  834. else {
  835. printf (_("CRITICAL - Cannot initiate SSL handshake.\n"));
  836. }
  837. SSL_free (ssl);
  838. }
  839. SSL_CTX_free (ctx);
  840. close (sd);
  841. return STATE_CRITICAL;
  842. }
  843. #endif
  844. #ifdef HAVE_SSL
  845. int
  846. check_certificate (X509 ** certificate)
  847. {
  848. ASN1_STRING *tm;
  849. int offset;
  850. struct tm stamp;
  851. int days_left;
  852. /* Retrieve timestamp of certificate */
  853. tm = X509_get_notAfter (*certificate);
  854. /* Generate tm structure to process timestamp */
  855. if (tm->type == V_ASN1_UTCTIME) {
  856. if (tm->length < 10) {
  857. printf (_("CRITICAL - Wrong time format in certificate.\n"));
  858. return STATE_CRITICAL;
  859. }
  860. else {
  861. stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
  862. if (stamp.tm_year < 50)
  863. stamp.tm_year += 100;
  864. offset = 0;
  865. }
  866. }
  867. else {
  868. if (tm->length < 12) {
  869. printf (_("CRITICAL - Wrong time format in certificate.\n"));
  870. return STATE_CRITICAL;
  871. }
  872. else {
  873. stamp.tm_year =
  874. (tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
  875. (tm->data[2] - '0') * 10 + (tm->data[3] - '0');
  876. stamp.tm_year -= 1900;
  877. offset = 2;
  878. }
  879. }
  880. stamp.tm_mon =
  881. (tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
  882. stamp.tm_mday =
  883. (tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
  884. stamp.tm_hour =
  885. (tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
  886. stamp.tm_min =
  887. (tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
  888. stamp.tm_sec = 0;
  889. stamp.tm_isdst = -1;
  890. days_left = (mktime (&stamp) - time (NULL)) / 86400;
  891. snprintf
  892. (timestamp, 17, "%02d/%02d/%04d %02d:%02d",
  893. stamp.tm_mon + 1,
  894. stamp.tm_mday, stamp.tm_year + 1900, stamp.tm_hour, stamp.tm_min);
  895. if (days_left > 0 && days_left <= days_till_exp) {
  896. printf (_("WARNING - Certificate expires in %d day(s) (%s).\n"), days_left, timestamp);
  897. return STATE_WARNING;
  898. }
  899. if (days_left < 0) {
  900. printf (_("CRITICAL - Certificate expired on %s.\n"), timestamp);
  901. return STATE_CRITICAL;
  902. }
  903. if (days_left == 0) {
  904. printf (_("WARNING - Certificate expires today (%s).\n"), timestamp);
  905. return STATE_WARNING;
  906. }
  907. printf (_("OK - Certificate will expire on %s.\n"), timestamp);
  908. return STATE_OK;
  909. }
  910. #endif
  911. char *perfd_time (long microsec)
  912. {
  913. return perfdata ("time", microsec, "us",
  914. check_warning_time, (int)(1e6*warning_time),
  915. check_critical_time, (int)(1e6*critical_time),
  916. TRUE, 0, FALSE, 0);
  917. }
  918. char *perfd_size (int page_len)
  919. {
  920. return perfdata ("size", page_len, "B",
  921. (min_page_len>0?TRUE:FALSE), min_page_len,
  922. (min_page_len>0?TRUE:FALSE), 0,
  923. TRUE, 0, FALSE, 0);
  924. }
  925. int
  926. my_recv (void)
  927. {
  928. int i;
  929. #ifdef HAVE_SSL
  930. if (use_ssl) {
  931. i = SSL_read (ssl, buffer, MAX_INPUT_BUFFER - 1);
  932. }
  933. else {
  934. i = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);
  935. }
  936. #else
  937. i = recv (sd, buffer, MAX_INPUT_BUFFER - 1, 0);
  938. #endif
  939. return i;
  940. }
  941. int
  942. my_close (void)
  943. {
  944. #ifdef HAVE_SSL
  945. if (use_ssl == TRUE) {
  946. SSL_shutdown (ssl);
  947. SSL_free (ssl);
  948. SSL_CTX_free (ctx);
  949. return 0;
  950. }
  951. else {
  952. #endif
  953. return close (sd);
  954. #ifdef HAVE_SSL
  955. }
  956. #endif
  957. }
  958. void
  959. print_help (void)
  960. {
  961. print_revision (progname, revision);
  962. printf (_("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"));
  963. printf (_(COPYRIGHT), copyright, email);
  964. printf (_("\
  965. This plugin tests the HTTP service on the specified host. It can test\n\
  966. normal (http) and secure (https) servers, follow redirects, search for\n\
  967. strings and regular expressions, check connection times, and report on\n\
  968. certificate expiration times.\n"));
  969. print_usage ();
  970. printf (_("NOTE: One or both of -H and -I must be specified\n"));
  971. printf (_(UT_HELP_VRSN));
  972. printf (_("\
  973. -H, --hostname=ADDRESS\n\
  974. Host name argument for servers using host headers (virtual host)\n\
  975. -I, --IP-address=ADDRESS\n\
  976. IP address or name (use numeric address if possible to bypass DNS lookup).\n\
  977. -p, --port=INTEGER\n\
  978. Port number (default: %d)\n"), HTTP_PORT);
  979. printf (_(UT_IPv46));
  980. #ifdef HAVE_SSL
  981. printf (_("\
  982. -S, --ssl\n\
  983. Connect via SSL\n\
  984. -C, --certificate=INTEGER\n\
  985. Minimum number of days a certificate has to be valid.\n\
  986. (when this option is used the url is not checked.)\n"));
  987. #endif
  988. printf (_("\
  989. -e, --expect=STRING\n\
  990. String to expect in first (status) line of server response (default: %s)\n\
  991. If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)\n\
  992. -s, --string=STRING\n\
  993. String to expect in the content\n\
  994. -u, --url=PATH\n\
  995. URL to GET or POST (default: /)\n\
  996. -P, --post=STRING\n\
  997. URL encoded http POST data\n\
  998. -T, --content-type=STRING\n\
  999. specify Content-Type header media type when POSTing\n"), HTTP_EXPECT);
  1000. #ifdef HAVE_REGEX_H
  1001. printf (_("\
  1002. -l, --linespan\n\
  1003. Allow regex to span newlines (must precede -r or -R)\n\
  1004. -r, --regex, --ereg=STRING\n\
  1005. Search page for regex STRING\n\
  1006. -R, --eregi=STRING\n\
  1007. Search page for case-insensitive regex STRING\n"));
  1008. #endif
  1009. printf (_("\
  1010. -a, --authorization=AUTH_PAIR\n\
  1011. Username:password on sites with basic authentication\n\
  1012. -L, --link=URL\n\
  1013. Wrap output in HTML link (obsoleted by urlize)\n\
  1014. -f, --onredirect=<ok|warning|critical|follow>\n\
  1015. How to handle redirected pages\n\
  1016. -m, --min=INTEGER\n\
  1017. Minimum page size required (bytes)\n"));
  1018. printf (_(UT_WARN_CRIT));
  1019. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  1020. printf (_(UT_VERBOSE));
  1021. printf (_("\
  1022. This plugin will attempt to open an HTTP connection with the host. Successful\n\
  1023. connects return STATE_OK, refusals and timeouts return STATE_CRITICAL, other\n\
  1024. errors return STATE_UNKNOWN. Successful connects, but incorrect reponse\n\
  1025. messages from the host result in STATE_WARNING return values. If you are\n\
  1026. checking a virtual server that uses 'host headers' you must supply the FQDN\n\
  1027. (fully qualified domain name) as the [host_name] argument.\n"));
  1028. #ifdef HAVE_SSL
  1029. printf (_("\n\
  1030. This plugin can also check whether an SSL enabled web server is able to\n\
  1031. serve content (optionally within a specified time) or whether the X509 \n\
  1032. certificate is still valid for the specified number of days.\n"));
  1033. printf (_("\n\
  1034. CHECK CONTENT: check_http -w 5 -c 10 --ssl www.verisign.com\n\n\
  1035. When the 'www.verisign.com' server returns its content within 5 seconds, a\n\
  1036. STATE_OK will be returned. When the server returns its content but exceeds\n\
  1037. the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,\n\
  1038. a STATE_CRITICAL will be returned.\n\n"));
  1039. printf (_("\
  1040. CHECK CERTIFICATE: check_http www.verisign.com -C 14\n\n\
  1041. When the certificate of 'www.verisign.com' is valid for more than 14 days, a\n\
  1042. STATE_OK is returned. When the certificate is still valid, but for less than\n\
  1043. 14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when\n\
  1044. the certificate is expired.\n"));
  1045. #endif
  1046. printf (_(UT_SUPPORT));
  1047. }
  1048. void
  1049. print_usage (void)
  1050. {
  1051. printf (_("\
  1052. Usage: %s (-H <vhost> | -I <IP-address>) [-u <uri>] [-p <port>]\n\
  1053. [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L]\n\
  1054. [-a auth] [-f <ok | warn | critcal | follow>] [-e <expect>]\n\
  1055. [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n\
  1056. [-P string] [-m min_pg_size] [-4|-6]\n"), progname);
  1057. printf (_(UT_HLP_VRS), progname, progname);
  1058. }