1 const char cgi_rcs[] = "$Id: cgi.c,v 1.3 2001/06/03 19:12:16 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.3 2001/06/03 19:12:16 oes
40 * introduced new cgi handling
42 * Revision 1.1 2001/06/03 11:03:48 oes
49 * adapted to new enlist_unique arg format
53 * introduced confdir option
55 * filters.c filtrers.h
57 * extracted-CGI relevant stuff
65 * support for new cgi mechansim
69 * functions for new list type: "map"
70 * extended enlist_unique
77 * deleted const struct interceptors
85 * added struct http_response
86 * changes struct interceptors to struct cgi_dispatcher
87 * moved HTML stuff to cgi.h
98 **********************************************************************/
104 #include <sys/types.h>
119 #include "miscutil.h"
120 #include "showargs.h"
122 const char cgi_h_rcs[] = CGI_H_VERSION;
124 const struct cgi_dispatcher cgi_dispatchers[] = {
127 "Show information about the version and configuration" },
128 /* { "show-url-info",
129 13, cgi_show_url_info,
130 "Show which actions apply to a URL and why" },*/
133 "HIDE Send the transparent or \"Junkbuster\" gif" },
135 /* { "untrusted-url",
136 15, ij_untrusted_url,
137 "HIDE Show why a URL was not trusted" }, */
138 #endif /* def TRUST_FILES */
141 "HIDE Send a page linking to all unhidden CGIs" },
142 { NULL, 0, NULL, NULL }
146 /*********************************************************************
148 * Function : dispatch_cgi
150 * Description : Checks if a request URL has either the magical hostname
151 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
152 * the (rest of the) path as a cgi name plus query string,
153 * prepares a map that maps CGI parameter names to their values,
154 * initializes the http_response struct, and calls the
155 * relevant CGI handler function.
158 * 1 : csp = Current client state (buffers, headers, etc...)
160 * Returns : http_response if match, NULL if nonmatch or handler fail
162 *********************************************************************/
163 struct http_response *cgi_dispatch(struct client_state *csp)
165 char *argstring = NULL;
166 const struct cgi_dispatcher *d;
167 struct map *param_list;
168 struct http_response *response;
171 * Should we intercept ?
174 /* Either the host matches CGI_PREFIX_HOST ..*/
175 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
177 /* ..then the path will all be for us */
178 argstring = csp->http->path;
180 /* Or it's the host part of HOME_PAGE_URL ? */
181 else if ( (0 == strcmpic(csp->http->host, *&HOME_PAGE_URL + 7 ))
182 && (0 == strncmpic(csp->http->path,"/config", 7))
183 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
185 /* then it's everything following "/config" */
186 argstring = csp->http->path + 7;
194 * We have intercepted it.
197 /* Get mem for response */
198 if (NULL == ( response = zalloc(sizeof(*response))))
203 /* remove any leading slash */
204 if (*argstring == '/')
209 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
210 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
211 csp->ip_addr_str, csp->http->cmd);
213 for (d = cgi_dispatchers; d->handler; d++)
215 if (strncmp(argstring, d->name, d->name_length) == 0)
217 param_list = parse_cgi(argstring + d->name_length);
218 if ((d->handler)(csp, response, param_list))
223 free_map(param_list);
234 /*********************************************************************
236 * Function : parse_cgi
238 * Description : Parse a URL-encoded argument string into name/value
239 * pairs and store them in a struct map list.
242 * 1 : string = string to be parsed
244 * Returns : poniter to param list, or NULL if failiure
246 *********************************************************************/
247 struct map *parse_cgi(char *argstring)
250 char *vector[BUFSIZ];
252 struct map *cgi_params = NULL;
254 if(*argstring == '?') argstring++;
255 tmp = strdup(argstring);
257 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
259 for (i = 0; i < pairs; i++)
261 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
264 cgi_params = map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
274 /*********************************************************************
276 * Function : make_http_response
278 * Description : Fill in the missing headers in an http response,
279 * and flatten the headers to an http head.
282 * 1 : rsp = pointer to http_response to be processed
284 * Returns : length of http head, or 0 on failiure
286 *********************************************************************/
287 int make_http_response(struct http_response *rsp)
291 /* Fill in the HTTP Status */
292 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
293 enlist_first(rsp->headers, buf);
295 /* Set the Content-Length */
296 if (rsp->content_length == 0)
298 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
302 sprintf(buf, "Content-Length: %d", rsp->content_length);
303 enlist(rsp->headers, buf);
305 /* Fill in the default headers FIXME: Are these correct? sequence OK? check rfc! */
306 enlist_unique(rsp->headers, "Pragma: no-cache", 7);
307 enlist_unique(rsp->headers, "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT", 14);
308 enlist_unique(rsp->headers, "Expires: Thu Jul 31, 1997 07:42:22 pm GMT", 8);
309 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
310 enlist(rsp->headers, "");
314 if (NULL == (rsp->head = list_to_text(rsp->headers)))
316 free_http_response(rsp);
320 return(strlen(rsp->head));
324 /*********************************************************************
326 * Function : free_http_response
328 * Description : Free the memory occupied by an http_response
329 * and its depandant structures.
332 * 1 : rsp = pointer to http_response to be freed
336 *********************************************************************/
337 void free_http_response(struct http_response *rsp)
344 destroy_list(rsp->headers);
349 /*********************************************************************
351 * Function : fill_template
353 * Description : CGI support function that loads a given HTML
354 * template from the confdir, and fills it in
355 * by replacing @name@ with value using pcrs,
356 * for each item in the output map.
359 * 1 : csp = Current client state (buffers, headers, etc...)
360 * 3 : template = name of the HTML template to be used
361 * 2 : answers = map with fill in symbol -> name pairs
362 * FIXME: needs better name!
364 * Returns : char * with filled out form, or NULL if failiure
366 *********************************************************************/
367 char *fill_template(struct client_state *csp, char *template, struct map *answers)
370 pcrs_job *job, *joblist = NULL;
372 char *new, *old = NULL;
377 * Open template file or fail
379 snprintf(buf, BUFSIZ, "%s/templates/%s", csp->config->confdir, template);
381 if(NULL == (fp = fopen(buf, "r")))
383 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
388 * Assemble pcrs joblist from answers map
390 for (m = answers; m; m = m->next)
394 snprintf(buf, BUFSIZ, "s°@%s@°%s°ig", m->name, m->value);
396 if(NULL == (job = pcrs_make_job(buf, &error)))
398 log_error(LOG_LEVEL_ERROR, "Adding template fill job %s failed with error %d",
400 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
411 * Read the file, ignoring comments
413 while (fgets(buf, BUFSIZ, fp))
415 /* skip lines starting with '#' */
416 if(*buf == '#') continue;
418 old = strsav(old, buf);
425 size = strlen(old) + 1;
428 for (job = joblist; NULL != job; job = job->next)
430 pcrs_exec_substitution(job, old, size, &new, &size);
431 if (old != buf) free(old);
436 * Free the jobs & return
438 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
444 /*********************************************************************
446 * Function : dump_map
448 * Description : HTML-dump a map for debugging
451 * 1 : map = map to dump
453 * Returns : string with HTML
455 *********************************************************************/
456 char *dump_map(struct map *map)
462 ret = strsav(ret, "<table>\n");
466 ret = strsav(ret, "<tr><td><b>");
467 ret = strsav(ret, p->name);
468 ret = strsav(ret, "</b></td><td>");
469 ret = strsav(ret, p->value);
470 ret = strsav(ret, "</td></tr>\n");
474 ret = strsav(ret, "</table>\n");
479 /*********************************************************************
481 * Function : cgi_default
483 * Description : CGI function that is called if no action was given
484 * lists menu of available unhidden CGIs.
487 * 1 : csp = Current client state (buffers, headers, etc...)
488 * 2 : rsp = http_response data structure for output
489 * 3 : parameters = map of cgi parameters
493 *********************************************************************/
494 int cgi_default(struct client_state *csp, struct http_response *rsp,
495 struct map *parameters)
497 char *p, *tmp = NULL;
499 const struct cgi_dispatcher *d;
500 struct map *exports = NULL;
502 /* List available unhidden CGI's and export as "other-cgis" */
503 for (d = cgi_dispatchers; d->handler; d++)
505 if (strncmp(d->description, "HIDE", 4))
507 snprintf(buf, BUFSIZ, "<li><a href=%s/config/%s>%s</a></li>",
508 HOME_PAGE_URL, d->name, d->description);
509 tmp = strsav(tmp, buf);
512 exports = map(exports, "other-cgis", 1, tmp, 0);
514 /* If there were other parameters, export a dump as "cgi-parameters" */
517 p = dump_map(parameters);
518 tmp = strsav(tmp, "<p>What made you think this cgi takes options?\n
519 Anyway, here they are, in case you're interested:</p>\n");
520 tmp = strsav(tmp, p);
521 exports = map(exports, "cgi-parameters", 1, tmp, 0);
526 exports = map(exports, "cgi-parameters", 1, "", 1);
529 rsp->body = fill_template(csp, "default", exports);
537 /*********************************************************************
539 * Function : cgi_send_banner
541 * Description : CGI function that returns a banner.
544 * 1 : csp = Current client state (buffers, headers, etc...)
545 * 2 : rsp = http_response data structure for output
546 * 3 : parameters = map of cgi parameters
549 * type : Selects the type of banner between "trans" and "jb".
550 * Defaults to "jb" if absent or != "trans".
554 *********************************************************************/
555 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
556 struct map *parameters)
558 if(strcmp(lookup(parameters, "type"), "trans"))
560 rsp->body = bindup(CJBGIF, sizeof(CJBGIF));
561 rsp->content_length = sizeof(CJBGIF);
565 rsp->body = bindup(CBLANKGIF, sizeof(CBLANKGIF));
566 rsp->content_length = sizeof(CBLANKGIF);
569 enlist(rsp->headers, "Content-Type: image/gif");
575 #ifdef FAST_REDIRECTS
576 /*********************************************************************
578 * Function : redirect_url
580 * Description : Checks for redirection URLs and returns a HTTP redirect
581 * to the destination URL.
584 * 1 : http = http_request request, check `basename's of blocklist
585 * 2 : csp = Current client state (buffers, headers, etc...)
587 * Returns : NULL if URL was clean, HTTP redirect otherwise.
589 *********************************************************************/
590 char *redirect_url(struct http_request *http, struct client_state *csp)
594 p = q = csp->http->path;
595 log_error(LOG_LEVEL_REDIRECTS, "checking path: %s", p);
597 /* find the last URL encoded in the request */
598 while (p = strstr(p, "http://"))
603 /* if there was any, generate and return a HTTP redirect */
604 if (q != csp->http->path)
606 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
608 p = (char *)malloc(strlen(HTTP_REDIRECT_TEMPLATE) + strlen(q));
609 sprintf(p, HTTP_REDIRECT_TEMPLATE, q);
618 #endif /* def FAST_REDIRECTS */
622 /*********************************************************************
624 * Function : cgi_show_status
626 * Description : CGI function that returns a a web page describing the
627 * current status of IJB.
630 * 1 : csp = Current client state (buffers, headers, etc...)
631 * 2 : rsp = http_response data structure for output
632 * 3 : parameters = map of cgi parameters
635 * type : Selects the type of banner between "trans" and "jb".
636 * Defaults to "jb" if absent or != "trans".
640 *********************************************************************/
641 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
642 struct map *parameters)
645 const struct gateway *g;
648 struct map *exports = NULL;
650 #ifdef SPLIT_PROXY_ARGS
654 const char * filename = NULL;
655 char * file_description = NULL;
658 p = lookup(parameters, "file");
662 if (csp->actions_list)
664 filename = csp->actions_list->filename;
665 file_description = "Actions List";
671 filename = csp->flist->filename;
672 file_description = "Forward List";
680 filename = csp->alist->filename;
681 file_description = "Access Control List";
684 #endif /* def ACL_FILES */
690 filename = csp->rlist->filename;
691 file_description = "Regex Filter List";
694 #endif /* def PCRS */
700 filename = csp->tlist->filename;
701 file_description = "Trust List";
704 #endif /* def TRUST_FILES */
707 if (NULL != filename)
709 exports = map(exports, "filename", 1, file_description, 1);
710 exports = map(exports, "filepath", 1, html_encode(filename), 0);
712 if ((fp = fopen(filename, "r")) == NULL)
714 exports = map(exports, "content", 1, "</pre><h1>ERROR OPENING FILE!</h1><pre>", 1);
718 while (fgets(buf, sizeof(buf), fp))
720 p = html_encode(buf);
725 s = strsav(s, "<br>");
729 exports = map(exports, "contents", 1, s, 0);
731 rsp->body = fill_template(csp, "show-status-file", exports);;
737 #endif /* def SPLIT_PROXY_ARGS */
739 exports = map(exports, "redirect-url", 1, REDIRECT_URL, 1);
740 exports = map(exports, "version", 1, VERSION, 1);
741 exports = map(exports, "home-page", 1, HOME_PAGE_URL, 1);
742 exports = map(exports, "invocation-args", 1, csp->config->proxy_args_header, 1);
743 exports = map(exports, "gateways", 1, csp->config->proxy_args_gateways, 1);
744 exports = map(exports, "gateway-protocols", 1, s, 0);
748 exports = map(exports, "statistics", 1, add_stats(NULL), 0);
750 exports = map(exports, "statistics", 1, "", 1);
751 #endif /* ndef STATISTICS */
753 #ifdef SPLIT_PROXY_ARGS
754 if (csp->actions_list)
756 exports = map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
760 exports = map(exports, "actions-filename", 1, "None specified", 1);
765 exports = map(exports, "forward-filename", 1, csp->flist->filename, 1);
769 exports = map(exports, "forward-filename", 1, "None specified", 1);
775 exports = map(exports, "acl-filename", 1, csp->alist->filename, 1);
779 exports = map(exports, "acl-filename", 1, "None specified", 1);
782 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
783 #endif /* ndef ACL_FILES */
788 exports = map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
792 exports = map(exports, "re-filter-filename", 1, "None specified", 1);
795 exports = map(exports, "re-filter-killer-start.*re-filter-killer-end", 1, "", 1);
796 #endif /* ndef PCRS */
801 exports = map(exports, "trust-filename", 1, csp->tlist->filename, 1);
805 exports = map(exports, "trust-filename", 1, "None specified", 1);
808 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
809 #endif /* ndef TRUST_FILES */
811 exports = map(exports, ".list", 1, "" , 1);
813 #else /* ifndef SPLIT_PROXY_ARGS */
814 exports = map(exports, "magic-eliminator-start.*magic-eliminator-end", 1, "", 1);
818 map(exports, "clist", 1, csp->clist->proxy_args , 1);
823 map(exports, "flist", 1, csp->flist->proxy_args , 1);
829 map(exports, "alist", 1, csp->alist->proxy_args , 1);
831 #endif /* def ACL_FILES */
836 map(exports, "rlist", 1, csp->rlist->proxy_args , 1);
838 #endif /* def PCRS */
843 map(exports, "tlist", 1, csp->tlist->proxy_args , 1);
845 #endif /* def TRUST_FILES */
847 #endif /* ndef SPLIT_PROXY_ARGS */
849 s = end_proxy_args(csp->config);
850 exports = map(exports, "rcs-and-defines", 1, s , 0);
853 rsp->body = fill_template(csp, "show-status", exports);
860 /*********************************************************************
862 * Function : cgi_show_url_info
864 * Description : (please fill me in)
867 * 1 : http = http_request request for crunched URL
868 * 2 : csp = Current client state (buffers, headers, etc...)
872 *********************************************************************/
873 char *cgi_show_url_info(struct http_request *http, struct client_state *csp)
875 char * query_string = strchr(http->path, '?');
878 if (query_string != NULL)
880 query_string = url_decode(query_string + 1);
881 if (strncmpic(query_string, "url=", 4) == 0)
883 host = strdup(query_string + 4);
893 struct file_list *fl;
894 struct url_actions *b;
895 struct url_spec url[1];
896 struct current_action_spec action[1];
898 init_current_action(action);
900 result = (char *)malloc(sizeof(C_URL_INFO_HEADER) + 2 * strlen(host));
901 sprintf(result, C_URL_INFO_HEADER, host, host);
903 s = current_action_to_text(action);
904 result = strsav(result, "<h3>Defaults:</h3>\n<p><b>{");
905 result = strsav(result, s);
906 result = strsav(result, " }</b></p>\n<h3>Patterns affecting the URL:</h3>\n<p>\n");
909 s = strchr(host, '/');
919 s = strchr(host, ':');
926 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
930 result = strsav(result, C_URL_INFO_FOOTER);
936 /* if splitting the domain fails, punt */
937 if (url->dbuf == NULL)
941 result = strsav(result, C_URL_INFO_FOOTER);
945 for (b = b->next; NULL != b; b = b->next)
947 if ((b->url->port == 0) || (b->url->port == port))
949 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
951 if ((b->url->path == NULL) ||
953 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
955 (strncmp(b->url->path, path, b->url->pathlen) == 0)
959 s = actions_to_text(b->action);
960 result = strsav(result, "<b>{");
961 result = strsav(result, s);
962 result = strsav(result, " }</b><br>\n<code>");
963 result = strsav(result, b->url->spec);
964 result = strsav(result, "</code><br>\n<br>\n");
967 merge_current_action(action, b->action);
979 s = current_action_to_text(action);
980 result = strsav(result, "</p>\n<h2>Final Results:</h2>\n<p><b>{");
981 result = strsav(result, s);
982 result = strsav(result, " }</b><br>\n<br>\n");
985 free_current_action(action);
987 result = strsav(result, C_URL_INFO_FOOTER);
992 return strdup(C_URL_INFO_FORM);
999 /*********************************************************************
1001 * Function : ij_untrusted_url
1003 * Description : This "crunch"es "http:/any.thing/ij-untrusted-url" and
1004 * returns a web page describing why it was untrusted.
1007 * 1 : http = http_request request for crunched URL
1008 * 2 : csp = Current client state (buffers, headers, etc...)
1010 * Returns : A string that contains why this was untrusted.
1012 *********************************************************************/
1013 char *ij_untrusted_url(struct http_request *http, struct client_state *csp)
1016 char *hostport, *path, *refer, *p, *v[9];
1018 struct url_spec **tl, *t;
1021 static const char format[] =
1022 "HTTP/1.0 200 OK\r\n"
1023 "Pragma: no-cache\n"
1024 "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT\n"
1025 "Expires: Thu Jul 31, 1997 07:42:22 pm GMT\n"
1026 "Content-Type: text/html\n\n"
1029 "<title>Internet Junkbuster: Request for untrusted URL</title>\n"
1035 "The " BANNER " Proxy "
1036 "<A href=\"" HOME_PAGE_URL "\">"
1037 "(" HOME_PAGE_URL ") </A>"
1038 "intercepted the request for %s%s\n"
1039 "because the URL is not trusted.\n"
1042 if ((n = ssplit(http->path, "?+", v, SZ(v), 0, 0)) == 4)
1044 hostport = url_decode(v[1]);
1045 path = url_decode(v[2]);
1046 refer = url_decode(v[3]);
1050 hostport = strdup("undefined_host");
1051 path = strdup("/undefined_path");
1052 refer = strdup("undefined");
1056 n += strlen(hostport);
1059 if ((p = (char *)malloc(n)))
1061 sprintf(p, format, hostport, path);
1064 strsav(p, "The referrer in this request was <strong>");
1066 strsav(p, "</strong><br>\n");
1072 p = strsav(p, "<h3>The following referrers are trusted</h3>\n");
1074 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1076 sprintf(buf, "%s<br>\n", t->spec);
1080 if (csp->config->trust_info->next)
1086 "You can learn more about what this means "
1087 "and what you may be able to do about it by "
1088 "reading the following documents:<br>\n"
1094 for (l = csp->config->trust_info->next; l ; l = l->next)
1097 "<li> <a href=%s>%s</a><br>\n",
1102 p = strsav(p, "</ol>\n");
1105 p = strsav(p, "</body>\n" "</html>\n");
1110 #endif /* def TRUST_FILES */
1114 /*********************************************************************
1116 * Function : add_stats
1118 * Description : Statistics function of JB. Called by `show_proxy_args'.
1121 * 1 : s = string that holds the proxy args description page
1123 * Returns : A pointer to the descriptive status web page.
1125 *********************************************************************/
1126 char *add_stats(char *s)
1129 * Output details of the number of requests rejected and
1130 * accepted. This is switchable in the junkbuster config.
1131 * Does nothing if this option is not enabled.
1134 float perc_rej; /* Percentage of http requests rejected */
1136 int local_urls_read = urls_read;
1137 int local_urls_rejected = urls_rejected;
1140 * Need to alter the stats not to include the fetch of this
1143 * Can't do following thread safely! doh!
1146 * urls_rejected--; * This will be incremented subsequently *
1149 s = strsav(s,"<h2>Statistics for this " BANNER ":</h2>\n");
1151 if (local_urls_read == 0)
1154 s = strsav(s,"No activity so far!\n");
1160 perc_rej = (float)local_urls_rejected * 100.0F /
1161 (float)local_urls_read;
1164 "%d requests received, %d filtered "
1167 local_urls_rejected, perc_rej);
1169 s = strsav(s,out_str);
1174 #endif /* def STATISTICS */