1 const char cgi_rcs[] = "$Id: $";
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.
41 **********************************************************************/
47 #include <sys/types.h>
66 const struct cgi_dispatcher cgi_dispatchers[] = {
69 "Show information about the version and configuration" },
71 13, cgi_show_url_info,
72 "Show which actions apply to a URL and why" },*/
75 "HIDE Send the transparent or \"Junkbuster\" gif" },
79 "HIDE Show why a URL was not trusted" }, */
80 #endif /* def TRUST_FILES */
83 "HIDE Send a page linking to all unhidden CGIs" },
84 { NULL, 0, NULL, NULL }
88 /*********************************************************************
90 * Function : dispatch_cgi
92 * Description : Checks if a request URL has either the magical hostname
93 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
94 * the (rest of the) path as a cgi name plus query string,
95 * prepares a map that maps CGI parameter names to their values,
96 * initializes the http_response struct, and calls the
97 * relevant CGI handler function.
100 * 1 : csp = Current client state (buffers, headers, etc...)
102 * Returns : http_response if match, NULL if nonmatch or handler fail
104 *********************************************************************/
105 struct http_response *cgi_dispatch(struct client_state *csp)
107 char *argstring = NULL;
108 const struct cgi_dispatcher *d;
109 struct map *param_list;
110 struct http_response *response;
113 * Should we intercept ?
116 /* Either the host matches CGI_PREFIX_HOST ..*/
117 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
119 /* ..then the path will all be for us */
120 argstring = csp->http->path;
122 /* Or it's the host part of HOME_PAGE_URL ? */
123 else if ( (0 == strcmpic(csp->http->host, *&HOME_PAGE_URL + 7 ))
124 && (0 == strncmpic(csp->http->path,"/config", 7))
125 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
127 /* then it's everything following "/config" */
128 argstring = csp->http->path + 7;
136 * We have intercepted it.
139 /* Get mem for response */
140 if (NULL == ( response = zalloc(sizeof(*response))))
145 /* remove any leading slash */
146 if (*argstring == '/')
151 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
152 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
153 csp->ip_addr_str, csp->http->cmd);
155 for (d = cgi_dispatchers; d->handler; d++)
157 if (strncmp(argstring, d->name, d->name_length) == 0)
159 param_list = parse_cgi(argstring + d->name_length);
160 if ((d->handler)(csp, response, param_list))
165 free_map(param_list);
176 /*********************************************************************
178 * Function : parse_cgi
180 * Description : Parse a URL-encoded argument string into name/value
181 * pairs and store them in a struct map list.
184 * 1 : string = string to be parsed
186 * Returns : poniter to param list, or NULL if failiure
188 *********************************************************************/
189 struct map *parse_cgi(char *argstring)
192 char *vector[BUFSIZ];
194 struct map *cgi_params = NULL;
196 if(*argstring == '?') argstring++;
197 tmp = strdup(argstring);
199 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
201 for (i = 0; i < pairs; i++)
203 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
206 cgi_params = map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
216 /*********************************************************************
218 * Function : make_http_response
220 * Description : Fill in the missing headers in an http response,
221 * and flatten the headers to an http head.
224 * 1 : rsp = pointer to http_response to be processed
226 * Returns : length of http head, or 0 on failiure
228 *********************************************************************/
229 int make_http_response(struct http_response *rsp)
233 /* Fill in the HTTP Status */
234 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
235 enlist_first(rsp->headers, buf);
237 /* Set the Content-Length */
238 if (rsp->content_length == 0)
240 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
244 sprintf(buf, "Content-Length: %d", rsp->content_length);
245 enlist(rsp->headers, buf);
247 /* Fill in the default headers FIXME: Are these correct? sequence OK? check rfc! */
248 enlist_unique(rsp->headers, "Pragma: no-cache", 7);
249 enlist_unique(rsp->headers, "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT", 14);
250 enlist_unique(rsp->headers, "Expires: Thu Jul 31, 1997 07:42:22 pm GMT", 8);
251 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
252 enlist(rsp->headers, "");
256 if (NULL == (rsp->head = list_to_text(rsp->headers)))
258 free_http_response(rsp);
262 return(strlen(rsp->head));
266 /*********************************************************************
268 * Function : free_http_response
270 * Description : Free the memory occupied by an http_response
271 * and its depandant structures.
274 * 1 : rsp = pointer to http_response to be freed
278 *********************************************************************/
279 void free_http_response(struct http_response *rsp)
286 destroy_list(rsp->headers);
291 /*********************************************************************
293 * Function : fill_template
295 * Description : CGI support function that loads a given HTML
296 * template from the confdir, and fills it in
297 * by replacing @name@ with value using pcrs,
298 * for each item in the output map.
301 * 1 : csp = Current client state (buffers, headers, etc...)
302 * 3 : template = name of the HTML template to be used
303 * 2 : answers = map with fill in symbol -> name pairs
304 * FIXME: needs better name!
306 * Returns : char * with filled out form, or NULL if failiure
308 *********************************************************************/
309 char *fill_template(struct client_state *csp, char *template, struct map *answers)
312 pcrs_job *job, *joblist = NULL;
314 char *new, *old = NULL;
319 * Open template file or fail
321 snprintf(buf, BUFSIZ, "%s/templates/%s", csp->config->confdir, template);
323 if(NULL == (fp = fopen(buf, "r")))
325 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
330 * Assemble pcrs joblist from answers map
332 for (m = answers; m; m = m->next)
336 snprintf(buf, BUFSIZ, "s°@%s@°%s°ig", m->name, m->value);
338 if(NULL == (job = pcrs_make_job(buf, &error)))
340 log_error(LOG_LEVEL_ERROR, "Adding template fill job %s failed with error %d",
342 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
353 * Read the file, ignoring comments
355 while (fgets(buf, BUFSIZ, fp))
357 /* skip lines starting with '#' */
358 if(*buf == '#') continue;
360 old = strsav(old, buf);
367 size = strlen(old) + 1;
370 for (job = joblist; NULL != job; job = job->next)
372 pcrs_exec_substitution(job, old, size, &new, &size);
373 if (old != buf) free(old);
378 * Free the jobs & return
380 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
386 /*********************************************************************
388 * Function : dump_map
390 * Description : HTML-dump a map for debugging
393 * 1 : map = map to dump
395 * Returns : string with HTML
397 *********************************************************************/
398 char *dump_map(struct map *map)
404 ret = strsav(ret, "<table>\n");
408 ret = strsav(ret, "<tr><td><b>");
409 ret = strsav(ret, p->name);
410 ret = strsav(ret, "</b></td><td>");
411 ret = strsav(ret, p->value);
412 ret = strsav(ret, "</td></tr>\n");
416 ret = strsav(ret, "</table>\n");
421 /*********************************************************************
423 * Function : cgi_default
425 * Description : CGI function that is called if no action was given
426 * lists menu of available unhidden CGIs.
429 * 1 : csp = Current client state (buffers, headers, etc...)
430 * 2 : rsp = http_response data structure for output
431 * 3 : parameters = map of cgi parameters
435 *********************************************************************/
436 int cgi_default(struct client_state *csp, struct http_response *rsp,
437 struct map *parameters)
439 char *p, *tmp = NULL;
441 const struct cgi_dispatcher *d;
442 struct map *exports = NULL;
444 /* List available unhidden CGI's and export as "other-cgis" */
445 for (d = cgi_dispatchers; d->handler; d++)
447 if (strncmp(d->description, "HIDE", 4))
449 snprintf(buf, BUFSIZ, "<li><a href=%s/config/%s>%s</a></li>",
450 HOME_PAGE_URL, d->name, d->description);
451 tmp = strsav(tmp, buf);
454 exports = map(exports, "other-cgis", 1, tmp, 0);
456 /* If there were other parameters, export a dump as "cgi-parameters" */
459 p = dump_map(parameters);
460 tmp = strsav(tmp, "<p>What made you think this cgi takes options?\n
461 Anyway, here they are, in case you're interested:</p>\n");
462 tmp = strsav(tmp, p);
463 exports = map(exports, "cgi-parameters", 1, tmp, 0);
468 exports = map(exports, "cgi-parameters", 1, "", 1);
471 rsp->body = fill_template(csp, "default", exports);
479 /*********************************************************************
481 * Function : cgi_send_banner
483 * Description : CGI function that returns a banner.
486 * 1 : csp = Current client state (buffers, headers, etc...)
487 * 2 : rsp = http_response data structure for output
488 * 3 : parameters = map of cgi parameters
491 * type : Selects the type of banner between "trans" and "jb".
492 * Defaults to "jb" if absent or != "trans".
496 *********************************************************************/
497 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
498 struct map *parameters)
500 if(strcmp(lookup(parameters, "type"), "trans"))
502 rsp->body = bindup(CJBGIF, sizeof(CJBGIF));
503 rsp->content_length = sizeof(CJBGIF);
507 rsp->body = bindup(CBLANKGIF, sizeof(CBLANKGIF));
508 rsp->content_length = sizeof(CBLANKGIF);
511 enlist(rsp->headers, "Content-Type: image/gif");
517 #ifdef FAST_REDIRECTS
518 /*********************************************************************
520 * Function : redirect_url
522 * Description : Checks for redirection URLs and returns a HTTP redirect
523 * to the destination URL.
526 * 1 : http = http_request request, check `basename's of blocklist
527 * 2 : csp = Current client state (buffers, headers, etc...)
529 * Returns : NULL if URL was clean, HTTP redirect otherwise.
531 *********************************************************************/
532 char *redirect_url(struct http_request *http, struct client_state *csp)
536 p = q = csp->http->path;
537 log_error(LOG_LEVEL_REDIRECTS, "checking path: %s", p);
539 /* find the last URL encoded in the request */
540 while (p = strstr(p, "http://"))
545 /* if there was any, generate and return a HTTP redirect */
546 if (q != csp->http->path)
548 log_error(LOG_LEVEL_REDIRECTS, "redirecting to: %s", q);
550 p = (char *)malloc(strlen(HTTP_REDIRECT_TEMPLATE) + strlen(q));
551 sprintf(p, HTTP_REDIRECT_TEMPLATE, q);
560 #endif /* def FAST_REDIRECTS */
564 /*********************************************************************
566 * Function : cgi_show_status
568 * Description : CGI function that returns a a web page describing the
569 * current status of IJB.
572 * 1 : csp = Current client state (buffers, headers, etc...)
573 * 2 : rsp = http_response data structure for output
574 * 3 : parameters = map of cgi parameters
577 * type : Selects the type of banner between "trans" and "jb".
578 * Defaults to "jb" if absent or != "trans".
582 *********************************************************************/
583 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
584 struct map *parameters)
587 const struct gateway *g;
590 struct map *exports = NULL;
592 #ifdef SPLIT_PROXY_ARGS
596 const char * filename = NULL;
597 char * file_description = NULL;
600 p = lookup(parameters, "file");
604 if (csp->actions_list)
606 filename = csp->actions_list->filename;
607 file_description = "Actions List";
613 filename = csp->flist->filename;
614 file_description = "Forward List";
622 filename = csp->alist->filename;
623 file_description = "Access Control List";
626 #endif /* def ACL_FILES */
632 filename = csp->rlist->filename;
633 file_description = "Regex Filter List";
636 #endif /* def PCRS */
642 filename = csp->tlist->filename;
643 file_description = "Trust List";
646 #endif /* def TRUST_FILES */
649 if (NULL != filename)
651 exports = map(exports, "filename", 1, file_description, 1);
652 exports = map(exports, "filepath", 1, html_encode(filename), 0);
654 if ((fp = fopen(filename, "r")) == NULL)
656 exports = map(exports, "content", 1, "</pre><h1>ERROR OPENING FILE!</h1><pre>", 1);
660 while (fgets(buf, sizeof(buf), fp))
662 p = html_encode(buf);
667 s = strsav(s, "<br>");
671 exports = map(exports, "contents", 1, s, 0);
673 rsp->body = fill_template(csp, "show-status-file", exports);;
679 #endif /* def SPLIT_PROXY_ARGS */
681 exports = map(exports, "redirect-url", 1, REDIRECT_URL, 1);
682 exports = map(exports, "version", 1, VERSION, 1);
683 exports = map(exports, "home-page", 1, HOME_PAGE_URL, 1);
684 exports = map(exports, "invocation-args", 1, csp->config->proxy_args_header, 1);
685 exports = map(exports, "gateways", 1, csp->config->proxy_args_gateways, 1);
686 exports = map(exports, "gateway-protocols", 1, s, 0);
690 exports = map(exports, "statistics", 1, add_stats(NULL), 0);
692 exports = map(exports, "statistics", 1, "", 1);
693 #endif /* ndef STATISTICS */
695 #ifdef SPLIT_PROXY_ARGS
696 if (csp->actions_list)
698 exports = map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
702 exports = map(exports, "actions-filename", 1, "None specified", 1);
707 exports = map(exports, "forward-filename", 1, csp->flist->filename, 1);
711 exports = map(exports, "forward-filename", 1, "None specified", 1);
717 exports = map(exports, "acl-filename", 1, csp->alist->filename, 1);
721 exports = map(exports, "acl-filename", 1, "None specified", 1);
724 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
725 #endif /* ndef ACL_FILES */
730 exports = map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
734 exports = map(exports, "re-filter-filename", 1, "None specified", 1);
737 exports = map(exports, "re-filter-killer-start.*re-filter-killer-end", 1, "", 1);
738 #endif /* ndef PCRS */
743 exports = map(exports, "trust-filename", 1, csp->tlist->filename, 1);
747 exports = map(exports, "trust-filename", 1, "None specified", 1);
750 exports = map(exports, "acl-killer-start.*acl-killer-end", 1, "", 1);
751 #endif /* ndef TRUST_FILES */
753 exports = map(exports, ".list", 1, "" , 1);
755 #else /* ifndef SPLIT_PROXY_ARGS */
756 exports = map(exports, "magic-eliminator-start.*magic-eliminator-end", 1, "", 1);
760 map(exports, "clist", 1, csp->clist->proxy_args , 1);
765 map(exports, "flist", 1, csp->flist->proxy_args , 1);
771 map(exports, "alist", 1, csp->alist->proxy_args , 1);
773 #endif /* def ACL_FILES */
778 map(exports, "rlist", 1, csp->rlist->proxy_args , 1);
780 #endif /* def PCRS */
785 map(exports, "tlist", 1, csp->tlist->proxy_args , 1);
787 #endif /* def TRUST_FILES */
789 #endif /* ndef SPLIT_PROXY_ARGS */
791 s = end_proxy_args(csp->config);
792 exports = map(exports, "rcs-and-defines", 1, s , 0);
795 rsp->body = fill_template(csp, "show-status", exports);
802 /*********************************************************************
804 * Function : cgi_show_url_info
806 * Description : (please fill me in)
809 * 1 : http = http_request request for crunched URL
810 * 2 : csp = Current client state (buffers, headers, etc...)
814 *********************************************************************/
815 char *cgi_show_url_info(struct http_request *http, struct client_state *csp)
817 char * query_string = strchr(http->path, '?');
820 if (query_string != NULL)
822 query_string = url_decode(query_string + 1);
823 if (strncmpic(query_string, "url=", 4) == 0)
825 host = strdup(query_string + 4);
835 struct file_list *fl;
836 struct url_actions *b;
837 struct url_spec url[1];
838 struct current_action_spec action[1];
840 init_current_action(action);
842 result = (char *)malloc(sizeof(C_URL_INFO_HEADER) + 2 * strlen(host));
843 sprintf(result, C_URL_INFO_HEADER, host, host);
845 s = current_action_to_text(action);
846 result = strsav(result, "<h3>Defaults:</h3>\n<p><b>{");
847 result = strsav(result, s);
848 result = strsav(result, " }</b></p>\n<h3>Patterns affecting the URL:</h3>\n<p>\n");
851 s = strchr(host, '/');
861 s = strchr(host, ':');
868 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
872 result = strsav(result, C_URL_INFO_FOOTER);
878 /* if splitting the domain fails, punt */
879 if (url->dbuf == NULL)
883 result = strsav(result, C_URL_INFO_FOOTER);
887 for (b = b->next; NULL != b; b = b->next)
889 if ((b->url->port == 0) || (b->url->port == port))
891 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
893 if ((b->url->path == NULL) ||
895 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
897 (strncmp(b->url->path, path, b->url->pathlen) == 0)
901 s = actions_to_text(b->action);
902 result = strsav(result, "<b>{");
903 result = strsav(result, s);
904 result = strsav(result, " }</b><br>\n<code>");
905 result = strsav(result, b->url->spec);
906 result = strsav(result, "</code><br>\n<br>\n");
909 merge_current_action(action, b->action);
921 s = current_action_to_text(action);
922 result = strsav(result, "</p>\n<h2>Final Results:</h2>\n<p><b>{");
923 result = strsav(result, s);
924 result = strsav(result, " }</b><br>\n<br>\n");
927 free_current_action(action);
929 result = strsav(result, C_URL_INFO_FOOTER);
934 return strdup(C_URL_INFO_FORM);
941 /*********************************************************************
943 * Function : ij_untrusted_url
945 * Description : This "crunch"es "http:/any.thing/ij-untrusted-url" and
946 * returns a web page describing why it was untrusted.
949 * 1 : http = http_request request for crunched URL
950 * 2 : csp = Current client state (buffers, headers, etc...)
952 * Returns : A string that contains why this was untrusted.
954 *********************************************************************/
955 char *ij_untrusted_url(struct http_request *http, struct client_state *csp)
958 char *hostport, *path, *refer, *p, *v[9];
960 struct url_spec **tl, *t;
963 static const char format[] =
964 "HTTP/1.0 200 OK\r\n"
966 "Last-Modified: Thu Jul 31, 1997 07:42:22 pm GMT\n"
967 "Expires: Thu Jul 31, 1997 07:42:22 pm GMT\n"
968 "Content-Type: text/html\n\n"
971 "<title>Internet Junkbuster: Request for untrusted URL</title>\n"
977 "The " BANNER " Proxy "
978 "<A href=\"" HOME_PAGE_URL "\">"
979 "(" HOME_PAGE_URL ") </A>"
980 "intercepted the request for %s%s\n"
981 "because the URL is not trusted.\n"
984 if ((n = ssplit(http->path, "?+", v, SZ(v), 0, 0)) == 4)
986 hostport = url_decode(v[1]);
987 path = url_decode(v[2]);
988 refer = url_decode(v[3]);
992 hostport = strdup("undefined_host");
993 path = strdup("/undefined_path");
994 refer = strdup("undefined");
998 n += strlen(hostport);
1001 if ((p = (char *)malloc(n)))
1003 sprintf(p, format, hostport, path);
1006 strsav(p, "The referrer in this request was <strong>");
1008 strsav(p, "</strong><br>\n");
1014 p = strsav(p, "<h3>The following referrers are trusted</h3>\n");
1016 for (tl = csp->config->trust_list; (t = *tl) ; tl++)
1018 sprintf(buf, "%s<br>\n", t->spec);
1022 if (csp->config->trust_info->next)
1028 "You can learn more about what this means "
1029 "and what you may be able to do about it by "
1030 "reading the following documents:<br>\n"
1036 for (l = csp->config->trust_info->next; l ; l = l->next)
1039 "<li> <a href=%s>%s</a><br>\n",
1044 p = strsav(p, "</ol>\n");
1047 p = strsav(p, "</body>\n" "</html>\n");
1052 #endif /* def TRUST_FILES */
1056 /*********************************************************************
1058 * Function : add_stats
1060 * Description : Statistics function of JB. Called by `show_proxy_args'.
1063 * 1 : s = string that holds the proxy args description page
1065 * Returns : A pointer to the descriptive status web page.
1067 *********************************************************************/
1068 char *add_stats(char *s)
1071 * Output details of the number of requests rejected and
1072 * accepted. This is switchable in the junkbuster config.
1073 * Does nothing if this option is not enabled.
1076 float perc_rej; /* Percentage of http requests rejected */
1078 int local_urls_read = urls_read;
1079 int local_urls_rejected = urls_rejected;
1082 * Need to alter the stats not to include the fetch of this
1085 * Can't do following thread safely! doh!
1088 * urls_rejected--; * This will be incremented subsequently *
1091 s = strsav(s,"<h2>Statistics for this " BANNER ":</h2>\n");
1093 if (local_urls_read == 0)
1096 s = strsav(s,"No activity so far!\n");
1102 perc_rej = (float)local_urls_rejected * 100.0F /
1103 (float)local_urls_read;
1106 "%d requests received, %d filtered "
1109 local_urls_rejected, perc_rej);
1111 s = strsav(s,out_str);
1116 #endif /* def STATISTICS */