check_http.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. /*****************************************************************************
  2. *
  3. * Nagios check_http plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 1999-2008 Nagios Plugins Development Team
  7. *
  8. * Description:
  9. *
  10. * This file contains the check_http plugin
  11. *
  12. * This plugin tests the HTTP service on the specified host. It can test
  13. * normal (http) and secure (https) servers, follow redirects, search for
  14. * strings and regular expressions, check connection times, and report on
  15. * certificate expiration times.
  16. *
  17. *
  18. * This program is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation, either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. *
  31. *
  32. *****************************************************************************/
  33. /* splint -I. -I../../plugins -I../../lib/ -I/usr/kerberos/include/ ../../plugins/check_http.c */
  34. const char *progname = "check_http";
  35. const char *copyright = "1999-2008";
  36. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  37. #include "common.h"
  38. #include "netutils.h"
  39. #include "utils.h"
  40. #include "base64.h"
  41. #include <ctype.h>
  42. #define INPUT_DELIMITER ";"
  43. #define STICKY_NONE 0
  44. #define STICKY_HOST 1
  45. #define STICKY_PORT 2
  46. #define HTTP_EXPECT "HTTP/1."
  47. enum {
  48. MAX_IPV4_HOSTLENGTH = 255,
  49. HTTP_PORT = 80,
  50. HTTPS_PORT = 443,
  51. MAX_PORT = 65535
  52. };
  53. #ifdef HAVE_SSL
  54. int check_cert = FALSE;
  55. int days_till_exp;
  56. char *randbuff;
  57. X509 *server_cert;
  58. # define my_recv(buf, len) ((use_ssl) ? np_net_ssl_read(buf, len) : read(sd, buf, len))
  59. # define my_send(buf, len) ((use_ssl) ? np_net_ssl_write(buf, len) : send(sd, buf, len, 0))
  60. #else /* ifndef HAVE_SSL */
  61. # define my_recv(buf, len) read(sd, buf, len)
  62. # define my_send(buf, len) send(sd, buf, len, 0)
  63. #endif /* HAVE_SSL */
  64. int no_body = FALSE;
  65. int maximum_age = -1;
  66. enum {
  67. REGS = 2,
  68. MAX_RE_SIZE = 256
  69. };
  70. #include "regex.h"
  71. regex_t preg;
  72. regmatch_t pmatch[REGS];
  73. char regexp[MAX_RE_SIZE];
  74. char errbuf[MAX_INPUT_BUFFER];
  75. int cflags = REG_NOSUB | REG_EXTENDED | REG_NEWLINE;
  76. int errcode;
  77. int invert_regex = 0;
  78. struct timeval tv;
  79. #define HTTP_URL "/"
  80. #define CRLF "\r\n"
  81. int specify_port = FALSE;
  82. int server_port = HTTP_PORT;
  83. char server_port_text[6] = "";
  84. char server_type[6] = "http";
  85. char *server_address;
  86. char *host_name;
  87. char *server_url;
  88. char *user_agent;
  89. int server_url_length;
  90. int server_expect_yn = 0;
  91. char server_expect[MAX_INPUT_BUFFER] = HTTP_EXPECT;
  92. char string_expect[MAX_INPUT_BUFFER] = "";
  93. double warning_time = 0;
  94. int check_warning_time = FALSE;
  95. double critical_time = 0;
  96. int check_critical_time = FALSE;
  97. char user_auth[MAX_INPUT_BUFFER] = "";
  98. char proxy_auth[MAX_INPUT_BUFFER] = "";
  99. int display_html = FALSE;
  100. char **http_opt_headers;
  101. int http_opt_headers_count = 0;
  102. int onredirect = STATE_OK;
  103. int followsticky = STICKY_NONE;
  104. int use_ssl = FALSE;
  105. int use_sni = FALSE;
  106. int verbose = FALSE;
  107. int sd;
  108. int min_page_len = 0;
  109. int max_page_len = 0;
  110. int redir_depth = 0;
  111. int max_depth = 15;
  112. char *http_method;
  113. char *http_post_data;
  114. char *http_content_type;
  115. char buffer[MAX_INPUT_BUFFER];
  116. int process_arguments (int, char **);
  117. int check_http (void);
  118. void redir (char *pos, char *status_line);
  119. int server_type_check(const char *type);
  120. int server_port_check(int ssl_flag);
  121. char *perfd_time (double microsec);
  122. char *perfd_size (int page_len);
  123. void print_help (void);
  124. void print_usage (void);
  125. int
  126. main (int argc, char **argv)
  127. {
  128. int result = STATE_UNKNOWN;
  129. setlocale (LC_ALL, "");
  130. bindtextdomain (PACKAGE, LOCALEDIR);
  131. textdomain (PACKAGE);
  132. /* Set default URL. Must be malloced for subsequent realloc if --onredirect=follow */
  133. server_url = strdup(HTTP_URL);
  134. server_url_length = strlen(server_url);
  135. asprintf (&user_agent, "User-Agent: check_http/v%s (nagios-plugins %s)",
  136. NP_VERSION, VERSION);
  137. /* Parse extra opts if any */
  138. argv=np_extra_opts (&argc, argv, progname);
  139. if (process_arguments (argc, argv) == ERROR)
  140. usage4 (_("Could not parse arguments"));
  141. if (display_html == TRUE)
  142. printf ("<A HREF=\"%s://%s:%d%s\" target=\"_blank\">",
  143. use_ssl ? "https" : "http", host_name ? host_name : server_address,
  144. server_port, server_url);
  145. /* initialize alarm signal handling, set socket timeout, start timer */
  146. (void) signal (SIGALRM, socket_timeout_alarm_handler);
  147. (void) alarm (socket_timeout);
  148. gettimeofday (&tv, NULL);
  149. result = check_http ();
  150. return result;
  151. }
  152. /* process command-line arguments */
  153. int
  154. process_arguments (int argc, char **argv)
  155. {
  156. int c = 1;
  157. char *p;
  158. enum {
  159. INVERT_REGEX = CHAR_MAX + 1,
  160. SNI_OPTION
  161. };
  162. int option = 0;
  163. static struct option longopts[] = {
  164. STD_LONG_OPTS,
  165. {"link", no_argument, 0, 'L'},
  166. {"nohtml", no_argument, 0, 'n'},
  167. {"ssl", no_argument, 0, 'S'},
  168. {"sni", no_argument, 0, SNI_OPTION},
  169. {"post", required_argument, 0, 'P'},
  170. {"method", required_argument, 0, 'j'},
  171. {"IP-address", required_argument, 0, 'I'},
  172. {"url", required_argument, 0, 'u'},
  173. {"port", required_argument, 0, 'p'},
  174. {"authorization", required_argument, 0, 'a'},
  175. {"proxy_authorization", required_argument, 0, 'b'},
  176. {"string", required_argument, 0, 's'},
  177. {"expect", required_argument, 0, 'e'},
  178. {"regex", required_argument, 0, 'r'},
  179. {"ereg", required_argument, 0, 'r'},
  180. {"eregi", required_argument, 0, 'R'},
  181. {"linespan", no_argument, 0, 'l'},
  182. {"onredirect", required_argument, 0, 'f'},
  183. {"certificate", required_argument, 0, 'C'},
  184. {"useragent", required_argument, 0, 'A'},
  185. {"header", required_argument, 0, 'k'},
  186. {"no-body", no_argument, 0, 'N'},
  187. {"max-age", required_argument, 0, 'M'},
  188. {"content-type", required_argument, 0, 'T'},
  189. {"pagesize", required_argument, 0, 'm'},
  190. {"invert-regex", no_argument, NULL, INVERT_REGEX},
  191. {"use-ipv4", no_argument, 0, '4'},
  192. {"use-ipv6", no_argument, 0, '6'},
  193. {0, 0, 0, 0}
  194. };
  195. if (argc < 2)
  196. return ERROR;
  197. for (c = 1; c < argc; c++) {
  198. if (strcmp ("-to", argv[c]) == 0)
  199. strcpy (argv[c], "-t");
  200. if (strcmp ("-hn", argv[c]) == 0)
  201. strcpy (argv[c], "-H");
  202. if (strcmp ("-wt", argv[c]) == 0)
  203. strcpy (argv[c], "-w");
  204. if (strcmp ("-ct", argv[c]) == 0)
  205. strcpy (argv[c], "-c");
  206. if (strcmp ("-nohtml", argv[c]) == 0)
  207. strcpy (argv[c], "-n");
  208. }
  209. while (1) {
  210. c = getopt_long (argc, argv, "Vvh46t:c:w:A:k:H:P:j:T:I:a:b:e:p:s:R:r:u:f:C:nlLSm:M:N", longopts, &option);
  211. if (c == -1 || c == EOF)
  212. break;
  213. switch (c) {
  214. case '?': /* usage */
  215. usage5 ();
  216. break;
  217. case 'h': /* help */
  218. print_help ();
  219. exit (STATE_OK);
  220. break;
  221. case 'V': /* version */
  222. print_revision (progname, NP_VERSION);
  223. exit (STATE_OK);
  224. break;
  225. case 't': /* timeout period */
  226. if (!is_intnonneg (optarg))
  227. usage2 (_("Timeout interval must be a positive integer"), optarg);
  228. else
  229. socket_timeout = atoi (optarg);
  230. break;
  231. case 'c': /* critical time threshold */
  232. if (!is_nonnegative (optarg))
  233. usage2 (_("Critical threshold must be integer"), optarg);
  234. else {
  235. critical_time = strtod (optarg, NULL);
  236. check_critical_time = TRUE;
  237. }
  238. break;
  239. case 'w': /* warning time threshold */
  240. if (!is_nonnegative (optarg))
  241. usage2 (_("Warning threshold must be integer"), optarg);
  242. else {
  243. warning_time = strtod (optarg, NULL);
  244. check_warning_time = TRUE;
  245. }
  246. break;
  247. case 'A': /* User Agent String */
  248. asprintf (&user_agent, "User-Agent: %s", optarg);
  249. break;
  250. case 'k': /* Additional headers */
  251. if (http_opt_headers_count == 0)
  252. http_opt_headers = malloc (sizeof (char *) * (++http_opt_headers_count));
  253. else
  254. http_opt_headers = realloc (http_opt_headers, sizeof (char *) * (++http_opt_headers_count));
  255. http_opt_headers[http_opt_headers_count - 1] = optarg;
  256. /* asprintf (&http_opt_headers, "%s", optarg); */
  257. break;
  258. case 'L': /* show html link */
  259. display_html = TRUE;
  260. break;
  261. case 'n': /* do not show html link */
  262. display_html = FALSE;
  263. break;
  264. case 'C': /* Check SSL cert validity */
  265. #ifdef HAVE_SSL
  266. if (!is_intnonneg (optarg))
  267. usage2 (_("Invalid certificate expiration period"), optarg);
  268. else {
  269. days_till_exp = atoi (optarg);
  270. check_cert = TRUE;
  271. }
  272. /* Fall through to -S option */
  273. #endif
  274. case 'S': /* use SSL */
  275. #ifndef HAVE_SSL
  276. usage4 (_("Invalid option - SSL is not available"));
  277. #endif
  278. use_ssl = TRUE;
  279. if (specify_port == FALSE)
  280. server_port = HTTPS_PORT;
  281. break;
  282. case SNI_OPTION:
  283. use_sni = TRUE;
  284. break;
  285. case 'f': /* onredirect */
  286. if (!strcmp (optarg, "stickyport"))
  287. onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST|STICKY_PORT;
  288. else if (!strcmp (optarg, "sticky"))
  289. onredirect = STATE_DEPENDENT, followsticky = STICKY_HOST;
  290. else if (!strcmp (optarg, "follow"))
  291. onredirect = STATE_DEPENDENT, followsticky = STICKY_NONE;
  292. else if (!strcmp (optarg, "unknown"))
  293. onredirect = STATE_UNKNOWN;
  294. else if (!strcmp (optarg, "ok"))
  295. onredirect = STATE_OK;
  296. else if (!strcmp (optarg, "warning"))
  297. onredirect = STATE_WARNING;
  298. else if (!strcmp (optarg, "critical"))
  299. onredirect = STATE_CRITICAL;
  300. else usage2 (_("Invalid onredirect option"), optarg);
  301. if (verbose)
  302. printf(_("option f:%d \n"), onredirect);
  303. break;
  304. /* Note: H, I, and u must be malloc'd or will fail on redirects */
  305. case 'H': /* Host Name (virtual host) */
  306. host_name = strdup (optarg);
  307. if (host_name[0] == '[') {
  308. if ((p = strstr (host_name, "]:")) != NULL) /* [IPv6]:port */
  309. server_port = atoi (p + 2);
  310. } else if ((p = strchr (host_name, ':')) != NULL
  311. && strchr (++p, ':') == NULL) /* IPv4:port or host:port */
  312. server_port = atoi (p);
  313. break;
  314. case 'I': /* Server IP-address */
  315. server_address = strdup (optarg);
  316. break;
  317. case 'u': /* URL path */
  318. server_url = strdup (optarg);
  319. server_url_length = strlen (server_url);
  320. break;
  321. case 'p': /* Server port */
  322. if (!is_intnonneg (optarg))
  323. usage2 (_("Invalid port number"), optarg);
  324. else {
  325. server_port = atoi (optarg);
  326. specify_port = TRUE;
  327. }
  328. break;
  329. case 'a': /* authorization info */
  330. strncpy (user_auth, optarg, MAX_INPUT_BUFFER - 1);
  331. user_auth[MAX_INPUT_BUFFER - 1] = 0;
  332. break;
  333. case 'b': /* proxy-authorization info */
  334. strncpy (proxy_auth, optarg, MAX_INPUT_BUFFER - 1);
  335. proxy_auth[MAX_INPUT_BUFFER - 1] = 0;
  336. break;
  337. case 'P': /* HTTP POST data in URL encoded format; ignored if settings already */
  338. if (! http_post_data)
  339. http_post_data = strdup (optarg);
  340. if (! http_method)
  341. http_method = strdup("POST");
  342. break;
  343. case 'j': /* Set HTTP method */
  344. if (http_method)
  345. free(http_method);
  346. http_method = strdup (optarg);
  347. break;
  348. case 's': /* string or substring */
  349. strncpy (string_expect, optarg, MAX_INPUT_BUFFER - 1);
  350. string_expect[MAX_INPUT_BUFFER - 1] = 0;
  351. break;
  352. case 'e': /* string or substring */
  353. strncpy (server_expect, optarg, MAX_INPUT_BUFFER - 1);
  354. server_expect[MAX_INPUT_BUFFER - 1] = 0;
  355. server_expect_yn = 1;
  356. break;
  357. case 'T': /* Content-type */
  358. asprintf (&http_content_type, "%s", optarg);
  359. break;
  360. case 'l': /* linespan */
  361. cflags &= ~REG_NEWLINE;
  362. break;
  363. case 'R': /* regex */
  364. cflags |= REG_ICASE;
  365. case 'r': /* regex */
  366. strncpy (regexp, optarg, MAX_RE_SIZE - 1);
  367. regexp[MAX_RE_SIZE - 1] = 0;
  368. errcode = regcomp (&preg, regexp, cflags);
  369. if (errcode != 0) {
  370. (void) regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  371. printf (_("Could Not Compile Regular Expression: %s"), errbuf);
  372. return ERROR;
  373. }
  374. break;
  375. case INVERT_REGEX:
  376. invert_regex = 1;
  377. break;
  378. case '4':
  379. address_family = AF_INET;
  380. break;
  381. case '6':
  382. #ifdef USE_IPV6
  383. address_family = AF_INET6;
  384. #else
  385. usage4 (_("IPv6 support not available"));
  386. #endif
  387. break;
  388. case 'v': /* verbose */
  389. verbose = TRUE;
  390. break;
  391. case 'm': /* min_page_length */
  392. {
  393. char *tmp;
  394. if (strchr(optarg, ':') != (char *)NULL) {
  395. /* range, so get two values, min:max */
  396. tmp = strtok(optarg, ":");
  397. if (tmp == NULL) {
  398. printf("Bad format: try \"-m min:max\"\n");
  399. exit (STATE_WARNING);
  400. } else
  401. min_page_len = atoi(tmp);
  402. tmp = strtok(NULL, ":");
  403. if (tmp == NULL) {
  404. printf("Bad format: try \"-m min:max\"\n");
  405. exit (STATE_WARNING);
  406. } else
  407. max_page_len = atoi(tmp);
  408. } else
  409. min_page_len = atoi (optarg);
  410. break;
  411. }
  412. case 'N': /* no-body */
  413. no_body = TRUE;
  414. break;
  415. case 'M': /* max-age */
  416. {
  417. int L = strlen(optarg);
  418. if (L && optarg[L-1] == 'm')
  419. maximum_age = atoi (optarg) * 60;
  420. else if (L && optarg[L-1] == 'h')
  421. maximum_age = atoi (optarg) * 60 * 60;
  422. else if (L && optarg[L-1] == 'd')
  423. maximum_age = atoi (optarg) * 60 * 60 * 24;
  424. else if (L && (optarg[L-1] == 's' ||
  425. isdigit (optarg[L-1])))
  426. maximum_age = atoi (optarg);
  427. else {
  428. fprintf (stderr, "unparsable max-age: %s\n", optarg);
  429. exit (STATE_WARNING);
  430. }
  431. }
  432. break;
  433. }
  434. }
  435. c = optind;
  436. if (server_address == NULL && c < argc)
  437. server_address = strdup (argv[c++]);
  438. if (host_name == NULL && c < argc)
  439. host_name = strdup (argv[c++]);
  440. if (server_address == NULL) {
  441. if (host_name == NULL)
  442. usage4 (_("You must specify a server address or host name"));
  443. else
  444. server_address = strdup (host_name);
  445. }
  446. if (check_critical_time && critical_time>(double)socket_timeout)
  447. socket_timeout = (int)critical_time + 1;
  448. if (http_method == NULL)
  449. http_method = strdup ("GET");
  450. return TRUE;
  451. }
  452. /* Returns 1 if we're done processing the document body; 0 to keep going */
  453. static int
  454. document_headers_done (char *full_page)
  455. {
  456. const char *body;
  457. for (body = full_page; *body; body++) {
  458. if (!strncmp (body, "\n\n", 2) || !strncmp (body, "\n\r\n", 3))
  459. break;
  460. }
  461. if (!*body)
  462. return 0; /* haven't read end of headers yet */
  463. full_page[body - full_page] = 0;
  464. return 1;
  465. }
  466. static time_t
  467. parse_time_string (const char *string)
  468. {
  469. struct tm tm;
  470. time_t t;
  471. memset (&tm, 0, sizeof(tm));
  472. /* Like this: Tue, 25 Dec 2001 02:59:03 GMT */
  473. if (isupper (string[0]) && /* Tue */
  474. islower (string[1]) &&
  475. islower (string[2]) &&
  476. ',' == string[3] &&
  477. ' ' == string[4] &&
  478. (isdigit(string[5]) || string[5] == ' ') && /* 25 */
  479. isdigit (string[6]) &&
  480. ' ' == string[7] &&
  481. isupper (string[8]) && /* Dec */
  482. islower (string[9]) &&
  483. islower (string[10]) &&
  484. ' ' == string[11] &&
  485. isdigit (string[12]) && /* 2001 */
  486. isdigit (string[13]) &&
  487. isdigit (string[14]) &&
  488. isdigit (string[15]) &&
  489. ' ' == string[16] &&
  490. isdigit (string[17]) && /* 02: */
  491. isdigit (string[18]) &&
  492. ':' == string[19] &&
  493. isdigit (string[20]) && /* 59: */
  494. isdigit (string[21]) &&
  495. ':' == string[22] &&
  496. isdigit (string[23]) && /* 03 */
  497. isdigit (string[24]) &&
  498. ' ' == string[25] &&
  499. 'G' == string[26] && /* GMT */
  500. 'M' == string[27] && /* GMT */
  501. 'T' == string[28]) {
  502. tm.tm_sec = 10 * (string[23]-'0') + (string[24]-'0');
  503. tm.tm_min = 10 * (string[20]-'0') + (string[21]-'0');
  504. tm.tm_hour = 10 * (string[17]-'0') + (string[18]-'0');
  505. tm.tm_mday = 10 * (string[5] == ' ' ? 0 : string[5]-'0') + (string[6]-'0');
  506. tm.tm_mon = (!strncmp (string+8, "Jan", 3) ? 0 :
  507. !strncmp (string+8, "Feb", 3) ? 1 :
  508. !strncmp (string+8, "Mar", 3) ? 2 :
  509. !strncmp (string+8, "Apr", 3) ? 3 :
  510. !strncmp (string+8, "May", 3) ? 4 :
  511. !strncmp (string+8, "Jun", 3) ? 5 :
  512. !strncmp (string+8, "Jul", 3) ? 6 :
  513. !strncmp (string+8, "Aug", 3) ? 7 :
  514. !strncmp (string+8, "Sep", 3) ? 8 :
  515. !strncmp (string+8, "Oct", 3) ? 9 :
  516. !strncmp (string+8, "Nov", 3) ? 10 :
  517. !strncmp (string+8, "Dec", 3) ? 11 :
  518. -1);
  519. tm.tm_year = ((1000 * (string[12]-'0') +
  520. 100 * (string[13]-'0') +
  521. 10 * (string[14]-'0') +
  522. (string[15]-'0'))
  523. - 1900);
  524. tm.tm_isdst = 0; /* GMT is never in DST, right? */
  525. if (tm.tm_mon < 0 || tm.tm_mday < 1 || tm.tm_mday > 31)
  526. return 0;
  527. /*
  528. This is actually wrong: we need to subtract the local timezone
  529. offset from GMT from this value. But, that's ok in this usage,
  530. because we only comparing these two GMT dates against each other,
  531. so it doesn't matter what time zone we parse them in.
  532. */
  533. t = mktime (&tm);
  534. if (t == (time_t) -1) t = 0;
  535. if (verbose) {
  536. const char *s = string;
  537. while (*s && *s != '\r' && *s != '\n')
  538. fputc (*s++, stdout);
  539. printf (" ==> %lu\n", (unsigned long) t);
  540. }
  541. return t;
  542. } else {
  543. return 0;
  544. }
  545. }
  546. /* Checks if the server 'reply' is one of the expected 'statuscodes' */
  547. static int
  548. expected_statuscode (const char *reply, const char *statuscodes)
  549. {
  550. char *expected, *code;
  551. int result = 0;
  552. if ((expected = strdup (statuscodes)) == NULL)
  553. die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
  554. for (code = strtok (expected, ","); code != NULL; code = strtok (NULL, ","))
  555. if (strstr (reply, code) != NULL) {
  556. result = 1;
  557. break;
  558. }
  559. free (expected);
  560. return result;
  561. }
  562. static int
  563. check_document_dates (const char *headers, char **msg)
  564. {
  565. const char *s;
  566. char *server_date = 0;
  567. char *document_date = 0;
  568. int date_result = STATE_OK;
  569. s = headers;
  570. while (*s) {
  571. const char *field = s;
  572. const char *value = 0;
  573. /* Find the end of the header field */
  574. while (*s && !isspace(*s) && *s != ':')
  575. s++;
  576. /* Remember the header value, if any. */
  577. if (*s == ':')
  578. value = ++s;
  579. /* Skip to the end of the header, including continuation lines. */
  580. while (*s && !(*s == '\n' && (s[1] != ' ' && s[1] != '\t')))
  581. s++;
  582. /* Avoid stepping over end-of-string marker */
  583. if (*s)
  584. s++;
  585. /* Process this header. */
  586. if (value && value > field+2) {
  587. char *ff = (char *) malloc (value-field);
  588. char *ss = ff;
  589. while (field < value-1)
  590. *ss++ = tolower(*field++);
  591. *ss++ = 0;
  592. if (!strcmp (ff, "date") || !strcmp (ff, "last-modified")) {
  593. const char *e;
  594. while (*value && isspace (*value))
  595. value++;
  596. for (e = value; *e && *e != '\r' && *e != '\n'; e++)
  597. ;
  598. ss = (char *) malloc (e - value + 1);
  599. strncpy (ss, value, e - value);
  600. ss[e - value] = 0;
  601. if (!strcmp (ff, "date")) {
  602. if (server_date) free (server_date);
  603. server_date = ss;
  604. } else {
  605. if (document_date) free (document_date);
  606. document_date = ss;
  607. }
  608. }
  609. free (ff);
  610. }
  611. }
  612. /* Done parsing the body. Now check the dates we (hopefully) parsed. */
  613. if (!server_date || !*server_date) {
  614. asprintf (msg, _("%sServer date unknown, "), *msg);
  615. date_result = max_state_alt(STATE_UNKNOWN, date_result);
  616. } else if (!document_date || !*document_date) {
  617. asprintf (msg, _("%sDocument modification date unknown, "), *msg);
  618. date_result = max_state_alt(STATE_CRITICAL, date_result);
  619. } else {
  620. time_t srv_data = parse_time_string (server_date);
  621. time_t doc_data = parse_time_string (document_date);
  622. if (srv_data <= 0) {
  623. asprintf (msg, _("%sServer date \"%100s\" unparsable, "), *msg, server_date);
  624. date_result = max_state_alt(STATE_CRITICAL, date_result);
  625. } else if (doc_data <= 0) {
  626. asprintf (msg, _("%sDocument date \"%100s\" unparsable, "), *msg, document_date);
  627. date_result = max_state_alt(STATE_CRITICAL, date_result);
  628. } else if (doc_data > srv_data + 30) {
  629. asprintf (msg, _("%sDocument is %d seconds in the future, "), *msg, (int)doc_data - (int)srv_data);
  630. date_result = max_state_alt(STATE_CRITICAL, date_result);
  631. } else if (doc_data < srv_data - maximum_age) {
  632. int n = (srv_data - doc_data);
  633. if (n > (60 * 60 * 24 * 2)) {
  634. asprintf (msg, _("%sLast modified %.1f days ago, "), *msg, ((float) n) / (60 * 60 * 24));
  635. date_result = max_state_alt(STATE_CRITICAL, date_result);
  636. } else {
  637. asprintf (msg, _("%sLast modified %d:%02d:%02d ago, "), *msg, n / (60 * 60), (n / 60) % 60, n % 60);
  638. date_result = max_state_alt(STATE_CRITICAL, date_result);
  639. }
  640. }
  641. free (server_date);
  642. free (document_date);
  643. }
  644. return date_result;
  645. }
  646. int
  647. get_content_length (const char *headers)
  648. {
  649. const char *s;
  650. int content_length = 0;
  651. s = headers;
  652. while (*s) {
  653. const char *field = s;
  654. const char *value = 0;
  655. /* Find the end of the header field */
  656. while (*s && !isspace(*s) && *s != ':')
  657. s++;
  658. /* Remember the header value, if any. */
  659. if (*s == ':')
  660. value = ++s;
  661. /* Skip to the end of the header, including continuation lines. */
  662. while (*s && !(*s == '\n' && (s[1] != ' ' && s[1] != '\t')))
  663. s++;
  664. /* Avoid stepping over end-of-string marker */
  665. if (*s)
  666. s++;
  667. /* Process this header. */
  668. if (value && value > field+2) {
  669. char *ff = (char *) malloc (value-field);
  670. char *ss = ff;
  671. while (field < value-1)
  672. *ss++ = tolower(*field++);
  673. *ss++ = 0;
  674. if (!strcmp (ff, "content-length")) {
  675. const char *e;
  676. while (*value && isspace (*value))
  677. value++;
  678. for (e = value; *e && *e != '\r' && *e != '\n'; e++)
  679. ;
  680. ss = (char *) malloc (e - value + 1);
  681. strncpy (ss, value, e - value);
  682. ss[e - value] = 0;
  683. content_length = atoi(ss);
  684. free (ss);
  685. }
  686. free (ff);
  687. }
  688. }
  689. return (content_length);
  690. }
  691. char *
  692. prepend_slash (char *path)
  693. {
  694. char *newpath;
  695. if (path[0] == '/')
  696. return path;
  697. if ((newpath = malloc (strlen(path) + 2)) == NULL)
  698. die (STATE_UNKNOWN, _("HTTP UNKNOWN - Memory allocation error\n"));
  699. newpath[0] = '/';
  700. strcpy (newpath + 1, path);
  701. free (path);
  702. return newpath;
  703. }
  704. int
  705. check_http (void)
  706. {
  707. char *msg;
  708. char *status_line;
  709. char *status_code;
  710. char *header;
  711. char *page;
  712. char *auth;
  713. int http_status;
  714. int i = 0;
  715. size_t pagesize = 0;
  716. char *full_page;
  717. char *full_page_new;
  718. char *buf;
  719. char *pos;
  720. long microsec;
  721. double elapsed_time;
  722. int page_len = 0;
  723. int result = STATE_OK;
  724. /* try to connect to the host at the given port number */
  725. if (my_tcp_connect (server_address, server_port, &sd) != STATE_OK)
  726. die (STATE_CRITICAL, _("HTTP CRITICAL - Unable to open TCP socket\n"));
  727. #ifdef HAVE_SSL
  728. if (use_ssl == TRUE) {
  729. np_net_ssl_init_with_hostname(sd, (use_sni ? host_name : NULL));
  730. if (check_cert == TRUE) {
  731. result = np_net_ssl_check_cert(days_till_exp);
  732. np_net_ssl_cleanup();
  733. if (sd) close(sd);
  734. return result;
  735. }
  736. }
  737. #endif /* HAVE_SSL */
  738. asprintf (&buf, "%s %s %s\r\n%s\r\n", http_method, server_url, host_name ? "HTTP/1.1" : "HTTP/1.0", user_agent);
  739. /* tell HTTP/1.1 servers not to keep the connection alive */
  740. asprintf (&buf, "%sConnection: close\r\n", buf);
  741. /* optionally send the host header info */
  742. if (host_name) {
  743. /*
  744. * Specify the port only if we're using a non-default port (see RFC 2616,
  745. * 14.23). Some server applications/configurations cause trouble if the
  746. * (default) port is explicitly specified in the "Host:" header line.
  747. */
  748. if ((use_ssl == FALSE && server_port == HTTP_PORT) ||
  749. (use_ssl == TRUE && server_port == HTTPS_PORT))
  750. asprintf (&buf, "%sHost: %s\r\n", buf, host_name);
  751. else
  752. asprintf (&buf, "%sHost: %s:%d\r\n", buf, host_name, server_port);
  753. }
  754. /* optionally send any other header tag */
  755. if (http_opt_headers_count) {
  756. for (i = 0; i < http_opt_headers_count ; i++) {
  757. for ((pos = strtok(http_opt_headers[i], INPUT_DELIMITER)); pos; (pos = strtok(NULL, INPUT_DELIMITER)))
  758. asprintf (&buf, "%s%s\r\n", buf, pos);
  759. }
  760. /* This cannot be free'd here because a redirection will then try to access this and segfault */
  761. /* Covered in a testcase in tests/check_http.t */
  762. /* free(http_opt_headers); */
  763. }
  764. /* optionally send the authentication info */
  765. if (strlen(user_auth)) {
  766. base64_encode_alloc (user_auth, strlen (user_auth), &auth);
  767. asprintf (&buf, "%sAuthorization: Basic %s\r\n", buf, auth);
  768. }
  769. /* optionally send the proxy authentication info */
  770. if (strlen(proxy_auth)) {
  771. base64_encode_alloc (proxy_auth, strlen (proxy_auth), &auth);
  772. asprintf (&buf, "%sProxy-Authorization: Basic %s\r\n", buf, auth);
  773. }
  774. /* either send http POST data (any data, not only POST)*/
  775. if (http_post_data) {
  776. if (http_content_type) {
  777. asprintf (&buf, "%sContent-Type: %s\r\n", buf, http_content_type);
  778. } else {
  779. asprintf (&buf, "%sContent-Type: application/x-www-form-urlencoded\r\n", buf);
  780. }
  781. asprintf (&buf, "%sContent-Length: %i\r\n\r\n", buf, (int)strlen (http_post_data));
  782. asprintf (&buf, "%s%s%s", buf, http_post_data, CRLF);
  783. }
  784. else {
  785. /* or just a newline so the server knows we're done with the request */
  786. asprintf (&buf, "%s%s", buf, CRLF);
  787. }
  788. if (verbose) printf ("%s\n", buf);
  789. my_send (buf, strlen (buf));
  790. /* fetch the page */
  791. full_page = strdup("");
  792. while ((i = my_recv (buffer, MAX_INPUT_BUFFER-1)) > 0) {
  793. buffer[i] = '\0';
  794. asprintf (&full_page_new, "%s%s", full_page, buffer);
  795. free (full_page);
  796. full_page = full_page_new;
  797. pagesize += i;
  798. if (no_body && document_headers_done (full_page)) {
  799. i = 0;
  800. break;
  801. }
  802. }
  803. if (i < 0 && errno != ECONNRESET) {
  804. #ifdef HAVE_SSL
  805. /*
  806. if (use_ssl) {
  807. sslerr=SSL_get_error(ssl, i);
  808. if ( sslerr == SSL_ERROR_SSL ) {
  809. die (STATE_WARNING, _("HTTP WARNING - Client Certificate Required\n"));
  810. } else {
  811. die (STATE_CRITICAL, _("HTTP CRITICAL - Error on receive\n"));
  812. }
  813. }
  814. else {
  815. */
  816. #endif
  817. die (STATE_CRITICAL, _("HTTP CRITICAL - Error on receive\n"));
  818. #ifdef HAVE_SSL
  819. /* XXX
  820. }
  821. */
  822. #endif
  823. }
  824. /* return a CRITICAL status if we couldn't read any data */
  825. if (pagesize == (size_t) 0)
  826. die (STATE_CRITICAL, _("HTTP CRITICAL - No data received from host\n"));
  827. /* close the connection */
  828. #ifdef HAVE_SSL
  829. np_net_ssl_cleanup();
  830. #endif
  831. if (sd) close(sd);
  832. /* Save check time */
  833. microsec = deltime (tv);
  834. elapsed_time = (double)microsec / 1.0e6;
  835. /* leave full_page untouched so we can free it later */
  836. page = full_page;
  837. if (verbose)
  838. printf ("%s://%s:%d%s is %d characters\n",
  839. use_ssl ? "https" : "http", server_address,
  840. server_port, server_url, (int)pagesize);
  841. /* find status line and null-terminate it */
  842. status_line = page;
  843. page += (size_t) strcspn (page, "\r\n");
  844. pos = page;
  845. page += (size_t) strspn (page, "\r\n");
  846. status_line[strcspn(status_line, "\r\n")] = 0;
  847. strip (status_line);
  848. if (verbose)
  849. printf ("STATUS: %s\n", status_line);
  850. /* find header info and null-terminate it */
  851. header = page;
  852. while (strcspn (page, "\r\n") > 0) {
  853. page += (size_t) strcspn (page, "\r\n");
  854. pos = page;
  855. if ((strspn (page, "\r") == 1 && strspn (page, "\r\n") >= 2) ||
  856. (strspn (page, "\n") == 1 && strspn (page, "\r\n") >= 2))
  857. page += (size_t) 2;
  858. else
  859. page += (size_t) 1;
  860. }
  861. page += (size_t) strspn (page, "\r\n");
  862. header[pos - header] = 0;
  863. if (verbose)
  864. printf ("**** HEADER ****\n%s\n**** CONTENT ****\n%s\n", header,
  865. (no_body ? " [[ skipped ]]" : page));
  866. /* make sure the status line matches the response we are looking for */
  867. if (!expected_statuscode (status_line, server_expect)) {
  868. if (server_port == HTTP_PORT)
  869. asprintf (&msg,
  870. _("Invalid HTTP response received from host: %s\n"),
  871. status_line);
  872. else
  873. asprintf (&msg,
  874. _("Invalid HTTP response received from host on port %d: %s\n"),
  875. server_port, status_line);
  876. die (STATE_CRITICAL, "HTTP CRITICAL - %s", msg);
  877. }
  878. /* Bypass normal status line check if server_expect was set by user and not default */
  879. /* NOTE: After this if/else block msg *MUST* be an asprintf-allocated string */
  880. if ( server_expect_yn ) {
  881. asprintf (&msg,
  882. _("Status line output matched \"%s\" - "), server_expect);
  883. if (verbose)
  884. printf ("%s\n",msg);
  885. }
  886. else {
  887. /* Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF */
  888. /* HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT */
  889. /* Status-Code = 3 DIGITS */
  890. status_code = strchr (status_line, ' ') + sizeof (char);
  891. if (strspn (status_code, "1234567890") != 3)
  892. die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status Line (%s)\n"), status_line);
  893. http_status = atoi (status_code);
  894. /* check the return code */
  895. if (http_status >= 600 || http_status < 100) {
  896. die (STATE_CRITICAL, _("HTTP CRITICAL: Invalid Status (%s)\n"), status_line);
  897. }
  898. /* server errors result in a critical state */
  899. else if (http_status >= 500) {
  900. asprintf (&msg, _("%s - "), status_line);
  901. result = STATE_CRITICAL;
  902. }
  903. /* client errors result in a warning state */
  904. else if (http_status >= 400) {
  905. asprintf (&msg, _("%s - "), status_line);
  906. result = max_state_alt(STATE_WARNING, result);
  907. }
  908. /* check redirected page if specified */
  909. else if (http_status >= 300) {
  910. if (onredirect == STATE_DEPENDENT)
  911. redir (header, status_line);
  912. else
  913. result = max_state_alt(onredirect, result);
  914. asprintf (&msg, _("%s - "), status_line);
  915. } /* end if (http_status >= 300) */
  916. else {
  917. /* Print OK status anyway */
  918. asprintf (&msg, _("%s - "), status_line);
  919. }
  920. } /* end else (server_expect_yn) */
  921. /* reset the alarm - must be called *after* redir or we'll never die on redirects! */
  922. alarm (0);
  923. if (maximum_age >= 0) {
  924. result = max_state_alt(check_document_dates(header, &msg), result);
  925. }
  926. /* Page and Header content checks go here */
  927. if (strlen (string_expect)) {
  928. if (!strstr (page, string_expect)) {
  929. asprintf (&msg, _("%sstring not found, "), msg);
  930. result = STATE_CRITICAL;
  931. }
  932. }
  933. if (strlen (regexp)) {
  934. errcode = regexec (&preg, page, REGS, pmatch, 0);
  935. if ((errcode == 0 && invert_regex == 0) || (errcode == REG_NOMATCH && invert_regex == 1)) {
  936. /* OK - No-op to avoid changing the logic around it */
  937. result = max_state_alt(STATE_OK, result);
  938. }
  939. else if ((errcode == REG_NOMATCH && invert_regex == 0) || (errcode == 0 && invert_regex == 1)) {
  940. if (invert_regex == 0)
  941. asprintf (&msg, _("%spattern not found, "), msg);
  942. else
  943. asprintf (&msg, _("%spattern found, "), msg);
  944. result = STATE_CRITICAL;
  945. }
  946. else {
  947. /* FIXME: Shouldn't that be UNKNOWN? */
  948. regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER);
  949. asprintf (&msg, _("%sExecute Error: %s, "), msg, errbuf);
  950. result = STATE_CRITICAL;
  951. }
  952. }
  953. /* make sure the page is of an appropriate size */
  954. /* page_len = get_content_length(header); */
  955. /* FIXME: Will this work with -N ? IMHO we should use
  956. * get_content_length(header) and always check if it's different than the
  957. * returned pagesize
  958. */
  959. /* FIXME: IIRC pagesize returns headers - shouldn't we make
  960. * it == get_content_length(header) ??
  961. */
  962. page_len = pagesize;
  963. if ((max_page_len > 0) && (page_len > max_page_len)) {
  964. asprintf (&msg, _("%spage size %d too large, "), msg, page_len);
  965. result = max_state_alt(STATE_WARNING, result);
  966. } else if ((min_page_len > 0) && (page_len < min_page_len)) {
  967. asprintf (&msg, _("%spage size %d too small, "), msg, page_len);
  968. result = max_state_alt(STATE_WARNING, result);
  969. }
  970. /* Cut-off trailing characters */
  971. if(msg[strlen(msg)-2] == ',')
  972. msg[strlen(msg)-2] = '\0';
  973. else
  974. msg[strlen(msg)-3] = '\0';
  975. /* check elapsed time */
  976. asprintf (&msg,
  977. _("%s - %d bytes in %.3f second response time %s|%s %s"),
  978. msg, page_len, elapsed_time,
  979. (display_html ? "</A>" : ""),
  980. perfd_time (elapsed_time), perfd_size (page_len));
  981. if (check_critical_time == TRUE && elapsed_time > critical_time)
  982. result = STATE_CRITICAL;
  983. if (check_warning_time == TRUE && elapsed_time > warning_time)
  984. result = max_state_alt(STATE_WARNING, result);
  985. die (result, "HTTP %s: %s\n", state_text(result), msg);
  986. /* die failed? */
  987. return STATE_UNKNOWN;
  988. }
  989. /* per RFC 2396 */
  990. #define URI_HTTP "%5[HTPShtps]"
  991. #define URI_HOST "%255[-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]"
  992. #define URI_PORT "%6d" /* MAX_PORT's width is 5 chars, 6 to detect overflow */
  993. #define URI_PATH "%[-_.!~*'();/?:@&=+$,%#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]"
  994. #define HD1 URI_HTTP "://" URI_HOST ":" URI_PORT "/" URI_PATH
  995. #define HD2 URI_HTTP "://" URI_HOST "/" URI_PATH
  996. #define HD3 URI_HTTP "://" URI_HOST ":" URI_PORT
  997. #define HD4 URI_HTTP "://" URI_HOST
  998. #define HD5 URI_PATH
  999. void
  1000. redir (char *pos, char *status_line)
  1001. {
  1002. int i = 0;
  1003. char *x;
  1004. char xx[2];
  1005. char type[6];
  1006. char *addr;
  1007. char *url;
  1008. addr = malloc (MAX_IPV4_HOSTLENGTH + 1);
  1009. if (addr == NULL)
  1010. die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate addr\n"));
  1011. url = malloc (strcspn (pos, "\r\n"));
  1012. if (url == NULL)
  1013. die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n"));
  1014. while (pos) {
  1015. sscanf (pos, "%1[Ll]%*1[Oo]%*1[Cc]%*1[Aa]%*1[Tt]%*1[Ii]%*1[Oo]%*1[Nn]:%n", xx, &i);
  1016. if (i == 0) {
  1017. pos += (size_t) strcspn (pos, "\r\n");
  1018. pos += (size_t) strspn (pos, "\r\n");
  1019. if (strlen(pos) == 0)
  1020. die (STATE_UNKNOWN,
  1021. _("HTTP UNKNOWN - Could not find redirect location - %s%s\n"),
  1022. status_line, (display_html ? "</A>" : ""));
  1023. continue;
  1024. }
  1025. pos += i;
  1026. pos += strspn (pos, " \t");
  1027. /*
  1028. * RFC 2616 (4.2): ``Header fields can be extended over multiple lines by
  1029. * preceding each extra line with at least one SP or HT.''
  1030. */
  1031. for (; (i = strspn (pos, "\r\n")); pos += i) {
  1032. pos += i;
  1033. if (!(i = strspn (pos, " \t"))) {
  1034. die (STATE_UNKNOWN, _("HTTP UNKNOWN - Empty redirect location%s\n"),
  1035. display_html ? "</A>" : "");
  1036. }
  1037. }
  1038. url = realloc (url, strcspn (pos, "\r\n") + 1);
  1039. if (url == NULL)
  1040. die (STATE_UNKNOWN, _("HTTP UNKNOWN - Could not allocate URL\n"));
  1041. /* URI_HTTP, URI_HOST, URI_PORT, URI_PATH */
  1042. if (sscanf (pos, HD1, type, addr, &i, url) == 4) {
  1043. url = prepend_slash (url);
  1044. use_ssl = server_type_check (type);
  1045. }
  1046. /* URI_HTTP URI_HOST URI_PATH */
  1047. else if (sscanf (pos, HD2, type, addr, url) == 3 ) {
  1048. url = prepend_slash (url);
  1049. use_ssl = server_type_check (type);
  1050. i = server_port_check (use_ssl);
  1051. }
  1052. /* URI_HTTP URI_HOST URI_PORT */
  1053. else if (sscanf (pos, HD3, type, addr, &i) == 3) {
  1054. strcpy (url, HTTP_URL);
  1055. use_ssl = server_type_check (type);
  1056. }
  1057. /* URI_HTTP URI_HOST */
  1058. else if (sscanf (pos, HD4, type, addr) == 2) {
  1059. strcpy (url, HTTP_URL);
  1060. use_ssl = server_type_check (type);
  1061. i = server_port_check (use_ssl);
  1062. }
  1063. /* URI_PATH */
  1064. else if (sscanf (pos, HD5, url) == 1) {
  1065. /* relative url */
  1066. if ((url[0] != '/')) {
  1067. if ((x = strrchr(server_url, '/')))
  1068. *x = '\0';
  1069. asprintf (&url, "%s/%s", server_url, url);
  1070. }
  1071. i = server_port;
  1072. strcpy (type, server_type);
  1073. strcpy (addr, host_name ? host_name : server_address);
  1074. }
  1075. else {
  1076. die (STATE_UNKNOWN,
  1077. _("HTTP UNKNOWN - Could not parse redirect location - %s%s\n"),
  1078. pos, (display_html ? "</A>" : ""));
  1079. }
  1080. break;
  1081. } /* end while (pos) */
  1082. if (++redir_depth > max_depth)
  1083. die (STATE_WARNING,
  1084. _("HTTP WARNING - maximum redirection depth %d exceeded - %s://%s:%d%s%s\n"),
  1085. max_depth, type, addr, i, url, (display_html ? "</A>" : ""));
  1086. if (server_port==i &&
  1087. !strcmp(server_address, addr) &&
  1088. (host_name && !strcmp(host_name, addr)) &&
  1089. !strcmp(server_url, url))
  1090. die (STATE_WARNING,
  1091. _("HTTP WARNING - redirection creates an infinite loop - %s://%s:%d%s%s\n"),
  1092. type, addr, i, url, (display_html ? "</A>" : ""));
  1093. strcpy (server_type, type);
  1094. free (host_name);
  1095. host_name = strdup (addr);
  1096. if (!(followsticky & STICKY_HOST)) {
  1097. free (server_address);
  1098. server_address = strdup (addr);
  1099. }
  1100. if (!(followsticky & STICKY_PORT)) {
  1101. server_port = i;
  1102. }
  1103. free (server_url);
  1104. server_url = url;
  1105. if (server_port > MAX_PORT)
  1106. die (STATE_UNKNOWN,
  1107. _("HTTP UNKNOWN - Redirection to port above %d - %s://%s:%d%s%s\n"),
  1108. MAX_PORT, server_type, server_address, server_port, server_url,
  1109. display_html ? "</A>" : "");
  1110. if (verbose)
  1111. printf (_("Redirection to %s://%s:%d%s\n"), server_type,
  1112. host_name ? host_name : server_address, server_port, server_url);
  1113. check_http ();
  1114. }
  1115. int
  1116. server_type_check (const char *type)
  1117. {
  1118. if (strcmp (type, "https"))
  1119. return FALSE;
  1120. else
  1121. return TRUE;
  1122. }
  1123. int
  1124. server_port_check (int ssl_flag)
  1125. {
  1126. if (ssl_flag)
  1127. return HTTPS_PORT;
  1128. else
  1129. return HTTP_PORT;
  1130. }
  1131. char *perfd_time (double elapsed_time)
  1132. {
  1133. return fperfdata ("time", elapsed_time, "s",
  1134. check_warning_time, warning_time,
  1135. check_critical_time, critical_time,
  1136. TRUE, 0, FALSE, 0);
  1137. }
  1138. char *perfd_size (int page_len)
  1139. {
  1140. return perfdata ("size", page_len, "B",
  1141. (min_page_len>0?TRUE:FALSE), min_page_len,
  1142. (min_page_len>0?TRUE:FALSE), 0,
  1143. TRUE, 0, FALSE, 0);
  1144. }
  1145. void
  1146. print_help (void)
  1147. {
  1148. print_revision (progname, NP_VERSION);
  1149. printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
  1150. printf (COPYRIGHT, copyright, email);
  1151. printf ("%s\n", _("This plugin tests the HTTP service on the specified host. It can test"));
  1152. printf ("%s\n", _("normal (http) and secure (https) servers, follow redirects, search for"));
  1153. printf ("%s\n", _("strings and regular expressions, check connection times, and report on"));
  1154. printf ("%s\n", _("certificate expiration times."));
  1155. printf ("\n\n");
  1156. print_usage ();
  1157. printf (_("NOTE: One or both of -H and -I must be specified"));
  1158. printf ("\n");
  1159. printf (UT_HELP_VRSN);
  1160. printf (UT_EXTRA_OPTS);
  1161. printf (" %s\n", "-H, --hostname=ADDRESS");
  1162. printf (" %s\n", _("Host name argument for servers using host headers (virtual host)"));
  1163. printf (" %s\n", _("Append a port to include it in the header (eg: example.com:5000)"));
  1164. printf (" %s\n", "-I, --IP-address=ADDRESS");
  1165. printf (" %s\n", _("IP address or name (use numeric address if possible to bypass DNS lookup)."));
  1166. printf (" %s\n", "-p, --port=INTEGER");
  1167. printf (" %s", _("Port number (default: "));
  1168. printf ("%d)\n", HTTP_PORT);
  1169. printf (UT_IPv46);
  1170. #ifdef HAVE_SSL
  1171. printf (" %s\n", "-S, --ssl");
  1172. printf (" %s\n", _("Connect via SSL. Port defaults to 443"));
  1173. printf (" %s\n", "--sni");
  1174. printf (" %s\n", _("Enable SSL/TLS hostname extension support (SNI)"));
  1175. printf (" %s\n", "-C, --certificate=INTEGER");
  1176. printf (" %s\n", _("Minimum number of days a certificate has to be valid. Port defaults to 443"));
  1177. printf (" %s\n", _("(when this option is used the URL is not checked.)\n"));
  1178. #endif
  1179. printf (" %s\n", "-e, --expect=STRING");
  1180. printf (" %s\n", _("Comma-delimited list of strings, at least one of them is expected in"));
  1181. printf (" %s", _("the first (status) line of the server response (default: "));
  1182. printf ("%s)\n", HTTP_EXPECT);
  1183. printf (" %s\n", _("If specified skips all other status line logic (ex: 3xx, 4xx, 5xx processing)"));
  1184. printf (" %s\n", "-s, --string=STRING");
  1185. printf (" %s\n", _("String to expect in the content"));
  1186. printf (" %s\n", "-u, --url=PATH");
  1187. printf (" %s\n", _("URL to GET or POST (default: /)"));
  1188. printf (" %s\n", "-P, --post=STRING");
  1189. printf (" %s\n", _("URL encoded http POST data"));
  1190. printf (" %s\n", "-j, --method=STRING (for example: HEAD, OPTIONS, TRACE, PUT, DELETE)");
  1191. printf (" %s\n", _("Set HTTP method."));
  1192. printf (" %s\n", "-N, --no-body");
  1193. printf (" %s\n", _("Don't wait for document body: stop reading after headers."));
  1194. printf (" %s\n", _("(Note that this still does an HTTP GET or POST, not a HEAD.)"));
  1195. printf (" %s\n", "-M, --max-age=SECONDS");
  1196. printf (" %s\n", _("Warn if document is more than SECONDS old. the number can also be of"));
  1197. printf (" %s\n", _("the form \"10m\" for minutes, \"10h\" for hours, or \"10d\" for days."));
  1198. printf (" %s\n", "-T, --content-type=STRING");
  1199. printf (" %s\n", _("specify Content-Type header media type when POSTing\n"));
  1200. printf (" %s\n", "-l, --linespan");
  1201. printf (" %s\n", _("Allow regex to span newlines (must precede -r or -R)"));
  1202. printf (" %s\n", "-r, --regex, --ereg=STRING");
  1203. printf (" %s\n", _("Search page for regex STRING"));
  1204. printf (" %s\n", "-R, --eregi=STRING");
  1205. printf (" %s\n", _("Search page for case-insensitive regex STRING"));
  1206. printf (" %s\n", "--invert-regex");
  1207. printf (" %s\n", _("Return CRITICAL if found, OK if not\n"));
  1208. printf (" %s\n", "-a, --authorization=AUTH_PAIR");
  1209. printf (" %s\n", _("Username:password on sites with basic authentication"));
  1210. printf (" %s\n", "-b, --proxy-authorization=AUTH_PAIR");
  1211. printf (" %s\n", _("Username:password on proxy-servers with basic authentication"));
  1212. printf (" %s\n", "-A, --useragent=STRING");
  1213. printf (" %s\n", _("String to be sent in http header as \"User Agent\""));
  1214. printf (" %s\n", "-k, --header=STRING");
  1215. printf (" %s\n", _(" Any other tags to be sent in http header. Use multiple times for additional headers"));
  1216. printf (" %s\n", "-L, --link");
  1217. printf (" %s\n", _("Wrap output in HTML link (obsoleted by urlize)"));
  1218. printf (" %s\n", "-f, --onredirect=<ok|warning|critical|follow|sticky|stickyport>");
  1219. printf (" %s\n", _("How to handle redirected pages. sticky is like follow but stick to the"));
  1220. printf (" %s\n", _("specified IP address. stickyport also ensure post stays the same."));
  1221. printf (" %s\n", "-m, --pagesize=INTEGER<:INTEGER>");
  1222. printf (" %s\n", _("Minimum page size required (bytes) : Maximum page size required (bytes)"));
  1223. printf (UT_WARN_CRIT);
  1224. printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  1225. printf (UT_VERBOSE);
  1226. printf ("\n");
  1227. printf ("%s\n", _("Notes:"));
  1228. printf (" %s\n", _("This plugin will attempt to open an HTTP connection with the host."));
  1229. printf (" %s\n", _("Successful connects return STATE_OK, refusals and timeouts return STATE_CRITICAL"));
  1230. printf (" %s\n", _("other errors return STATE_UNKNOWN. Successful connects, but incorrect reponse"));
  1231. printf (" %s\n", _("messages from the host result in STATE_WARNING return values. If you are"));
  1232. printf (" %s\n", _("checking a virtual server that uses 'host headers' you must supply the FQDN"));
  1233. printf (" %s\n", _("(fully qualified domain name) as the [host_name] argument."));
  1234. #ifdef HAVE_SSL
  1235. printf ("\n");
  1236. printf (" %s\n", _("This plugin can also check whether an SSL enabled web server is able to"));
  1237. printf (" %s\n", _("serve content (optionally within a specified time) or whether the X509 "));
  1238. printf (" %s\n", _("certificate is still valid for the specified number of days."));
  1239. printf ("\n");
  1240. printf ("%s\n", _("Examples:"));
  1241. printf (" %s\n\n", "CHECK CONTENT: check_http -w 5 -c 10 --ssl -H www.verisign.com");
  1242. printf (" %s\n", _("When the 'www.verisign.com' server returns its content within 5 seconds,"));
  1243. printf (" %s\n", _("a STATE_OK will be returned. When the server returns its content but exceeds"));
  1244. printf (" %s\n", _("the 5-second threshold, a STATE_WARNING will be returned. When an error occurs,"));
  1245. printf (" %s\n\n", _("a STATE_CRITICAL will be returned."));
  1246. printf (" %s\n\n", "CHECK CERTIFICATE: check_http -H www.verisign.com -C 14");
  1247. printf (" %s\n", _("When the certificate of 'www.verisign.com' is valid for more than 14 days,"));
  1248. printf (" %s\n", _("a STATE_OK is returned. When the certificate is still valid, but for less than"));
  1249. printf (" %s\n", _("14 days, a STATE_WARNING is returned. A STATE_CRITICAL will be returned when"));
  1250. printf (" %s\n", _("the certificate is expired."));
  1251. #endif
  1252. printf (UT_SUPPORT);
  1253. }
  1254. void
  1255. print_usage (void)
  1256. {
  1257. printf ("%s\n", _("Usage:"));
  1258. printf (" %s -H <vhost> | -I <IP-address> [-u <uri>] [-p <port>]\n",progname);
  1259. printf (" [-w <warn time>] [-c <critical time>] [-t <timeout>] [-L] [-a auth]\n");
  1260. printf (" [-b proxy_auth] [-f <ok|warning|critcal|follow|sticky|stickyport>]\n");
  1261. printf (" [-e <expect>] [-s string] [-l] [-r <regex> | -R <case-insensitive regex>]\n");
  1262. printf (" [-P string] [-m <min_pg_size>:<max_pg_size>] [-4|-6] [-N] [-M <age>]\n");
  1263. printf (" [-A string] [-k string] [-S] [--sni] [-C <age>] [-T <content-type>]\n");
  1264. printf (" [-j method]\n");
  1265. }