1 const char cgi_rcs[] = "$Id: cgi.c,v 1.22 2001/09/16 11:00:10 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.22 2001/09/16 11:00:10 jongfoster
40 * New function alloc_http_response, for symmetry with free_http_response
42 * Revision 1.21 2001/09/13 23:53:03 jongfoster
43 * Support for both static and dynamically generated CGI pages.
44 * Correctly setting Last-Modified: and Expires: HTTP headers.
46 * Revision 1.20 2001/09/13 23:40:36 jongfoster
47 * (Cosmetic only) Indentation correction
49 * Revision 1.19 2001/09/13 23:31:25 jongfoster
50 * Moving image data to cgi.c rather than cgi.h.
52 * Revision 1.18 2001/08/05 16:06:20 jongfoster
53 * Modifiying "struct map" so that there are now separate header and
54 * "map_entry" structures. This means that functions which modify a
55 * map no longer need to return a pointer to the modified map.
56 * Also, it no longer reverses the order of the entries (which may be
57 * important with some advanced template substitutions).
59 * Revision 1.17 2001/08/05 15:57:38 oes
60 * Adapted finish_http_response to new list_to_text
62 * Revision 1.16 2001/08/01 21:33:18 jongfoster
63 * Changes to fill_template() that reduce memory usage without having
64 * an impact on performance. I also renamed some variables so as not
65 * to clash with the C++ keywords "new" and "template".
67 * Revision 1.15 2001/08/01 21:19:22 jongfoster
68 * Moving file version information to a separate CGI page.
70 * Revision 1.14 2001/08/01 00:19:03 jongfoster
71 * New function: map_conditional() for an if-then-else syntax.
72 * Changing to use new version of show_defines()
74 * Revision 1.13 2001/07/30 22:08:36 jongfoster
75 * Tidying up #defines:
76 * - All feature #defines are now of the form FEATURE_xxx
77 * - Permanently turned off WIN_GUI_EDIT
78 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
80 * Revision 1.12 2001/07/29 18:47:05 jongfoster
81 * Adding missing #include "loadcfg.h"
83 * Revision 1.11 2001/07/18 17:24:37 oes
84 * Changed to conform to new pcrs interface
86 * Revision 1.10 2001/07/13 13:53:13 oes
87 * Removed all #ifdef PCRS and related code
89 * Revision 1.9 2001/06/29 21:45:41 oes
90 * Indentation, CRLF->LF, Tab-> Space
92 * Revision 1.8 2001/06/29 13:21:46 oes
93 * - Cosmetics: renamed and reordered functions, variables,
94 * texts, improved comments etc
96 * - Removed ij_untrusted_url() The relevant
97 * info is now part of the "untrusted" page,
98 * which is generated by filters.c:trust_url()
100 * - Generators of content now call finish_http_response()
101 * themselves, making jcc.c:chat() a little less
104 * - Removed obsolete "Pragma: no-cache" from our headers
106 * - http_responses now know their head length
108 * - fill_template now uses the new interface to pcrs, so that
109 * - long jobs (like whole files) no longer have to be assembled
110 * in a fixed size buffer
111 * - the new T (trivial) option is used, and the replacement may
112 * contain Perl syntax backrefs without confusing pcrs
114 * - Introduced default_exports() which generates a set of exports
115 * common to all CGIs and other content generators
117 * - Introduced convenience function map_block_killer()
119 * - Introduced convenience function make_menu()
121 * - Introduced CGI-like function error_response() which generates
122 * the "No such domain" and "Connect failed" messages using the
125 * - cgi_show_url_info:
126 * - adapted to new CGI features
127 * - form and answers now generated from same template
128 * - http:// prefix in URL now OK
131 * - adapted to new CGI features
132 * - no longer uses csp->init_proxy_args
135 * - moved menu generation to make_menu()
137 * - add_stats now writes single export map entries instead
140 * - Moved redirect_url() to filters.c
142 * - Fixed mem leak in free_http_response(), map_block_killer(),
144 * - Removed logentry from cancelled commit
146 * Revision 1.7 2001/06/09 10:51:58 jongfoster
147 * Changing "show URL info" handler to new style.
148 * Changing BUFSIZ ==> BUFFER_SIZE
150 * Revision 1.6 2001/06/07 23:05:19 jongfoster
151 * Removing code related to old forward and ACL files.
153 * Revision 1.5 2001/06/05 19:59:16 jongfoster
154 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
156 * Revision 1.4 2001/06/04 10:41:52 swa
157 * show version string of cgi.h and cgi.c
159 * Revision 1.3 2001/06/03 19:12:16 oes
160 * introduced new cgi handling
162 * No revisions before 1.3
164 **********************************************************************/
170 #include <sys/types.h>
177 #define snprintf _snprintf
178 #endif /* def _WIN32 */
189 #include "miscutil.h"
190 #include "showargs.h"
193 const char cgi_h_rcs[] = CGI_H_VERSION;
195 const struct cgi_dispatcher cgi_dispatcher[] = {
198 "Show information about the current configuration" },
200 13, cgi_show_url_info,
201 "Show which actions apply to a URL and why" },
203 12, cgi_show_version,
204 "Show the source code version numbers" },
207 "HIDE Send the transparent or \"Junkbuster\" gif" },
210 "Junkbuster main page" },
211 { NULL, 0, NULL, NULL }
218 * Hint: You can encode your own GIFs like that:
219 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
222 const char image_junkbuster_gif_data[] =
223 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
224 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
225 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
226 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
227 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
228 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
229 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
232 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
235 const char image_blank_gif_data[] =
236 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
237 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
238 "\000\001\000\000\002\002D\001\000;";
240 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
243 /*********************************************************************
245 * Function : dispatch_cgi
247 * Description : Checks if a request URL has either the magical hostname
248 * i.j.b or matches HOME_PAGE_URL/config/. If so, it parses
249 * the (rest of the) path as a cgi name plus query string,
250 * prepares a map that maps CGI parameter names to their values,
251 * initializes the http_response struct, and calls the
252 * relevant CGI handler function.
255 * 1 : csp = Current client state (buffers, headers, etc...)
257 * Returns : http_response if match, NULL if nonmatch or handler fail
259 *********************************************************************/
260 struct http_response *dispatch_cgi(struct client_state *csp)
262 char *argstring = NULL;
263 const struct cgi_dispatcher *d;
264 struct map *param_list;
265 struct http_response *rsp;
268 * Should we intercept ?
271 /* Either the host matches CGI_PREFIX_HOST ..*/
272 if (0 == strcmpic(csp->http->host, CGI_PREFIX_HOST))
274 /* ..then the path will all be for us */
275 argstring = csp->http->path;
277 /* Or it's the host part HOME_PAGE_URL, and the path /config ? */
278 else if ( (0 == strcmpic(csp->http->host, HOME_PAGE_URL + 7 ))
279 && (0 == strncmpic(csp->http->path,"/config", 7))
280 && ((csp->http->path[7] == '/') || (csp->http->path[7] == '\0')))
282 /* then it's everything following "/config" */
283 argstring = csp->http->path + 7;
291 * This is a CGI call.
294 /* Get mem for response or fail*/
295 if (NULL == (rsp = alloc_http_response()))
300 /* Remove leading slash */
301 if (*argstring == '/')
306 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
307 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
308 csp->ip_addr_str, csp->http->cmd);
310 /* Find and start the right CGI function*/
311 for (d = cgi_dispatcher; d->handler; d++)
313 if (strncmp(argstring, d->name, d->name_length) == 0)
315 if (NULL == (param_list =
316 parse_cgi_parameters(argstring + d->name_length)))
318 free_map(param_list);
319 free_http_response(rsp);
322 if ((d->handler)(csp, rsp, param_list))
324 free_map(param_list);
325 free_http_response(rsp);
329 free_map(param_list);
330 return(finish_http_response(rsp));
334 /* Can't get here, since cgi_default will match all requests */
335 free_http_response(rsp);
341 /*********************************************************************
343 * Function : parse_cgi_parameters
345 * Description : Parse a URL-encoded argument string into name/value
346 * pairs and store them in a struct map list.
349 * 1 : string = string to be parsed
351 * Returns : pointer to param list, or NULL if out of memory.
353 *********************************************************************/
354 struct map *parse_cgi_parameters(char *argstring)
357 char *vector[BUFFER_SIZE];
359 struct map *cgi_params;
361 if (NULL == (cgi_params = new_map()))
366 if(*argstring == '?')
370 if (NULL == (tmp = strdup(argstring)))
372 free_map(cgi_params);
376 pairs = ssplit(tmp, "&", vector, SZ(vector), 1, 1);
378 for (i = 0; i < pairs; i++)
380 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
383 map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0);
393 /*********************************************************************
395 * Function : cgi_default
397 * Description : CGI function that is called if no action was given.
398 * Lists menu of available unhidden CGIs.
401 * 1 : csp = Current client state (buffers, headers, etc...)
402 * 2 : rsp = http_response data structure for output
403 * 3 : parameters = map of cgi parameters
407 *********************************************************************/
408 int cgi_default(struct client_state *csp, struct http_response *rsp,
409 struct map *parameters)
413 struct map * exports = default_exports(csp, "");
415 /* If there were other parameters, export a dump as "cgi-parameters" */
418 p = dump_map(parameters);
419 tmp = strsav(tmp, "<p>What made you think this cgi takes parameters?\n"
420 "Anyway, here they are, in case you're interested:</p>\n");
421 tmp = strsav(tmp, p);
422 map(exports, "cgi-parameters", 1, tmp, 0);
427 map(exports, "cgi-parameters", 1, "", 1);
430 rsp->body = fill_template(csp, "default", exports);
437 /*********************************************************************
439 * Function : cgi_send_banner
441 * Description : CGI function that returns a banner.
444 * 1 : csp = Current client state (buffers, headers, etc...)
445 * 2 : rsp = http_response data structure for output
446 * 3 : parameters = map of cgi parameters
449 * type : Selects the type of banner between "trans" and "jb".
450 * Defaults to "jb" if absent or != "trans".
454 *********************************************************************/
455 int cgi_send_banner(struct client_state *csp, struct http_response *rsp,
456 struct map *parameters)
458 if(strcmp(lookup(parameters, "type"), "trans"))
460 rsp->body = bindup(image_junkbuster_gif_data, image_junkbuster_gif_length);
461 rsp->content_length = image_junkbuster_gif_length;
465 rsp->body = bindup(image_blank_gif_data, image_blank_gif_length);
466 rsp->content_length = image_blank_gif_length;
469 enlist(rsp->headers, "Content-Type: image/gif");
477 /*********************************************************************
479 * Function : cgi_show_version
481 * Description : CGI function that returns a a web page describing the
482 * file versions of IJB.
485 * 1 : csp = Current client state (buffers, headers, etc...)
486 * 2 : rsp = http_response data structure for output
487 * 3 : parameters = map of cgi parameters
490 * type : Selects the type of banner between "trans" and "jb".
491 * Defaults to "jb" if absent or != "trans".
495 *********************************************************************/
496 int cgi_show_version(struct client_state *csp, struct http_response *rsp,
497 struct map *parameters)
499 struct map * exports = default_exports(csp, "show-version");
501 map(exports, "sourceversions", 1, show_rcs(), 0);
503 rsp->body = fill_template(csp, "show-version", exports);
510 /*********************************************************************
512 * Function : cgi_show_status
514 * Description : CGI function that returns a a web page describing the
515 * current status of IJB.
518 * 1 : csp = Current client state (buffers, headers, etc...)
519 * 2 : rsp = http_response data structure for output
520 * 3 : parameters = map of cgi parameters
523 * type : Selects the type of banner between "trans" and "jb".
524 * Defaults to "jb" if absent or != "trans".
528 *********************************************************************/
529 int cgi_show_status(struct client_state *csp, struct http_response *rsp,
530 struct map *parameters)
536 char buf[BUFFER_SIZE];
538 const char * filename = NULL;
539 char * file_description = NULL;
541 struct map * exports = default_exports(csp, "show-status");
543 switch (*(lookup(parameters, "file")))
546 if (csp->actions_list)
548 filename = csp->actions_list->filename;
549 file_description = "Actions List";
556 filename = csp->rlist->filename;
557 file_description = "Regex Filter List";
565 filename = csp->tlist->filename;
566 file_description = "Trust List";
569 #endif /* def FEATURE_TRUST */
572 if (NULL != filename)
574 map(exports, "file-description", 1, file_description, 1);
575 map(exports, "filepath", 1, html_encode(filename), 0);
577 if ((fp = fopen(filename, "r")) == NULL)
579 map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1);
583 while (fgets(buf, sizeof(buf), fp))
585 p = html_encode(buf);
590 s = strsav(s, "<br>");
594 map(exports, "contents", 1, s, 0);
596 rsp->body = fill_template(csp, "show-status-file", exports);
602 map(exports, "redirect-url", 1, REDIRECT_URL, 1);
605 for (i=0; i < Argc; i++)
607 s = strsav(s, Argv[i]);
610 map(exports, "invocation", 1, s, 0);
612 map(exports, "options", 1, csp->config->proxy_args, 1);
613 show_defines(exports);
615 #ifdef FEATURE_STATISTICS
617 #else /* ndef FEATURE_STATISTICS */
618 map_block_killer(exports, "statistics");
619 #endif /* ndef FEATURE_STATISTICS */
621 if (csp->actions_list)
623 map(exports, "actions-filename", 1, csp->actions_list->filename, 1);
627 map(exports, "actions-filename", 1, "None specified", 1);
632 map(exports, "re-filter-filename", 1, csp->rlist->filename, 1);
636 map(exports, "re-filter-filename", 1, "None specified", 1);
642 map(exports, "trust-filename", 1, csp->tlist->filename, 1);
646 map(exports, "trust-filename", 1, "None specified", 1);
649 map_block_killer(exports, "trust-support");
650 #endif /* ndef FEATURE_TRUST */
652 rsp->body = fill_template(csp, "show-status", exports);
659 /*********************************************************************
661 * Function : cgi_show_url_info
663 * Description : CGI function that determines and shows which actions
664 * junkbuster will perform for a given url, and which
665 * matches starting from the defaults have lead to that.
668 * 1 : csp = Current client state (buffers, headers, etc...)
669 * 2 : rsp = http_response data structure for output
670 * 3 : parameters = map of cgi parameters
673 * url : The url whose actions are to be determined.
674 * If url is unset, the url-given conditional will be
675 * set, so that all but the form can be suppressed in
680 *********************************************************************/
681 int cgi_show_url_info(struct client_state *csp, struct http_response *rsp,
682 struct map *parameters)
686 struct map * exports = default_exports(csp, "show-url-info");
688 if (NULL == (url_param = strdup(lookup(parameters, "url"))) || *url_param == '\0')
690 map_block_killer(exports, "url-given");
691 map(exports, "url", 1, "", 1);
695 char *matches = NULL;
700 struct file_list *fl;
701 struct url_actions *b;
702 struct url_spec url[1];
703 struct current_action_spec action[1];
706 host += (strncmp(url_param, "http://", 7)) ? 0 : 7;
708 map(exports, "url", 1, host, 1);
709 map(exports, "url-html", 1, html_encode(host), 0);
711 init_current_action(action);
713 s = current_action_to_text(action);
714 map(exports, "default", 1, s , 0);
716 if (((fl = csp->actions_list) == NULL) || ((b = fl->f) == NULL))
718 map(exports, "matches", 1, "none" , 1);
719 map(exports, "final", 1, lookup(exports, "default"), 1);
722 free_current_action(action);
724 rsp->body = fill_template(csp, "show-url-info", exports);
730 s = strchr(host, '/');
740 s = strchr(host, ':');
750 /* if splitting the domain fails, punt */
751 if (url->dbuf == NULL)
753 map(exports, "matches", 1, "none" , 1);
754 map(exports, "final", 1, lookup(exports, "default"), 1);
758 free_current_action(action);
760 rsp->body = fill_template(csp, "show-url-info", exports);
766 for (b = b->next; NULL != b; b = b->next)
768 if ((b->url->port == 0) || (b->url->port == port))
770 if ((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0))
772 if ((b->url->path == NULL) ||
774 (regexec(b->url->preg, path, 0, NULL, 0) == 0)
776 (strncmp(b->url->path, path, b->url->pathlen) == 0)
780 s = actions_to_text(b->action);
781 matches = strsav(matches, "<b>{");
782 matches = strsav(matches, s);
783 matches = strsav(matches, " }</b><br>\n<code>");
784 matches = strsav(matches, b->url->spec);
785 matches = strsav(matches, "</code><br>\n<br>\n");
788 merge_current_action(action, b->action);
797 map(exports, "matches", 1, matches , 0);
801 map(exports, "matches", 1, "none", 1);
811 s = current_action_to_text(action);
812 map(exports, "final", 1, s, 0);
815 free_current_action(action);
818 rsp->body = fill_template(csp, "show-url-info", exports);
825 /*********************************************************************
827 * Function : error_response
829 * Description : returns an http_response that explains the reason
830 * why a request failed.
833 * 1 : csp = Current client state (buffers, headers, etc...)
834 * 2 : templatename = Which template should be used for the answer
835 * 3 : errno = system error number
837 * Returns : NULL if no memory, else http_response
839 *********************************************************************/
840 struct http_response *error_response(struct client_state *csp, const char *templatename, int err)
842 struct http_response *rsp;
843 struct map * exports = default_exports(csp, NULL);
845 if (NULL == (rsp = alloc_http_response()))
850 map(exports, "host-html", 1, html_encode(csp->http->host), 0);
851 map(exports, "hostport", 1, csp->http->hostport, 1);
852 map(exports, "hostport-html", 1, html_encode(csp->http->hostport), 0);
853 map(exports, "path", 1, csp->http->path, 1);
854 map(exports, "path-html", 1, html_encode(csp->http->path), 0);
855 map(exports, "error", 1, safe_strerror(err), 0);
856 map(exports, "host-ip", 1, csp->http->host_ip_addr_str, 1);
858 rsp->body = fill_template(csp, templatename, exports);
861 if (!strcmp(templatename, "no-such-domain"))
863 rsp->status = strdup("404 No such domain");
865 else if (!strcmp(templatename, "connect-failed"))
867 rsp->status = strdup("503 Connect failed");
870 return(finish_http_response(rsp));
874 /*********************************************************************
876 * Function : get_http_time
878 * Description : Get the time in a format suitable for use in a
879 * HTTP header - e.g.:
880 * "Sun, 06 Nov 1994 08:49:37 GMT"
883 * 1 : time_offset = Time returned will be current time
884 * plus this number of seconds.
885 * 2 : buf = Destination for result. Must be long enough
886 * to hold 29 characters plus a trailing zero.
890 *********************************************************************/
891 static void get_http_time(int time_offset, char * buf)
893 static const char day_names[7][4] =
894 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
895 static const char month_names[12][4] =
896 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
897 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
904 time(¤t_time); /* get current time */
906 /* FIXME: is this needed? time() can't fail on Win32. What about Linux?
907 if(current_time <= 0)
913 current_time += time_offset;
915 /* get and save the gmt */
916 t = gmtime(¤t_time);
918 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
920 "%s, %02d %s %4d %02d:%02d:%02d GMT",
921 day_names[t->tm_wday],
923 month_names[t->tm_mon],
933 /*********************************************************************
935 * Function : finish_http_response
937 * Description : Fill in the missing headers in an http response,
938 * and flatten the headers to an http head.
941 * 1 : rsp = pointer to http_response to be processed
943 * Returns : http_response, or NULL on failiure
945 *********************************************************************/
946 struct http_response *finish_http_response(struct http_response *rsp)
948 char buf[BUFFER_SIZE];
951 * Fill in the HTTP Status
953 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
954 enlist_first(rsp->headers, buf);
957 * Set the Content-Length
959 if (rsp->content_length == 0)
961 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
963 sprintf(buf, "Content-Length: %d", rsp->content_length);
964 enlist(rsp->headers, buf);
967 * Fill in the default headers:
969 * Content-Type: default to text/html if not already specified.
970 * Date: set to current date/time.
971 * Last-Modified: set to date/time the page was last changed.
972 * Expires: set to date/time page next needs reloading.
973 * Cache-Control: set to "no-cache" if applicable.
975 * See http://www.w3.org/Protocols/rfc2068/rfc2068
977 enlist_unique(rsp->headers, "Content-Type: text/html", 13);
982 * Set Expires to about 10 min into the future so it'll get reloaded
983 * occasionally, e.g. if IJB gets upgraded.
986 get_http_time(0, buf);
987 enlist_unique_header(rsp->headers, "Date", buf);
989 /* Some date in the past. */
990 enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
992 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
993 enlist_unique_header(rsp->headers, "Expires", buf);
998 * Compliant browsers should not cache this due to the "Cache-Control"
999 * setting. However, to be certain, we also set both "Last-Modified"
1000 * and "Expires" to the current time.
1002 enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1003 get_http_time(0, buf);
1004 enlist_unique_header(rsp->headers, "Date", buf);
1005 enlist_unique_header(rsp->headers, "Last-Modified", buf);
1006 enlist_unique_header(rsp->headers, "Expires", buf);
1013 if (NULL == (rsp->head = list_to_text(rsp->headers)))
1015 free_http_response(rsp);
1018 rsp->head_length = strlen(rsp->head);
1025 /*********************************************************************
1027 * Function : alloc_http_response
1029 * Description : Allocates a new http_response structure.
1033 * Returns : pointer to a new http_response, or NULL.
1035 *********************************************************************/
1036 struct http_response * alloc_http_response(void)
1038 return (struct http_response *) zalloc(sizeof(struct http_response));
1042 /*********************************************************************
1044 * Function : free_http_response
1046 * Description : Free the memory occupied by an http_response
1047 * and its depandant structures.
1050 * 1 : rsp = pointer to http_response to be freed
1054 *********************************************************************/
1055 void free_http_response(struct http_response *rsp)
1062 destroy_list(rsp->headers);
1069 /*********************************************************************
1071 * Function : fill_template
1073 * Description : CGI support function that loads a given HTML
1074 * template from the confdir, and fills it in
1075 * by replacing @name@ with value using pcrs,
1076 * for each item in the output map.
1079 * 1 : csp = Current client state (buffers, headers, etc...)
1080 * 3 : template = name of the HTML template to be used
1081 * 2 : exports = map with fill in symbol -> name pairs
1083 * Returns : char * with filled out form, or NULL if failiure
1085 *********************************************************************/
1086 char *fill_template(struct client_state *csp, const char *templatename, struct map *exports)
1088 struct map_entry *m;
1090 char buf[BUFFER_SIZE];
1091 char *tmp_out_buffer;
1092 char *file_buffer = NULL;
1099 * Open template file or fail
1101 snprintf(buf, BUFFER_SIZE, "%s/templates/%s", csp->config->confdir, templatename);
1103 if(NULL == (fp = fopen(buf, "r")))
1105 log_error(LOG_LEVEL_ERROR, "error loading template %s: %E", buf);
1111 * Read the file, ignoring comments
1113 while (fgets(buf, BUFFER_SIZE, fp))
1115 /* skip lines starting with '#' */
1116 if(*buf == '#') continue;
1118 file_buffer = strsav(file_buffer, buf);
1126 size = strlen(file_buffer) + 1;
1129 * Assemble pcrs joblist from exports map
1131 for (m = exports->first; m != NULL; m = m->next)
1133 /* Enclose name in @@ */
1134 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1136 /* Make and run job. */
1137 job = pcrs_compile(buf, m->value, "sigTU", &error);
1140 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1144 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1145 if (file_buffer != tmp_out_buffer)
1148 file_buffer = tmp_out_buffer;
1158 return(file_buffer);
1163 /*********************************************************************
1165 * Function : default_exports
1167 * Description : returns a struct map list that contains exports
1168 * which are common to all CGI functions.
1171 * 1 : exports = Structure to write output to. This
1172 * structure should be newly allocated and will be
1174 * 1 : csp = Current client state (buffers, headers, etc...)
1175 * 2 : caller = name of CGI who calls us and which should
1176 * be excluded from the generated menu.
1177 * Returns : NULL if no memory, else map
1179 *********************************************************************/
1180 struct map * default_exports(const struct client_state *csp, const char *caller)
1183 struct map * exports = new_map();
1185 map(exports, "version", 1, VERSION, 1);
1186 map(exports, "my-ip-address", 1, csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown", 1);
1187 map(exports, "my-hostname", 1, csp->my_hostname ? csp->my_hostname : "unknown", 1);
1188 map(exports, "admin-address", 1, csp->config->admin_address ? csp->config->admin_address : "fill@me.in.please", 1);
1189 map(exports, "homepage", 1, HOME_PAGE_URL, 1);
1190 map(exports, "default-cgi", 1, HOME_PAGE_URL "/config", 1);
1191 map(exports, "menu", 1, make_menu(caller), 0);
1192 map(exports, "code-status", 1, CODE_STATUS, 1);
1194 snprintf(buf, 20, "%d", csp->config->hport);
1195 map(exports, "my-port", 1, buf, 1);
1197 if(!strcmp(CODE_STATUS, "stable"))
1199 map_block_killer(exports, "unstable");
1202 if(csp->config->proxy_info_url != NULL)
1204 map(exports, "proxy-info-url", 1, csp->config->proxy_info_url, 1);
1208 map_block_killer(exports, "have-proxy-info");
1215 /*********************************************************************
1217 * Function : map_block_killer
1219 * Description : Convenience function.
1220 * Adds a "killer" for the conditional HTML-template
1221 * block <name>, i.e. a substitution of the regex
1222 * "if-<name>-start.*if-<name>-end" to the given
1226 * 1 : exports = map to extend
1227 * 2 : name = name of conditional block
1229 * Returns : extended map
1231 *********************************************************************/
1232 void map_block_killer(struct map *exports, const char *name)
1234 char buf[1000]; /* Will do, since the names are hardwired */
1236 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1237 map(exports, buf, 1, "", 1);
1241 /*********************************************************************
1243 * Function : map_conditional
1245 * Description : Convenience function.
1246 * Adds an "if-then-else" for the conditional HTML-template
1247 * block <name>, i.e. a substitution of the form:
1254 * The control structure and one of the alternatives
1258 * 1 : exports = map to extend
1259 * 2 : name = name of conditional block
1260 * 3 : choose_first = nonzero for first, zero for second.
1262 * Returns : extended map
1264 *********************************************************************/
1265 void map_conditional(struct map *exports, const char *name, int choose_first)
1267 char buf[1000]; /* Will do, since the names are hardwired */
1269 snprintf(buf, 1000, (choose_first
1270 ? "else-not-%s@.*@endif-%s"
1271 : "if-%s-then@.*@else-not-%s"),
1273 map(exports, buf, 1, "", 1);
1275 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1276 map(exports, buf, 1, "", 1);
1280 /*********************************************************************
1282 * Function : make_menu
1284 * Description : Returns an HTML-formatted menu of the available
1285 * unhidden CGIs, excluding the one given in <self>.
1287 * Parameters : self = name of CGI to leave out, can be NULL
1289 * Returns : menu string
1291 *********************************************************************/
1292 char *make_menu(const char *self)
1294 const struct cgi_dispatcher *d;
1295 char buf[BUFFER_SIZE];
1296 char *result = NULL;
1300 self = "NO-SUCH-CGI!";
1303 /* List available unhidden CGI's and export as "other-cgis" */
1304 for (d = cgi_dispatcher; d->handler; d++)
1306 if (strncmp(d->description, "HIDE", 4) && strcmp(d->name, self))
1308 snprintf(buf, BUFFER_SIZE, "<li><a href=%s/config/%s>%s</a></li>\n",
1309 HOME_PAGE_URL, d->name, d->description);
1310 result = strsav(result, buf);
1318 /*********************************************************************
1320 * Function : dump_map
1322 * Description : HTML-dump a map for debugging
1325 * 1 : the_map = map to dump
1327 * Returns : string with HTML
1329 *********************************************************************/
1330 char *dump_map(const struct map *the_map)
1332 struct map_entry *cur_entry = the_map->first;
1335 ret = strsav(ret, "<table>\n");
1339 ret = strsav(ret, "<tr><td><b>");
1340 ret = strsav(ret, cur_entry->name);
1341 ret = strsav(ret, "</b></td><td>");
1342 ret = strsav(ret, cur_entry->value);
1343 ret = strsav(ret, "</td></tr>\n");
1344 cur_entry = cur_entry->next;
1347 ret = strsav(ret, "</table>\n");
1353 #ifdef FEATURE_STATISTICS
1354 /*********************************************************************
1356 * Function : add_stats
1358 * Description : Add the blocking statistics to a given map.
1361 * 1 : exports = map to write to.
1363 * Returns : pointer to extended map
1365 *********************************************************************/
1366 struct map *add_stats(struct map *exports)
1368 float perc_rej; /* Percentage of http requests rejected */
1370 int local_urls_read = urls_read;
1371 int local_urls_rejected = urls_rejected;
1374 * Need to alter the stats not to include the fetch of this
1377 * Can't do following thread safely! doh!
1380 * urls_rejected--; * This will be incremented subsequently *
1383 if (local_urls_read == 0)
1385 map_block_killer(exports, "have-stats");
1389 map_block_killer(exports, "have-no-stats");
1391 perc_rej = (float)local_urls_rejected * 100.0F /
1392 (float)local_urls_read;
1394 sprintf(buf, "%d", local_urls_read);
1395 map(exports, "requests-received", 1, buf, 1);
1397 sprintf(buf, "%d", local_urls_rejected);
1398 map(exports, "requests-blocked", 1, buf, 1);
1400 sprintf(buf, "%6.2f", perc_rej);
1401 map(exports, "percent-blocked", 1, buf, 1);
1407 #endif /* def FEATURE_STATISTICS */