1 const char cgi_rcs[] = "$Id: cgi.c,v 1.21 2001/09/13 23:53:03 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.21 2001/09/13 23:53:03 jongfoster
40 * Support for both static and dynamically generated CGI pages.
41 * Correctly setting Last-Modified: and Expires: HTTP headers.
43 * Revision 1.20 2001/09/13 23:40:36 jongfoster
44 * (Cosmetic only) Indentation correction
46 * Revision 1.19 2001/09/13 23:31:25 jongfoster
47 * Moving image data to cgi.c rather than cgi.h.
49 * Revision 1.18 2001/08/05 16:06:20 jongfoster
50 * Modifiying "struct map" so that there are now separate header and
51 * "map_entry" structures. This means that functions which modify a
52 * map no longer need to return a pointer to the modified map.
53 * Also, it no longer reverses the order of the entries (which may be
54 * important with some advanced template substitutions).
56 * Revision 1.17 2001/08/05 15:57:38 oes
57 * Adapted finish_http_response to new list_to_text
59 * Revision 1.16 2001/08/01 21:33:18 jongfoster
60 * Changes to fill_template() that reduce memory usage without having
61 * an impact on performance. I also renamed some variables so as not
62 * to clash with the C++ keywords "new" and "template".
64 * Revision 1.15 2001/08/01 21:19:22 jongfoster
65 * Moving file version information to a separate CGI page.
67 * Revision 1.14 2001/08/01 00:19:03 jongfoster
68 * New function: map_conditional() for an if-then-else syntax.
69 * Changing to use new version of show_defines()
71 * Revision 1.13 2001/07/30 22:08:36 jongfoster
72 * Tidying up #defines:
73 * - All feature #defines are now of the form FEATURE_xxx
74 * - Permanently turned off WIN_GUI_EDIT
75 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
77 * Revision 1.12 2001/07/29 18:47:05 jongfoster
78 * Adding missing #include "loadcfg.h"
80 * Revision 1.11 2001/07/18 17:24:37 oes
81 * Changed to conform to new pcrs interface
83 * Revision 1.10 2001/07/13 13:53:13 oes
84 * Removed all #ifdef PCRS and related code
86 * Revision 1.9 2001/06/29 21:45:41 oes
87 * Indentation, CRLF->LF, Tab-> Space
89 * Revision 1.8 2001/06/29 13:21:46 oes
90 * - Cosmetics: renamed and reordered functions, variables,
91 * texts, improved comments etc
93 * - Removed ij_untrusted_url() The relevant
94 * info is now part of the "untrusted" page,
95 * which is generated by filters.c:trust_url()
97 * - Generators of content now call finish_http_response()
98 * themselves, making jcc.c:chat() a little less
101 * - Removed obsolete "Pragma: no-cache" from our headers
103 * - http_responses now know their head length
105 * - fill_template now uses the new interface to pcrs, so that
106 * - long jobs (like whole files) no longer have to be assembled
107 * in a fixed size buffer
108 * - the new T (trivial) option is used, and the replacement may
109 * contain Perl syntax backrefs without confusing pcrs
111 * - Introduced default_exports() which generates a set of exports
112 * common to all CGIs and other content generators
114 * - Introduced convenience function map_block_killer()
116 * - Introduced convenience function make_menu()
118 * - Introduced CGI-like function error_response() which generates
119 * the "No such domain" and "Connect failed" messages using the
122 * - cgi_show_url_info:
123 * - adapted to new CGI features
124 * - form and answers now generated from same template
125 * - http:// prefix in URL now OK
128 * - adapted to new CGI features
129 * - no longer uses csp->init_proxy_args
132 * - moved menu generation to make_menu()
134 * - add_stats now writes single export map entries instead
137 * - Moved redirect_url() to filters.c
139 * - Fixed mem leak in free_http_response(), map_block_killer(),
141 * - Removed logentry from cancelled commit
143 * Revision 1.7 2001/06/09 10:51:58 jongfoster
144 * Changing "show URL info" handler to new style.
145 * Changing BUFSIZ ==> BUFFER_SIZE
147 * Revision 1.6 2001/06/07 23:05:19 jongfoster
148 * Removing code related to old forward and ACL files.
150 * Revision 1.5 2001/06/05 19:59:16 jongfoster
151 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
153 * Revision 1.4 2001/06/04 10:41:52 swa
154 * show version string of cgi.h and cgi.c
156 * Revision 1.3 2001/06/03 19:12:16 oes
157 * introduced new cgi handling
159 * No revisions before 1.3
161 **********************************************************************/
167 #include <sys/types.h>
174 #define snprintf _snprintf
175 #endif /* def _WIN32 */
186 #include "miscutil.h"
187 #include "showargs.h"
190 const char cgi_h_rcs[] = CGI_H_VERSION;
192 const struct cgi_dispatcher cgi_dispatcher[] = {
195 "Show information about the current configuration" },
197 13, cgi_show_url_info,
198 "Show which actions apply to a URL and why" },
200 12, cgi_show_version,
201 "Show the source code version numbers" },
204 "HIDE Send the transparent or \"Junkbuster\" gif" },
207 "Junkbuster main page" },
208 { NULL, 0, NULL, NULL }
215 * Hint: You can encode your own GIFs like that:
216 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
219 const char image_junkbuster_gif_data[] =
220 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
221 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
222 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
223 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
224 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
225 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
226 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
229 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
232 const char image_blank_gif_data[] =
233 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
234 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
235 "\000\001\000\000\002\002D\001\000;";
237 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
240 /*********************************************************************
242 * Function : dispatch_cgi
244 * Description : Checks if a request URL has either the magical hostname
245 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
246 * the (rest of the) path as a cgi name plus query string,
247 * prepares a map that maps CGI parameter names to their values,
248 * initializes the http_response struct, and calls the
249 * relevant CGI handler function.
252 * 1 : csp = Current client state (buffers, headers, etc...)
254 * Returns : http_response if match, NULL if nonmatch or handler fail
256 *********************************************************************/
257 struct http_response *dispatch_cgi(struct client_state *csp)
259 char *argstring = NULL;
260 const struct cgi_dispatcher *d;
261 struct map *param_list;
262 struct http_response *rsp;
265 * Should we intercept ?
268 /* Either the host matches CGI_PREFIX_HOST ..*/
269 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
271 /* ..then the path will all be for us */
272 argstring = csp->http->path;
274 /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
275 else if ( (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
276 && (0 == strncmpic(csp->http->path,"/config", 7))
277 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
279 /* then it's everything following "/config" */
280 argstring = csp->http->path + 7;
288 * This is a CGI call.
291 /* Get mem for response or fail*/
292 if (NULL == (rsp = alloc_http_response()))
297 /* Remove leading slash */
298 if (*argstring == '/')
303 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
304 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
305 csp->ip_addr_str, csp->http->cmd);
307 /* Find and start the right CGI function*/
308 for (d = cgi_dispatcher; d->handler; d++)
310 if (strncmp(argstring, d->name, d->name_length) == 0)
312 param_list = parse_cgi_parameters(argstring + d->name_length);
313 if ((d->handler)(csp, rsp, param_list))
318 free_map(param_list);
319 return(finish_http_response(rsp));
323 /* Can't get here, since cgi_default will match all requests */
330 /*********************************************************************
332 * Function : parse_cgi_parameters
334 * Description : Parse a URL-encoded argument string into name/value
335 * pairs and store them in a struct map list.
338 * 1 : string = string to be parsed
340 * Returns : pointer to param list
342 *********************************************************************/
343 struct map *parse_cgi_parameters(char *argstring)
346 char *vector[BUFFER_SIZE];
348 struct map *cgi_params = new_map();
350 if(*argstring == '?')
354 tmp = strdup(argstring);
356 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
358 for (i = 0; i < pairs; i++)
360 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
363 map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
373 /*********************************************************************
375 * Function : cgi_default
377 * Description : CGI function that is called if no action was given.
378 * Lists menu of available unhidden CGIs.
381 * 1 : csp = Current client state (buffers, headers, etc...)
382 * 2 : rsp = http_response data structure for output
383 * 3 : parameters = map of cgi parameters
387 *********************************************************************/
388 int cgi_default(struct client_state *csp, struct http_response *rsp,
389 struct map *parameters)
393 struct map * exports = default_exports(csp, "");
395 /* If there were other parameters, export a dump as "cgi-parameters" */
398 p = dump_map(parameters);
399 tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
400 "Anyway, here they are, in case you're interested:</p>\n");
401 tmp = strsav(tmp, p);
402 map(exports, "cgi-parameters", 1, tmp, 0);
407 map(exports, "cgi-parameters", 1, "", 1);
410 rsp->body = fill_template(csp, "default", exports);
417 /*********************************************************************
419 * Function : cgi_send_banner
421 * Description : CGI function that returns a banner.
424 * 1 : csp = Current client state (buffers, headers, etc...)
425 * 2 : rsp = http_response data structure for output
426 * 3 : parameters = map of cgi parameters
429 * type : Selects the type of banner between "trans" and "jb".
430 * Defaults to "jb" if absent or != "trans".
434 *********************************************************************/
435 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
436 struct map *parameters)
438 if(strcmp(lookup(parameters, "type"), "trans"))
440 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
441 rsp->content_length = image_junkbuster_gif_length;
445 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
446 rsp->content_length = image_blank_gif_length;
449 enlist(rsp->headers, "Content-Type: image/gif");
457 /*********************************************************************
459 * Function : cgi_show_version
461 * Description : CGI function that returns a a web page describing the
462 * file versions of IJB.
465 * 1 : csp = Current client state (buffers, headers, etc...)
466 * 2 : rsp = http_response data structure for output
467 * 3 : parameters = map of cgi parameters
470 * type : Selects the type of banner between "trans" and "jb".
471 * Defaults to "jb" if absent or != "trans".
475 *********************************************************************/
476 int cgi_show_version(struct client_state *csp, struct http_response *rsp,
477 struct map *parameters)
479 struct map * exports = default_exports(csp, "show-version");
481 map(exports, "sourceversions", 1, show_rcs(), 0);
483 rsp->body = fill_template(csp, "show-version", exports);
490 /*********************************************************************
492 * Function : cgi_show_status
494 * Description : CGI function that returns a a web page describing the
495 * current status of IJB.
498 * 1 : csp = Current client state (buffers, headers, etc...)
499 * 2 : rsp = http_response data structure for output
500 * 3 : parameters = map of cgi parameters
503 * type : Selects the type of banner between "trans" and "jb".
504 * Defaults to "jb" if absent or != "trans".
508 *********************************************************************/
509 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
510 struct map *parameters)
516 char buf[BUFFER_SIZE];
518 const char * filename = NULL;
519 char * file_description = NULL;
521 struct map * exports = default_exports(csp, "show-status");
523 switch (*(lookup(parameters, "file")))
526 if (csp->actions_list)
528 filename = csp->actions_list->filename;
529 file_description = "Actions List";
536 filename = csp->rlist->filename;
537 file_description = "Regex Filter List";
545 filename = csp->tlist->filename;
546 file_description = "Trust List";
549 #endif /* def FEATURE_TRUST */
552 if (NULL != filename)
554 map(exports, "file-description", 1, file_description, 1);
555 map(exports, "filepath", 1, html_encode(filename), 0);
557 if ((fp = fopen(filename, "r")) == NULL)
559 map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
563 while (fgets(buf, sizeof(buf), fp))
565 p = html_encode(buf);
570 s = strsav(s, "<br>");
574 map(exports, "contents", 1, s, 0);
576 rsp->body = fill_template(csp, "show-status-file", exports);
582 map(exports, "redirect-url", 1, REDIRECT_URL, 1);
585 for (i=0; i < Argc; i++)
587 s = strsav(s, Argv[i]);
590 map(exports, "invocation", 1, s, 0);
592 map(exports, "options", 1, csp->config->proxy_args, 1);
593 show_defines(exports);
595 #ifdef FEATURE_STATISTICS
597 #else /* ndef FEATURE_STATISTICS */
598 map_block_killer(exports, "statistics");
599 #endif /* ndef FEATURE_STATISTICS */
601 if (csp->actions_list)
603 map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
607 map(exports, "actions-filename", 1, "None specified", 1);
612 map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
616 map(exports, "re-filter-filename", 1, "None specified", 1);
622 map(exports, "trust-filename", 1, csp->tlist->filename, 1);
626 map(exports, "trust-filename", 1, "None specified", 1);
629 map_block_killer(exports, "trust-support");
630 #endif /* ndef FEATURE_TRUST */
632 rsp->body = fill_template(csp, "show-status", exports);
639 /*********************************************************************
641 * Function : cgi_show_url_info
643 * Description : CGI function that determines and shows which actions
644 * junkbuster will perform for a given url, and which
645 * matches starting from the defaults have lead to that.
648 * 1 : csp = Current client state (buffers, headers, etc...)
649 * 2 : rsp = http_response data structure for output
650 * 3 : parameters = map of cgi parameters
653 * url : The url whose actions are to be determined.
654 * If url is unset, the url-given conditional will be
655 * set, so that all but the form can be suppressed in
660 *********************************************************************/
661 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
662 struct map *parameters)
666 struct map * exports = default_exports(csp, "show-url-info");
668 if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
670 map_block_killer(exports, "url-given");
671 map(exports, "url", 1, "", 1);
675 char *matches = NULL;
680 struct file_list *fl;
681 struct url_actions *b;
682 struct url_spec url[1];
683 struct current_action_spec action[1];
686 host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
688 map(exports, "url", 1, host, 1);
689 map(exports, "url-html", 1, html_encode(host), 0);
691 init_current_action(action);
693 s = current_action_to_text(action);
694 map(exports, "default", 1, s , 0);
696 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
698 map(exports, "matches", 1, "none" , 1);
699 map(exports, "final", 1, lookup(exports, "default"), 1);
702 free_current_action(action);
704 rsp->body = fill_template(csp, "show-url-info", exports);
710 s = strchr(host, '/');
720 s = strchr(host, ':');
730 /* if splitting the domain fails, punt */
731 if (url->dbuf == NULL)
733 map(exports, "matches", 1, "none" , 1);
734 map(exports, "final", 1, lookup(exports, "default"), 1);
738 free_current_action(action);
740 rsp->body = fill_template(csp, "show-url-info", exports);
746 for (b = b->next; NULL != b; b = b->next)
748 if ((b->url->port == 0) || (b->url->port == port))
750 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
752 if ((b->url->path == NULL) ||
754 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
756 (strncmp(b->url->path, path, b->url->pathlen) == 0)
760 s = actions_to_text(b->action);
761 matches = strsav(matches, "<b>{");
762 matches = strsav(matches, s);
763 matches = strsav(matches, " }</b><br>\n<code>");
764 matches = strsav(matches, b->url->spec);
765 matches = strsav(matches, "</code><br>\n<br>\n");
768 merge_current_action(action, b->action);
777 map(exports, "matches", 1, matches , 0);
781 map(exports, "matches", 1, "none", 1);
791 s = current_action_to_text(action);
792 map(exports, "final", 1, s, 0);
795 free_current_action(action);
798 rsp->body = fill_template(csp, "show-url-info", exports);
805 /*********************************************************************
807 * Function : error_response
809 * Description : returns an http_response that explains the reason
810 * why a request failed.
813 * 1 : csp = Current client state (buffers, headers, etc...)
814 * 2 : templatename = Which template should be used for the answer
815 * 3 : errno = system error number
817 * Returns : NULL if no memory, else http_response
819 *********************************************************************/
820 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
822 struct http_response *rsp;
823 struct map * exports = default_exports(csp, NULL);
825 if (NULL == (rsp = alloc_http_response()))
830 map(exports, "host-html", 1, html_encode(csp->http->host), 0);
831 map(exports, "hostport", 1, csp->http->hostport, 1);
832 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
833 map(exports, "path", 1, csp->http->path, 1);
834 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
835 map(exports, "error", 1, safe_strerror(err), 0);
836 map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
838 rsp->body = fill_template(csp, templatename, exports);
841 if (!strcmp(templatename, "no-such-domain"))
843 rsp->status = strdup("404 No such domain");
845 else if (!strcmp(templatename, "connect-failed"))
847 rsp->status = strdup("503 Connect failed");
850 return(finish_http_response(rsp));
854 /*********************************************************************
856 * Function : get_http_time
858 * Description : Get the time in a format suitable for use in a
859 * HTTP header - e.g.:
860 * "Sun, 06 Nov 1994 08:49:37 GMT"
863 * 1 : time_offset = Time returned will be current time
864 * plus this number of seconds.
865 * 2 : buf = Destination for result. Must be long enough
866 * to hold 29 characters plus a trailing zero.
870 *********************************************************************/
871 static void get_http_time(int time_offset, char * buf)
873 static const char day_names[7][4] =
874 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
875 static const char month_names[12][4] =
876 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
877 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
884 time(¤t_time); /* get current time */
886 /* FIXME: is this needed? time() can't fail on Win32. What about Linux?
887 if(current_time <= 0)
893 current_time += time_offset;
895 /* get and save the gmt */
896 t = gmtime(¤t_time);
898 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
900 "%s, %02d %s %4d %02d:%02d:%02d GMT",
901 day_names[t->tm_wday],
903 month_names[t->tm_mon],
913 /*********************************************************************
915 * Function : finish_http_response
917 * Description : Fill in the missing headers in an http response,
918 * and flatten the headers to an http head.
921 * 1 : rsp = pointer to http_response to be processed
923 * Returns : http_response, or NULL on failiure
925 *********************************************************************/
926 struct http_response *finish_http_response(struct http_response *rsp)
928 char buf[BUFFER_SIZE];
931 * Fill in the HTTP Status
933 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
934 enlist_first(rsp->headers, buf);
937 * Set the Content-Length
939 if (rsp->content_length == 0)
941 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
943 sprintf(buf, "Content-Length: %d", rsp->content_length);
944 enlist(rsp->headers, buf);
947 * Fill in the default headers:
949 * Content-Type: default to text/html if not already specified.
950 * Date: set to current date/time.
951 * Last-Modified: set to date/time the page was last changed.
952 * Expires: set to date/time page next needs reloading.
953 * Cache-Control: set to "no-cache" if applicable.
955 * See http://www.w3.org/Protocols/rfc2068/rfc2068
957 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
962 * Set Expires to about 10 min into the future so it'll get reloaded
963 * occasionally, e.g. if IJB gets upgraded.
966 get_http_time(0, buf);
967 enlist_unique_header(rsp->headers, "Date", buf);
969 /* Some date in the past. */
970 enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
972 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
973 enlist_unique_header(rsp->headers, "Expires", buf);
978 * Compliant browsers should not cache this due to the "Cache-Control"
979 * setting. However, to be certain, we also set both "Last-Modified"
980 * and "Expires" to the current time.
982 enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
983 get_http_time(0, buf);
984 enlist_unique_header(rsp->headers, "Date", buf);
985 enlist_unique_header(rsp->headers, "Last-Modified", buf);
986 enlist_unique_header(rsp->headers, "Expires", buf);
993 if (NULL == (rsp->head = list_to_text(rsp->headers)))
995 free_http_response(rsp);
998 rsp->head_length = strlen(rsp->head);
1005 /*********************************************************************
1007 * Function : alloc_http_response
1009 * Description : Allocates a new http_response structure.
1013 * Returns : pointer to a new http_response, or NULL.
1015 *********************************************************************/
1016 struct http_response * alloc_http_response(void)
1018 return (struct http_response *) zalloc(sizeof(struct http_response));
1022 /*********************************************************************
1024 * Function : free_http_response
1026 * Description : Free the memory occupied by an http_response
1027 * and its depandant structures.
1030 * 1 : rsp = pointer to http_response to be freed
1034 *********************************************************************/
1035 void free_http_response(struct http_response *rsp)
1042 destroy_list(rsp->headers);
1049 /*********************************************************************
1051 * Function : fill_template
1053 * Description : CGI support function that loads a given HTML
1054 * template from the confdir, and fills it in
1055 * by replacing @name@ with value using pcrs,
1056 * for each item in the output map.
1059 * 1 : csp = Current client state (buffers, headers, etc...)
1060 * 3 : template = name of the HTML template to be used
1061 * 2 : exports = map with fill in symbol -> name pairs
1063 * Returns : char * with filled out form, or NULL if failiure
1065 *********************************************************************/
1066 char *fill_template(struct client_state *csp, const char *templatename, struct map *exports)
1068 struct map_entry *m;
1070 char buf[BUFFER_SIZE];
1071 char *tmp_out_buffer;
1072 char *file_buffer = NULL;
1079 * Open template file or fail
1081 snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
1083 if(NULL == (fp = fopen(buf, "r")))
1085 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
1091 * Read the file, ignoring comments
1093 while (fgets(buf, BUFFER_SIZE, fp))
1095 /* skip lines starting with '#' */
1096 if(*buf == '#') continue;
1098 file_buffer = strsav(file_buffer, buf);
1106 size = strlen(file_buffer) + 1;
1109 * Assemble pcrs joblist from exports map
1111 for (m = exports->first; m != NULL; m = m->next)
1113 /* Enclose name in @@ */
1114 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1116 /* Make and run job. */
1117 job = pcrs_compile(buf, m->value, "sigTU", &error);
1120 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1124 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1125 if (file_buffer != tmp_out_buffer)
1128 file_buffer = tmp_out_buffer;
1138 return(file_buffer);
1143 /*********************************************************************
1145 * Function : default_exports
1147 * Description : returns a struct map list that contains exports
1148 * which are common to all CGI functions.
1151 * 1 : exports = Structure to write output to. This
1152 * structure should be newly allocated and will be
1154 * 1 : csp = Current client state (buffers, headers, etc...)
1155 * 2 : caller = name of CGI who calls us and which should
1156 * be excluded from the generated menu.
1157 * Returns : NULL if no memory, else map
1159 *********************************************************************/
1160 struct map * default_exports(const struct client_state *csp, const char *caller)
1163 struct map * exports = new_map();
1165 map(exports, "version", 1, VERSION, 1);
1166 map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1167 map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1168 map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
1169 map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1170 map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1171 map(exports, "menu", 1, make_menu(caller), 0);
1172 map(exports, "code-status", 1, CODE_STATUS, 1);
1174 snprintf(buf, 20, "%d", csp->config->hport);
1175 map(exports, "my-port", 1, buf, 1);
1177 if(!strcmp(CODE_STATUS, "stable"))
1179 map_block_killer(exports, "unstable");
1182 if(csp->config->proxy_info_url != NULL)
1184 map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1188 map_block_killer(exports, "have-proxy-info");
1195 /*********************************************************************
1197 * Function : map_block_killer
1199 * Description : Convenience function.
1200 * Adds a "killer" for the conditional HTML-template
1201 * block <name>, i.e. a substitution of the regex
1202 * "if-<name>-start.*if-<name>-end" to the given
1206 * 1 : exports = map to extend
1207 * 2 : name = name of conditional block
1209 * Returns : extended map
1211 *********************************************************************/
1212 void map_block_killer(struct map *exports, const char *name)
1214 char buf[1000]; /* Will do, since the names are hardwired */
1216 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1217 map(exports, buf, 1, "", 1);
1221 /*********************************************************************
1223 * Function : map_conditional
1225 * Description : Convenience function.
1226 * Adds an "if-then-else" for the conditional HTML-template
1227 * block <name>, i.e. a substitution of the form:
1234 * The control structure and one of the alternatives
1238 * 1 : exports = map to extend
1239 * 2 : name = name of conditional block
1240 * 3 : choose_first = nonzero for first, zero for second.
1242 * Returns : extended map
1244 *********************************************************************/
1245 void map_conditional(struct map *exports, const char *name, int choose_first)
1247 char buf[1000]; /* Will do, since the names are hardwired */
1249 snprintf(buf, 1000, (choose_first
1250 ? "else-not-%s@.*@endif-%s"
1251 : "if-%s-then@.*@else-not-%s"),
1253 map(exports, buf, 1, "", 1);
1255 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1256 map(exports, buf, 1, "", 1);
1260 /*********************************************************************
1262 * Function : make_menu
1264 * Description : Returns an HTML-formatted menu of the available
1265 * unhidden CGIs, excluding the one given in <self>.
1267 * Parameters : self = name of CGI to leave out, can be NULL
1269 * Returns : menu string
1271 *********************************************************************/
1272 char *make_menu(const char *self)
1274 const struct cgi_dispatcher *d;
1275 char buf[BUFFER_SIZE];
1276 char *result = NULL;
1280 self = "NO-SUCH-CGI!";
1283 /* List available unhidden CGI's and export as "other-cgis" */
1284 for (d = cgi_dispatcher; d->handler; d++)
1286 if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1288 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1289 HOME_PAGE_URL, d->name, d->description);
1290 result = strsav(result, buf);
1298 /*********************************************************************
1300 * Function : dump_map
1302 * Description : HTML-dump a map for debugging
1305 * 1 : the_map = map to dump
1307 * Returns : string with HTML
1309 *********************************************************************/
1310 char *dump_map(const struct map *the_map)
1312 struct map_entry *cur_entry = the_map->first;
1315 ret = strsav(ret, "<table>\n");
1319 ret = strsav(ret, "<tr><td><b>");
1320 ret = strsav(ret, cur_entry->name);
1321 ret = strsav(ret, "</b></td><td>");
1322 ret = strsav(ret, cur_entry->value);
1323 ret = strsav(ret, "</td></tr>\n");
1324 cur_entry = cur_entry->next;
1327 ret = strsav(ret, "</table>\n");
1333 #ifdef FEATURE_STATISTICS
1334 /*********************************************************************
1336 * Function : add_stats
1338 * Description : Add the blocking statistics to a given map.
1341 * 1 : exports = map to write to.
1343 * Returns : pointer to extended map
1345 *********************************************************************/
1346 struct map *add_stats(struct map *exports)
1348 float perc_rej; /* Percentage of http requests rejected */
1350 int local_urls_read = urls_read;
1351 int local_urls_rejected = urls_rejected;
1354 * Need to alter the stats not to include the fetch of this
1357 * Can't do following thread safely! doh!
1360 * urls_rejected--; * This will be incremented subsequently *
1363 if (local_urls_read == 0)
1365 map_block_killer(exports, "have-stats");
1369 map_block_killer(exports, "have-no-stats");
1371 perc_rej = (float)local_urls_rejected * 100.0F /
1372 (float)local_urls_read;
1374 sprintf(buf, "%d", local_urls_read);
1375 map(exports, "requests-received", 1, buf, 1);
1377 sprintf(buf, "%d", local_urls_rejected);
1378 map(exports, "requests-blocked", 1, buf, 1);
1380 sprintf(buf, "%6.2f", perc_rej);
1381 map(exports, "percent-blocked", 1, buf, 1);
1387 #endif /* def FEATURE_STATISTICS */