1 const char cgi_rcs[] = "$Id: cgi.c,v 1.41 2002/01/17 20:56:22 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.
8 * This only contains the framework functions, the
9 * actual handler functions are declared elsewhere.
11 * Functions declared include:
14 * Copyright : Written by and Copyright (C) 2001 the SourceForge
15 * IJBSWA team. http://ijbswa.sourceforge.net
17 * Based on the Internet Junkbuster originally written
18 * by and Copyright (C) 1997 Anonymous Coders and
19 * Junkbusters Corporation. http://www.junkbusters.com
21 * This program is free software; you can redistribute it
22 * and/or modify it under the terms of the GNU General
23 * Public License as published by the Free Software
24 * Foundation; either version 2 of the License, or (at
25 * your option) any later version.
27 * This program is distributed in the hope that it will
28 * be useful, but WITHOUT ANY WARRANTY; without even the
29 * implied warranty of MERCHANTABILITY or FITNESS FOR A
30 * PARTICULAR PURPOSE. See the GNU General Public
31 * License for more details.
33 * The GNU General Public License should be included with
34 * this file. If not, you can view it at
35 * http://www.gnu.org/copyleft/gpl.html
36 * or write to the Free Software Foundation, Inc., 59
37 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
41 * Revision 1.41 2002/01/17 20:56:22 jongfoster
42 * Replacing hard references to the URL of the config interface
43 * with #defines from project.h
45 * Revision 1.40 2002/01/09 14:26:46 oes
46 * Added support for thread-safe gmtime_r call.
48 * Revision 1.39 2001/11/16 00:48:13 jongfoster
49 * Fixing a compiler warning
51 * Revision 1.38 2001/11/13 00:31:21 jongfoster
52 * - Adding new CGIs for use by non-JavaScript browsers:
53 * edit-actions-url-form
54 * edit-actions-add-url-form
55 * edit-actions-remove-url-form
56 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
59 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
60 * Show enablement/disablement status in almost all templates.
61 * There is a little trickiness here: apparent recursive resolution of
62 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
63 * the actual enablement status. So a similar construct,
64 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
67 * Revision 1.36 2001/10/26 17:33:27 oes
70 * Revision 1.35 2001/10/23 21:48:19 jongfoster
71 * Cleaning up error handling in CGI functions - they now send back
72 * a HTML error page and should never cause a FATAL error. (Fixes one
73 * potential source of "denial of service" attacks).
75 * CGI actions file editor that works and is actually useful.
77 * Ability to toggle JunkBuster remotely using a CGI call.
79 * You can turn off both the above features in the main configuration
80 * file, e.g. if you are running a multi-user proxy.
82 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
83 * Only show "Local support" on templates conditionally:
84 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
85 * - if not, no Local support section appears
87 * Revision 1.33 2001/10/14 22:28:41 jongfoster
90 * Revision 1.32 2001/10/14 22:20:18 jongfoster
91 * - Changes to CGI dispatching method to match CGI names exactly,
92 * rather than doing a prefix match.
93 * - No longer need to count the length of the CGI handler names by hand.
94 * - Adding new handler for 404 error when disptching a CGI, if none of
96 * - Adding new handlers for CGI actionsfile editor.
98 * Revision 1.31 2001/10/10 10:56:39 oes
99 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
101 * Revision 1.30 2001/10/02 15:30:57 oes
102 * Introduced show-request cgi
104 * Revision 1.29 2001/09/20 15:47:44 steudten
106 * Fix BUG: Modify int size to size_t size in fill_template()
107 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
109 * Revision 1.28 2001/09/19 18:00:37 oes
110 * - Deletef time() FIXME (Can't fail under Linux either, if
111 * the argument is guaranteed to be in out address space,
114 * - Pointer notation cosmetics
115 * - Fixed a minor bug in template_fill(): Failiure of
116 * pcrs_execute() now secure.
118 * Revision 1.27 2001/09/16 17:08:54 jongfoster
119 * Moving simple CGI functions from cgi.c to new file cgisimple.c
121 * Revision 1.26 2001/09/16 15:47:37 jongfoster
122 * First version of CGI-based edit interface. This is very much a
123 * work-in-progress, and you can't actually use it to edit anything
124 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
125 * to have any effect.
127 * Revision 1.25 2001/09/16 15:02:35 jongfoster
128 * Adding i.j.b/robots.txt.
129 * Inlining add_stats() since it's only ever called from one place.
131 * Revision 1.24 2001/09/16 11:38:01 jongfoster
132 * Splitting fill_template() into 2 functions:
133 * template_load() loads the file
134 * template_fill() performs the PCRS regexps.
135 * This is because the CGI edit interface has a "table row"
136 * template which is used many times in the page - this
137 * change means it's only loaded from disk once.
139 * Revision 1.23 2001/09/16 11:16:05 jongfoster
140 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
142 * Revision 1.22 2001/09/16 11:00:10 jongfoster
143 * New function alloc_http_response, for symmetry with free_http_response
145 * Revision 1.21 2001/09/13 23:53:03 jongfoster
146 * Support for both static and dynamically generated CGI pages.
147 * Correctly setting Last-Modified: and Expires: HTTP headers.
149 * Revision 1.20 2001/09/13 23:40:36 jongfoster
150 * (Cosmetic only) Indentation correction
152 * Revision 1.19 2001/09/13 23:31:25 jongfoster
153 * Moving image data to cgi.c rather than cgi.h.
155 * Revision 1.18 2001/08/05 16:06:20 jongfoster
156 * Modifiying "struct map" so that there are now separate header and
157 * "map_entry" structures. This means that functions which modify a
158 * map no longer need to return a pointer to the modified map.
159 * Also, it no longer reverses the order of the entries (which may be
160 * important with some advanced template substitutions).
162 * Revision 1.17 2001/08/05 15:57:38 oes
163 * Adapted finish_http_response to new list_to_text
165 * Revision 1.16 2001/08/01 21:33:18 jongfoster
166 * Changes to fill_template() that reduce memory usage without having
167 * an impact on performance. I also renamed some variables so as not
168 * to clash with the C++ keywords "new" and "template".
170 * Revision 1.15 2001/08/01 21:19:22 jongfoster
171 * Moving file version information to a separate CGI page.
173 * Revision 1.14 2001/08/01 00:19:03 jongfoster
174 * New function: map_conditional() for an if-then-else syntax.
175 * Changing to use new version of show_defines()
177 * Revision 1.13 2001/07/30 22:08:36 jongfoster
178 * Tidying up #defines:
179 * - All feature #defines are now of the form FEATURE_xxx
180 * - Permanently turned off WIN_GUI_EDIT
181 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
183 * Revision 1.12 2001/07/29 18:47:05 jongfoster
184 * Adding missing #include "loadcfg.h"
186 * Revision 1.11 2001/07/18 17:24:37 oes
187 * Changed to conform to new pcrs interface
189 * Revision 1.10 2001/07/13 13:53:13 oes
190 * Removed all #ifdef PCRS and related code
192 * Revision 1.9 2001/06/29 21:45:41 oes
193 * Indentation, CRLF->LF, Tab-> Space
195 * Revision 1.8 2001/06/29 13:21:46 oes
196 * - Cosmetics: renamed and reordered functions, variables,
197 * texts, improved comments etc
199 * - Removed ij_untrusted_url() The relevant
200 * info is now part of the "untrusted" page,
201 * which is generated by filters.c:trust_url()
203 * - Generators of content now call finish_http_response()
204 * themselves, making jcc.c:chat() a little less
207 * - Removed obsolete "Pragma: no-cache" from our headers
209 * - http_responses now know their head length
211 * - fill_template now uses the new interface to pcrs, so that
212 * - long jobs (like whole files) no longer have to be assembled
213 * in a fixed size buffer
214 * - the new T (trivial) option is used, and the replacement may
215 * contain Perl syntax backrefs without confusing pcrs
217 * - Introduced default_exports() which generates a set of exports
218 * common to all CGIs and other content generators
220 * - Introduced convenience function map_block_killer()
222 * - Introduced convenience function make_menu()
224 * - Introduced CGI-like function error_response() which generates
225 * the "No such domain" and "Connect failed" messages using the
228 * - cgi_show_url_info:
229 * - adapted to new CGI features
230 * - form and answers now generated from same template
231 * - http:// prefix in URL now OK
234 * - adapted to new CGI features
235 * - no longer uses csp->init_proxy_args
238 * - moved menu generation to make_menu()
240 * - add_stats now writes single export map entries instead
243 * - Moved redirect_url() to filters.c
245 * - Fixed mem leak in free_http_response(), map_block_killer(),
247 * - Removed logentry from cancelled commit
249 * Revision 1.7 2001/06/09 10:51:58 jongfoster
250 * Changing "show URL info" handler to new style.
251 * Changing BUFSIZ ==> BUFFER_SIZE
253 * Revision 1.6 2001/06/07 23:05:19 jongfoster
254 * Removing code related to old forward and ACL files.
256 * Revision 1.5 2001/06/05 19:59:16 jongfoster
257 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
259 * Revision 1.4 2001/06/04 10:41:52 swa
260 * show version string of cgi.h and cgi.c
262 * Revision 1.3 2001/06/03 19:12:16 oes
263 * introduced new cgi handling
265 * No revisions before 1.3
267 **********************************************************************/
273 #include <sys/types.h>
280 #define snprintf _snprintf
281 #endif /* def _WIN32 */
289 #include "miscutil.h"
290 #include "cgisimple.h"
291 #ifdef FEATURE_CGI_EDIT_ACTIONS
293 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
295 /* loadcfg.h is for g_bToggleIJB only */
297 const char cgi_h_rcs[] = CGI_H_VERSION;
299 static const struct cgi_dispatcher cgi_dispatchers[] = {
302 "Junkbuster main page" },
305 "Show information about the current configuration" },
308 "Show the source code version numbers" },
311 "Show the client's request headers." },
314 "Show which actions apply to a URL and why" },
317 "Toggle JunkBuster on or off" },
318 #ifdef FEATURE_CGI_EDIT_ACTIONS
321 "Edit the actions list" },
324 { "eaa", /* Shortcut for edit-actions-add-url-form */
325 cgi_edit_actions_add_url_form,
327 { "eau", /* Shortcut for edit-actions-url-form */
328 cgi_edit_actions_url_form,
330 { "ear", /* Shortcut for edit-actions-remove-url-form */
331 cgi_edit_actions_remove_url_form,
333 { "eas", /* Shortcut for edit-actions-for-url */
334 cgi_edit_actions_for_url,
336 { "easa", /* Shortcut for edit-actions-section-add */
337 cgi_edit_actions_section_add,
339 { "easr", /* Shortcut for edit-actions-section-remove */
340 cgi_edit_actions_section_remove,
342 { "eass", /* Shortcut for edit-actions-section-swap */
343 cgi_edit_actions_section_swap,
345 { "edit-actions-for-url",
346 cgi_edit_actions_for_url,
347 NULL /* Edit the actions for (a) specified URL(s) */ },
348 { "edit-actions-list",
349 cgi_edit_actions_list,
350 NULL /* Edit the actions list */ },
351 { "edit-actions-submit",
352 cgi_edit_actions_submit,
353 NULL /* Change the actions for (a) specified URL(s) */ },
354 { "edit-actions-url",
355 cgi_edit_actions_url,
356 NULL /* Change a URL pattern in the actionsfile */ },
357 { "edit-actions-url-form",
358 cgi_edit_actions_url_form,
359 NULL /* Form to change a URL pattern in the actionsfile */ },
360 { "edit-actions-add-url",
361 cgi_edit_actions_add_url,
362 NULL /* Add a URL pattern to the actionsfile */ },
363 { "edit-actions-add-url-form",
364 cgi_edit_actions_add_url_form,
365 NULL /* Form to add a URL pattern to the actionsfile */ },
366 { "edit-actions-remove-url",
367 cgi_edit_actions_remove_url,
368 NULL /* Remove a URL pattern from the actionsfile */ },
369 { "edit-actions-remove-url-form",
370 cgi_edit_actions_remove_url_form,
371 NULL /* Form to remove a URL pattern from the actionsfile */ },
372 { "edit-actions-section-add",
373 cgi_edit_actions_section_add,
374 NULL /* Remove a section from the actionsfile */ },
375 { "edit-actions-section-remove",
376 cgi_edit_actions_section_remove,
377 NULL /* Remove a section from the actionsfile */ },
378 { "edit-actions-section-swap",
379 cgi_edit_actions_section_swap,
380 NULL /* Swap two sections in the actionsfile */ },
381 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
384 NULL /* Sends a robots.txt file to tell robots to go away. */ },
387 NULL /* Send the transparent or \"Junkbuster\" gif */ },
390 NULL /* Send a transparent gif (short name) */ },
391 { NULL, /* NULL Indicates end of list and default page */
393 NULL /* Unknown CGI page */ }
400 * Hint: You can encode your own GIFs like this:
401 * perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o,", unpack("C", $c)); }'
404 const char image_junkbuster_gif_data[] =
405 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
406 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
407 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
408 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
409 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
410 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
411 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
414 const int image_junkbuster_gif_length = sizeof(image_junkbuster_gif_data) - 1;
417 const char image_blank_gif_data[] =
418 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
419 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
420 "\000\001\000\000\002\002D\001\000;";
422 const int image_blank_gif_length = sizeof(image_blank_gif_data) - 1;
425 static struct http_response cgi_error_memory_response[1];
428 static struct http_response *dispatch_known_cgi(struct client_state * csp,
430 static struct map *parse_cgi_parameters(char *argstring);
433 /*********************************************************************
435 * Function : dispatch_cgi
437 * Description : Checks if a request URL has either the magical
438 * hostname CGI_SITE_1_HOST (usully http://i.j.b/) or
439 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
440 * http://ijbswa.sourceforge.net/config). If so, it passes
441 * the (rest of the) path onto dispatch_known_cgi, which
442 * calls the relevant CGI handler function.
445 * 1 : csp = Current client state (buffers, headers, etc...)
447 * Returns : http_response if match, NULL if nonmatch or handler fail
449 *********************************************************************/
450 struct http_response *dispatch_cgi(struct client_state *csp)
452 const char *host = csp->http->host;
453 const char *path = csp->http->path;
456 * Should we intercept ?
459 /* Note: "example.com" and "example.com." are equivalent hostnames. */
461 /* Either the host matches CGI_SITE_1_HOST ..*/
462 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
463 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
464 && (path[0] == '/') )
466 /* ..then the path will all be for us. Remove leading '/' */
469 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
470 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
471 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
472 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
474 /* take everything following CGI_SITE_2_PATH */
475 path += strlen(CGI_SITE_2_PATH);
478 /* skip the forward slash after CGI_SITE_2_PATH */
481 else if (*path != '\0')
484 * wierdness: URL is /configXXX, where XXX is some string
485 * Do *NOT* intercept.
497 * This is a CGI call.
500 return dispatch_known_cgi(csp, path);
504 /*********************************************************************
506 * Function : dispatch_known_cgi
508 * Description : Processes a CGI once dispatch_cgi has determined that
509 * it matches one of the magic prefixes. Parses the path
510 * as a cgi name plus query string, prepares a map that
511 * maps CGI parameter names to their values, initializes
512 * the http_response struct, and calls the relevant CGI
516 * 1 : csp = Current client state (buffers, headers, etc...)
517 * 2 : path = Path of CGI, with the CGI prefix removed.
518 * Should not have a leading "/".
520 * Returns : http_response, or NULL on handler failure or out of
523 *********************************************************************/
524 static struct http_response *dispatch_known_cgi(struct client_state * csp,
527 const struct cgi_dispatcher *d;
528 struct map *param_list;
529 struct http_response *rsp;
530 char *query_args_start;
534 if (NULL == (path_copy = strdup(path)))
536 return cgi_error_memory();
539 query_args_start = path_copy;
540 while (*query_args_start && *query_args_start != '?')
544 if (*query_args_start == '?')
546 *query_args_start++ = '\0';
549 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
552 return cgi_error_memory();
558 * path_copy = CGI call name
559 * param_list = CGI params, as map
562 /* Get mem for response or fail*/
563 if (NULL == (rsp = alloc_http_response()))
566 free_map(param_list);
567 return cgi_error_memory();
570 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
571 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
572 csp->ip_addr_str, csp->http->cmd);
574 /* Find and start the right CGI function*/
575 for (d = cgi_dispatchers; FOREVER; d++)
577 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
579 err = (d->handler)(csp, rsp, param_list);
581 free_map(param_list);
582 if (err == JB_ERR_CGI_PARAMS)
584 err = cgi_error_bad_param(csp, rsp);
589 return finish_http_response(rsp);
593 /* Error in handler, probably out-of-memory */
594 free_http_response(rsp);
595 return cgi_error_memory();
602 /*********************************************************************
604 * Function : parse_cgi_parameters
606 * Description : Parse a URL-encoded argument string into name/value
607 * pairs and store them in a struct map list.
610 * 1 : string = string to be parsed. Will be trashed.
612 * Returns : pointer to param list, or NULL if out of memory.
614 *********************************************************************/
615 static struct map *parse_cgi_parameters(char *argstring)
618 char *vector[BUFFER_SIZE];
620 struct map *cgi_params;
622 if (NULL == (cgi_params = new_map()))
627 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
629 for (i = 0; i < pairs; i++)
631 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
634 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
636 free_map(cgi_params);
647 /*********************************************************************
649 * Function : error_response
651 * Description : returns an http_response that explains the reason
652 * why a request failed.
655 * 1 : csp = Current client state (buffers, headers, etc...)
656 * 2 : templatename = Which template should be used for the answer
657 * 3 : sys_err = system error number
659 * Returns : A http_response. If we run out of memory, this
660 * will be cgi_error_memory().
662 *********************************************************************/
663 struct http_response *error_response(struct client_state *csp,
664 const char *templatename,
668 struct http_response *rsp;
669 struct map * exports = default_exports(csp, NULL);
672 return cgi_error_memory();
675 if (NULL == (rsp = alloc_http_response()))
678 return cgi_error_memory();
681 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
682 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
683 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
684 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
685 if (!err) err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
690 free_http_response(rsp);
691 return cgi_error_memory();
694 if (!strcmp(templatename, "no-such-domain"))
696 rsp->status = strdup("404 No such domain");
697 if (rsp->status == NULL)
700 free_http_response(rsp);
701 return cgi_error_memory();
704 else if (!strcmp(templatename, "connect-failed"))
706 rsp->status = strdup("503 Connect failed");
707 if (rsp->status == NULL)
710 free_http_response(rsp);
711 return cgi_error_memory();
715 err = template_fill_for_cgi(csp, templatename, exports, rsp);
718 free_http_response(rsp);
719 return cgi_error_memory();
722 return finish_http_response(rsp);
726 /*********************************************************************
728 * Function : cgi_init_error_messages
730 * Description : Call at the start of the program to initialize
731 * the error message used by cgi_error_memory().
737 *********************************************************************/
738 void cgi_init_error_messages(void)
740 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
741 cgi_error_memory_response->head =
742 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
743 "Content-Type: text/html\r\n"
745 cgi_error_memory_response->body =
747 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
749 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
750 "<p>JunkBuster <b>ran out of memory</b> whilst processing your request.</p>\r\n"
751 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
755 cgi_error_memory_response->head_length =
756 strlen(cgi_error_memory_response->head);
757 cgi_error_memory_response->content_length =
758 strlen(cgi_error_memory_response->body);
762 /*********************************************************************
764 * Function : cgi_error_memory
766 * Description : Called if a CGI function runs out of memory.
767 * Returns a statically-allocated error response.
770 * 1 : csp = Current client state (buffers, headers, etc...)
771 * 2 : rsp = http_response data structure for output
772 * 3 : template_name = Name of template that could not
775 * Returns : JB_ERR_OK on success
776 * JB_ERR_MEMORY on out-of-memory error.
778 *********************************************************************/
779 struct http_response *cgi_error_memory(void)
781 /* assert that it's been initialized. */
782 assert(cgi_error_memory_response->head);
784 return cgi_error_memory_response;
788 /*********************************************************************
790 * Function : cgi_error_no_template
792 * Description : Almost-CGI function that is called if a templae
793 * cannot be loaded. Note this is not a true CGI,
794 * it takes a template name rather than a map of
798 * 1 : csp = Current client state (buffers, headers, etc...)
799 * 2 : rsp = http_response data structure for output
800 * 3 : template_name = Name of template that could not
803 * Returns : JB_ERR_OK on success
804 * JB_ERR_MEMORY on out-of-memory error.
806 *********************************************************************/
807 jb_err cgi_error_no_template(struct client_state *csp,
808 struct http_response *rsp,
809 const char *template_name)
811 static const char status[] =
812 "500 Internal JunkBuster Proxy Error";
813 static const char body_prefix[] =
815 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
817 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
818 "<p>JunkBuster encountered an error whilst processing your request:</p>\r\n"
819 "<p><b>Could not load template file <code>";
820 static const char body_suffix[] =
821 "</code></b></p>\r\n"
822 "<p>Please contact your proxy administrator.</p>\r\n"
823 "<p>If you are the proxy administrator, please put the required file "
824 "in the <code><i>(confdir)</i>/templates</code> directory. The "
825 "location of the <code><i>(confdir)</i></code> directory "
826 "is specified in the main JunkBuster <code>config</code> "
827 "file. (It's typically the JunkBuster install directory"
829 ", or <code>/etc/junkbuster/</code>"
830 #endif /* ndef _WIN32 */
837 assert(template_name);
839 /* Reset rsp, if needed */
843 rsp->content_length = 0;
844 rsp->head_length = 0;
847 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
848 if (rsp->body == NULL)
850 return JB_ERR_MEMORY;
852 strcpy(rsp->body, body_prefix);
853 strcat(rsp->body, template_name);
854 strcat(rsp->body, body_suffix);
856 rsp->status = strdup(status);
857 if (rsp->body == NULL)
859 return JB_ERR_MEMORY;
866 /*********************************************************************
868 * Function : cgi_error_bad_param
870 * Description : CGI function that is called if the parameters
871 * (query string) for a CGI were wrong.
874 * 1 : csp = Current client state (buffers, headers, etc...)
875 * 2 : rsp = http_response data structure for output
877 * CGI Parameters : none
879 * Returns : JB_ERR_OK on success
880 * JB_ERR_MEMORY on out-of-memory error.
882 *********************************************************************/
883 jb_err cgi_error_bad_param(struct client_state *csp,
884 struct http_response *rsp)
891 if (NULL == (exports = default_exports(csp, NULL)))
893 return JB_ERR_MEMORY;
896 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
900 /*********************************************************************
902 * Function : get_http_time
904 * Description : Get the time in a format suitable for use in a
905 * HTTP header - e.g.:
906 * "Sun, 06 Nov 1994 08:49:37 GMT"
909 * 1 : time_offset = Time returned will be current time
910 * plus this number of seconds.
911 * 2 : buf = Destination for result. Must be long enough
912 * to hold 29 characters plus a trailing zero.
916 *********************************************************************/
917 void get_http_time(int time_offset, char *buf)
919 static const char day_names[7][4] =
920 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
921 static const char month_names[12][4] =
922 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
923 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
930 time(¤t_time); /* get current time */
932 current_time += time_offset;
934 /* get and save the gmt */
938 t = gmtime_r(¤t_time, &dummy);
940 t = gmtime(¤t_time);
944 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
946 "%s, %02d %s %4d %02d:%02d:%02d GMT",
947 day_names[t->tm_wday],
949 month_names[t->tm_mon],
959 /*********************************************************************
961 * Function : finish_http_response
963 * Description : Fill in the missing headers in an http response,
964 * and flatten the headers to an http head.
967 * 1 : rsp = pointer to http_response to be processed
969 * Returns : A http_response, usually the rsp parameter.
970 * On error, free()s rsp and returns cgi_error_memory()
972 *********************************************************************/
973 struct http_response *finish_http_response(struct http_response *rsp)
975 char buf[BUFFER_SIZE];
978 /* Special case - do NOT change this statically allocated response,
979 * which is ready for output anyway.
981 if (rsp == cgi_error_memory_response)
987 * Fill in the HTTP Status
989 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
990 err = enlist_first(rsp->headers, buf);
993 * Set the Content-Length
995 if (rsp->content_length == 0)
997 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1001 sprintf(buf, "Content-Length: %d", rsp->content_length);
1002 err = enlist(rsp->headers, buf);
1006 * Fill in the default headers:
1008 * Content-Type: default to text/html if not already specified.
1009 * Date: set to current date/time.
1010 * Last-Modified: set to date/time the page was last changed.
1011 * Expires: set to date/time page next needs reloading.
1012 * Cache-Control: set to "no-cache" if applicable.
1014 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1016 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1021 * Set Expires to about 10 min into the future so it'll get reloaded
1022 * occasionally, e.g. if IJB gets upgraded.
1027 get_http_time(0, buf);
1028 err = enlist_unique_header(rsp->headers, "Date", buf);
1031 /* Some date in the past. */
1032 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1036 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1037 err = enlist_unique_header(rsp->headers, "Expires", buf);
1043 * Compliant browsers should not cache this due to the "Cache-Control"
1044 * setting. However, to be certain, we also set both "Last-Modified"
1045 * and "Expires" to the current time.
1047 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1049 get_http_time(0, buf);
1050 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1051 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1052 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1059 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1061 free_http_response(rsp);
1062 return cgi_error_memory();
1064 rsp->head_length = strlen(rsp->head);
1071 /*********************************************************************
1073 * Function : alloc_http_response
1075 * Description : Allocates a new http_response structure.
1079 * Returns : pointer to a new http_response, or NULL.
1081 *********************************************************************/
1082 struct http_response *alloc_http_response(void)
1084 return (struct http_response *) zalloc(sizeof(struct http_response));
1089 /*********************************************************************
1091 * Function : free_http_response
1093 * Description : Free the memory occupied by an http_response
1094 * and its depandant structures.
1097 * 1 : rsp = pointer to http_response to be freed
1101 *********************************************************************/
1102 void free_http_response(struct http_response *rsp)
1105 * Must special case cgi_error_memory_response, which is never freed.
1107 if (rsp && (rsp != cgi_error_memory_response))
1112 destroy_list(rsp->headers);
1119 /*********************************************************************
1121 * Function : template_load
1123 * Description : CGI support function that loads a given HTML
1124 * template from the confdir, ignoring comment
1128 * 1 : csp = Current client state (buffers, headers, etc...)
1129 * 2 : template_ptr = Destination for pointer to loaded
1131 * 3 : template = name of the HTML template to be used
1133 * Returns : JB_ERR_OK on success
1134 * JB_ERR_MEMORY on out-of-memory error.
1135 * JB_ERR_FILE if the template file cannot be read
1137 *********************************************************************/
1138 jb_err template_load(struct client_state *csp, char ** template_ptr,
1139 const char *templatename)
1141 char *templates_dir_path;
1145 char buf[BUFFER_SIZE];
1148 assert(template_ptr);
1149 assert(templatename);
1151 *template_ptr = NULL;
1154 * Open template file or fail
1157 templates_dir_path = make_path(csp->config->confdir, "templates");
1158 if (templates_dir_path == NULL)
1160 return JB_ERR_MEMORY;
1163 full_path = make_path(templates_dir_path, templatename);
1164 free(templates_dir_path);
1165 if (full_path == NULL)
1167 return JB_ERR_MEMORY;
1170 file_buffer = strdup("");
1171 if (file_buffer == NULL)
1174 return JB_ERR_MEMORY;
1177 if (NULL == (fp = fopen(full_path, "r")))
1179 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1187 * Read the file, ignoring comments.
1189 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1190 * This is unlikely in practise.
1192 while (fgets(buf, BUFFER_SIZE, fp))
1194 /* skip lines starting with '#' */
1200 if (string_append(&file_buffer, buf))
1203 return JB_ERR_MEMORY;
1208 *template_ptr = file_buffer;
1214 /*********************************************************************
1216 * Function : template_fill
1218 * Description : CGI support function that fills in a pre-loaded
1219 * HTML template by replacing @name@ with value using
1220 * pcrs, for each item in the output map.
1222 * Note that a leading '$' charachter in the export map's
1223 * values will be stripped and toggle on backreference
1227 * 1 : template_ptr = IN: Template to be filled out.
1229 * OUT: Filled out template.
1230 * Caller must free().
1231 * 2 : exports = map with fill in symbol -> name pairs
1233 * Returns : JB_ERR_OK on success
1234 * JB_ERR_MEMORY on out-of-memory error
1236 *********************************************************************/
1237 jb_err template_fill(char **template_ptr, const struct map *exports)
1239 struct map_entry *m;
1241 char buf[BUFFER_SIZE];
1242 char *tmp_out_buffer;
1248 assert(template_ptr);
1249 assert(*template_ptr);
1252 file_buffer = *template_ptr;
1253 size = strlen(file_buffer) + 1;
1256 * Assemble pcrs joblist from exports map
1258 for (m = exports->first; m != NULL; m = m->next)
1260 if (*m->name == '$')
1263 * First character of name is '$', so remove this flag
1264 * character and allow backreferences ($1 etc) in the
1265 * "replace with" text.
1267 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1273 * Treat the "replace with" text as a literal string -
1274 * no quoting needed, no backreferences allowed.
1275 * ("Trivial" ['T'] flag).
1279 /* Enclose name in @@ */
1280 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1284 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1286 /* Make and run job. */
1287 job = pcrs_compile(buf, m->value, flags, &error);
1290 if (error == PCRS_ERR_NOMEM)
1293 *template_ptr = NULL;
1294 return JB_ERR_MEMORY;
1298 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1299 /* Hope it wasn't important and silently ignore the invalid job */
1304 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1307 if (NULL == tmp_out_buffer)
1309 *template_ptr = NULL;
1310 return JB_ERR_MEMORY;
1312 file_buffer = tmp_out_buffer;
1319 *template_ptr = file_buffer;
1324 /*********************************************************************
1326 * Function : template_fill_for_cgi
1328 * Description : CGI support function that loads a HTML template
1329 * and fills it in. Handles file-not-found errors
1330 * by sending a HTML error message. For convenience,
1331 * this function also frees the passed "exports" map.
1334 * 1 : csp = Client state
1335 * 2 : templatename = name of the HTML template to be used
1336 * 3 : exports = map with fill in symbol -> name pairs.
1337 * Will be freed by this function.
1339 * Returns : JB_ERR_OK on success
1340 * JB_ERR_MEMORY on out-of-memory error
1342 *********************************************************************/
1343 jb_err template_fill_for_cgi(struct client_state *csp,
1344 const char *templatename,
1345 struct map *exports,
1346 struct http_response *rsp)
1351 assert(templatename);
1355 err = template_load(csp, &rsp->body, templatename);
1356 if (err == JB_ERR_FILE)
1359 return cgi_error_no_template(csp, rsp, templatename);
1364 return err; /* JB_ERR_MEMORY */
1366 err = template_fill(&rsp->body, exports);
1372 /*********************************************************************
1374 * Function : default_exports
1376 * Description : returns a struct map list that contains exports
1377 * which are common to all CGI functions.
1380 * 1 : csp = Current client state (buffers, headers, etc...)
1381 * 2 : caller = name of CGI who calls us and which should
1382 * be excluded from the generated menu. May be
1384 * Returns : NULL if no memory, else a new map. Caller frees.
1386 *********************************************************************/
1387 struct map *default_exports(const struct client_state *csp, const char *caller)
1391 struct map * exports;
1392 int local_help_exists = 0;
1396 exports = new_map();
1397 if (exports == NULL)
1402 err = map(exports, "version", 1, html_encode(VERSION), 0);
1403 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1404 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1405 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1406 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1407 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1408 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1409 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1411 snprintf(buf, 20, "%d", csp->config->hport);
1412 if (!err) err = map(exports, "my-port", 1, buf, 1);
1414 if(!strcmp(CODE_STATUS, "stable"))
1416 if (!err) err = map_block_killer(exports, "unstable");
1419 if (csp->config->admin_address != NULL)
1421 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1422 local_help_exists = 1;
1426 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1429 if (csp->config->proxy_info_url != NULL)
1431 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1432 local_help_exists = 1;
1436 if (!err) err = map_block_killer(exports, "have-proxy-info");
1439 if (local_help_exists == 0)
1441 if (!err) err = map_block_killer(exports, "have-help-info");
1454 /*********************************************************************
1456 * Function : map_block_killer
1458 * Description : Convenience function.
1459 * Adds a "killer" for the conditional HTML-template
1460 * block <name>, i.e. a substitution of the regex
1461 * "if-<name>-start.*if-<name>-end" to the given
1465 * 1 : exports = map to extend
1466 * 2 : name = name of conditional block
1468 * Returns : JB_ERR_OK on success
1469 * JB_ERR_MEMORY on out-of-memory error.
1471 *********************************************************************/
1472 jb_err map_block_killer(struct map *exports, const char *name)
1474 char buf[1000]; /* Will do, since the names are hardwired */
1478 assert(strlen(name) < 490);
1480 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1481 return map(exports, buf, 1, "", 1);
1485 /*********************************************************************
1487 * Function : map_block_keep
1489 * Description : Convenience function. Removes the markers used
1490 * by map-block-killer, to save a few bytes.
1491 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1494 * 1 : exports = map to extend
1495 * 2 : name = name of conditional block
1497 * Returns : JB_ERR_OK on success
1498 * JB_ERR_MEMORY on out-of-memory error.
1500 *********************************************************************/
1501 jb_err map_block_keep(struct map *exports, const char *name)
1504 char buf[500]; /* Will do, since the names are hardwired */
1508 assert(strlen(name) < 490);
1510 snprintf(buf, 500, "if-%s-start", name);
1511 err = map(exports, buf, 1, "", 1);
1518 snprintf(buf, 500, "if-%s-end", name);
1519 return map(exports, buf, 1, "", 1);
1523 /*********************************************************************
1525 * Function : map_conditional
1527 * Description : Convenience function.
1528 * Adds an "if-then-else" for the conditional HTML-template
1529 * block <name>, i.e. a substitution of the form:
1536 * The control structure and one of the alternatives
1540 * 1 : exports = map to extend
1541 * 2 : name = name of conditional block
1542 * 3 : choose_first = nonzero for first, zero for second.
1544 * Returns : JB_ERR_OK on success
1545 * JB_ERR_MEMORY on out-of-memory error.
1547 *********************************************************************/
1548 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1550 char buf[1000]; /* Will do, since the names are hardwired */
1555 assert(strlen(name) < 480);
1557 snprintf(buf, 1000, (choose_first
1558 ? "else-not-%s@.*@endif-%s"
1559 : "if-%s-then@.*@else-not-%s"),
1562 err = map(exports, buf, 1, "", 1);
1568 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1569 return map(exports, buf, 1, "", 1);
1573 /*********************************************************************
1575 * Function : make_menu
1577 * Description : Returns an HTML-formatted menu of the available
1578 * unhidden CGIs, excluding the one given in <self>.
1580 * Parameters : self = name of CGI to leave out, can be NULL
1582 * Returns : menu string, or NULL on out-of-memory error.
1584 *********************************************************************/
1585 char *make_menu(const char *self)
1587 const struct cgi_dispatcher *d;
1588 char *result = strdup("");
1592 self = "NO-SUCH-CGI!";
1595 /* List available unhidden CGI's and export as "other-cgis" */
1596 for (d = cgi_dispatchers; d->name; d++)
1598 if (d->description && strcmp(d->name, self))
1600 string_append(&result, "<li><a href=\"" CGI_PREFIX);
1601 string_append(&result, d->name);
1602 string_append(&result, "\">");
1603 string_append(&result, d->description);
1604 string_append(&result, "</a></li>\n");
1612 /*********************************************************************
1614 * Function : dump_map
1616 * Description : HTML-dump a map for debugging
1619 * 1 : the_map = map to dump
1621 * Returns : string with HTML
1623 *********************************************************************/
1624 char *dump_map(const struct map *the_map)
1626 struct map_entry *cur_entry;
1627 char *ret = strdup("");
1629 string_append(&ret, "<table>\n");
1631 for (cur_entry = the_map->first;
1632 (cur_entry != NULL) && (ret != NULL);
1633 cur_entry = cur_entry->next)
1635 string_append(&ret, "<tr><td><b>");
1636 string_join (&ret, html_encode(cur_entry->name));
1637 string_append(&ret, "</b></td><td>");
1638 string_join (&ret, html_encode(cur_entry->value));
1639 string_append(&ret, "</td></tr>\n");
1642 string_append(&ret, "</table>\n");