1 const char cgi_rcs[] = "$Id: cgi.c,v 1.1 2001/06/03 11:03:48 oes 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.1 2001/06/03 11:03:48 oes
46 * adapted to new enlist_unique arg format
50 * introduced confdir option
52 * filters.c filtrers.h
54 * extracted-CGI relevant stuff
62 * support for new cgi mechansim
66 * functions for new list type: "map"
67 * extended enlist_unique
74 * deleted const struct interceptors
82 * added struct http_response
83 * changes struct interceptors to struct cgi_dispatcher
84 * moved HTML stuff to cgi.h
95 **********************************************************************/
101 #include <sys/types.h>
116 #include "miscutil.h"
117 #include "showargs.h"
120 const struct cgi_dispatcher cgi_dispatchers[] = {
123 "Show information about the version and configuration" },
124 /* { "show-url-info",
125 13, cgi_show_url_info,
126 "Show which actions apply to a URL and why" },*/
129 "HIDE Send the transparent or \"Junkbuster\" gif" },
131 /* { "untrusted-url",
132 15, ij_untrusted_url,
133 "HIDE Show why a URL was not trusted" }, */
134 #endif /* def TRUST_FILES */
137 "HIDE Send a page linking to all unhidden CGIs" },
138 { NULL, 0, NULL, NULL }
142 /*********************************************************************
144 * Function : dispatch_cgi
146 * Description : Checks if a request URL has either the magical hostname
147 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
148 * the (rest of the) path as a cgi name plus query string,
149 * prepares a map that maps CGI parameter names to their values,
150 * initializes the http_response struct, and calls the
151 * relevant CGI handler function.
154 * 1 : csp = Current client state (buffers, headers, etc...)
156 * Returns : http_response if match, NULL if nonmatch or handler fail
158 *********************************************************************/
159 struct http_response *cgi_dispatch(struct client_state *csp)
161 char *argstring = NULL;
162 const struct cgi_dispatcher *d;
163 struct map *param_list;
164 struct http_response *response;
167 * Should we intercept ?
170 /* Either the host matches CGI_PREFIX_HOST ..*/
171 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
173 /* ..then the path will all be for us */
174 argstring = csp->http->path;
176 /* Or it's the host part of HOME_PAGE_URL ? */
177 else if ( (0 == strcmpic(csp->http->host, *&HOME_PAGE_URL + 7 ))
178 && (0 == strncmpic(csp->http->path,"/config", 7))
179 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
181 /* then it's everything following "/config" */
182 argstring = csp->http->path + 7;
190 * We have intercepted it.
193 /* Get mem for response */
194 if (NULL == ( response = zalloc(sizeof(*response))))
199 /* remove any leading slash */
200 if (*argstring == '/')
205 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
206 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
207 csp->ip_addr_str, csp->http->cmd);
209 for (d = cgi_dispatchers; d->handler; d++)
211 if (strncmp(argstring, d->name, d->name_length) == 0)
213 param_list = parse_cgi(argstring + d->name_length);
214 if ((d->handler)(csp, response, param_list))
219 free_map(param_list);
230 /*********************************************************************
232 * Function : parse_cgi
234 * Description : Parse a URL-encoded argument string into name/value
235 * pairs and store them in a struct map list.
238 * 1 : string = string to be parsed
240 * Returns : poniter to param list, or NULL if failiure
242 *********************************************************************/
243 struct map *parse_cgi(char *argstring)
246 char *vector[BUFSIZ];
248 struct map *cgi_params = NULL;
250 if(*argstring == '?') argstring++;
251 tmp = strdup(argstring);
253 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
255 for (i = 0; i < pairs; i++)
257 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
260 cgi_params = map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
270 /*********************************************************************
272 * Function : make_http_response
274 * Description : Fill in the missing headers in an http response,
275 * and flatten the headers to an http head.
278 * 1 : rsp = pointer to http_response to be processed
280 * Returns : length of http head, or 0 on failiure
282 *********************************************************************/
283 int make_http_response(struct http_response *rsp)
287 /* Fill in the HTTP Status */
288 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
289 enlist_first(rsp->headers, buf);
291 /* Set the Content-Length */
292 if (rsp->content_length == 0)
294 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
298 sprintf(buf, "Content-Length: %d", rsp->content_length);
299 enlist(rsp->headers, buf);
301 /* Fill in the default headers FIXME: Are these correct? sequence OK? check rfc! */
302 enlist_unique(rsp->headers, "Pragma: no-cache", 7);
303 enlist_unique(rsp->headers, "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT", 14);
304 enlist_unique(rsp->headers, "Expires: Thu Jul 31, 1997 07:42:22 pm GMT", 8);
305 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
306 enlist(rsp->headers, "");
310 if (NULL == (rsp->head = list_to_text(rsp->headers)))
312 free_http_response(rsp);
316 return(strlen(rsp->head));
320 /*********************************************************************
322 * Function : free_http_response
324 * Description : Free the memory occupied by an http_response
325 * and its depandant structures.
328 * 1 : rsp = pointer to http_response to be freed
332 *********************************************************************/
333 void free_http_response(struct http_response *rsp)
340 destroy_list(rsp->headers);
345 /*********************************************************************
347 * Function : fill_template
349 * Description : CGI support function that loads a given HTML
350 * template from the confdir, and fills it in
351 * by replacing @name@ with value using pcrs,
352 * for each item in the output map.
355 * 1 : csp = Current client state (buffers, headers, etc...)
356 * 3 : template = name of the HTML template to be used
357 * 2 : answers = map with fill in symbol -> name pairs
358 * FIXME: needs better name!
360 * Returns : char * with filled out form, or NULL if failiure
362 *********************************************************************/
363 char *fill_template(struct client_state *csp, char *template, struct map *answers)
366 pcrs_job *job, *joblist = NULL;
368 char *new, *old = NULL;
373 * Open template file or fail
375 snprintf(buf, BUFSIZ, "%s/templates/%s", csp->config->confdir, template);
377 if(NULL == (fp = fopen(buf, "r")))
379 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
384 * Assemble pcrs joblist from answers map
386 for (m = answers; m; m = m->next)
390 snprintf(buf, BUFSIZ, "s°@%s@°%s°ig", m->name, m->value);
392 if(NULL == (job = pcrs_make_job(buf, &error)))
394 log_error(LOG_LEVEL_ERROR, "Adding template fill job %s failed with error %d",
396 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
407 * Read the file, ignoring comments
409 while (fgets(buf, BUFSIZ, fp))
411 /* skip lines starting with '#' */
412 if(*buf == '#') continue;
414 old = strsav(old, buf);
421 size = strlen(old) + 1;
424 for (job = joblist; NULL != job; job = job->next)
426 pcrs_exec_substitution(job, old, size, &new, &size);
427 if (old != buf) free(old);
432 * Free the jobs & return
434 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
440 /*********************************************************************
442 * Function : dump_map
444 * Description : HTML-dump a map for debugging
447 * 1 : map = map to dump
449 * Returns : string with HTML
451 *********************************************************************/
452 char *dump_map(struct map *map)
458 ret = strsav(ret, "<table>\n");
462 ret = strsav(ret, "<tr><td><b>");
463 ret = strsav(ret, p->name);
464 ret = strsav(ret, "</b></td><td>");
465 ret = strsav(ret, p->value);
466 ret = strsav(ret, "</td></tr>\n");
470 ret = strsav(ret, "</table>\n");
475 /*********************************************************************
477 * Function : cgi_default
479 * Description : CGI function that is called if no action was given
480 * lists menu of available unhidden CGIs.
483 * 1 : csp = Current client state (buffers, headers, etc...)
484 * 2 : rsp = http_response data structure for output
485 * 3 : parameters = map of cgi parameters
489 *********************************************************************/
490 int cgi_default(struct client_state *csp, struct http_response *rsp,
491 struct map *parameters)
493 char *p, *tmp = NULL;
495 const struct cgi_dispatcher *d;
496 struct map *exports = NULL;
498 /* List available unhidden CGI's and export as "other-cgis" */
499 for (d = cgi_dispatchers; d->handler; d++)
501 if (strncmp(d->description, "HIDE", 4))
503 snprintf(buf, BUFSIZ, "<li><a href=%s/config/%s>%s</a></li>",
504 HOME_PAGE_URL, d->name, d->description);
505 tmp = strsav(tmp, buf);
508 exports = map(exports, "other-cgis", 1, tmp, 0);
510 /* If there were other parameters, export a dump as "cgi-parameters" */
513 p = dump_map(parameters);
514 tmp = strsav(tmp, "<p>What made you think this cgi takes options?\n
515 Anyway, here they are, in case you're interested:</p>\n");
516 tmp = strsav(tmp, p);
517 exports = map(exports, "cgi-parameters", 1, tmp, 0);
522 exports = map(exports, "cgi-parameters", 1, "", 1);
525 rsp->body = fill_template(csp, "default", exports);
533 /*********************************************************************
535 * Function : cgi_send_banner
537 * Description : CGI function that returns a banner.
540 * 1 : csp = Current client state (buffers, headers, etc...)
541 * 2 : rsp = http_response data structure for output
542 * 3 : parameters = map of cgi parameters
545 * type : Selects the type of banner between "trans" and "jb".
546 * Defaults to "jb" if absent or != "trans".
550 *********************************************************************/
551 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
552 struct map *parameters)
554 if(strcmp(lookup(parameters, "type"), "trans"))
556 rsp->body = bindup(CJBGIF, sizeof(CJBGIF));
557 rsp->content_length = sizeof(CJBGIF);
561 rsp->body = bindup(CBLANKGIF, sizeof(CBLANKGIF));
562 rsp->content_length = sizeof(CBLANKGIF);
565 enlist(rsp->headers, "Content-Type: image/gif");
571 #ifdef FAST_REDIRECTS
572 /*********************************************************************
574 * Function : redirect_url
576 * Description : Checks for redirection URLs and returns a HTTP redirect
577 * to the destination URL.
580 * 1 : http = http_request request, check `basename's of blocklist
581 * 2 : csp = Current client state (buffers, headers, etc...)
583 * Returns : NULL if URL was clean, HTTP redirect otherwise.
585 *********************************************************************/
586 char *redirect_url(struct http_request *http, struct client_state *csp)
590 p = q = csp->http->path;
591 log_error(LOG_LEVEL_REDIRECTS, "checking path: %s", p);
593 /* find the last URL encoded in the request */
594 while (p = strstr(p, "http://"))
599 /* if there was any, generate and return a HTTP redirect */
600 if (q != csp->http->path)
602 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
604 p = (char *)malloc(strlen(HTTP_REDIRECT_TEMPLATE) + strlen(q));
605 sprintf(p, HTTP_REDIRECT_TEMPLATE, q);
614 #endif /* def FAST_REDIRECTS */
618 /*********************************************************************
620 * Function : cgi_show_status
622 * Description : CGI function that returns a a web page describing the
623 * current status of IJB.
626 * 1 : csp = Current client state (buffers, headers, etc...)
627 * 2 : rsp = http_response data structure for output
628 * 3 : parameters = map of cgi parameters
631 * type : Selects the type of banner between "trans" and "jb".
632 * Defaults to "jb" if absent or != "trans".
636 *********************************************************************/
637 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
638 struct map *parameters)
641 const struct gateway *g;
644 struct map *exports = NULL;
646 #ifdef SPLIT_PROXY_ARGS
650 const char * filename = NULL;
651 char * file_description = NULL;
654 p = lookup(parameters, "file");
658 if (csp->actions_list)
660 filename = csp->actions_list->filename;
661 file_description = "Actions List";
667 filename = csp->flist->filename;
668 file_description = "Forward List";
676 filename = csp->alist->filename;
677 file_description = "Access Control List";
680 #endif /* def ACL_FILES */
686 filename = csp->rlist->filename;
687 file_description = "Regex Filter List";
690 #endif /* def PCRS */
696 filename = csp->tlist->filename;
697 file_description = "Trust List";
700 #endif /* def TRUST_FILES */
703 if (NULL != filename)
705 exports = map(exports, "filename", 1, file_description, 1);
706 exports = map(exports, "filepath", 1, html_encode(filename), 0);
708 if ((fp = fopen(filename, "r")) == NULL)
710 exports = map(exports, "content", 1, "</pre><h1>ERROR OPENING FILE!</h1><pre>", 1);
714 while (fgets(buf, sizeof(buf), fp))
716 p = html_encode(buf);
721 s = strsav(s, "<br>");
725 exports = map(exports, "contents", 1, s, 0);
727 rsp->body = fill_template(csp, "show-status-file", exports);;
733 #endif /* def SPLIT_PROXY_ARGS */
735 exports = map(exports, "redirect-url", 1, REDIRECT_URL, 1);
736 exports = map(exports, "version", 1, VERSION, 1);
737 exports = map(exports, "home-page", 1, HOME_PAGE_URL, 1);
738 exports = map(exports, "invocation-args", 1, csp->config->proxy_args_header, 1);
739 exports = map(exports, "gateways", 1, csp->config->proxy_args_gateways, 1);
740 exports = map(exports, "gateway-protocols", 1, s, 0);
744 exports = map(exports, "statistics", 1, add_stats(NULL), 0);
746 exports = map(exports, "statistics", 1, "", 1);
747 #endif /* ndef STATISTICS */
749 #ifdef SPLIT_PROXY_ARGS
750 if (csp->actions_list)
752 exports = map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
756 exports = map(exports, "actions-filename", 1, "None specified", 1);
761 exports = map(exports, "forward-filename", 1, csp->flist->filename, 1);
765 exports = map(exports, "forward-filename", 1, "None specified", 1);
771 exports = map(exports, "acl-filename", 1, csp->alist->filename, 1);
775 exports = map(exports, "acl-filename", 1, "None specified", 1);
778 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
779 #endif /* ndef ACL_FILES */
784 exports = map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
788 exports = map(exports, "re-filter-filename", 1, "None specified", 1);
791 exports = map(exports, "re-filter-killer-start.*re-filter-killer-end", 1, "", 1);
792 #endif /* ndef PCRS */
797 exports = map(exports, "trust-filename", 1, csp->tlist->filename, 1);
801 exports = map(exports, "trust-filename", 1, "None specified", 1);
804 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
805 #endif /* ndef TRUST_FILES */
807 exports = map(exports, ".list", 1, "" , 1);
809 #else /* ifndef SPLIT_PROXY_ARGS */
810 exports = map(exports, "magic-eliminator-start.*magic-eliminator-end", 1, "", 1);
814 map(exports, "clist", 1, csp->clist->proxy_args , 1);
819 map(exports, "flist", 1, csp->flist->proxy_args , 1);
825 map(exports, "alist", 1, csp->alist->proxy_args , 1);
827 #endif /* def ACL_FILES */
832 map(exports, "rlist", 1, csp->rlist->proxy_args , 1);
834 #endif /* def PCRS */
839 map(exports, "tlist", 1, csp->tlist->proxy_args , 1);
841 #endif /* def TRUST_FILES */
843 #endif /* ndef SPLIT_PROXY_ARGS */
845 s = end_proxy_args(csp->config);
846 exports = map(exports, "rcs-and-defines", 1, s , 0);
849 rsp->body = fill_template(csp, "show-status", exports);
856 /*********************************************************************
858 * Function : cgi_show_url_info
860 * Description : (please fill me in)
863 * 1 : http = http_request request for crunched URL
864 * 2 : csp = Current client state (buffers, headers, etc...)
868 *********************************************************************/
869 char *cgi_show_url_info(struct http_request *http, struct client_state *csp)
871 char * query_string = strchr(http->path, '?');
874 if (query_string != NULL)
876 query_string = url_decode(query_string + 1);
877 if (strncmpic(query_string, "url=", 4) == 0)
879 host = strdup(query_string + 4);
889 struct file_list *fl;
890 struct url_actions *b;
891 struct url_spec url[1];
892 struct current_action_spec action[1];
894 init_current_action(action);
896 result = (char *)malloc(sizeof(C_URL_INFO_HEADER) + 2 * strlen(host));
897 sprintf(result, C_URL_INFO_HEADER, host, host);
899 s = current_action_to_text(action);
900 result = strsav(result, "<h3>Defaults:</h3>\n<p><b>{");
901 result = strsav(result, s);
902 result = strsav(result, " }</b></p>\n<h3>Patterns affecting the URL:</h3>\n<p>\n");
905 s = strchr(host, '/');
915 s = strchr(host, ':');
922 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
926 result = strsav(result, C_URL_INFO_FOOTER);
932 /* if splitting the domain fails, punt */
933 if (url->dbuf == NULL)
937 result = strsav(result, C_URL_INFO_FOOTER);
941 for (b = b->next; NULL != b; b = b->next)
943 if ((b->url->port == 0) || (b->url->port == port))
945 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
947 if ((b->url->path == NULL) ||
949 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
951 (strncmp(b->url->path, path, b->url->pathlen) == 0)
955 s = actions_to_text(b->action);
956 result = strsav(result, "<b>{");
957 result = strsav(result, s);
958 result = strsav(result, " }</b><br>\n<code>");
959 result = strsav(result, b->url->spec);
960 result = strsav(result, "</code><br>\n<br>\n");
963 merge_current_action(action, b->action);
975 s = current_action_to_text(action);
976 result = strsav(result, "</p>\n<h2>Final Results:</h2>\n<p><b>{");
977 result = strsav(result, s);
978 result = strsav(result, " }</b><br>\n<br>\n");
981 free_current_action(action);
983 result = strsav(result, C_URL_INFO_FOOTER);
988 return strdup(C_URL_INFO_FORM);
995 /*********************************************************************
997 * Function : ij_untrusted_url
999 * Description : This "crunch"es "http:/any.thing/ij-untrusted-url" and
1000 * returns a web page describing why it was untrusted.
1003 * 1 : http = http_request request for crunched URL
1004 * 2 : csp = Current client state (buffers, headers, etc...)
1006 * Returns : A string that contains why this was untrusted.
1008 *********************************************************************/
1009 char *ij_untrusted_url(struct http_request *http, struct client_state *csp)
1012 char *hostport, *path, *refer, *p, *v[9];
1014 struct url_spec **tl, *t;
1017 static const char format[] =
1018 "HTTP/1.0 200 OK\r\n"
1019 "Pragma: no-cache\n"
1020 "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT\n"
1021 "Expires: Thu Jul 31, 1997 07:42:22 pm GMT\n"
1022 "Content-Type: text/html\n\n"
1025 "<title>Internet Junkbuster: Request for untrusted URL</title>\n"
1031 "The " BANNER " Proxy "
1032 "<A href=\"" HOME_PAGE_URL "\">"
1033 "(" HOME_PAGE_URL ") </A>"
1034 "intercepted the request for %s%s\n"
1035 "because the URL is not trusted.\n"
1038 if ((n = ssplit(http->path, "?+", v, SZ(v), 0, 0)) == 4)
1040 hostport = url_decode(v[1]);
1041 path = url_decode(v[2]);
1042 refer = url_decode(v[3]);
1046 hostport = strdup("undefined_host");
1047 path = strdup("/undefined_path");
1048 refer = strdup("undefined");
1052 n += strlen(hostport);
1055 if ((p = (char *)malloc(n)))
1057 sprintf(p, format, hostport, path);
1060 strsav(p, "The referrer in this request was <strong>");
1062 strsav(p, "</strong><br>\n");
1068 p = strsav(p, "<h3>The following referrers are trusted</h3>\n");
1070 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1072 sprintf(buf, "%s<br>\n", t->spec);
1076 if (csp->config->trust_info->next)
1082 "You can learn more about what this means "
1083 "and what you may be able to do about it by "
1084 "reading the following documents:<br>\n"
1090 for (l = csp->config->trust_info->next; l ; l = l->next)
1093 "<li> <a href=%s>%s</a><br>\n",
1098 p = strsav(p, "</ol>\n");
1101 p = strsav(p, "</body>\n" "</html>\n");
1106 #endif /* def TRUST_FILES */
1110 /*********************************************************************
1112 * Function : add_stats
1114 * Description : Statistics function of JB. Called by `show_proxy_args'.
1117 * 1 : s = string that holds the proxy args description page
1119 * Returns : A pointer to the descriptive status web page.
1121 *********************************************************************/
1122 char *add_stats(char *s)
1125 * Output details of the number of requests rejected and
1126 * accepted. This is switchable in the junkbuster config.
1127 * Does nothing if this option is not enabled.
1130 float perc_rej; /* Percentage of http requests rejected */
1132 int local_urls_read = urls_read;
1133 int local_urls_rejected = urls_rejected;
1136 * Need to alter the stats not to include the fetch of this
1139 * Can't do following thread safely! doh!
1142 * urls_rejected--; * This will be incremented subsequently *
1145 s = strsav(s,"<h2>Statistics for this " BANNER ":</h2>\n");
1147 if (local_urls_read == 0)
1150 s = strsav(s,"No activity so far!\n");
1156 perc_rej = (float)local_urls_rejected * 100.0F /
1157 (float)local_urls_read;
1160 "%d requests received, %d filtered "
1163 local_urls_rejected, perc_rej);
1165 s = strsav(s,out_str);
1170 #endif /* def STATISTICS */