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