1 const char cgi_rcs[] = "$Id: cgi.c,v 1.6 2001/06/07 23:05:19 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/cgi.c,v $
6 * Purpose : Declares functions to intercept request, generate
7 * html or gif answers, and to compose HTTP resonses.
9 * Functions declared include:
12 * Copyright : Written by and Copyright (C) 2001 the SourceForge
13 * IJBSWA team. http://ijbswa.sourceforge.net
15 * Based on the Internet Junkbuster originally written
16 * by and Copyright (C) 1997 Anonymous Coders and
17 * Junkbusters Corporation. http://www.junkbusters.com
19 * This program is free software; you can redistribute it
20 * and/or modify it under the terms of the GNU General
21 * Public License as published by the Free Software
22 * Foundation; either version 2 of the License, or (at
23 * your option) any later version.
25 * This program is distributed in the hope that it will
26 * be useful, but WITHOUT ANY WARRANTY; without even the
27 * implied warranty of MERCHANTABILITY or FITNESS FOR A
28 * PARTICULAR PURPOSE. See the GNU General Public
29 * License for more details.
31 * The GNU General Public License should be included with
32 * this file. If not, you can view it at
33 * http://www.gnu.org/copyleft/gpl.html
34 * or write to the Free Software Foundation, Inc., 59
35 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39 * Revision 1.6 2001/06/07 23:05:19 jongfoster
40 * Removing code related to old forward and ACL files.
42 * Revision 1.5 2001/06/05 19:59:16 jongfoster
43 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
45 * Revision 1.4 2001/06/04 10:41:52 swa
46 * show version string of cgi.h and cgi.c
48 * Revision 1.3 2001/06/03 19:12:16 oes
49 * introduced new cgi handling
51 * Revision 1.1 2001/06/03 11:03:48 oes
58 * adapted to new enlist_unique arg format
62 * introduced confdir option
64 * filters.c filtrers.h
66 * extracted-CGI relevant stuff
74 * support for new cgi mechansim
78 * functions for new list type: "map"
79 * extended enlist_unique
86 * deleted const struct interceptors
94 * added struct http_response
95 * changes struct interceptors to struct cgi_dispatcher
96 * moved HTML stuff to cgi.h
107 **********************************************************************/
113 #include <sys/types.h>
119 #define snprintf _snprintf
120 #endif /* def _WIN32 */
132 #include "miscutil.h"
133 #include "showargs.h"
135 const char cgi_h_rcs[] = CGI_H_VERSION;
137 const struct cgi_dispatcher cgi_dispatchers[] = {
140 "Show information about the version and configuration" },
142 13, cgi_show_url_info,
143 "Show which actions apply to a URL and why" },
146 "HIDE Send the transparent or \"Junkbuster\" gif" },
148 /* { "untrusted-url",
149 15, ij_untrusted_url,
150 "HIDE Show why a URL was not trusted" }, */
151 #endif /* def TRUST_FILES */
154 "HIDE Send a page linking to all unhidden CGIs" },
155 { NULL, 0, NULL, NULL }
159 /*********************************************************************
161 * Function : dispatch_cgi
163 * Description : Checks if a request URL has either the magical hostname
164 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
165 * the (rest of the) path as a cgi name plus query string,
166 * prepares a map that maps CGI parameter names to their values,
167 * initializes the http_response struct, and calls the
168 * relevant CGI handler function.
171 * 1 : csp = Current client state (buffers, headers, etc...)
173 * Returns : http_response if match, NULL if nonmatch or handler fail
175 *********************************************************************/
176 struct http_response *cgi_dispatch(struct client_state *csp)
178 char *argstring = NULL;
179 const struct cgi_dispatcher *d;
180 struct map *param_list;
181 struct http_response *response;
184 * Should we intercept ?
187 /* Either the host matches CGI_PREFIX_HOST ..*/
188 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
190 /* ..then the path will all be for us */
191 argstring = csp->http->path;
193 /* Or it's the host part of HOME_PAGE_URL ? */
194 else if ( (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
195 && (0 == strncmpic(csp->http->path,"/config", 7))
196 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
198 /* then it's everything following "/config" */
199 argstring = csp->http->path + 7;
207 * We have intercepted it.
210 /* Get mem for response */
211 if (NULL == ( response = zalloc(sizeof(*response))))
216 /* remove any leading slash */
217 if (*argstring == '/')
222 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
223 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
224 csp->ip_addr_str, csp->http->cmd);
226 for (d = cgi_dispatchers; d->handler; d++)
228 if (strncmp(argstring, d->name, d->name_length) == 0)
230 param_list = parse_cgi(argstring + d->name_length);
231 if ((d->handler)(csp, response, param_list))
236 free_map(param_list);
247 /*********************************************************************
249 * Function : parse_cgi
251 * Description : Parse a URL-encoded argument string into name/value
252 * pairs and store them in a struct map list.
255 * 1 : string = string to be parsed
257 * Returns : poniter to param list, or NULL if failiure
259 *********************************************************************/
260 struct map *parse_cgi(char *argstring)
263 char *vector[BUFFER_SIZE];
265 struct map *cgi_params = NULL;
267 if(*argstring == '?') argstring++;
268 tmp = strdup(argstring);
270 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
272 for (i = 0; i < pairs; i++)
274 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
277 cgi_params = map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
287 /*********************************************************************
289 * Function : make_http_response
291 * Description : Fill in the missing headers in an http response,
292 * and flatten the headers to an http head.
295 * 1 : rsp = pointer to http_response to be processed
297 * Returns : length of http head, or 0 on failiure
299 *********************************************************************/
300 int make_http_response(struct http_response *rsp)
302 char buf[BUFFER_SIZE];
304 /* Fill in the HTTP Status */
305 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
306 enlist_first(rsp->headers, buf);
308 /* Set the Content-Length */
309 if (rsp->content_length == 0)
311 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
315 sprintf(buf, "Content-Length: %d", rsp->content_length);
316 enlist(rsp->headers, buf);
318 /* Fill in the default headers FIXME: Are these correct? sequence OK? check rfc! */
319 enlist_unique(rsp->headers, "Pragma: no-cache", 7);
320 enlist_unique(rsp->headers, "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT", 14);
321 enlist_unique(rsp->headers, "Expires: Thu Jul 31, 1997 07:42:22 pm GMT", 8);
322 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
323 enlist(rsp->headers, "");
327 if (NULL == (rsp->head = list_to_text(rsp->headers)))
329 free_http_response(rsp);
333 return(strlen(rsp->head));
337 /*********************************************************************
339 * Function : free_http_response
341 * Description : Free the memory occupied by an http_response
342 * and its depandant structures.
345 * 1 : rsp = pointer to http_response to be freed
349 *********************************************************************/
350 void free_http_response(struct http_response *rsp)
357 destroy_list(rsp->headers);
362 /*********************************************************************
364 * Function : fill_template
366 * Description : CGI support function that loads a given HTML
367 * template from the confdir, and fills it in
368 * by replacing @name@ with value using pcrs,
369 * for each item in the output map.
372 * 1 : csp = Current client state (buffers, headers, etc...)
373 * 3 : template = name of the HTML template to be used
374 * 2 : answers = map with fill in symbol -> name pairs
375 * FIXME: needs better name!
377 * Returns : char * with filled out form, or NULL if failiure
379 *********************************************************************/
380 char *fill_template(struct client_state *csp, char *template, struct map *answers)
383 pcrs_job *job, *joblist = NULL;
384 char buf[BUFFER_SIZE];
385 char *new, *old = NULL;
390 * Open template file or fail
392 snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, template);
394 if(NULL == (fp = fopen(buf, "r")))
396 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
401 * Assemble pcrs joblist from answers map
403 for (m = answers; m; m = m->next)
407 snprintf(buf, BUFFER_SIZE, "s°@%s@°%s°ig", m->name, m->value);
409 if(NULL == (job = pcrs_make_job(buf, &error)))
411 log_error(LOG_LEVEL_ERROR, "Adding template fill job %s failed with error %d",
413 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
424 * Read the file, ignoring comments
426 while (fgets(buf, BUFFER_SIZE, fp))
428 /* skip lines starting with '#' */
429 if(*buf == '#') continue;
431 old = strsav(old, buf);
438 size = strlen(old) + 1;
441 for (job = joblist; NULL != job; job = job->next)
443 pcrs_exec_substitution(job, old, size, &new, &size);
444 if (old != buf) free(old);
449 * Free the jobs & return
451 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
457 /*********************************************************************
459 * Function : dump_map
461 * Description : HTML-dump a map for debugging
464 * 1 : map = map to dump
466 * Returns : string with HTML
468 *********************************************************************/
469 char *dump_map(struct map *map)
475 ret = strsav(ret, "<table>\n");
479 ret = strsav(ret, "<tr><td><b>");
480 ret = strsav(ret, p->name);
481 ret = strsav(ret, "</b></td><td>");
482 ret = strsav(ret, p->value);
483 ret = strsav(ret, "</td></tr>\n");
487 ret = strsav(ret, "</table>\n");
492 /*********************************************************************
494 * Function : cgi_default
496 * Description : CGI function that is called if no action was given
497 * lists menu of available unhidden CGIs.
500 * 1 : csp = Current client state (buffers, headers, etc...)
501 * 2 : rsp = http_response data structure for output
502 * 3 : parameters = map of cgi parameters
506 *********************************************************************/
507 int cgi_default(struct client_state *csp, struct http_response *rsp,
508 struct map *parameters)
510 char *p, *tmp = NULL;
511 char buf[BUFFER_SIZE];
512 const struct cgi_dispatcher *d;
513 struct map *exports = NULL;
515 /* List available unhidden CGI's and export as "other-cgis" */
516 for (d = cgi_dispatchers; d->handler; d++)
518 if (strncmp(d->description, "HIDE", 4))
520 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>",
521 HOME_PAGE_URL, d->name, d->description);
522 tmp = strsav(tmp, buf);
525 exports = map(exports, "other-cgis", 1, tmp, 0);
527 /* If there were other parameters, export a dump as "cgi-parameters" */
530 p = dump_map(parameters);
531 tmp = strsav(tmp, "<p>What made you think this cgi takes options?\n"
532 "Anyway, here they are, in case you're interested:</p>\n");
533 tmp = strsav(tmp, p);
534 exports = map(exports, "cgi-parameters", 1, tmp, 0);
539 exports = map(exports, "cgi-parameters", 1, "", 1);
542 rsp->body = fill_template(csp, "default", exports);
550 /*********************************************************************
552 * Function : cgi_send_banner
554 * Description : CGI function that returns a banner.
557 * 1 : csp = Current client state (buffers, headers, etc...)
558 * 2 : rsp = http_response data structure for output
559 * 3 : parameters = map of cgi parameters
562 * type : Selects the type of banner between "trans" and "jb".
563 * Defaults to "jb" if absent or != "trans".
567 *********************************************************************/
568 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
569 struct map *parameters)
571 if(strcmp(lookup(parameters, "type"), "trans"))
573 rsp->body = bindup(CJBGIF, sizeof(CJBGIF));
574 rsp->content_length = sizeof(CJBGIF);
578 rsp->body = bindup(CBLANKGIF, sizeof(CBLANKGIF));
579 rsp->content_length = sizeof(CBLANKGIF);
582 enlist(rsp->headers, "Content-Type: image/gif");
588 #ifdef FAST_REDIRECTS
589 /*********************************************************************
591 * Function : redirect_url
593 * Description : Checks for redirection URLs and returns a HTTP redirect
594 * to the destination URL.
597 * 1 : http = http_request request, check `basename's of blocklist
598 * 2 : csp = Current client state (buffers, headers, etc...)
600 * Returns : NULL if URL was clean, HTTP redirect otherwise.
602 *********************************************************************/
603 char *redirect_url(struct http_request *http, struct client_state *csp)
607 p = q = csp->http->path;
608 log_error(LOG_LEVEL_REDIRECTS, "checking path: %s", p);
610 /* find the last URL encoded in the request */
611 while (p = strstr(p, "http://"))
616 /* if there was any, generate and return a HTTP redirect */
617 if (q != csp->http->path)
619 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
621 p = (char *)malloc(strlen(HTTP_REDIRECT_TEMPLATE) + strlen(q));
622 sprintf(p, HTTP_REDIRECT_TEMPLATE, q);
631 #endif /* def FAST_REDIRECTS */
635 /*********************************************************************
637 * Function : cgi_show_status
639 * Description : CGI function that returns a a web page describing the
640 * current status of IJB.
643 * 1 : csp = Current client state (buffers, headers, etc...)
644 * 2 : rsp = http_response data structure for output
645 * 3 : parameters = map of cgi parameters
648 * type : Selects the type of banner between "trans" and "jb".
649 * Defaults to "jb" if absent or != "trans".
653 *********************************************************************/
654 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
655 struct map *parameters)
658 struct map *exports = NULL;
660 #ifdef SPLIT_PROXY_ARGS
662 char buf[BUFFER_SIZE];
664 const char * filename = NULL;
665 char * file_description = NULL;
668 p = lookup(parameters, "file");
672 if (csp->actions_list)
674 filename = csp->actions_list->filename;
675 file_description = "Actions List";
683 filename = csp->rlist->filename;
684 file_description = "Regex Filter List";
687 #endif /* def PCRS */
693 filename = csp->tlist->filename;
694 file_description = "Trust List";
697 #endif /* def TRUST_FILES */
700 if (NULL != filename)
702 exports = map(exports, "filename", 1, file_description, 1);
703 exports = map(exports, "filepath", 1, html_encode(filename), 0);
705 if ((fp = fopen(filename, "r")) == NULL)
707 exports = map(exports, "content", 1, "</pre><h1>ERROR OPENING FILE!</h1><pre>", 1);
711 while (fgets(buf, sizeof(buf), fp))
713 p = html_encode(buf);
718 s = strsav(s, "<br>");
722 exports = map(exports, "contents", 1, s, 0);
724 rsp->body = fill_template(csp, "show-status-file", exports);;
730 #endif /* def SPLIT_PROXY_ARGS */
732 exports = map(exports, "redirect-url", 1, REDIRECT_URL, 1);
733 exports = map(exports, "version", 1, VERSION, 1);
734 exports = map(exports, "home-page", 1, HOME_PAGE_URL, 1);
735 exports = map(exports, "invocation-args", 1, csp->config->proxy_args_header, 1);
739 exports = map(exports, "statistics", 1, add_stats(NULL), 0);
741 exports = map(exports, "statistics", 1, "", 1);
742 #endif /* ndef STATISTICS */
744 #ifdef SPLIT_PROXY_ARGS
745 if (csp->actions_list)
747 exports = map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
751 exports = map(exports, "actions-filename", 1, "None specified", 1);
757 exports = map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
761 exports = map(exports, "re-filter-filename", 1, "None specified", 1);
764 exports = map(exports, "re-filter-killer-start.*re-filter-killer-end", 1, "", 1);
765 #endif /* ndef PCRS */
770 exports = map(exports, "trust-filename", 1, csp->tlist->filename, 1);
774 exports = map(exports, "trust-filename", 1, "None specified", 1);
777 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
778 #endif /* ndef TRUST_FILES */
780 exports = map(exports, ".list", 1, "" , 1);
782 #else /* ifndef SPLIT_PROXY_ARGS */
783 exports = map(exports, "magic-eliminator-start.*magic-eliminator-end", 1, "", 1);
787 map(exports, "clist", 1, csp->clist->proxy_args , 1);
793 map(exports, "rlist", 1, csp->rlist->proxy_args , 1);
795 #endif /* def PCRS */
800 map(exports, "tlist", 1, csp->tlist->proxy_args , 1);
802 #endif /* def TRUST_FILES */
804 #endif /* ndef SPLIT_PROXY_ARGS */
806 s = end_proxy_args(csp->config);
807 exports = map(exports, "rcs-and-defines", 1, s , 0);
810 rsp->body = fill_template(csp, "show-status", exports);
817 /*********************************************************************
819 * Function : cgi_show_url_info
821 * Description : (please fill me in)
824 * 1 : http = http_request request for crunched URL
825 * 2 : csp = Current client state (buffers, headers, etc...)
829 *********************************************************************/
830 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
\r
831 struct map *parameters)
\r
833 const char * host_param = lookup(parameters, "url");
\r
834 char * host = NULL;
\r
836 if (*host_param != '\0')
\r
838 host = strdup(host_param);
842 char * matches = NULL;
846 struct file_list *fl;
847 struct url_actions *b;
848 struct url_spec url[1];
849 struct current_action_spec action[1];
850 struct map *exports = NULL;
\r
852 exports = map(exports, "url", 1, html_encode(host), 0);
\r
854 init_current_action(action);
856 s = current_action_to_text(action);
857 exports = map(exports, "default", 1, s , 0);
\r
859 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
\r
861 exports = map(exports, "matches", 1, "" , 1);
\r
862 exports = map(exports, "final", 1, lookup(exports, "default"), 1);
\r
865 free_current_action(action);
\r
867 rsp->body = fill_template(csp, "show-url-info", exports);
\r
873 s = strchr(host, '/');
883 s = strchr(host, ':');
893 /* if splitting the domain fails, punt */
894 if (url->dbuf == NULL)
896 exports = map(exports, "matches", 1, "" , 1);
\r
897 exports = map(exports, "final", 1, lookup(exports, "default"), 1);
\r
901 free_current_action(action);
\r
903 rsp->body = fill_template(csp, "show-url-info", exports);
\r
909 for (b = b->next; NULL != b; b = b->next)
911 if ((b->url->port == 0) || (b->url->port == port))
913 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
915 if ((b->url->path == NULL) ||
917 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
919 (strncmp(b->url->path, path, b->url->pathlen) == 0)
923 s = actions_to_text(b->action);
924 matches = strsav(matches, "<b>{");
925 matches = strsav(matches, s);
926 matches = strsav(matches, " }</b><br>\n<code>");
927 matches = strsav(matches, b->url->spec);
928 matches = strsav(matches, "</code><br>\n<br>\n");
931 merge_current_action(action, b->action);
937 exports = map(exports, "matches", 1, matches , 0);
\r
946 s = current_action_to_text(action);
947 exports = map(exports, "final", 1, s, 0);
\r
950 free_current_action(action);
952 rsp->body = fill_template(csp, "show-url-info", exports);
\r
959 rsp->body = fill_template(csp, "show-url-info-form", NULL);
\r
968 /*********************************************************************
970 * Function : ij_untrusted_url
972 * Description : This "crunch"es "http:/any.thing/ij-untrusted-url" and
973 * returns a web page describing why it was untrusted.
976 * 1 : http = http_request request for crunched URL
977 * 2 : csp = Current client state (buffers, headers, etc...)
979 * Returns : A string that contains why this was untrusted.
981 *********************************************************************/
982 char *ij_untrusted_url(struct http_request *http, struct client_state *csp)
985 char *hostport, *path, *refer, *p, *v[9];
986 char buf[BUFFER_SIZE];
987 struct url_spec **tl, *t;
990 static const char format[] =
991 "HTTP/1.0 200 OK\r\n"
993 "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT\n"
994 "Expires: Thu Jul 31, 1997 07:42:22 pm GMT\n"
995 "Content-Type: text/html\n\n"
998 "<title>Internet Junkbuster: Request for untrusted URL</title>\n"
1004 "The " BANNER " Proxy "
1005 "<A href=\"" HOME_PAGE_URL "\">"
1006 "(" HOME_PAGE_URL ") </A>"
1007 "intercepted the request for %s%s\n"
1008 "because the URL is not trusted.\n"
1011 if ((n = ssplit(http->path, "?+", v, SZ(v), 0, 0)) == 4)
1013 hostport = url_decode(v[1]);
1014 path = url_decode(v[2]);
1015 refer = url_decode(v[3]);
1019 hostport = strdup("undefined_host");
1020 path = strdup("/undefined_path");
1021 refer = strdup("undefined");
1025 n += strlen(hostport);
1028 if ((p = (char *)malloc(n)))
1030 sprintf(p, format, hostport, path);
1033 strsav(p, "The referrer in this request was <strong>");
1035 strsav(p, "</strong><br>\n");
1041 p = strsav(p, "<h3>The following referrers are trusted</h3>\n");
1043 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1045 sprintf(buf, "%s<br>\n", t->spec);
1049 if (csp->config->trust_info->next)
1055 "You can learn more about what this means "
1056 "and what you may be able to do about it by "
1057 "reading the following documents:<br>\n"
1063 for (l = csp->config->trust_info->next; l ; l = l->next)
1066 "<li> <a href=%s>%s</a><br>\n",
1071 p = strsav(p, "</ol>\n");
1074 p = strsav(p, "</body>\n" "</html>\n");
1079 #endif /* def TRUST_FILES */
1083 /*********************************************************************
1085 * Function : add_stats
1087 * Description : Statistics function of JB. Called by `show_proxy_args'.
1090 * 1 : s = string that holds the proxy args description page
1092 * Returns : A pointer to the descriptive status web page.
1094 *********************************************************************/
1095 char *add_stats(char *s)
1098 * Output details of the number of requests rejected and
1099 * accepted. This is switchable in the junkbuster config.
1100 * Does nothing if this option is not enabled.
1103 float perc_rej; /* Percentage of http requests rejected */
1105 int local_urls_read = urls_read;
1106 int local_urls_rejected = urls_rejected;
1109 * Need to alter the stats not to include the fetch of this
1112 * Can't do following thread safely! doh!
1115 * urls_rejected--; * This will be incremented subsequently *
1118 s = strsav(s,"<h2>Statistics for this " BANNER ":</h2>\n");
1120 if (local_urls_read == 0)
1123 s = strsav(s,"No activity so far!\n");
1129 perc_rej = (float)local_urls_rejected * 100.0F /
1130 (float)local_urls_read;
1133 "%d requests received, %d filtered "
1136 local_urls_rejected, perc_rej);
1138 s = strsav(s,out_str);
1143 #endif /* def STATISTICS */