]> git.ipfire.org Git - thirdparty/squid.git/blob - tools/cachemgr.cc
Merged from trunk
[thirdparty/squid.git] / tools / cachemgr.cc
1 /*
2 * DEBUG: section -- CGI Cache Manager
3 * AUTHOR: Duane Wessels
4 *
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
7 *
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
30 *
31 */
32
33 #include "squid.h"
34 #include "base64.h"
35 #include "getfullhostname.h"
36 #include "html_quote.h"
37 #include "ip/Address.h"
38 #include "rfc1123.h"
39 #include "rfc1738.h"
40 #include "util.h"
41
42 #if HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45 #if HAVE_STDIO_H
46 #include <stdio.h>
47 #endif
48 #if HAVE_CTYPE_H
49 #include <ctype.h>
50 #endif
51 #if HAVE_ERRNO_H
52 #include <errno.h>
53 #endif
54 #if HAVE_FCNTL_H
55 #include <fcntl.h>
56 #endif
57 #if HAVE_GRP_H
58 #include <grp.h>
59 #endif
60 #if HAVE_GNUMALLOC_H
61 #include <gnumalloc.h>
62 #elif HAVE_MALLOC_H
63 #include <malloc.h>
64 #endif
65 #if HAVE_MEMORY_H
66 #include <memory.h>
67 #endif
68 #if HAVE_NETDB_H
69 #include <netdb.h>
70 #endif
71 #if HAVE_PWD_H
72 #include <pwd.h>
73 #endif
74 #if HAVE_SIGNAL_H
75 #include <signal.h>
76 #endif
77 #if HAVE_TIME_H
78 #include <time.h>
79 #endif
80 #if HAVE_SYS_PARAM_H
81 #include <sys/param.h>
82 #endif
83 #if HAVE_SYS_SOCKET_H
84 #include <sys/socket.h>
85 #endif
86 #if HAVE_NETINET_IN_H
87 #include <netinet/in.h>
88 #endif
89 #if HAVE_ARPA_INET_H
90 #include <arpa/inet.h>
91 #endif
92 #if HAVE_SYS_STAT_H
93 #include <sys/stat.h>
94 #endif
95 #if HAVE_SYS_UN_H
96 #include <sys/un.h>
97 #endif
98 #if HAVE_SYS_WAIT_H
99 #include <sys/wait.h>
100 #endif
101 #if HAVE_LIBC_H
102 #include <libc.h>
103 #endif
104 #if HAVE_STRING_H
105 #include <string.h>
106 #endif
107 #if HAVE_STRINGS_H
108 #include <strings.h>
109 #endif
110 #if HAVE_BSTRING_H
111 #include <bstring.h>
112 #endif
113 #if HAVE_CRYPT_H
114 #include <crypt.h>
115 #endif
116 #if HAVE_FNMATCH_H
117 extern "C" {
118 #include <fnmatch.h>
119 }
120 #endif
121
122 #ifndef DEFAULT_CACHEMGR_CONFIG
123 #define DEFAULT_CACHEMGR_CONFIG "/etc/squid/cachemgr.conf"
124 #endif
125
126 typedef struct {
127 char *server;
128 char *hostname;
129 int port;
130 char *action;
131 char *user_name;
132 char *passwd;
133 char *pub_auth;
134 char *workers;
135 char *processes;
136 } cachemgr_request;
137
138 /*
139 * Static variables and constants
140 */
141 static const time_t passwd_ttl = 60 * 60 * 3; /* in sec */
142 static const char *script_name = "/cgi-bin/cachemgr.cgi";
143 static const char *progname = NULL;
144 static time_t now;
145
146 /*
147 * Function prototypes
148 */
149 static const char *safe_str(const char *str);
150 static const char *xstrtok(char **str, char del);
151 static void print_trailer(void);
152 static void auth_html(const char *host, int port, const char *user_name);
153 static void error_html(const char *msg);
154 static char *menu_url(cachemgr_request * req, const char *action);
155 static int parse_status_line(const char *sline, const char **statusStr);
156 static cachemgr_request *read_request(void);
157 static char *read_get_request(void);
158 static char *read_post_request(void);
159
160 static void make_pub_auth(cachemgr_request * req);
161 static void decode_pub_auth(cachemgr_request * req);
162 static void reset_auth(cachemgr_request * req);
163 static const char *make_auth_header(const cachemgr_request * req);
164
165 static int check_target_acl(const char *hostname, int port);
166
167 #if _SQUID_MSWIN_
168 static int s_iInitCount = 0;
169
170 int Win32SockInit(void)
171 {
172 int iVersionRequested;
173 WSADATA wsaData;
174 int err;
175
176 if (s_iInitCount > 0) {
177 ++s_iInitCount;
178 return (0);
179 } else if (s_iInitCount < 0)
180 return (s_iInitCount);
181
182 /* s_iInitCount == 0. Do the initailization */
183 iVersionRequested = MAKEWORD(2, 0);
184
185 err = WSAStartup((WORD) iVersionRequested, &wsaData);
186
187 if (err) {
188 s_iInitCount = -1;
189 return (s_iInitCount);
190 }
191
192 if (LOBYTE(wsaData.wVersion) != 2 ||
193 HIBYTE(wsaData.wVersion) != 0) {
194 s_iInitCount = -2;
195 WSACleanup();
196 return (s_iInitCount);
197 }
198
199 ++s_iInitCount;
200 return (s_iInitCount);
201 }
202
203 void Win32SockCleanup(void)
204 {
205 if (--s_iInitCount == 0)
206 WSACleanup();
207
208 return;
209 }
210
211 #endif
212
213 static const char *
214 safe_str(const char *str)
215 {
216 return str ? str : "";
217 }
218
219 /* relaxed number format */
220 static int
221 is_number(const char *str)
222 {
223 return strspn(str, "\t -+01234567890./\n") == strlen(str);
224 }
225
226 static const char *
227 xstrtok(char **str, char del)
228 {
229 if (*str) {
230 char *p = strchr(*str, del);
231 char *tok = *str;
232 int len;
233
234 if (p) {
235 *str = p + 1;
236 *p = '\0';
237 } else
238 *str = NULL;
239
240 /* trim */
241 len = strlen(tok);
242
243 while (len && xisspace(tok[len - 1]))
244 tok[--len] = '\0';
245
246 while (xisspace(*tok))
247 ++tok;
248
249 return tok;
250 } else
251 return "";
252 }
253
254 static void
255 print_trailer(void)
256 {
257 printf("<HR noshade size=\"1px\">\n");
258 printf("<ADDRESS>\n");
259 printf("Generated %s, by %s/%s@%s\n",
260 mkrfc1123(now), progname, VERSION, getfullhostname());
261 printf("</ADDRESS></BODY></HTML>\n");
262 }
263
264 static void
265 auth_html(const char *host, int port, const char *user_name)
266 {
267 FILE *fp;
268 int need_host = 1;
269
270 if (!user_name)
271 user_name = "";
272
273 if (!host || !strlen(host))
274 host = "";
275
276 fp = fopen("cachemgr.conf", "r");
277
278 if (fp == NULL)
279 fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r");
280
281 if (fp == NULL)
282 printf("X-Error: message=\"Unable to open config %s\"", DEFAULT_CACHEMGR_CONFIG);
283
284 printf("Content-Type: text/html\r\n\r\n");
285
286 printf("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
287
288 printf("<HTML><HEAD><TITLE>Cache Manager Interface</TITLE>\n");
289
290 printf("<STYLE type=\"text/css\"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}--></STYLE>\n");
291
292 printf("<script type=\"text/javascript\">\n");
293 printf("function TS(t, s) {\n");
294 printf(" var x = new XMLHttpRequest();\n");
295 printf(" x.open('GET', 'http' + s + '://' + t + '/squid-internal-mgr/', true);\n");
296 printf(" x.onreadystatechange=function() {\n");
297 printf(" if (x.readyState==4) {\n");
298 printf(" if ((x.status>=200 && x.status <= 299) || x.status==401) {\n");
299 printf(" var v = x.getResponseHeader('Server');\n");
300 printf(" if (v.substring(0,8) == 'squid/3.' && (v[8]=='H' || parseInt(v.substring(8)) >= 2)) {\n");
301 printf(" var d = document.getElementById('H' + s + 'mgr');\n");
302 printf(" if (d.innerHTML == '') d.innerHTML = '<h2>HTTP' + (s=='s'?'S':'') + ' Managed Proxies</h2>';\n");
303 printf(" d.innerHTML = d.innerHTML + '<p>Host: <a href=\"http' + s + '://' + t + '/squid-internal-mgr/\">' + t + '</a></p>';\n");
304 printf(" }}}}\n");
305 printf(" x.send(null);\n");
306 printf("}\n");
307 printf("</script>\n");
308
309 printf("</HEAD>\n");
310
311 printf("<BODY><H1>Cache Manager Interface</H1>\n");
312
313 printf("<P>This is a WWW interface to the instrumentation interface\n");
314
315 printf("for the Squid object cache.</P>\n");
316
317 printf("<HR noshade size=\"1px\">\n");
318
319 printf("<div id=\"Hsmgr\"></div>\n");
320 printf("<div id=\"Hmgr\"></div>\n");
321 printf("<div id=\"Cmgr\">\n");
322 printf("<h2>CGI Managed Proxies</h2>\n");
323 printf("<FORM METHOD=\"POST\" ACTION=\"%s\">\n", script_name);
324
325 printf("<TABLE BORDER=\"0\" CELLPADDING=\"10\" CELLSPACING=\"1\">\n");
326
327 if (fp != NULL) {
328 int servers = 0;
329 char config_line[BUFSIZ];
330
331 while (fgets(config_line, BUFSIZ, fp)) {
332 char *server, *comment;
333 strtok(config_line, "\r\n");
334
335 if (config_line[0] == '#')
336 continue;
337
338 if (config_line[0] == '\0')
339 continue;
340
341 if ((server = strtok(config_line, " \t")) == NULL)
342 continue;
343
344 if (strchr(server, '*') || strchr(server, '[') || strchr(server, '?')) {
345 need_host = -1;
346 continue;
347 }
348
349 comment = strtok(NULL, "");
350
351 if (comment)
352 while (*comment == ' ' || *comment == '\t')
353 ++comment;
354
355 if (!comment || !*comment)
356 comment = server;
357
358 if (!servers)
359 printf("<TR><TH ALIGN=\"left\">Cache Server:</TH><TD><SELECT id=\"server\" NAME=\"server\">\n");
360
361 printf("<OPTION VALUE=\"%s\"%s>%s</OPTION>\n", server, (servers || *host) ? "" : " SELECTED", comment);
362 ++servers;
363 }
364
365 if (servers) {
366 if (need_host == 1 && !*host)
367 need_host = 0;
368
369 if (need_host)
370 printf("<OPTION VALUE=\"\"%s>Other</OPTION>\n", (*host) ? " SELECTED" : "");
371
372 printf("</SELECT></TR>\n");
373 }
374
375 fclose(fp);
376 }
377
378 if (need_host) {
379 if (need_host == 1 && !*host)
380 host = "localhost";
381
382 printf("<TR><TH ALIGN=\"left\">Cache Host:</TH><TD><INPUT NAME=\"host\" ");
383
384 printf("size=\"30\" VALUE=\"%s\"></TD></TR>\n", host);
385
386 printf("<TR><TH ALIGN=\"left\">Cache Port:</TH><TD><INPUT NAME=\"port\" ");
387
388 printf("size=\"30\" VALUE=\"%d\"></TD></TR>\n", port);
389 }
390
391 printf("<TR><TH ALIGN=\"left\">Manager name:</TH><TD><INPUT NAME=\"user_name\" ");
392
393 printf("size=\"30\" VALUE=\"%s\"></TD></TR>\n", user_name);
394
395 printf("<TR><TH ALIGN=\"left\">Password:</TH><TD><INPUT TYPE=\"password\" NAME=\"passwd\" ");
396
397 printf("size=\"30\" VALUE=\"\"></TD></TR>\n");
398
399 printf("</TABLE><BR CLEAR=\"all\">\n");
400
401 printf("<INPUT TYPE=\"submit\" VALUE=\"Continue...\">\n");
402
403 printf("</FORM></div>\n");
404
405 printf("<script type=\"text/javascript\">\n");
406 printf("var s = document.getElementById(\"server\");\n");
407 printf("for (var i = 0; i < s.childElementCount; i++) {\n");
408 printf(" TS(s.children[i].value, '');\n");
409 printf(" TS(s.children[i].value, 's');\n");
410 printf("}</script>\n");
411
412 print_trailer();
413 }
414
415 static void
416 error_html(const char *msg)
417 {
418 printf("Content-Type: text/html\r\n\r\n");
419 printf("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
420 printf("<HTML><HEAD><TITLE>Cache Manager Error</TITLE>\n");
421 printf("<STYLE type=\"text/css\"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}--></STYLE></HEAD>\n");
422 printf("<BODY><H1>Cache Manager Error</H1>\n");
423 printf("<P>\n%s</P>\n", html_quote(msg));
424 print_trailer();
425 }
426
427 /* returns http status extracted from status line or -1 on parsing failure */
428 static int
429 parse_status_line(const char *sline, const char **statusStr)
430 {
431 const char *sp = strchr(sline, ' ');
432
433 if (statusStr)
434 *statusStr = NULL;
435
436 if (strncasecmp(sline, "HTTP/", 5) || !sp)
437 return -1;
438
439 while (xisspace(*++sp));
440 if (!xisdigit(*sp))
441 return -1;
442
443 if (statusStr)
444 *statusStr = sp;
445
446 return atoi(sp);
447 }
448
449 static char *
450 menu_url(cachemgr_request * req, const char *action)
451 {
452 static char url[1024];
453 snprintf(url, sizeof(url), "%s?host=%s&port=%d&user_name=%s&operation=%s&auth=%s",
454 script_name,
455 req->hostname,
456 req->port,
457 safe_str(req->user_name),
458 action,
459 safe_str(req->pub_auth));
460 return url;
461 }
462
463 static const char *
464 munge_menu_line(const char *buf, cachemgr_request * req)
465 {
466 char *x;
467 const char *a;
468 const char *d;
469 const char *p;
470 char *a_url;
471 char *buf_copy;
472 static char html[2 * 1024];
473
474 if (strlen(buf) < 1)
475 return buf;
476
477 if (*buf != ' ')
478 return buf;
479
480 buf_copy = x = xstrdup(buf);
481
482 a = xstrtok(&x, '\t');
483
484 d = xstrtok(&x, '\t');
485
486 p = xstrtok(&x, '\t');
487
488 a_url = xstrdup(menu_url(req, a));
489
490 /* no reason to give a url for a disabled action */
491 if (!strcmp(p, "disabled"))
492 snprintf(html, sizeof(html), "<LI type=\"circle\">%s (disabled)<A HREF=\"%s\">.</A>\n", d, a_url);
493 else
494 /* disable a hidden action (requires a password, but password is not in squid.conf) */
495 if (!strcmp(p, "hidden"))
496 snprintf(html, sizeof(html), "<LI type=\"circle\">%s (hidden)<A HREF=\"%s\">.</A>\n", d, a_url);
497 else
498 /* disable link if authentication is required and we have no password */
499 if (!strcmp(p, "protected") && !req->passwd)
500 snprintf(html, sizeof(html), "<LI type=\"circle\">%s (requires <a href=\"%s\">authentication</a>)<A HREF=\"%s\">.</A>\n",
501 d, menu_url(req, "authenticate"), a_url);
502 else
503 /* highlight protected but probably available entries */
504 if (!strcmp(p, "protected"))
505 snprintf(html, sizeof(html), "<LI type=\"square\"><A HREF=\"%s\"><font color=\"#FF0000\">%s</font></A>\n",
506 a_url, d);
507
508 /* public entry or unknown type of protection */
509 else
510 snprintf(html, sizeof(html), "<LI type=\"disk\"><A HREF=\"%s\">%s</A>\n", a_url, d);
511
512 xfree(a_url);
513
514 xfree(buf_copy);
515
516 return html;
517 }
518
519 static const char *
520 munge_other_line(const char *buf, cachemgr_request * req)
521 {
522 static const char *ttags[] = {"td", "th"};
523
524 static char html[4096];
525 static int table_line_num = 0;
526 static int next_is_header = 0;
527 int is_header = 0;
528 const char *ttag;
529 char *buf_copy;
530 char *x, *p;
531 int l = 0;
532 /* does it look like a table? */
533
534 if (!strchr(buf, '\t') || *buf == '\t') {
535 /* nope, just text */
536 snprintf(html, sizeof(html), "%s%s",
537 table_line_num ? "</table>\n<pre>" : "", html_quote(buf));
538 table_line_num = 0;
539 return html;
540 }
541
542 /* start html table */
543 if (!table_line_num) {
544 l += snprintf(html + l, sizeof(html) - l, "</pre><table cellpadding=\"2\" cellspacing=\"1\">\n");
545 next_is_header = 0;
546 }
547
548 /* remove '\n' */
549 is_header = (!table_line_num || next_is_header) && !strchr(buf, ':') && !is_number(buf);
550
551 ttag = ttags[is_header];
552
553 /* record starts */
554 l += snprintf(html + l, sizeof(html) - l, "<tr>");
555
556 /* substitute '\t' */
557 buf_copy = x = xstrdup(buf);
558
559 if ((p = strchr(x, '\n')))
560 *p = '\0';
561
562 while (x && strlen(x)) {
563 int column_span = 1;
564 const char *cell = xstrtok(&x, '\t');
565
566 while (x && *x == '\t') {
567 ++column_span;
568 ++x;
569 }
570
571 l += snprintf(html + l, sizeof(html) - l, "<%s colspan=\"%d\" align=\"%s\">%s</%s>",
572 ttag, column_span,
573 is_header ? "center" : is_number(cell) ? "right" : "left",
574 html_quote(cell), ttag);
575 }
576
577 xfree(buf_copy);
578 /* record ends */
579 snprintf(html + l, sizeof(html) - l, "</tr>\n");
580 next_is_header = is_header && strstr(buf, "\t\t");
581 ++table_line_num;
582 return html;
583 }
584
585 static const char *
586 munge_action_line(const char *_buf, cachemgr_request * req)
587 {
588 static char html[2 * 1024];
589 char *buf = xstrdup(_buf);
590 char *x = buf;
591 const char *action, *description;
592 char *p;
593
594 if ((p = strchr(x, '\n')))
595 *p = '\0';
596 action = xstrtok(&x, '\t');
597 description = xstrtok(&x, '\t');
598 if (!description)
599 description = action;
600 if (!action)
601 return "";
602 snprintf(html, sizeof(html), " <a href=\"%s\">%s</a>", menu_url(req, action), description);
603 return html;
604 }
605
606 static int
607 read_reply(int s, cachemgr_request * req)
608 {
609 char buf[4 * 1024];
610 #if _SQUID_MSWIN_
611
612 int reply;
613 char *tmpfile = tempnam(NULL, "tmp0000");
614 FILE *fp = fopen(tmpfile, "w+");
615 #else
616
617 FILE *fp = fdopen(s, "r");
618 #endif
619 /* interpretation states */
620 enum {
621 isStatusLine, isHeaders, isActions, isBodyStart, isBody, isForward, isEof, isForwardEof, isSuccess, isError
622 } istate = isStatusLine;
623 int parse_menu = 0;
624 const char *action = req->action;
625 const char *statusStr = NULL;
626 int status = -1;
627
628 if (0 == strlen(req->action))
629 parse_menu = 1;
630 else if (0 == strcasecmp(req->action, "menu"))
631 parse_menu = 1;
632
633 if (fp == NULL) {
634 #if _SQUID_MSWIN_
635 perror(tmpfile);
636 xfree(tmpfile);
637 #else
638
639 perror("fdopen");
640 #endif
641
642 close(s);
643 return 1;
644 }
645
646 #if _SQUID_MSWIN_
647
648 while ((reply=recv(s, buf , sizeof(buf), 0)) > 0)
649 fwrite(buf, 1, reply, fp);
650
651 rewind(fp);
652
653 #endif
654
655 if (parse_menu)
656 action = "menu";
657
658 /* read reply interpreting one line at a time depending on state */
659 while (istate < isEof) {
660 if (!fgets(buf, sizeof(buf), fp))
661 istate = istate == isForward ? isForwardEof : isEof;
662
663 switch (istate) {
664
665 case isStatusLine:
666 /* get HTTP status */
667 /* uncomment the following if you want to debug headers */
668 /* fputs("\r\n\r\n", stdout); */
669 status = parse_status_line(buf, &statusStr);
670 istate = status == 200 ? isHeaders : isForward;
671 /* if cache asks for authentication, we have to reset our info */
672
673 if (status == 401 || status == 407) {
674 reset_auth(req);
675 status = 403; /* Forbiden, see comments in case isForward: */
676 }
677
678 /* this is a way to pass HTTP status to the Web server */
679 if (statusStr)
680 printf("Status: %d %s", status, statusStr); /* statusStr has '\n' */
681
682 break;
683
684 case isHeaders:
685 /* forward header field */
686 if (!strcmp(buf, "\r\n")) { /* end of headers */
687 fputs("Content-Type: text/html\r\n", stdout); /* add our type */
688 istate = isBodyStart;
689 }
690
691 if (strncasecmp(buf, "Content-Type:", 13)) /* filter out their type */
692 fputs(buf, stdout);
693
694 break;
695
696 case isBodyStart:
697 printf("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
698
699 printf("<HTML><HEAD><TITLE>CacheMgr@%s: %s</TITLE>\n",
700 req->hostname, action);
701
702 printf("<STYLE type=\"text/css\"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}TABLE{background-color:#333333;border:0pt;padding:0pt}TH,TD{background-color:#ffffff;white-space:nowrap}--></STYLE>\n");
703
704 printf("</HEAD><BODY>\n");
705
706 if (parse_menu) {
707 printf("<H2><a href=\"%s\">Cache Manager</a> menu for %s:</H2>",
708 menu_url(req, "authenticate"), req->hostname);
709 printf("<UL>\n");
710 } else {
711 printf("<P><A HREF=\"%s\">%s</A>\n<HR noshade size=\"1px\">\n",
712 menu_url(req, "menu"), "Cache Manager menu");
713 printf("<PRE>\n");
714 }
715
716 istate = isActions;
717 /* yes, fall through, we do not want to loose the first line */
718
719 case isActions:
720 if (strncmp(buf, "action:", 7) == 0) {
721 fputs(" ", stdout);
722 fputs(munge_action_line(buf + 7, req), stdout);
723 break;
724 }
725 if (parse_menu) {
726 printf("<UL>\n");
727 } else {
728 printf("<HR noshade size=\"1px\">\n");
729 printf("<PRE>\n");
730 }
731
732 istate = isBody;
733 /* yes, fall through, we do not want to loose the first line */
734
735 case isBody:
736 /* interpret [and reformat] cache response */
737
738 if (parse_menu)
739 fputs(munge_menu_line(buf, req), stdout);
740 else
741 fputs(munge_other_line(buf, req), stdout);
742
743 break;
744
745 case isForward:
746 /* forward: no modifications allowed */
747 /*
748 * Note: we currently do not know any way to get browser.reply to
749 * 401 to .cgi because web server filters out all auth info. Thus we
750 * disable authentication headers for now.
751 */
752 if (!strncasecmp(buf, "WWW-Authenticate:", 17) || !strncasecmp(buf, "Proxy-Authenticate:", 19)); /* skip */
753 else
754 fputs(buf, stdout);
755
756 break;
757
758 case isEof:
759 /* print trailers */
760 if (parse_menu)
761 printf("</UL>\n");
762 else
763 printf("</table></PRE>\n");
764
765 print_trailer();
766
767 istate = isSuccess;
768
769 break;
770
771 case isForwardEof:
772 /* indicate that we finished processing an "error" sequence */
773 istate = isError;
774
775 break;
776
777 default:
778 printf("%s: internal bug: invalid state reached: %d", script_name, istate);
779
780 istate = isError;
781 }
782 }
783
784 fclose(fp);
785 #if _SQUID_MSWIN_
786
787 remove(tmpfile);
788 xfree(tmpfile);
789 close(s);
790
791 #endif
792
793 return 0;
794 }
795
796 static int
797 process_request(cachemgr_request * req)
798 {
799
800 char ipbuf[MAX_IPSTRLEN];
801 struct addrinfo *AI = NULL;
802 Ip::Address S;
803 int s;
804 int l;
805
806 static char buf[2 * 1024];
807
808 if (req == NULL) {
809 auth_html(CACHEMGR_HOSTNAME, CACHE_HTTP_PORT, "");
810 return 1;
811 }
812
813 if (req->hostname == NULL) {
814 req->hostname = xstrdup(CACHEMGR_HOSTNAME);
815 }
816
817 if (req->port == 0) {
818 req->port = CACHE_HTTP_PORT;
819 }
820
821 if (req->action == NULL) {
822 req->action = xstrdup("");
823 }
824
825 if (strcmp(req->action, "authenticate") == 0) {
826 auth_html(req->hostname, req->port, req->user_name);
827 return 0;
828 }
829
830 if (!check_target_acl(req->hostname, req->port)) {
831 snprintf(buf, 1024, "target %s:%d not allowed in cachemgr.conf\n", req->hostname, req->port);
832 error_html(buf);
833 return 1;
834 }
835
836 S = *gethostbyname(req->hostname);
837
838 if ( !S.IsAnyAddr() ) {
839 (void) 0;
840 } else if ((S = req->hostname))
841 (void) 0;
842 else {
843 snprintf(buf, 1024, "Unknown host: %s\n", req->hostname);
844 error_html(buf);
845 return 1;
846 }
847
848 S.SetPort(req->port);
849
850 S.GetAddrInfo(AI);
851
852 #if USE_IPV6
853 if ((s = socket( AI->ai_family, SOCK_STREAM, 0)) < 0) {
854 #else
855 if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
856 #endif
857 snprintf(buf, 1024, "socket: %s\n", xstrerror());
858 error_html(buf);
859 return 1;
860 }
861
862 if (connect(s, AI->ai_addr, AI->ai_addrlen) < 0) {
863 snprintf(buf, 1024, "connect %s: %s\n",
864 S.ToURL(ipbuf,MAX_IPSTRLEN),
865 xstrerror());
866 error_html(buf);
867 S.FreeAddrInfo(AI);
868 return 1;
869 }
870
871 S.FreeAddrInfo(AI);
872
873 l = snprintf(buf, sizeof(buf),
874 "GET cache_object://%s/%s%s%s HTTP/1.0\r\n"
875 "User-Agent: cachemgr.cgi/%s\r\n"
876 "Accept: */*\r\n"
877 "%s" /* Authentication info or nothing */
878 "\r\n",
879 req->hostname,
880 req->action,
881 req->workers? "?workers=" : (req->processes ? "?processes=" : ""),
882 req->workers? req->workers : (req->processes ? req->processes: ""),
883 VERSION,
884 make_auth_header(req));
885 if (write(s, buf, l) < 0) {
886 fprintf(stderr,"ERROR: (%d) writing request: '%s'\n", errno, buf);
887 } else {
888 debug("wrote request: '%s'\n", buf);
889 }
890 return read_reply(s, req);
891 }
892
893 int
894 main(int argc, char *argv[])
895 {
896 char *s;
897 cachemgr_request *req;
898
899 now = time(NULL);
900 #if _SQUID_MSWIN_
901
902 Win32SockInit();
903 atexit(Win32SockCleanup);
904 _setmode( _fileno( stdin ), _O_BINARY );
905 _setmode( _fileno( stdout ), _O_BINARY );
906 _fmode = _O_BINARY;
907
908 if ((s = strrchr(argv[0], '\\')))
909 #else
910
911 if ((s = strrchr(argv[0], '/')))
912 #endif
913
914 progname = xstrdup(s + 1);
915 else
916 progname = xstrdup(argv[0]);
917
918 if ((s = getenv("SCRIPT_NAME")) != NULL)
919 script_name = xstrdup(s);
920
921 char **args = argv;
922 while (argc > 1 && args[1][0] == '-') {
923 // const char *value = "";
924 char option = args[1][1];
925 switch (option) {
926 case 'd':
927 debug_enabled = 1;
928 break;
929 default:
930 #if 0 // unused for now.
931 if (strlen(args[1]) > 2) {
932 value = args[1] + 2;
933 } else if (argc > 2) {
934 value = args[2];
935 ++args;
936 --argc;
937 } else
938 value = "";
939 #endif
940 break;
941 }
942 ++args;
943 --argc;
944 }
945
946 req = read_request();
947
948 return process_request(req);
949 }
950
951 static char *
952 read_post_request(void)
953 {
954 char *s;
955 char *buf;
956 int len;
957
958 if ((s = getenv("REQUEST_METHOD")) == NULL)
959 return NULL;
960
961 if (0 != strcasecmp(s, "POST"))
962 return NULL;
963
964 if ((s = getenv("CONTENT_LENGTH")) == NULL)
965 return NULL;
966
967 if ((len = atoi(s)) <= 0)
968 return NULL;
969
970 buf = (char *)xmalloc(len + 1);
971
972 if (fread(buf, len, 1, stdin) == 0)
973 return NULL;
974
975 buf[len] = '\0';
976
977 return buf;
978 }
979
980 static char *
981 read_get_request(void)
982 {
983 char *s;
984
985 if ((s = getenv("QUERY_STRING")) == NULL)
986 return NULL;
987
988 return xstrdup(s);
989 }
990
991 static cachemgr_request *
992 read_request(void)
993 {
994 char *buf;
995
996 cachemgr_request *req;
997 char *s;
998 char *t;
999 char *q;
1000
1001 if ((buf = read_post_request()) != NULL)
1002 (void) 0;
1003 else if ((buf = read_get_request()) != NULL)
1004 (void) 0;
1005 else
1006 return NULL;
1007
1008 #if _SQUID_MSWIN_
1009
1010 if (strlen(buf) == 0 || strlen(buf) == 4000)
1011 #else
1012
1013 if (strlen(buf) == 0)
1014 #endif
1015 {
1016 xfree(buf);
1017 return NULL;
1018 }
1019
1020 req = (cachemgr_request *)xcalloc(1, sizeof(cachemgr_request));
1021
1022 for (s = strtok(buf, "&"); s != NULL; s = strtok(NULL, "&")) {
1023 t = xstrdup(s);
1024
1025 if ((q = strchr(t, '=')) == NULL)
1026 continue;
1027
1028 *q = '\0';
1029 ++q;
1030
1031 rfc1738_unescape(t);
1032
1033 rfc1738_unescape(q);
1034
1035 if (0 == strcasecmp(t, "server") && strlen(q))
1036 req->server = xstrdup(q);
1037 else if (0 == strcasecmp(t, "host") && strlen(q))
1038 req->hostname = xstrdup(q);
1039 else if (0 == strcasecmp(t, "port") && strlen(q))
1040 req->port = atoi(q);
1041 else if (0 == strcasecmp(t, "user_name") && strlen(q))
1042 req->user_name = xstrdup(q);
1043 else if (0 == strcasecmp(t, "passwd") && strlen(q))
1044 req->passwd = xstrdup(q);
1045 else if (0 == strcasecmp(t, "auth") && strlen(q))
1046 req->pub_auth = xstrdup(q), decode_pub_auth(req);
1047 else if (0 == strcasecmp(t, "operation"))
1048 req->action = xstrdup(q);
1049 else if (0 == strcasecmp(t, "workers") && strlen(q))
1050 req->workers = xstrdup(q);
1051 else if (0 == strcasecmp(t, "processes") && strlen(q))
1052 req->processes = xstrdup(q);
1053 }
1054
1055 if (req->server && !req->hostname) {
1056 char *p;
1057 req->hostname = strtok(req->server, ":");
1058
1059 if ((p = strtok(NULL, ":")))
1060 req->port = atoi(p);
1061 }
1062
1063 make_pub_auth(req);
1064 debug("cmgr: got req: host: '%s' port: %d uname: '%s' passwd: '%s' auth: '%s' oper: '%s' workers: '%s' processes: '%s'\n",
1065 safe_str(req->hostname), req->port, safe_str(req->user_name), safe_str(req->passwd), safe_str(req->pub_auth), safe_str(req->action), safe_str(req->workers), safe_str(req->processes));
1066 return req;
1067 }
1068
1069 /* Routines to support authentication */
1070
1071 /*
1072 * Encodes auth info into a "public" form.
1073 * Currently no powerful encryption is used.
1074 */
1075 static void
1076 make_pub_auth(cachemgr_request * req)
1077 {
1078 static char buf[1024];
1079 safe_free(req->pub_auth);
1080 debug("cmgr: encoding for pub...\n");
1081
1082 if (!req->passwd || !strlen(req->passwd))
1083 return;
1084
1085 /* host | time | user | passwd */
1086 const int bufLen = snprintf(buf, sizeof(buf), "%s|%d|%s|%s",
1087 req->hostname,
1088 (int) now,
1089 req->user_name ? req->user_name : "",
1090 req->passwd);
1091 debug("cmgr: pre-encoded for pub: %s\n", buf);
1092
1093 const int encodedLen = base64_encode_len(bufLen);
1094 req->pub_auth = (char *) xmalloc(encodedLen);
1095 base64_encode_str(req->pub_auth, encodedLen, buf, bufLen);
1096 debug("cmgr: encoded: '%s'\n", req->pub_auth);
1097 }
1098
1099 static void
1100 decode_pub_auth(cachemgr_request * req)
1101 {
1102 char *buf;
1103 const char *host_name;
1104 const char *time_str;
1105 const char *user_name;
1106 const char *passwd;
1107
1108 debug("cmgr: decoding pub: '%s'\n", safe_str(req->pub_auth));
1109 safe_free(req->passwd);
1110
1111 if (!req->pub_auth || strlen(req->pub_auth) < 4 + strlen(safe_str(req->hostname)))
1112 return;
1113
1114 const int decodedLen = base64_decode_len(req->pub_auth);
1115 buf = (char*)xmalloc(decodedLen);
1116 base64_decode(buf, decodedLen, req->pub_auth);
1117
1118 debug("cmgr: length ok\n");
1119
1120 /* parse ( a lot of memory leaks, but that is cachemgr style :) */
1121 if ((host_name = strtok(buf, "|")) == NULL)
1122 return;
1123
1124 debug("cmgr: decoded host: '%s'\n", host_name);
1125
1126 if ((time_str = strtok(NULL, "|")) == NULL)
1127 return;
1128
1129 debug("cmgr: decoded time: '%s' (now: %d)\n", time_str, (int) now);
1130
1131 if ((user_name = strtok(NULL, "|")) == NULL)
1132 return;
1133
1134 debug("cmgr: decoded uname: '%s'\n", user_name);
1135
1136 if ((passwd = strtok(NULL, "|")) == NULL)
1137 return;
1138
1139 debug("cmgr: decoded passwd: '%s'\n", passwd);
1140
1141 /* verify freshness and validity */
1142 if (atoi(time_str) + passwd_ttl < now)
1143 return;
1144
1145 if (strcasecmp(host_name, req->hostname))
1146 return;
1147
1148 debug("cmgr: verified auth. info.\n");
1149
1150 /* ok, accept */
1151 xfree(req->user_name);
1152
1153 req->user_name = xstrdup(user_name);
1154
1155 req->passwd = xstrdup(passwd);
1156
1157 xfree(buf);
1158 }
1159
1160 static void
1161 reset_auth(cachemgr_request * req)
1162 {
1163 safe_free(req->passwd);
1164 safe_free(req->pub_auth);
1165 }
1166
1167 static const char *
1168 make_auth_header(const cachemgr_request * req)
1169 {
1170 static char buf[1024];
1171 size_t stringLength = 0;
1172
1173 if (!req->passwd)
1174 return "";
1175
1176 int bufLen = snprintf(buf, sizeof(buf), "%s:%s",
1177 req->user_name ? req->user_name : "",
1178 req->passwd);
1179
1180 int encodedLen = base64_encode_len(bufLen);
1181 if (encodedLen <= 0)
1182 return "";
1183
1184 char *str64 = static_cast<char*>(xmalloc(encodedLen));
1185 base64_encode_str(str64, encodedLen, buf, bufLen);
1186
1187 stringLength += snprintf(buf, sizeof(buf), "Authorization: Basic %s\r\n", str64);
1188
1189 assert(stringLength < sizeof(buf));
1190
1191 snprintf(&buf[stringLength], sizeof(buf) - stringLength, "Proxy-Authorization: Basic %s\r\n", str64);
1192
1193 return buf;
1194 }
1195
1196 static int
1197 check_target_acl(const char *hostname, int port)
1198 {
1199 char config_line[BUFSIZ];
1200 FILE *fp = NULL;
1201 int ret = 0;
1202 fp = fopen("cachemgr.conf", "r");
1203
1204 if (fp == NULL)
1205 fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r");
1206
1207 if (fp == NULL) {
1208 #ifdef CACHEMGR_HOSTNAME_DEFINED
1209
1210 if (strcmp(hostname, CACHEMGR_HOSTNAME) == 0 && port == CACHE_HTTP_PORT)
1211 return 1;
1212
1213 #else
1214
1215 if (strcmp(hostname, "localhost") == 0)
1216 return 1;
1217
1218 if (strcmp(hostname, getfullhostname()) == 0)
1219 return 1;
1220
1221 #endif
1222
1223 return 0;
1224 }
1225
1226 while (fgets(config_line, BUFSIZ, fp)) {
1227 char *token = NULL;
1228 strtok(config_line, " \r\n\t");
1229
1230 if (config_line[0] == '#')
1231 continue;
1232
1233 if (config_line[0] == '\0')
1234 continue;
1235
1236 if ((token = strtok(config_line, ":")) == NULL)
1237 continue;
1238
1239 #if HAVE_FNMATCH_H
1240
1241 if (fnmatch(token, hostname, 0) != 0)
1242 continue;
1243
1244 #else
1245
1246 if (strcmp(token, hostname) != 0)
1247 continue;
1248
1249 #endif
1250
1251 if ((token = strtok(NULL, ":")) != NULL) {
1252 int i;
1253
1254 if (strcmp(token, "*") == 0)
1255
1256 ; /* Wildcard port specification */
1257 else if (strcasecmp(token, "any") == 0)
1258
1259 ; /* Wildcard port specification */
1260 else if (sscanf(token, "%d", &i) != 1)
1261 continue;
1262
1263 else if (i != port)
1264 continue;
1265 } else if (port != CACHE_HTTP_PORT)
1266 continue;
1267
1268 ret = 1;
1269
1270 break;
1271 }
1272
1273 fclose(fp);
1274 return ret;
1275 }