1 const char cgi_rcs[] = "$Id: cgi.c,v 1.48 2002/03/08 17:47:07 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.48 2002/03/08 17:47:07 jongfoster
44 * Revision 1.47 2002/03/08 16:41:33 oes
45 * Added GIF images again
47 * Revision 1.46 2002/03/07 03:48:38 oes
48 * - Changed built-in images from GIF to PNG
49 * (with regard to Unisys patent issue)
50 * - Added a 4x4 pattern PNG which is less intrusive
51 * than the logo but also clearly marks the deleted banners
53 * Revision 1.45 2002/03/06 22:54:35 jongfoster
54 * Automated function-comment nitpicking.
56 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
57 * - Better error reporting on OS/2
58 * - Fix double-slash comment (oops)
60 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
61 * - Re-enable OS/2 building after new parms were added
62 * - Fix false out of memory report when resolving CGI templates when no IP
63 * address is available of failed attempt (a la no such domain)
65 * Revision 1.42 2002/01/21 00:33:20 jongfoster
66 * Replacing strsav() with the safer string_append() or string_join().
67 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
68 * Adding missing html_encode() to error message generators.
69 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
71 * Revision 1.41 2002/01/17 20:56:22 jongfoster
72 * Replacing hard references to the URL of the config interface
73 * with #defines from project.h
75 * Revision 1.40 2002/01/09 14:26:46 oes
76 * Added support for thread-safe gmtime_r call.
78 * Revision 1.39 2001/11/16 00:48:13 jongfoster
79 * Fixing a compiler warning
81 * Revision 1.38 2001/11/13 00:31:21 jongfoster
82 * - Adding new CGIs for use by non-JavaScript browsers:
83 * edit-actions-url-form
84 * edit-actions-add-url-form
85 * edit-actions-remove-url-form
86 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
89 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
90 * Show enablement/disablement status in almost all templates.
91 * There is a little trickiness here: apparent recursive resolution of
92 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
93 * the actual enablement status. So a similar construct,
94 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
97 * Revision 1.36 2001/10/26 17:33:27 oes
100 * Revision 1.35 2001/10/23 21:48:19 jongfoster
101 * Cleaning up error handling in CGI functions - they now send back
102 * a HTML error page and should never cause a FATAL error. (Fixes one
103 * potential source of "denial of service" attacks).
105 * CGI actions file editor that works and is actually useful.
107 * Ability to toggle JunkBuster remotely using a CGI call.
109 * You can turn off both the above features in the main configuration
110 * file, e.g. if you are running a multi-user proxy.
112 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
113 * Only show "Local support" on templates conditionally:
114 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
115 * - if not, no Local support section appears
117 * Revision 1.33 2001/10/14 22:28:41 jongfoster
118 * Fixing stupid typo.
120 * Revision 1.32 2001/10/14 22:20:18 jongfoster
121 * - Changes to CGI dispatching method to match CGI names exactly,
122 * rather than doing a prefix match.
123 * - No longer need to count the length of the CGI handler names by hand.
124 * - Adding new handler for 404 error when disptching a CGI, if none of
125 * the handlers match.
126 * - Adding new handlers for CGI actionsfile editor.
128 * Revision 1.31 2001/10/10 10:56:39 oes
129 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
131 * Revision 1.30 2001/10/02 15:30:57 oes
132 * Introduced show-request cgi
134 * Revision 1.29 2001/09/20 15:47:44 steudten
136 * Fix BUG: Modify int size to size_t size in fill_template()
137 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
139 * Revision 1.28 2001/09/19 18:00:37 oes
140 * - Deletef time() FIXME (Can't fail under Linux either, if
141 * the argument is guaranteed to be in out address space,
144 * - Pointer notation cosmetics
145 * - Fixed a minor bug in template_fill(): Failiure of
146 * pcrs_execute() now secure.
148 * Revision 1.27 2001/09/16 17:08:54 jongfoster
149 * Moving simple CGI functions from cgi.c to new file cgisimple.c
151 * Revision 1.26 2001/09/16 15:47:37 jongfoster
152 * First version of CGI-based edit interface. This is very much a
153 * work-in-progress, and you can't actually use it to edit anything
154 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
155 * to have any effect.
157 * Revision 1.25 2001/09/16 15:02:35 jongfoster
158 * Adding i.j.b/robots.txt.
159 * Inlining add_stats() since it's only ever called from one place.
161 * Revision 1.24 2001/09/16 11:38:01 jongfoster
162 * Splitting fill_template() into 2 functions:
163 * template_load() loads the file
164 * template_fill() performs the PCRS regexps.
165 * This is because the CGI edit interface has a "table row"
166 * template which is used many times in the page - this
167 * change means it's only loaded from disk once.
169 * Revision 1.23 2001/09/16 11:16:05 jongfoster
170 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
172 * Revision 1.22 2001/09/16 11:00:10 jongfoster
173 * New function alloc_http_response, for symmetry with free_http_response
175 * Revision 1.21 2001/09/13 23:53:03 jongfoster
176 * Support for both static and dynamically generated CGI pages.
177 * Correctly setting Last-Modified: and Expires: HTTP headers.
179 * Revision 1.20 2001/09/13 23:40:36 jongfoster
180 * (Cosmetic only) Indentation correction
182 * Revision 1.19 2001/09/13 23:31:25 jongfoster
183 * Moving image data to cgi.c rather than cgi.h.
185 * Revision 1.18 2001/08/05 16:06:20 jongfoster
186 * Modifiying "struct map" so that there are now separate header and
187 * "map_entry" structures. This means that functions which modify a
188 * map no longer need to return a pointer to the modified map.
189 * Also, it no longer reverses the order of the entries (which may be
190 * important with some advanced template substitutions).
192 * Revision 1.17 2001/08/05 15:57:38 oes
193 * Adapted finish_http_response to new list_to_text
195 * Revision 1.16 2001/08/01 21:33:18 jongfoster
196 * Changes to fill_template() that reduce memory usage without having
197 * an impact on performance. I also renamed some variables so as not
198 * to clash with the C++ keywords "new" and "template".
200 * Revision 1.15 2001/08/01 21:19:22 jongfoster
201 * Moving file version information to a separate CGI page.
203 * Revision 1.14 2001/08/01 00:19:03 jongfoster
204 * New function: map_conditional() for an if-then-else syntax.
205 * Changing to use new version of show_defines()
207 * Revision 1.13 2001/07/30 22:08:36 jongfoster
208 * Tidying up #defines:
209 * - All feature #defines are now of the form FEATURE_xxx
210 * - Permanently turned off WIN_GUI_EDIT
211 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
213 * Revision 1.12 2001/07/29 18:47:05 jongfoster
214 * Adding missing #include "loadcfg.h"
216 * Revision 1.11 2001/07/18 17:24:37 oes
217 * Changed to conform to new pcrs interface
219 * Revision 1.10 2001/07/13 13:53:13 oes
220 * Removed all #ifdef PCRS and related code
222 * Revision 1.9 2001/06/29 21:45:41 oes
223 * Indentation, CRLF->LF, Tab-> Space
225 * Revision 1.8 2001/06/29 13:21:46 oes
226 * - Cosmetics: renamed and reordered functions, variables,
227 * texts, improved comments etc
229 * - Removed ij_untrusted_url() The relevant
230 * info is now part of the "untrusted" page,
231 * which is generated by filters.c:trust_url()
233 * - Generators of content now call finish_http_response()
234 * themselves, making jcc.c:chat() a little less
237 * - Removed obsolete "Pragma: no-cache" from our headers
239 * - http_responses now know their head length
241 * - fill_template now uses the new interface to pcrs, so that
242 * - long jobs (like whole files) no longer have to be assembled
243 * in a fixed size buffer
244 * - the new T (trivial) option is used, and the replacement may
245 * contain Perl syntax backrefs without confusing pcrs
247 * - Introduced default_exports() which generates a set of exports
248 * common to all CGIs and other content generators
250 * - Introduced convenience function map_block_killer()
252 * - Introduced convenience function make_menu()
254 * - Introduced CGI-like function error_response() which generates
255 * the "No such domain" and "Connect failed" messages using the
258 * - cgi_show_url_info:
259 * - adapted to new CGI features
260 * - form and answers now generated from same template
261 * - http:// prefix in URL now OK
264 * - adapted to new CGI features
265 * - no longer uses csp->init_proxy_args
268 * - moved menu generation to make_menu()
270 * - add_stats now writes single export map entries instead
273 * - Moved redirect_url() to filters.c
275 * - Fixed mem leak in free_http_response(), map_block_killer(),
277 * - Removed logentry from cancelled commit
279 * Revision 1.7 2001/06/09 10:51:58 jongfoster
280 * Changing "show URL info" handler to new style.
281 * Changing BUFSIZ ==> BUFFER_SIZE
283 * Revision 1.6 2001/06/07 23:05:19 jongfoster
284 * Removing code related to old forward and ACL files.
286 * Revision 1.5 2001/06/05 19:59:16 jongfoster
287 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
289 * Revision 1.4 2001/06/04 10:41:52 swa
290 * show version string of cgi.h and cgi.c
292 * Revision 1.3 2001/06/03 19:12:16 oes
293 * introduced new cgi handling
295 * No revisions before 1.3
297 **********************************************************************/
303 #include <sys/types.h>
310 #define snprintf _snprintf
311 #endif /* def _WIN32 */
319 #include "miscutil.h"
320 #include "cgisimple.h"
321 #ifdef FEATURE_CGI_EDIT_ACTIONS
323 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
325 /* loadcfg.h is for g_bToggleIJB only */
327 const char cgi_h_rcs[] = CGI_H_VERSION;
329 static const struct cgi_dispatcher cgi_dispatchers[] = {
332 "Junkbuster main page" },
335 "Show information about the current configuration" },
338 "Show the source code version numbers" },
341 "Show the client's request headers." },
344 "Show which actions apply to a URL and why" },
347 "Toggle JunkBuster on or off" },
348 #ifdef FEATURE_CGI_EDIT_ACTIONS
351 "Edit the actions list" },
354 { "eaa", /* Shortcut for edit-actions-add-url-form */
355 cgi_edit_actions_add_url_form,
357 { "eau", /* Shortcut for edit-actions-url-form */
358 cgi_edit_actions_url_form,
360 { "ear", /* Shortcut for edit-actions-remove-url-form */
361 cgi_edit_actions_remove_url_form,
363 { "eas", /* Shortcut for edit-actions-for-url */
364 cgi_edit_actions_for_url,
366 { "easa", /* Shortcut for edit-actions-section-add */
367 cgi_edit_actions_section_add,
369 { "easr", /* Shortcut for edit-actions-section-remove */
370 cgi_edit_actions_section_remove,
372 { "eass", /* Shortcut for edit-actions-section-swap */
373 cgi_edit_actions_section_swap,
375 { "edit-actions-for-url",
376 cgi_edit_actions_for_url,
377 NULL /* Edit the actions for (a) specified URL(s) */ },
378 { "edit-actions-list",
379 cgi_edit_actions_list,
380 NULL /* Edit the actions list */ },
381 { "edit-actions-submit",
382 cgi_edit_actions_submit,
383 NULL /* Change the actions for (a) specified URL(s) */ },
384 { "edit-actions-url",
385 cgi_edit_actions_url,
386 NULL /* Change a URL pattern in the actionsfile */ },
387 { "edit-actions-url-form",
388 cgi_edit_actions_url_form,
389 NULL /* Form to change a URL pattern in the actionsfile */ },
390 { "edit-actions-add-url",
391 cgi_edit_actions_add_url,
392 NULL /* Add a URL pattern to the actionsfile */ },
393 { "edit-actions-add-url-form",
394 cgi_edit_actions_add_url_form,
395 NULL /* Form to add a URL pattern to the actionsfile */ },
396 { "edit-actions-remove-url",
397 cgi_edit_actions_remove_url,
398 NULL /* Remove a URL pattern from the actionsfile */ },
399 { "edit-actions-remove-url-form",
400 cgi_edit_actions_remove_url_form,
401 NULL /* Form to remove a URL pattern from the actionsfile */ },
402 { "edit-actions-section-add",
403 cgi_edit_actions_section_add,
404 NULL /* Remove a section from the actionsfile */ },
405 { "edit-actions-section-remove",
406 cgi_edit_actions_section_remove,
407 NULL /* Remove a section from the actionsfile */ },
408 { "edit-actions-section-swap",
409 cgi_edit_actions_section_swap,
410 NULL /* Swap two sections in the actionsfile */ },
411 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
414 NULL /* Sends a robots.txt file to tell robots to go away. */ },
417 NULL /* Send a built-in image */ },
419 cgi_transparent_image,
420 NULL /* Send a transparent image (short name) */ },
421 { NULL, /* NULL Indicates end of list and default page */
423 NULL /* Unknown CGI page */ }
428 * Bulit-in images for ad replacement
430 * Hint: You can encode your own images like this:
431 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
434 #ifdef FEATURE_NO_GIFS
437 * "Junkbuster" logo, as a PNG.
439 const char image_logo_data[] =
440 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
441 "\122\000\000\000\104\000\000\000\013\001\003\000\000\000\374"
442 "\323\271\110\000\000\000\004\147\101\115\101\000\000\261\217"
443 "\013\374\141\005\000\000\000\006\120\114\124\105\310\310\310"
444 "\000\000\000\062\100\100\345\000\000\000\001\164\122\116\123"
445 "\000\100\346\330\146\000\000\000\001\142\113\107\104\000\210"
446 "\005\035\110\000\000\000\126\111\104\101\124\170\332\143\140"
447 "\200\003\066\006\146\066\006\006\011\124\326\331\315\146\147"
448 "\316\333\174\116\000\262\156\247\347\334\234\071\373\001\220"
449 "\065\373\130\316\035\311\331\015\020\326\161\311\337\014\014"
450 "\151\147\147\247\345\034\236\331\014\144\335\235\155\236\173"
451 "\163\366\154\006\006\233\334\331\162\307\316\363\174\106\330"
452 "\300\000\000\002\127\040\324\250\204\044\102\000\000\000\000"
453 "\111\105\116\104\256\102\140\202";
456 * Checkerboard pattern, as a PNG.
458 const char image_pattern_data[] =
459 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
460 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
461 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
462 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
463 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
464 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
465 "\000\000\000\111\105\116\104\256\102\140\202";
468 * 1x1 transparant PNG.
470 const char image_blank_data[] =
471 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
472 "\122\000\000\000\002\000\000\000\002\010\002\000\000\000\375"
473 "\324\232\163\000\000\000\006\142\113\107\104\000\310\000\310"
474 "\000\310\052\045\225\037\000\000\000\027\111\104\101\124\170"
475 "\332\143\374\377\377\377\311\223\047\031\116\234\070\361\377"
476 "\377\177\000\112\335\012\257\162\103\306\335\000\000\000\000"
477 "\111\105\116\104\256\102\140\202o";
481 * "Junkbuster" logo, as a GIF.
483 const char image_logo_data[] =
484 "GIF89aD\000\013\000\360\000\000\000\000\000\377\377\377!"
485 "\371\004\001\000\000\001\000,\000\000\000\000D\000\013\000"
486 "\000\002a\214\217\251\313\355\277\000\200G&K\025\316hC\037"
487 "\200\234\230Y\2309\235S\230\266\206\372J\253<\3131\253\271"
488 "\270\215\342\254\013\203\371\202\264\334P\207\332\020o\266"
489 "N\215I\332=\211\312\3513\266:\026AK)\364\370\365aobr\305"
490 "\372\003S\275\274k2\354\254z\347?\335\274x\306^9\374\276"
494 * Checkerboard pattern, as a GIF.
496 const char image_pattern_data[] =
497 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
498 "\310\377\377\377\041\376\025\111\040\165\163\145\144\040\164"
499 "\157\040\142\145\040\141\040\142\141\156\156\145\162\000\054"
500 "\000\000\000\000\004\000\004\000\000\002\005\104\174\147\270"
504 * 1x1 transparant GIF.
506 const char image_blank_data[] =
507 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
508 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
509 "\000\001\000\000\002\002D\001\000;";
512 const size_t image_logo_length = sizeof(image_logo_data) - 1;
513 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
514 const size_t image_blank_length = sizeof(image_blank_data) - 1;
517 static struct http_response cgi_error_memory_response[1];
519 static struct http_response *dispatch_known_cgi(struct client_state * csp,
521 static struct map *parse_cgi_parameters(char *argstring);
524 /*********************************************************************
526 * Function : dispatch_cgi
528 * Description : Checks if a request URL has either the magical
529 * hostname CGI_SITE_1_HOST (usully http://i.j.b/) or
530 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
531 * http://ijbswa.sourceforge.net/config). If so, it passes
532 * the (rest of the) path onto dispatch_known_cgi, which
533 * calls the relevant CGI handler function.
536 * 1 : csp = Current client state (buffers, headers, etc...)
538 * Returns : http_response if match, NULL if nonmatch or handler fail
540 *********************************************************************/
541 struct http_response *dispatch_cgi(struct client_state *csp)
543 const char *host = csp->http->host;
544 const char *path = csp->http->path;
547 * Should we intercept ?
550 /* Note: "example.com" and "example.com." are equivalent hostnames. */
552 /* Either the host matches CGI_SITE_1_HOST ..*/
553 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
554 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
555 && (path[0] == '/') )
557 /* ..then the path will all be for us. Remove leading '/' */
560 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
561 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
562 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
563 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
565 /* take everything following CGI_SITE_2_PATH */
566 path += strlen(CGI_SITE_2_PATH);
569 /* skip the forward slash after CGI_SITE_2_PATH */
572 else if (*path != '\0')
575 * wierdness: URL is /configXXX, where XXX is some string
576 * Do *NOT* intercept.
588 * This is a CGI call.
591 return dispatch_known_cgi(csp, path);
595 /*********************************************************************
597 * Function : dispatch_known_cgi
599 * Description : Processes a CGI once dispatch_cgi has determined that
600 * it matches one of the magic prefixes. Parses the path
601 * as a cgi name plus query string, prepares a map that
602 * maps CGI parameter names to their values, initializes
603 * the http_response struct, and calls the relevant CGI
607 * 1 : csp = Current client state (buffers, headers, etc...)
608 * 2 : path = Path of CGI, with the CGI prefix removed.
609 * Should not have a leading "/".
611 * Returns : http_response, or NULL on handler failure or out of
614 *********************************************************************/
615 static struct http_response *dispatch_known_cgi(struct client_state * csp,
618 const struct cgi_dispatcher *d;
619 struct map *param_list;
620 struct http_response *rsp;
621 char *query_args_start;
625 if (NULL == (path_copy = strdup(path)))
627 return cgi_error_memory();
630 query_args_start = path_copy;
631 while (*query_args_start && *query_args_start != '?')
635 if (*query_args_start == '?')
637 *query_args_start++ = '\0';
640 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
643 return cgi_error_memory();
649 * path_copy = CGI call name
650 * param_list = CGI params, as map
653 /* Get mem for response or fail*/
654 if (NULL == (rsp = alloc_http_response()))
657 free_map(param_list);
658 return cgi_error_memory();
661 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
662 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
663 csp->ip_addr_str, csp->http->cmd);
665 /* Find and start the right CGI function*/
669 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
671 err = (d->handler)(csp, rsp, param_list);
673 free_map(param_list);
674 if (err == JB_ERR_CGI_PARAMS)
676 err = cgi_error_bad_param(csp, rsp);
681 return finish_http_response(rsp);
685 /* Error in handler, probably out-of-memory */
686 free_http_response(rsp);
687 return cgi_error_memory();
695 /*********************************************************************
697 * Function : parse_cgi_parameters
699 * Description : Parse a URL-encoded argument string into name/value
700 * pairs and store them in a struct map list.
703 * 1 : string = string to be parsed. Will be trashed.
705 * Returns : pointer to param list, or NULL if out of memory.
707 *********************************************************************/
708 static struct map *parse_cgi_parameters(char *argstring)
711 char *vector[BUFFER_SIZE];
713 struct map *cgi_params;
715 if (NULL == (cgi_params = new_map()))
720 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
722 for (i = 0; i < pairs; i++)
724 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
727 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
729 free_map(cgi_params);
740 /*********************************************************************
742 * Function : error_response
744 * Description : returns an http_response that explains the reason
745 * why a request failed.
748 * 1 : csp = Current client state (buffers, headers, etc...)
749 * 2 : templatename = Which template should be used for the answer
750 * 3 : sys_err = system error number
752 * Returns : A http_response. If we run out of memory, this
753 * will be cgi_error_memory().
755 *********************************************************************/
756 struct http_response *error_response(struct client_state *csp,
757 const char *templatename,
761 struct http_response *rsp;
762 struct map * exports = default_exports(csp, NULL);
765 return cgi_error_memory();
768 if (NULL == (rsp = alloc_http_response()))
771 return cgi_error_memory();
774 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
775 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
776 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
777 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
780 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
783 /* Some failures, like "404 no such domain", don't have an IP address. */
784 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
792 free_http_response(rsp);
793 return cgi_error_memory();
796 if (!strcmp(templatename, "no-such-domain"))
798 rsp->status = strdup("404 No such domain");
799 if (rsp->status == NULL)
802 free_http_response(rsp);
803 return cgi_error_memory();
806 else if (!strcmp(templatename, "connect-failed"))
808 rsp->status = strdup("503 Connect failed");
809 if (rsp->status == NULL)
812 free_http_response(rsp);
813 return cgi_error_memory();
817 err = template_fill_for_cgi(csp, templatename, exports, rsp);
820 free_http_response(rsp);
821 return cgi_error_memory();
824 return finish_http_response(rsp);
828 /*********************************************************************
830 * Function : cgi_init_error_messages
832 * Description : Call at the start of the program to initialize
833 * the error message used by cgi_error_memory().
839 *********************************************************************/
840 void cgi_init_error_messages(void)
842 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
843 cgi_error_memory_response->head =
844 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
845 "Content-Type: text/html\r\n"
847 cgi_error_memory_response->body =
849 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
851 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
852 "<p>JunkBuster <b>ran out of memory</b> while processing your request.</p>\r\n"
853 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
857 cgi_error_memory_response->head_length =
858 strlen(cgi_error_memory_response->head);
859 cgi_error_memory_response->content_length =
860 strlen(cgi_error_memory_response->body);
864 /*********************************************************************
866 * Function : cgi_error_memory
868 * Description : Called if a CGI function runs out of memory.
869 * Returns a statically-allocated error response.
872 * 1 : csp = Current client state (buffers, headers, etc...)
873 * 2 : rsp = http_response data structure for output
874 * 3 : template_name = Name of template that could not
877 * Returns : JB_ERR_OK on success
878 * JB_ERR_MEMORY on out-of-memory error.
880 *********************************************************************/
881 struct http_response *cgi_error_memory(void)
883 /* assert that it's been initialized. */
884 assert(cgi_error_memory_response->head);
886 return cgi_error_memory_response;
890 /*********************************************************************
892 * Function : cgi_error_no_template
894 * Description : Almost-CGI function that is called if a templae
895 * cannot be loaded. Note this is not a true CGI,
896 * it takes a template name rather than a map of
900 * 1 : csp = Current client state (buffers, headers, etc...)
901 * 2 : rsp = http_response data structure for output
902 * 3 : template_name = Name of template that could not
905 * Returns : JB_ERR_OK on success
906 * JB_ERR_MEMORY on out-of-memory error.
908 *********************************************************************/
909 jb_err cgi_error_no_template(struct client_state *csp,
910 struct http_response *rsp,
911 const char *template_name)
913 static const char status[] =
914 "500 Internal JunkBuster Proxy Error";
915 static const char body_prefix[] =
917 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
919 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
920 "<p>JunkBuster encountered an error while processing your request:</p>\r\n"
921 "<p><b>Could not load template file <code>";
922 static const char body_suffix[] =
923 "</code></b></p>\r\n"
924 "<p>Please contact your proxy administrator.</p>\r\n"
925 "<p>If you are the proxy administrator, please put the required file "
926 "in the <code><i>(confdir)</i>/templates</code> directory. The "
927 "location of the <code><i>(confdir)</i></code> directory "
928 "is specified in the main JunkBuster <code>config</code> "
929 "file. (It's typically the JunkBuster install directory"
931 ", or <code>/etc/junkbuster/</code>"
932 #endif /* ndef _WIN32 */
939 assert(template_name);
941 /* Reset rsp, if needed */
945 rsp->content_length = 0;
946 rsp->head_length = 0;
949 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
950 if (rsp->body == NULL)
952 return JB_ERR_MEMORY;
954 strcpy(rsp->body, body_prefix);
955 strcat(rsp->body, template_name);
956 strcat(rsp->body, body_suffix);
958 rsp->status = strdup(status);
959 if (rsp->body == NULL)
961 return JB_ERR_MEMORY;
968 /*********************************************************************
970 * Function : cgi_error_bad_param
972 * Description : CGI function that is called if the parameters
973 * (query string) for a CGI were wrong.
976 * 1 : csp = Current client state (buffers, headers, etc...)
977 * 2 : rsp = http_response data structure for output
979 * CGI Parameters : none
981 * Returns : JB_ERR_OK on success
982 * JB_ERR_MEMORY on out-of-memory error.
984 *********************************************************************/
985 jb_err cgi_error_bad_param(struct client_state *csp,
986 struct http_response *rsp)
993 if (NULL == (exports = default_exports(csp, NULL)))
995 return JB_ERR_MEMORY;
998 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1002 /*********************************************************************
1004 * Function : get_http_time
1006 * Description : Get the time in a format suitable for use in a
1007 * HTTP header - e.g.:
1008 * "Sun, 06 Nov 1994 08:49:37 GMT"
1011 * 1 : time_offset = Time returned will be current time
1012 * plus this number of seconds.
1013 * 2 : buf = Destination for result. Must be long enough
1014 * to hold 29 characters plus a trailing zero.
1018 *********************************************************************/
1019 void get_http_time(int time_offset, char *buf)
1021 static const char day_names[7][4] =
1022 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1023 static const char month_names[12][4] =
1024 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1025 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1028 time_t current_time;
1032 time(¤t_time); /* get current time */
1034 current_time += time_offset;
1036 /* get and save the gmt */
1038 #ifdef HAVE_GMTIME_R
1040 t = gmtime_r(¤t_time, &dummy);
1042 t = gmtime(¤t_time);
1046 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1048 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1049 day_names[t->tm_wday],
1051 month_names[t->tm_mon],
1061 /*********************************************************************
1063 * Function : finish_http_response
1065 * Description : Fill in the missing headers in an http response,
1066 * and flatten the headers to an http head.
1069 * 1 : rsp = pointer to http_response to be processed
1071 * Returns : A http_response, usually the rsp parameter.
1072 * On error, free()s rsp and returns cgi_error_memory()
1074 *********************************************************************/
1075 struct http_response *finish_http_response(struct http_response *rsp)
1077 char buf[BUFFER_SIZE];
1080 /* Special case - do NOT change this statically allocated response,
1081 * which is ready for output anyway.
1083 if (rsp == cgi_error_memory_response)
1089 * Fill in the HTTP Status
1091 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1092 err = enlist_first(rsp->headers, buf);
1095 * Set the Content-Length
1097 if (rsp->content_length == 0)
1099 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1103 sprintf(buf, "Content-Length: %d", rsp->content_length);
1104 err = enlist(rsp->headers, buf);
1108 * Fill in the default headers:
1110 * Content-Type: default to text/html if not already specified.
1111 * Date: set to current date/time.
1112 * Last-Modified: set to date/time the page was last changed.
1113 * Expires: set to date/time page next needs reloading.
1114 * Cache-Control: set to "no-cache" if applicable.
1116 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1118 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1123 * Set Expires to about 10 min into the future so it'll get reloaded
1124 * occasionally, e.g. if IJB gets upgraded.
1129 get_http_time(0, buf);
1130 err = enlist_unique_header(rsp->headers, "Date", buf);
1133 /* Some date in the past. */
1134 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1138 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1139 err = enlist_unique_header(rsp->headers, "Expires", buf);
1145 * Compliant browsers should not cache this due to the "Cache-Control"
1146 * setting. However, to be certain, we also set both "Last-Modified"
1147 * and "Expires" to the current time.
1149 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1151 get_http_time(0, buf);
1152 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1153 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1154 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1161 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1163 free_http_response(rsp);
1164 return cgi_error_memory();
1166 rsp->head_length = strlen(rsp->head);
1173 /*********************************************************************
1175 * Function : alloc_http_response
1177 * Description : Allocates a new http_response structure.
1181 * Returns : pointer to a new http_response, or NULL.
1183 *********************************************************************/
1184 struct http_response *alloc_http_response(void)
1186 return (struct http_response *) zalloc(sizeof(struct http_response));
1191 /*********************************************************************
1193 * Function : free_http_response
1195 * Description : Free the memory occupied by an http_response
1196 * and its depandant structures.
1199 * 1 : rsp = pointer to http_response to be freed
1203 *********************************************************************/
1204 void free_http_response(struct http_response *rsp)
1207 * Must special case cgi_error_memory_response, which is never freed.
1209 if (rsp && (rsp != cgi_error_memory_response))
1214 destroy_list(rsp->headers);
1221 /*********************************************************************
1223 * Function : template_load
1225 * Description : CGI support function that loads a given HTML
1226 * template from the confdir, ignoring comment
1230 * 1 : csp = Current client state (buffers, headers, etc...)
1231 * 2 : template_ptr = Destination for pointer to loaded
1233 * 3 : template = name of the HTML template to be used
1235 * Returns : JB_ERR_OK on success
1236 * JB_ERR_MEMORY on out-of-memory error.
1237 * JB_ERR_FILE if the template file cannot be read
1239 *********************************************************************/
1240 jb_err template_load(struct client_state *csp, char ** template_ptr,
1241 const char *templatename)
1243 char *templates_dir_path;
1247 char buf[BUFFER_SIZE];
1250 assert(template_ptr);
1251 assert(templatename);
1253 *template_ptr = NULL;
1256 * Open template file or fail
1259 templates_dir_path = make_path(csp->config->confdir, "templates");
1260 if (templates_dir_path == NULL)
1262 return JB_ERR_MEMORY;
1265 full_path = make_path(templates_dir_path, templatename);
1266 free(templates_dir_path);
1267 if (full_path == NULL)
1269 return JB_ERR_MEMORY;
1272 file_buffer = strdup("");
1273 if (file_buffer == NULL)
1276 return JB_ERR_MEMORY;
1279 if (NULL == (fp = fopen(full_path, "r")))
1281 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1289 * Read the file, ignoring comments.
1291 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1292 * This is unlikely in practise.
1294 while (fgets(buf, BUFFER_SIZE, fp))
1296 /* skip lines starting with '#' */
1302 if (string_append(&file_buffer, buf))
1305 return JB_ERR_MEMORY;
1310 *template_ptr = file_buffer;
1316 /*********************************************************************
1318 * Function : template_fill
1320 * Description : CGI support function that fills in a pre-loaded
1321 * HTML template by replacing @name@ with value using
1322 * pcrs, for each item in the output map.
1324 * Note that a leading '$' charachter in the export map's
1325 * values will be stripped and toggle on backreference
1329 * 1 : template_ptr = IN: Template to be filled out.
1331 * OUT: Filled out template.
1332 * Caller must free().
1333 * 2 : exports = map with fill in symbol -> name pairs
1335 * Returns : JB_ERR_OK on success
1336 * JB_ERR_MEMORY on out-of-memory error
1338 *********************************************************************/
1339 jb_err template_fill(char **template_ptr, const struct map *exports)
1341 struct map_entry *m;
1343 char buf[BUFFER_SIZE];
1344 char *tmp_out_buffer;
1350 assert(template_ptr);
1351 assert(*template_ptr);
1354 file_buffer = *template_ptr;
1355 size = strlen(file_buffer) + 1;
1358 * Assemble pcrs joblist from exports map
1360 for (m = exports->first; m != NULL; m = m->next)
1362 if (*m->name == '$')
1365 * First character of name is '$', so remove this flag
1366 * character and allow backreferences ($1 etc) in the
1367 * "replace with" text.
1369 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1375 * Treat the "replace with" text as a literal string -
1376 * no quoting needed, no backreferences allowed.
1377 * ("Trivial" ['T'] flag).
1381 /* Enclose name in @@ */
1382 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1386 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1388 /* Make and run job. */
1389 job = pcrs_compile(buf, m->value, flags, &error);
1392 if (error == PCRS_ERR_NOMEM)
1395 *template_ptr = NULL;
1396 return JB_ERR_MEMORY;
1400 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1401 /* Hope it wasn't important and silently ignore the invalid job */
1406 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1409 if (NULL == tmp_out_buffer)
1411 *template_ptr = NULL;
1412 return JB_ERR_MEMORY;
1414 file_buffer = tmp_out_buffer;
1421 *template_ptr = file_buffer;
1426 /*********************************************************************
1428 * Function : template_fill_for_cgi
1430 * Description : CGI support function that loads a HTML template
1431 * and fills it in. Handles file-not-found errors
1432 * by sending a HTML error message. For convenience,
1433 * this function also frees the passed "exports" map.
1436 * 1 : csp = Client state
1437 * 2 : templatename = name of the HTML template to be used
1438 * 3 : exports = map with fill in symbol -> name pairs.
1439 * Will be freed by this function.
1441 * Returns : JB_ERR_OK on success
1442 * JB_ERR_MEMORY on out-of-memory error
1444 *********************************************************************/
1445 jb_err template_fill_for_cgi(struct client_state *csp,
1446 const char *templatename,
1447 struct map *exports,
1448 struct http_response *rsp)
1453 assert(templatename);
1457 err = template_load(csp, &rsp->body, templatename);
1458 if (err == JB_ERR_FILE)
1461 return cgi_error_no_template(csp, rsp, templatename);
1466 return err; /* JB_ERR_MEMORY */
1468 err = template_fill(&rsp->body, exports);
1474 /*********************************************************************
1476 * Function : default_exports
1478 * Description : returns a struct map list that contains exports
1479 * which are common to all CGI functions.
1482 * 1 : csp = Current client state (buffers, headers, etc...)
1483 * 2 : caller = name of CGI who calls us and which should
1484 * be excluded from the generated menu. May be
1486 * Returns : NULL if no memory, else a new map. Caller frees.
1488 *********************************************************************/
1489 struct map *default_exports(const struct client_state *csp, const char *caller)
1493 struct map * exports;
1494 int local_help_exists = 0;
1498 exports = new_map();
1499 if (exports == NULL)
1504 err = map(exports, "version", 1, html_encode(VERSION), 0);
1505 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1506 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1507 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1508 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1509 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1510 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1511 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1513 snprintf(buf, 20, "%d", csp->config->hport);
1514 if (!err) err = map(exports, "my-port", 1, buf, 1);
1516 if(!strcmp(CODE_STATUS, "stable"))
1518 if (!err) err = map_block_killer(exports, "unstable");
1521 if (csp->config->admin_address != NULL)
1523 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1524 local_help_exists = 1;
1528 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1531 if (csp->config->proxy_info_url != NULL)
1533 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1534 local_help_exists = 1;
1538 if (!err) err = map_block_killer(exports, "have-proxy-info");
1541 if (local_help_exists == 0)
1543 if (!err) err = map_block_killer(exports, "have-help-info");
1556 /*********************************************************************
1558 * Function : map_block_killer
1560 * Description : Convenience function.
1561 * Adds a "killer" for the conditional HTML-template
1562 * block <name>, i.e. a substitution of the regex
1563 * "if-<name>-start.*if-<name>-end" to the given
1567 * 1 : exports = map to extend
1568 * 2 : name = name of conditional block
1570 * Returns : JB_ERR_OK on success
1571 * JB_ERR_MEMORY on out-of-memory error.
1573 *********************************************************************/
1574 jb_err map_block_killer(struct map *exports, const char *name)
1576 char buf[1000]; /* Will do, since the names are hardwired */
1580 assert(strlen(name) < 490);
1582 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1583 return map(exports, buf, 1, "", 1);
1587 /*********************************************************************
1589 * Function : map_block_keep
1591 * Description : Convenience function. Removes the markers used
1592 * by map-block-killer, to save a few bytes.
1593 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1596 * 1 : exports = map to extend
1597 * 2 : name = name of conditional block
1599 * Returns : JB_ERR_OK on success
1600 * JB_ERR_MEMORY on out-of-memory error.
1602 *********************************************************************/
1603 jb_err map_block_keep(struct map *exports, const char *name)
1606 char buf[500]; /* Will do, since the names are hardwired */
1610 assert(strlen(name) < 490);
1612 snprintf(buf, 500, "if-%s-start", name);
1613 err = map(exports, buf, 1, "", 1);
1620 snprintf(buf, 500, "if-%s-end", name);
1621 return map(exports, buf, 1, "", 1);
1625 /*********************************************************************
1627 * Function : map_conditional
1629 * Description : Convenience function.
1630 * Adds an "if-then-else" for the conditional HTML-template
1631 * block <name>, i.e. a substitution of the form:
1638 * The control structure and one of the alternatives
1642 * 1 : exports = map to extend
1643 * 2 : name = name of conditional block
1644 * 3 : choose_first = nonzero for first, zero for second.
1646 * Returns : JB_ERR_OK on success
1647 * JB_ERR_MEMORY on out-of-memory error.
1649 *********************************************************************/
1650 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1652 char buf[1000]; /* Will do, since the names are hardwired */
1657 assert(strlen(name) < 480);
1659 snprintf(buf, 1000, (choose_first
1660 ? "else-not-%s@.*@endif-%s"
1661 : "if-%s-then@.*@else-not-%s"),
1664 err = map(exports, buf, 1, "", 1);
1670 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1671 return map(exports, buf, 1, "", 1);
1675 /*********************************************************************
1677 * Function : make_menu
1679 * Description : Returns an HTML-formatted menu of the available
1680 * unhidden CGIs, excluding the one given in <self>.
1682 * Parameters : self = name of CGI to leave out, can be NULL
1684 * Returns : menu string, or NULL on out-of-memory error.
1686 *********************************************************************/
1687 char *make_menu(const char *self)
1689 const struct cgi_dispatcher *d;
1690 char *result = strdup("");
1694 self = "NO-SUCH-CGI!";
1697 /* List available unhidden CGI's and export as "other-cgis" */
1698 for (d = cgi_dispatchers; d->name; d++)
1700 if (d->description && strcmp(d->name, self))
1702 string_append(&result, "<li><a href=\"" CGI_PREFIX);
1703 string_append(&result, d->name);
1704 string_append(&result, "\">");
1705 string_append(&result, d->description);
1706 string_append(&result, "</a></li>\n");
1714 /*********************************************************************
1716 * Function : dump_map
1718 * Description : HTML-dump a map for debugging
1721 * 1 : the_map = map to dump
1723 * Returns : string with HTML
1725 *********************************************************************/
1726 char *dump_map(const struct map *the_map)
1728 struct map_entry *cur_entry;
1729 char *ret = strdup("");
1731 string_append(&ret, "<table>\n");
1733 for (cur_entry = the_map->first;
1734 (cur_entry != NULL) && (ret != NULL);
1735 cur_entry = cur_entry->next)
1737 string_append(&ret, "<tr><td><b>");
1738 string_join (&ret, html_encode(cur_entry->name));
1739 string_append(&ret, "</b></td><td>");
1740 string_join (&ret, html_encode(cur_entry->value));
1741 string_append(&ret, "</td></tr>\n");
1744 string_append(&ret, "</table>\n");