1 const char cgi_rcs[] = "$Id: cgi.c,v 1.4 2001/06/04 10:41:52 swa 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.4 2001/06/04 10:41:52 swa
40 * show version string of cgi.h and cgi.c
42 * Revision 1.3 2001/06/03 19:12:16 oes
43 * introduced new cgi handling
45 * Revision 1.1 2001/06/03 11:03:48 oes
52 * adapted to new enlist_unique arg format
56 * introduced confdir option
58 * filters.c filtrers.h
60 * extracted-CGI relevant stuff
68 * support for new cgi mechansim
72 * functions for new list type: "map"
73 * extended enlist_unique
80 * deleted const struct interceptors
88 * added struct http_response
89 * changes struct interceptors to struct cgi_dispatcher
90 * moved HTML stuff to cgi.h
101 **********************************************************************/
107 #include <sys/types.h>
113 #define snprintf _snprintf
114 #endif /* def _WIN32 */
126 #include "miscutil.h"
127 #include "showargs.h"
129 const char cgi_h_rcs[] = CGI_H_VERSION;
131 const struct cgi_dispatcher cgi_dispatchers[] = {
134 "Show information about the version and configuration" },
135 /* { "show-url-info",
136 13, cgi_show_url_info,
137 "Show which actions apply to a URL and why" },*/
140 "HIDE Send the transparent or \"Junkbuster\" gif" },
142 /* { "untrusted-url",
143 15, ij_untrusted_url,
144 "HIDE Show why a URL was not trusted" }, */
145 #endif /* def TRUST_FILES */
148 "HIDE Send a page linking to all unhidden CGIs" },
149 { NULL, 0, NULL, NULL }
153 /*********************************************************************
155 * Function : dispatch_cgi
157 * Description : Checks if a request URL has either the magical hostname
158 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
159 * the (rest of the) path as a cgi name plus query string,
160 * prepares a map that maps CGI parameter names to their values,
161 * initializes the http_response struct, and calls the
162 * relevant CGI handler function.
165 * 1 : csp = Current client state (buffers, headers, etc...)
167 * Returns : http_response if match, NULL if nonmatch or handler fail
169 *********************************************************************/
170 struct http_response *cgi_dispatch(struct client_state *csp)
172 char *argstring = NULL;
173 const struct cgi_dispatcher *d;
174 struct map *param_list;
175 struct http_response *response;
178 * Should we intercept ?
181 /* Either the host matches CGI_PREFIX_HOST ..*/
182 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
184 /* ..then the path will all be for us */
185 argstring = csp->http->path;
187 /* Or it's the host part of HOME_PAGE_URL ? */
188 else if ( (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
189 && (0 == strncmpic(csp->http->path,"/config", 7))
190 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
192 /* then it's everything following "/config" */
193 argstring = csp->http->path + 7;
201 * We have intercepted it.
204 /* Get mem for response */
205 if (NULL == ( response = zalloc(sizeof(*response))))
210 /* remove any leading slash */
211 if (*argstring == '/')
216 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
217 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
218 csp->ip_addr_str, csp->http->cmd);
220 for (d = cgi_dispatchers; d->handler; d++)
222 if (strncmp(argstring, d->name, d->name_length) == 0)
224 param_list = parse_cgi(argstring + d->name_length);
225 if ((d->handler)(csp, response, param_list))
230 free_map(param_list);
241 /*********************************************************************
243 * Function : parse_cgi
245 * Description : Parse a URL-encoded argument string into name/value
246 * pairs and store them in a struct map list.
249 * 1 : string = string to be parsed
251 * Returns : poniter to param list, or NULL if failiure
253 *********************************************************************/
254 struct map *parse_cgi(char *argstring)
257 char *vector[BUFSIZ];
259 struct map *cgi_params = NULL;
261 if(*argstring == '?') argstring++;
262 tmp = strdup(argstring);
264 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
266 for (i = 0; i < pairs; i++)
268 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
271 cgi_params = map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
281 /*********************************************************************
283 * Function : make_http_response
285 * Description : Fill in the missing headers in an http response,
286 * and flatten the headers to an http head.
289 * 1 : rsp = pointer to http_response to be processed
291 * Returns : length of http head, or 0 on failiure
293 *********************************************************************/
294 int make_http_response(struct http_response *rsp)
298 /* Fill in the HTTP Status */
299 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
300 enlist_first(rsp->headers, buf);
302 /* Set the Content-Length */
303 if (rsp->content_length == 0)
305 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
309 sprintf(buf, "Content-Length: %d", rsp->content_length);
310 enlist(rsp->headers, buf);
312 /* Fill in the default headers FIXME: Are these correct? sequence OK? check rfc! */
313 enlist_unique(rsp->headers, "Pragma: no-cache", 7);
314 enlist_unique(rsp->headers, "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT", 14);
315 enlist_unique(rsp->headers, "Expires: Thu Jul 31, 1997 07:42:22 pm GMT", 8);
316 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
317 enlist(rsp->headers, "");
321 if (NULL == (rsp->head = list_to_text(rsp->headers)))
323 free_http_response(rsp);
327 return(strlen(rsp->head));
331 /*********************************************************************
333 * Function : free_http_response
335 * Description : Free the memory occupied by an http_response
336 * and its depandant structures.
339 * 1 : rsp = pointer to http_response to be freed
343 *********************************************************************/
344 void free_http_response(struct http_response *rsp)
351 destroy_list(rsp->headers);
356 /*********************************************************************
358 * Function : fill_template
360 * Description : CGI support function that loads a given HTML
361 * template from the confdir, and fills it in
362 * by replacing @name@ with value using pcrs,
363 * for each item in the output map.
366 * 1 : csp = Current client state (buffers, headers, etc...)
367 * 3 : template = name of the HTML template to be used
368 * 2 : answers = map with fill in symbol -> name pairs
369 * FIXME: needs better name!
371 * Returns : char * with filled out form, or NULL if failiure
373 *********************************************************************/
374 char *fill_template(struct client_state *csp, char *template, struct map *answers)
377 pcrs_job *job, *joblist = NULL;
379 char *new, *old = NULL;
384 * Open template file or fail
386 snprintf(buf, BUFSIZ, "%s/templates/%s", csp->config->confdir, template);
388 if(NULL == (fp = fopen(buf, "r")))
390 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
395 * Assemble pcrs joblist from answers map
397 for (m = answers; m; m = m->next)
401 snprintf(buf, BUFSIZ, "s°@%s@°%s°ig", m->name, m->value);
403 if(NULL == (job = pcrs_make_job(buf, &error)))
405 log_error(LOG_LEVEL_ERROR, "Adding template fill job %s failed with error %d",
407 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
418 * Read the file, ignoring comments
420 while (fgets(buf, BUFSIZ, fp))
422 /* skip lines starting with '#' */
423 if(*buf == '#') continue;
425 old = strsav(old, buf);
432 size = strlen(old) + 1;
435 for (job = joblist; NULL != job; job = job->next)
437 pcrs_exec_substitution(job, old, size, &new, &size);
438 if (old != buf) free(old);
443 * Free the jobs & return
445 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
451 /*********************************************************************
453 * Function : dump_map
455 * Description : HTML-dump a map for debugging
458 * 1 : map = map to dump
460 * Returns : string with HTML
462 *********************************************************************/
463 char *dump_map(struct map *map)
469 ret = strsav(ret, "<table>\n");
473 ret = strsav(ret, "<tr><td><b>");
474 ret = strsav(ret, p->name);
475 ret = strsav(ret, "</b></td><td>");
476 ret = strsav(ret, p->value);
477 ret = strsav(ret, "</td></tr>\n");
481 ret = strsav(ret, "</table>\n");
486 /*********************************************************************
488 * Function : cgi_default
490 * Description : CGI function that is called if no action was given
491 * lists menu of available unhidden CGIs.
494 * 1 : csp = Current client state (buffers, headers, etc...)
495 * 2 : rsp = http_response data structure for output
496 * 3 : parameters = map of cgi parameters
500 *********************************************************************/
501 int cgi_default(struct client_state *csp, struct http_response *rsp,
502 struct map *parameters)
504 char *p, *tmp = NULL;
506 const struct cgi_dispatcher *d;
507 struct map *exports = NULL;
509 /* List available unhidden CGI's and export as "other-cgis" */
510 for (d = cgi_dispatchers; d->handler; d++)
512 if (strncmp(d->description, "HIDE", 4))
514 snprintf(buf, BUFSIZ, "<li><a href=%s/config/%s>%s</a></li>",
515 HOME_PAGE_URL, d->name, d->description);
516 tmp = strsav(tmp, buf);
519 exports = map(exports, "other-cgis", 1, tmp, 0);
521 /* If there were other parameters, export a dump as "cgi-parameters" */
524 p = dump_map(parameters);
525 tmp = strsav(tmp, "<p>What made you think this cgi takes options?\n"
526 "Anyway, here they are, in case you're interested:</p>\n");
527 tmp = strsav(tmp, p);
528 exports = map(exports, "cgi-parameters", 1, tmp, 0);
533 exports = map(exports, "cgi-parameters", 1, "", 1);
536 rsp->body = fill_template(csp, "default", exports);
544 /*********************************************************************
546 * Function : cgi_send_banner
548 * Description : CGI function that returns a banner.
551 * 1 : csp = Current client state (buffers, headers, etc...)
552 * 2 : rsp = http_response data structure for output
553 * 3 : parameters = map of cgi parameters
556 * type : Selects the type of banner between "trans" and "jb".
557 * Defaults to "jb" if absent or != "trans".
561 *********************************************************************/
562 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
563 struct map *parameters)
565 if(strcmp(lookup(parameters, "type"), "trans"))
567 rsp->body = bindup(CJBGIF, sizeof(CJBGIF));
568 rsp->content_length = sizeof(CJBGIF);
572 rsp->body = bindup(CBLANKGIF, sizeof(CBLANKGIF));
573 rsp->content_length = sizeof(CBLANKGIF);
576 enlist(rsp->headers, "Content-Type: image/gif");
582 #ifdef FAST_REDIRECTS
583 /*********************************************************************
585 * Function : redirect_url
587 * Description : Checks for redirection URLs and returns a HTTP redirect
588 * to the destination URL.
591 * 1 : http = http_request request, check `basename's of blocklist
592 * 2 : csp = Current client state (buffers, headers, etc...)
594 * Returns : NULL if URL was clean, HTTP redirect otherwise.
596 *********************************************************************/
597 char *redirect_url(struct http_request *http, struct client_state *csp)
601 p = q = csp->http->path;
602 log_error(LOG_LEVEL_REDIRECTS, "checking path: %s", p);
604 /* find the last URL encoded in the request */
605 while (p = strstr(p, "http://"))
610 /* if there was any, generate and return a HTTP redirect */
611 if (q != csp->http->path)
613 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
615 p = (char *)malloc(strlen(HTTP_REDIRECT_TEMPLATE) + strlen(q));
616 sprintf(p, HTTP_REDIRECT_TEMPLATE, q);
625 #endif /* def FAST_REDIRECTS */
629 /*********************************************************************
631 * Function : cgi_show_status
633 * Description : CGI function that returns a a web page describing the
634 * current status of IJB.
637 * 1 : csp = Current client state (buffers, headers, etc...)
638 * 2 : rsp = http_response data structure for output
639 * 3 : parameters = map of cgi parameters
642 * type : Selects the type of banner between "trans" and "jb".
643 * Defaults to "jb" if absent or != "trans".
647 *********************************************************************/
648 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
649 struct map *parameters)
652 struct map *exports = NULL;
654 #ifdef SPLIT_PROXY_ARGS
658 const char * filename = NULL;
659 char * file_description = NULL;
662 p = lookup(parameters, "file");
666 if (csp->actions_list)
668 filename = csp->actions_list->filename;
669 file_description = "Actions List";
675 filename = csp->flist->filename;
676 file_description = "Forward List";
684 filename = csp->alist->filename;
685 file_description = "Access Control List";
688 #endif /* def ACL_FILES */
694 filename = csp->rlist->filename;
695 file_description = "Regex Filter List";
698 #endif /* def PCRS */
704 filename = csp->tlist->filename;
705 file_description = "Trust List";
708 #endif /* def TRUST_FILES */
711 if (NULL != filename)
713 exports = map(exports, "filename", 1, file_description, 1);
714 exports = map(exports, "filepath", 1, html_encode(filename), 0);
716 if ((fp = fopen(filename, "r")) == NULL)
718 exports = map(exports, "content", 1, "</pre><h1>ERROR OPENING FILE!</h1><pre>", 1);
722 while (fgets(buf, sizeof(buf), fp))
724 p = html_encode(buf);
729 s = strsav(s, "<br>");
733 exports = map(exports, "contents", 1, s, 0);
735 rsp->body = fill_template(csp, "show-status-file", exports);;
741 #endif /* def SPLIT_PROXY_ARGS */
743 exports = map(exports, "redirect-url", 1, REDIRECT_URL, 1);
744 exports = map(exports, "version", 1, VERSION, 1);
745 exports = map(exports, "home-page", 1, HOME_PAGE_URL, 1);
746 exports = map(exports, "invocation-args", 1, csp->config->proxy_args_header, 1);
747 exports = map(exports, "gateways", 1, csp->config->proxy_args_gateways, 1);
748 exports = map(exports, "gateway-protocols", 1, s, 0);
752 exports = map(exports, "statistics", 1, add_stats(NULL), 0);
754 exports = map(exports, "statistics", 1, "", 1);
755 #endif /* ndef STATISTICS */
757 #ifdef SPLIT_PROXY_ARGS
758 if (csp->actions_list)
760 exports = map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
764 exports = map(exports, "actions-filename", 1, "None specified", 1);
769 exports = map(exports, "forward-filename", 1, csp->flist->filename, 1);
773 exports = map(exports, "forward-filename", 1, "None specified", 1);
779 exports = map(exports, "acl-filename", 1, csp->alist->filename, 1);
783 exports = map(exports, "acl-filename", 1, "None specified", 1);
786 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
787 #endif /* ndef ACL_FILES */
792 exports = map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
796 exports = map(exports, "re-filter-filename", 1, "None specified", 1);
799 exports = map(exports, "re-filter-killer-start.*re-filter-killer-end", 1, "", 1);
800 #endif /* ndef PCRS */
805 exports = map(exports, "trust-filename", 1, csp->tlist->filename, 1);
809 exports = map(exports, "trust-filename", 1, "None specified", 1);
812 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
813 #endif /* ndef TRUST_FILES */
815 exports = map(exports, ".list", 1, "" , 1);
817 #else /* ifndef SPLIT_PROXY_ARGS */
818 exports = map(exports, "magic-eliminator-start.*magic-eliminator-end", 1, "", 1);
822 map(exports, "clist", 1, csp->clist->proxy_args , 1);
827 map(exports, "flist", 1, csp->flist->proxy_args , 1);
833 map(exports, "alist", 1, csp->alist->proxy_args , 1);
835 #endif /* def ACL_FILES */
840 map(exports, "rlist", 1, csp->rlist->proxy_args , 1);
842 #endif /* def PCRS */
847 map(exports, "tlist", 1, csp->tlist->proxy_args , 1);
849 #endif /* def TRUST_FILES */
851 #endif /* ndef SPLIT_PROXY_ARGS */
853 s = end_proxy_args(csp->config);
854 exports = map(exports, "rcs-and-defines", 1, s , 0);
857 rsp->body = fill_template(csp, "show-status", exports);
864 /*********************************************************************
866 * Function : cgi_show_url_info
868 * Description : (please fill me in)
871 * 1 : http = http_request request for crunched URL
872 * 2 : csp = Current client state (buffers, headers, etc...)
876 *********************************************************************/
877 char *cgi_show_url_info(struct http_request *http, struct client_state *csp)
879 char * query_string = strchr(http->path, '?');
882 if (query_string != NULL)
884 query_string = url_decode(query_string + 1);
885 if (strncmpic(query_string, "url=", 4) == 0)
887 host = strdup(query_string + 4);
897 struct file_list *fl;
898 struct url_actions *b;
899 struct url_spec url[1];
900 struct current_action_spec action[1];
902 init_current_action(action);
904 result = (char *)malloc(sizeof(C_URL_INFO_HEADER) + 2 * strlen(host));
905 sprintf(result, C_URL_INFO_HEADER, host, host);
907 s = current_action_to_text(action);
908 result = strsav(result, "<h3>Defaults:</h3>\n<p><b>{");
909 result = strsav(result, s);
910 result = strsav(result, " }</b></p>\n<h3>Patterns affecting the URL:</h3>\n<p>\n");
913 s = strchr(host, '/');
923 s = strchr(host, ':');
930 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
934 result = strsav(result, C_URL_INFO_FOOTER);
940 /* if splitting the domain fails, punt */
941 if (url->dbuf == NULL)
945 result = strsav(result, C_URL_INFO_FOOTER);
949 for (b = b->next; NULL != b; b = b->next)
951 if ((b->url->port == 0) || (b->url->port == port))
953 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
955 if ((b->url->path == NULL) ||
957 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
959 (strncmp(b->url->path, path, b->url->pathlen) == 0)
963 s = actions_to_text(b->action);
964 result = strsav(result, "<b>{");
965 result = strsav(result, s);
966 result = strsav(result, " }</b><br>\n<code>");
967 result = strsav(result, b->url->spec);
968 result = strsav(result, "</code><br>\n<br>\n");
971 merge_current_action(action, b->action);
983 s = current_action_to_text(action);
984 result = strsav(result, "</p>\n<h2>Final Results:</h2>\n<p><b>{");
985 result = strsav(result, s);
986 result = strsav(result, " }</b><br>\n<br>\n");
989 free_current_action(action);
991 result = strsav(result, C_URL_INFO_FOOTER);
996 return strdup(C_URL_INFO_FORM);
1003 /*********************************************************************
1005 * Function : ij_untrusted_url
1007 * Description : This "crunch"es "http:/any.thing/ij-untrusted-url" and
1008 * returns a web page describing why it was untrusted.
1011 * 1 : http = http_request request for crunched URL
1012 * 2 : csp = Current client state (buffers, headers, etc...)
1014 * Returns : A string that contains why this was untrusted.
1016 *********************************************************************/
1017 char *ij_untrusted_url(struct http_request *http, struct client_state *csp)
1020 char *hostport, *path, *refer, *p, *v[9];
1022 struct url_spec **tl, *t;
1025 static const char format[] =
1026 "HTTP/1.0 200 OK\r\n"
1027 "Pragma: no-cache\n"
1028 "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT\n"
1029 "Expires: Thu Jul 31, 1997 07:42:22 pm GMT\n"
1030 "Content-Type: text/html\n\n"
1033 "<title>Internet Junkbuster: Request for untrusted URL</title>\n"
1039 "The " BANNER " Proxy "
1040 "<A href=\"" HOME_PAGE_URL "\">"
1041 "(" HOME_PAGE_URL ") </A>"
1042 "intercepted the request for %s%s\n"
1043 "because the URL is not trusted.\n"
1046 if ((n = ssplit(http->path, "?+", v, SZ(v), 0, 0)) == 4)
1048 hostport = url_decode(v[1]);
1049 path = url_decode(v[2]);
1050 refer = url_decode(v[3]);
1054 hostport = strdup("undefined_host");
1055 path = strdup("/undefined_path");
1056 refer = strdup("undefined");
1060 n += strlen(hostport);
1063 if ((p = (char *)malloc(n)))
1065 sprintf(p, format, hostport, path);
1068 strsav(p, "The referrer in this request was <strong>");
1070 strsav(p, "</strong><br>\n");
1076 p = strsav(p, "<h3>The following referrers are trusted</h3>\n");
1078 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1080 sprintf(buf, "%s<br>\n", t->spec);
1084 if (csp->config->trust_info->next)
1090 "You can learn more about what this means "
1091 "and what you may be able to do about it by "
1092 "reading the following documents:<br>\n"
1098 for (l = csp->config->trust_info->next; l ; l = l->next)
1101 "<li> <a href=%s>%s</a><br>\n",
1106 p = strsav(p, "</ol>\n");
1109 p = strsav(p, "</body>\n" "</html>\n");
1114 #endif /* def TRUST_FILES */
1118 /*********************************************************************
1120 * Function : add_stats
1122 * Description : Statistics function of JB. Called by `show_proxy_args'.
1125 * 1 : s = string that holds the proxy args description page
1127 * Returns : A pointer to the descriptive status web page.
1129 *********************************************************************/
1130 char *add_stats(char *s)
1133 * Output details of the number of requests rejected and
1134 * accepted. This is switchable in the junkbuster config.
1135 * Does nothing if this option is not enabled.
1138 float perc_rej; /* Percentage of http requests rejected */
1140 int local_urls_read = urls_read;
1141 int local_urls_rejected = urls_rejected;
1144 * Need to alter the stats not to include the fetch of this
1147 * Can't do following thread safely! doh!
1150 * urls_rejected--; * This will be incremented subsequently *
1153 s = strsav(s,"<h2>Statistics for this " BANNER ":</h2>\n");
1155 if (local_urls_read == 0)
1158 s = strsav(s,"No activity so far!\n");
1164 perc_rej = (float)local_urls_rejected * 100.0F /
1165 (float)local_urls_read;
1168 "%d requests received, %d filtered "
1171 local_urls_rejected, perc_rej);
1173 s = strsav(s,out_str);
1178 #endif /* def STATISTICS */