1 const char cgi_rcs[] = "$Id: cgi.c,v 1.45 2002/03/06 22:54:35 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.45 2002/03/06 22:54:35 jongfoster
42 * Automated function-comment nitpicking.
44 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
45 * - Better error reporting on OS/2
46 * - Fix double-slash comment (oops)
48 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
49 * - Re-enable OS/2 building after new parms were added
50 * - Fix false out of memory report when resolving CGI templates when no IP
51 * address is available of failed attempt (a la no such domain)
53 * Revision 1.42 2002/01/21 00:33:20 jongfoster
54 * Replacing strsav() with the safer string_append() or string_join().
55 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
56 * Adding missing html_encode() to error message generators.
57 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
59 * Revision 1.41 2002/01/17 20:56:22 jongfoster
60 * Replacing hard references to the URL of the config interface
61 * with #defines from project.h
63 * Revision 1.40 2002/01/09 14:26:46 oes
64 * Added support for thread-safe gmtime_r call.
66 * Revision 1.39 2001/11/16 00:48:13 jongfoster
67 * Fixing a compiler warning
69 * Revision 1.38 2001/11/13 00:31:21 jongfoster
70 * - Adding new CGIs for use by non-JavaScript browsers:
71 * edit-actions-url-form
72 * edit-actions-add-url-form
73 * edit-actions-remove-url-form
74 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
77 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
78 * Show enablement/disablement status in almost all templates.
79 * There is a little trickiness here: apparent recursive resolution of
80 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
81 * the actual enablement status. So a similar construct,
82 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
85 * Revision 1.36 2001/10/26 17:33:27 oes
88 * Revision 1.35 2001/10/23 21:48:19 jongfoster
89 * Cleaning up error handling in CGI functions - they now send back
90 * a HTML error page and should never cause a FATAL error. (Fixes one
91 * potential source of "denial of service" attacks).
93 * CGI actions file editor that works and is actually useful.
95 * Ability to toggle JunkBuster remotely using a CGI call.
97 * You can turn off both the above features in the main configuration
98 * file, e.g. if you are running a multi-user proxy.
100 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
101 * Only show "Local support" on templates conditionally:
102 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
103 * - if not, no Local support section appears
105 * Revision 1.33 2001/10/14 22:28:41 jongfoster
106 * Fixing stupid typo.
108 * Revision 1.32 2001/10/14 22:20:18 jongfoster
109 * - Changes to CGI dispatching method to match CGI names exactly,
110 * rather than doing a prefix match.
111 * - No longer need to count the length of the CGI handler names by hand.
112 * - Adding new handler for 404 error when disptching a CGI, if none of
113 * the handlers match.
114 * - Adding new handlers for CGI actionsfile editor.
116 * Revision 1.31 2001/10/10 10:56:39 oes
117 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
119 * Revision 1.30 2001/10/02 15:30:57 oes
120 * Introduced show-request cgi
122 * Revision 1.29 2001/09/20 15:47:44 steudten
124 * Fix BUG: Modify int size to size_t size in fill_template()
125 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
127 * Revision 1.28 2001/09/19 18:00:37 oes
128 * - Deletef time() FIXME (Can't fail under Linux either, if
129 * the argument is guaranteed to be in out address space,
132 * - Pointer notation cosmetics
133 * - Fixed a minor bug in template_fill(): Failiure of
134 * pcrs_execute() now secure.
136 * Revision 1.27 2001/09/16 17:08:54 jongfoster
137 * Moving simple CGI functions from cgi.c to new file cgisimple.c
139 * Revision 1.26 2001/09/16 15:47:37 jongfoster
140 * First version of CGI-based edit interface. This is very much a
141 * work-in-progress, and you can't actually use it to edit anything
142 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
143 * to have any effect.
145 * Revision 1.25 2001/09/16 15:02:35 jongfoster
146 * Adding i.j.b/robots.txt.
147 * Inlining add_stats() since it's only ever called from one place.
149 * Revision 1.24 2001/09/16 11:38:01 jongfoster
150 * Splitting fill_template() into 2 functions:
151 * template_load() loads the file
152 * template_fill() performs the PCRS regexps.
153 * This is because the CGI edit interface has a "table row"
154 * template which is used many times in the page - this
155 * change means it's only loaded from disk once.
157 * Revision 1.23 2001/09/16 11:16:05 jongfoster
158 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
160 * Revision 1.22 2001/09/16 11:00:10 jongfoster
161 * New function alloc_http_response, for symmetry with free_http_response
163 * Revision 1.21 2001/09/13 23:53:03 jongfoster
164 * Support for both static and dynamically generated CGI pages.
165 * Correctly setting Last-Modified: and Expires: HTTP headers.
167 * Revision 1.20 2001/09/13 23:40:36 jongfoster
168 * (Cosmetic only) Indentation correction
170 * Revision 1.19 2001/09/13 23:31:25 jongfoster
171 * Moving image data to cgi.c rather than cgi.h.
173 * Revision 1.18 2001/08/05 16:06:20 jongfoster
174 * Modifiying "struct map" so that there are now separate header and
175 * "map_entry" structures. This means that functions which modify a
176 * map no longer need to return a pointer to the modified map.
177 * Also, it no longer reverses the order of the entries (which may be
178 * important with some advanced template substitutions).
180 * Revision 1.17 2001/08/05 15:57:38 oes
181 * Adapted finish_http_response to new list_to_text
183 * Revision 1.16 2001/08/01 21:33:18 jongfoster
184 * Changes to fill_template() that reduce memory usage without having
185 * an impact on performance. I also renamed some variables so as not
186 * to clash with the C++ keywords "new" and "template".
188 * Revision 1.15 2001/08/01 21:19:22 jongfoster
189 * Moving file version information to a separate CGI page.
191 * Revision 1.14 2001/08/01 00:19:03 jongfoster
192 * New function: map_conditional() for an if-then-else syntax.
193 * Changing to use new version of show_defines()
195 * Revision 1.13 2001/07/30 22:08:36 jongfoster
196 * Tidying up #defines:
197 * - All feature #defines are now of the form FEATURE_xxx
198 * - Permanently turned off WIN_GUI_EDIT
199 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
201 * Revision 1.12 2001/07/29 18:47:05 jongfoster
202 * Adding missing #include "loadcfg.h"
204 * Revision 1.11 2001/07/18 17:24:37 oes
205 * Changed to conform to new pcrs interface
207 * Revision 1.10 2001/07/13 13:53:13 oes
208 * Removed all #ifdef PCRS and related code
210 * Revision 1.9 2001/06/29 21:45:41 oes
211 * Indentation, CRLF->LF, Tab-> Space
213 * Revision 1.8 2001/06/29 13:21:46 oes
214 * - Cosmetics: renamed and reordered functions, variables,
215 * texts, improved comments etc
217 * - Removed ij_untrusted_url() The relevant
218 * info is now part of the "untrusted" page,
219 * which is generated by filters.c:trust_url()
221 * - Generators of content now call finish_http_response()
222 * themselves, making jcc.c:chat() a little less
225 * - Removed obsolete "Pragma: no-cache" from our headers
227 * - http_responses now know their head length
229 * - fill_template now uses the new interface to pcrs, so that
230 * - long jobs (like whole files) no longer have to be assembled
231 * in a fixed size buffer
232 * - the new T (trivial) option is used, and the replacement may
233 * contain Perl syntax backrefs without confusing pcrs
235 * - Introduced default_exports() which generates a set of exports
236 * common to all CGIs and other content generators
238 * - Introduced convenience function map_block_killer()
240 * - Introduced convenience function make_menu()
242 * - Introduced CGI-like function error_response() which generates
243 * the "No such domain" and "Connect failed" messages using the
246 * - cgi_show_url_info:
247 * - adapted to new CGI features
248 * - form and answers now generated from same template
249 * - http:// prefix in URL now OK
252 * - adapted to new CGI features
253 * - no longer uses csp->init_proxy_args
256 * - moved menu generation to make_menu()
258 * - add_stats now writes single export map entries instead
261 * - Moved redirect_url() to filters.c
263 * - Fixed mem leak in free_http_response(), map_block_killer(),
265 * - Removed logentry from cancelled commit
267 * Revision 1.7 2001/06/09 10:51:58 jongfoster
268 * Changing "show URL info" handler to new style.
269 * Changing BUFSIZ ==> BUFFER_SIZE
271 * Revision 1.6 2001/06/07 23:05:19 jongfoster
272 * Removing code related to old forward and ACL files.
274 * Revision 1.5 2001/06/05 19:59:16 jongfoster
275 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
277 * Revision 1.4 2001/06/04 10:41:52 swa
278 * show version string of cgi.h and cgi.c
280 * Revision 1.3 2001/06/03 19:12:16 oes
281 * introduced new cgi handling
283 * No revisions before 1.3
285 **********************************************************************/
291 #include <sys/types.h>
298 #define snprintf _snprintf
299 #endif /* def _WIN32 */
307 #include "miscutil.h"
308 #include "cgisimple.h"
309 #ifdef FEATURE_CGI_EDIT_ACTIONS
311 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
313 /* loadcfg.h is for g_bToggleIJB only */
315 const char cgi_h_rcs[] = CGI_H_VERSION;
317 static const struct cgi_dispatcher cgi_dispatchers[] = {
320 "Junkbuster main page" },
323 "Show information about the current configuration" },
326 "Show the source code version numbers" },
329 "Show the client's request headers." },
332 "Show which actions apply to a URL and why" },
335 "Toggle JunkBuster on or off" },
336 #ifdef FEATURE_CGI_EDIT_ACTIONS
339 "Edit the actions list" },
342 { "eaa", /* Shortcut for edit-actions-add-url-form */
343 cgi_edit_actions_add_url_form,
345 { "eau", /* Shortcut for edit-actions-url-form */
346 cgi_edit_actions_url_form,
348 { "ear", /* Shortcut for edit-actions-remove-url-form */
349 cgi_edit_actions_remove_url_form,
351 { "eas", /* Shortcut for edit-actions-for-url */
352 cgi_edit_actions_for_url,
354 { "easa", /* Shortcut for edit-actions-section-add */
355 cgi_edit_actions_section_add,
357 { "easr", /* Shortcut for edit-actions-section-remove */
358 cgi_edit_actions_section_remove,
360 { "eass", /* Shortcut for edit-actions-section-swap */
361 cgi_edit_actions_section_swap,
363 { "edit-actions-for-url",
364 cgi_edit_actions_for_url,
365 NULL /* Edit the actions for (a) specified URL(s) */ },
366 { "edit-actions-list",
367 cgi_edit_actions_list,
368 NULL /* Edit the actions list */ },
369 { "edit-actions-submit",
370 cgi_edit_actions_submit,
371 NULL /* Change the actions for (a) specified URL(s) */ },
372 { "edit-actions-url",
373 cgi_edit_actions_url,
374 NULL /* Change a URL pattern in the actionsfile */ },
375 { "edit-actions-url-form",
376 cgi_edit_actions_url_form,
377 NULL /* Form to change a URL pattern in the actionsfile */ },
378 { "edit-actions-add-url",
379 cgi_edit_actions_add_url,
380 NULL /* Add a URL pattern to the actionsfile */ },
381 { "edit-actions-add-url-form",
382 cgi_edit_actions_add_url_form,
383 NULL /* Form to add a URL pattern to the actionsfile */ },
384 { "edit-actions-remove-url",
385 cgi_edit_actions_remove_url,
386 NULL /* Remove a URL pattern from the actionsfile */ },
387 { "edit-actions-remove-url-form",
388 cgi_edit_actions_remove_url_form,
389 NULL /* Form to remove a URL pattern from the actionsfile */ },
390 { "edit-actions-section-add",
391 cgi_edit_actions_section_add,
392 NULL /* Remove a section from the actionsfile */ },
393 { "edit-actions-section-remove",
394 cgi_edit_actions_section_remove,
395 NULL /* Remove a section from the actionsfile */ },
396 { "edit-actions-section-swap",
397 cgi_edit_actions_section_swap,
398 NULL /* Swap two sections in the actionsfile */ },
399 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
402 NULL /* Sends a robots.txt file to tell robots to go away. */ },
405 NULL /* Send a built-in png image */ },
408 NULL /* Send a transparent png (short name) */ },
409 { NULL, /* NULL Indicates end of list and default page */
411 NULL /* Unknown CGI page */ }
416 * Bulit-in images for ad replacement
418 * Hint: You can encode your own PNGs like this:
419 * cat yourfile.png | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
421 const char image_logo_data[] =
422 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
423 "\122\000\000\000\104\000\000\000\013\001\003\000\000\000\374"
424 "\323\271\110\000\000\000\004\147\101\115\101\000\000\261\217"
425 "\013\374\141\005\000\000\000\006\120\114\124\105\310\310\310"
426 "\000\000\000\062\100\100\345\000\000\000\001\164\122\116\123"
427 "\000\100\346\330\146\000\000\000\001\142\113\107\104\000\210"
428 "\005\035\110\000\000\000\126\111\104\101\124\170\332\143\140"
429 "\200\003\066\006\146\066\006\006\011\124\326\331\315\146\147"
430 "\316\333\174\116\000\262\156\247\347\334\234\071\373\001\220"
431 "\065\373\130\316\035\311\331\015\020\326\161\311\337\014\014"
432 "\151\147\147\247\345\034\236\331\014\144\335\235\155\236\173"
433 "\163\366\154\006\006\233\334\331\162\307\316\363\174\106\330"
434 "\300\000\000\002\127\040\324\250\204\044\102\000\000\000\000"
435 "\111\105\116\104\256\102\140\202";
437 const size_t image_logo_length = sizeof(image_logo_data) - 1;
439 const char image_pattern_data[] =
440 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
441 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
442 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
443 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
444 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
445 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
446 "\000\000\000\111\105\116\104\256\102\140\202";
448 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
450 const char image_blank_data[] =
451 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
452 "\122\000\000\000\002\000\000\000\002\010\002\000\000\000\375"
453 "\324\232\163\000\000\000\006\142\113\107\104\000\310\000\310"
454 "\000\310\052\045\225\037\000\000\000\027\111\104\101\124\170"
455 "\332\143\374\377\377\377\311\223\047\031\116\234\070\361\377"
456 "\377\177\000\112\335\012\257\162\103\306\335\000\000\000\000"
457 "\111\105\116\104\256\102\140\202o";
459 const size_t image_blank_length = sizeof(image_blank_data) - 1;
462 static struct http_response cgi_error_memory_response[1];
464 static struct http_response *dispatch_known_cgi(struct client_state * csp,
466 static struct map *parse_cgi_parameters(char *argstring);
469 /*********************************************************************
471 * Function : dispatch_cgi
473 * Description : Checks if a request URL has either the magical
474 * hostname CGI_SITE_1_HOST (usully http://i.j.b/) or
475 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
476 * http://ijbswa.sourceforge.net/config). If so, it passes
477 * the (rest of the) path onto dispatch_known_cgi, which
478 * calls the relevant CGI handler function.
481 * 1 : csp = Current client state (buffers, headers, etc...)
483 * Returns : http_response if match, NULL if nonmatch or handler fail
485 *********************************************************************/
486 struct http_response *dispatch_cgi(struct client_state *csp)
488 const char *host = csp->http->host;
489 const char *path = csp->http->path;
492 * Should we intercept ?
495 /* Note: "example.com" and "example.com." are equivalent hostnames. */
497 /* Either the host matches CGI_SITE_1_HOST ..*/
498 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
499 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
500 && (path[0] == '/') )
502 /* ..then the path will all be for us. Remove leading '/' */
505 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
506 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
507 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
508 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
510 /* take everything following CGI_SITE_2_PATH */
511 path += strlen(CGI_SITE_2_PATH);
514 /* skip the forward slash after CGI_SITE_2_PATH */
517 else if (*path != '\0')
520 * wierdness: URL is /configXXX, where XXX is some string
521 * Do *NOT* intercept.
533 * This is a CGI call.
536 return dispatch_known_cgi(csp, path);
540 /*********************************************************************
542 * Function : dispatch_known_cgi
544 * Description : Processes a CGI once dispatch_cgi has determined that
545 * it matches one of the magic prefixes. Parses the path
546 * as a cgi name plus query string, prepares a map that
547 * maps CGI parameter names to their values, initializes
548 * the http_response struct, and calls the relevant CGI
552 * 1 : csp = Current client state (buffers, headers, etc...)
553 * 2 : path = Path of CGI, with the CGI prefix removed.
554 * Should not have a leading "/".
556 * Returns : http_response, or NULL on handler failure or out of
559 *********************************************************************/
560 static struct http_response *dispatch_known_cgi(struct client_state * csp,
563 const struct cgi_dispatcher *d;
564 struct map *param_list;
565 struct http_response *rsp;
566 char *query_args_start;
570 if (NULL == (path_copy = strdup(path)))
572 return cgi_error_memory();
575 query_args_start = path_copy;
576 while (*query_args_start && *query_args_start != '?')
580 if (*query_args_start == '?')
582 *query_args_start++ = '\0';
585 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
588 return cgi_error_memory();
594 * path_copy = CGI call name
595 * param_list = CGI params, as map
598 /* Get mem for response or fail*/
599 if (NULL == (rsp = alloc_http_response()))
602 free_map(param_list);
603 return cgi_error_memory();
606 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
607 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
608 csp->ip_addr_str, csp->http->cmd);
610 /* Find and start the right CGI function*/
611 for (d = cgi_dispatchers; FOREVER; d++)
613 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
615 err = (d->handler)(csp, rsp, param_list);
617 free_map(param_list);
618 if (err == JB_ERR_CGI_PARAMS)
620 err = cgi_error_bad_param(csp, rsp);
625 return finish_http_response(rsp);
629 /* Error in handler, probably out-of-memory */
630 free_http_response(rsp);
631 return cgi_error_memory();
638 /*********************************************************************
640 * Function : parse_cgi_parameters
642 * Description : Parse a URL-encoded argument string into name/value
643 * pairs and store them in a struct map list.
646 * 1 : string = string to be parsed. Will be trashed.
648 * Returns : pointer to param list, or NULL if out of memory.
650 *********************************************************************/
651 static struct map *parse_cgi_parameters(char *argstring)
654 char *vector[BUFFER_SIZE];
656 struct map *cgi_params;
658 if (NULL == (cgi_params = new_map()))
663 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
665 for (i = 0; i < pairs; i++)
667 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
670 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
672 free_map(cgi_params);
683 /*********************************************************************
685 * Function : error_response
687 * Description : returns an http_response that explains the reason
688 * why a request failed.
691 * 1 : csp = Current client state (buffers, headers, etc...)
692 * 2 : templatename = Which template should be used for the answer
693 * 3 : sys_err = system error number
695 * Returns : A http_response. If we run out of memory, this
696 * will be cgi_error_memory().
698 *********************************************************************/
699 struct http_response *error_response(struct client_state *csp,
700 const char *templatename,
704 struct http_response *rsp;
705 struct map * exports = default_exports(csp, NULL);
708 return cgi_error_memory();
711 if (NULL == (rsp = alloc_http_response()))
714 return cgi_error_memory();
717 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
718 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
719 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
720 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
723 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
726 /* Some failures, like "404 no such domain", don't have an IP address. */
727 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
735 free_http_response(rsp);
736 return cgi_error_memory();
739 if (!strcmp(templatename, "no-such-domain"))
741 rsp->status = strdup("404 No such domain");
742 if (rsp->status == NULL)
745 free_http_response(rsp);
746 return cgi_error_memory();
749 else if (!strcmp(templatename, "connect-failed"))
751 rsp->status = strdup("503 Connect failed");
752 if (rsp->status == NULL)
755 free_http_response(rsp);
756 return cgi_error_memory();
760 err = template_fill_for_cgi(csp, templatename, exports, rsp);
763 free_http_response(rsp);
764 return cgi_error_memory();
767 return finish_http_response(rsp);
771 /*********************************************************************
773 * Function : cgi_init_error_messages
775 * Description : Call at the start of the program to initialize
776 * the error message used by cgi_error_memory().
782 *********************************************************************/
783 void cgi_init_error_messages(void)
785 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
786 cgi_error_memory_response->head =
787 "HTTP/1.0 500 Internal JunkBuster Proxy Error\r\n"
788 "Content-Type: text/html\r\n"
790 cgi_error_memory_response->body =
792 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
794 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
795 "<p>JunkBuster <b>ran out of memory</b> while processing your request.</p>\r\n"
796 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
800 cgi_error_memory_response->head_length =
801 strlen(cgi_error_memory_response->head);
802 cgi_error_memory_response->content_length =
803 strlen(cgi_error_memory_response->body);
807 /*********************************************************************
809 * Function : cgi_error_memory
811 * Description : Called if a CGI function runs out of memory.
812 * Returns a statically-allocated error response.
815 * 1 : csp = Current client state (buffers, headers, etc...)
816 * 2 : rsp = http_response data structure for output
817 * 3 : template_name = Name of template that could not
820 * Returns : JB_ERR_OK on success
821 * JB_ERR_MEMORY on out-of-memory error.
823 *********************************************************************/
824 struct http_response *cgi_error_memory(void)
826 /* assert that it's been initialized. */
827 assert(cgi_error_memory_response->head);
829 return cgi_error_memory_response;
833 /*********************************************************************
835 * Function : cgi_error_no_template
837 * Description : Almost-CGI function that is called if a templae
838 * cannot be loaded. Note this is not a true CGI,
839 * it takes a template name rather than a map of
843 * 1 : csp = Current client state (buffers, headers, etc...)
844 * 2 : rsp = http_response data structure for output
845 * 3 : template_name = Name of template that could not
848 * Returns : JB_ERR_OK on success
849 * JB_ERR_MEMORY on out-of-memory error.
851 *********************************************************************/
852 jb_err cgi_error_no_template(struct client_state *csp,
853 struct http_response *rsp,
854 const char *template_name)
856 static const char status[] =
857 "500 Internal JunkBuster Proxy Error";
858 static const char body_prefix[] =
860 "<head><title>500 Internal JunkBuster Proxy Error</title></head>\r\n"
862 "<h1>500 Internal JunkBuster Proxy Error</h1>\r\n"
863 "<p>JunkBuster encountered an error while processing your request:</p>\r\n"
864 "<p><b>Could not load template file <code>";
865 static const char body_suffix[] =
866 "</code></b></p>\r\n"
867 "<p>Please contact your proxy administrator.</p>\r\n"
868 "<p>If you are the proxy administrator, please put the required file "
869 "in the <code><i>(confdir)</i>/templates</code> directory. The "
870 "location of the <code><i>(confdir)</i></code> directory "
871 "is specified in the main JunkBuster <code>config</code> "
872 "file. (It's typically the JunkBuster install directory"
874 ", or <code>/etc/junkbuster/</code>"
875 #endif /* ndef _WIN32 */
882 assert(template_name);
884 /* Reset rsp, if needed */
888 rsp->content_length = 0;
889 rsp->head_length = 0;
892 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
893 if (rsp->body == NULL)
895 return JB_ERR_MEMORY;
897 strcpy(rsp->body, body_prefix);
898 strcat(rsp->body, template_name);
899 strcat(rsp->body, body_suffix);
901 rsp->status = strdup(status);
902 if (rsp->body == NULL)
904 return JB_ERR_MEMORY;
911 /*********************************************************************
913 * Function : cgi_error_bad_param
915 * Description : CGI function that is called if the parameters
916 * (query string) for a CGI were wrong.
919 * 1 : csp = Current client state (buffers, headers, etc...)
920 * 2 : rsp = http_response data structure for output
922 * CGI Parameters : none
924 * Returns : JB_ERR_OK on success
925 * JB_ERR_MEMORY on out-of-memory error.
927 *********************************************************************/
928 jb_err cgi_error_bad_param(struct client_state *csp,
929 struct http_response *rsp)
936 if (NULL == (exports = default_exports(csp, NULL)))
938 return JB_ERR_MEMORY;
941 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
945 /*********************************************************************
947 * Function : get_http_time
949 * Description : Get the time in a format suitable for use in a
950 * HTTP header - e.g.:
951 * "Sun, 06 Nov 1994 08:49:37 GMT"
954 * 1 : time_offset = Time returned will be current time
955 * plus this number of seconds.
956 * 2 : buf = Destination for result. Must be long enough
957 * to hold 29 characters plus a trailing zero.
961 *********************************************************************/
962 void get_http_time(int time_offset, char *buf)
964 static const char day_names[7][4] =
965 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
966 static const char month_names[12][4] =
967 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
968 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
975 time(¤t_time); /* get current time */
977 current_time += time_offset;
979 /* get and save the gmt */
983 t = gmtime_r(¤t_time, &dummy);
985 t = gmtime(¤t_time);
989 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
991 "%s, %02d %s %4d %02d:%02d:%02d GMT",
992 day_names[t->tm_wday],
994 month_names[t->tm_mon],
1004 /*********************************************************************
1006 * Function : finish_http_response
1008 * Description : Fill in the missing headers in an http response,
1009 * and flatten the headers to an http head.
1012 * 1 : rsp = pointer to http_response to be processed
1014 * Returns : A http_response, usually the rsp parameter.
1015 * On error, free()s rsp and returns cgi_error_memory()
1017 *********************************************************************/
1018 struct http_response *finish_http_response(struct http_response *rsp)
1020 char buf[BUFFER_SIZE];
1023 /* Special case - do NOT change this statically allocated response,
1024 * which is ready for output anyway.
1026 if (rsp == cgi_error_memory_response)
1032 * Fill in the HTTP Status
1034 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1035 err = enlist_first(rsp->headers, buf);
1038 * Set the Content-Length
1040 if (rsp->content_length == 0)
1042 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1046 sprintf(buf, "Content-Length: %d", rsp->content_length);
1047 err = enlist(rsp->headers, buf);
1051 * Fill in the default headers:
1053 * Content-Type: default to text/html if not already specified.
1054 * Date: set to current date/time.
1055 * Last-Modified: set to date/time the page was last changed.
1056 * Expires: set to date/time page next needs reloading.
1057 * Cache-Control: set to "no-cache" if applicable.
1059 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1061 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1066 * Set Expires to about 10 min into the future so it'll get reloaded
1067 * occasionally, e.g. if IJB gets upgraded.
1072 get_http_time(0, buf);
1073 err = enlist_unique_header(rsp->headers, "Date", buf);
1076 /* Some date in the past. */
1077 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1081 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1082 err = enlist_unique_header(rsp->headers, "Expires", buf);
1088 * Compliant browsers should not cache this due to the "Cache-Control"
1089 * setting. However, to be certain, we also set both "Last-Modified"
1090 * and "Expires" to the current time.
1092 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1094 get_http_time(0, buf);
1095 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1096 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1097 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1104 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1106 free_http_response(rsp);
1107 return cgi_error_memory();
1109 rsp->head_length = strlen(rsp->head);
1116 /*********************************************************************
1118 * Function : alloc_http_response
1120 * Description : Allocates a new http_response structure.
1124 * Returns : pointer to a new http_response, or NULL.
1126 *********************************************************************/
1127 struct http_response *alloc_http_response(void)
1129 return (struct http_response *) zalloc(sizeof(struct http_response));
1134 /*********************************************************************
1136 * Function : free_http_response
1138 * Description : Free the memory occupied by an http_response
1139 * and its depandant structures.
1142 * 1 : rsp = pointer to http_response to be freed
1146 *********************************************************************/
1147 void free_http_response(struct http_response *rsp)
1150 * Must special case cgi_error_memory_response, which is never freed.
1152 if (rsp && (rsp != cgi_error_memory_response))
1157 destroy_list(rsp->headers);
1164 /*********************************************************************
1166 * Function : template_load
1168 * Description : CGI support function that loads a given HTML
1169 * template from the confdir, ignoring comment
1173 * 1 : csp = Current client state (buffers, headers, etc...)
1174 * 2 : template_ptr = Destination for pointer to loaded
1176 * 3 : template = name of the HTML template to be used
1178 * Returns : JB_ERR_OK on success
1179 * JB_ERR_MEMORY on out-of-memory error.
1180 * JB_ERR_FILE if the template file cannot be read
1182 *********************************************************************/
1183 jb_err template_load(struct client_state *csp, char ** template_ptr,
1184 const char *templatename)
1186 char *templates_dir_path;
1190 char buf[BUFFER_SIZE];
1193 assert(template_ptr);
1194 assert(templatename);
1196 *template_ptr = NULL;
1199 * Open template file or fail
1202 templates_dir_path = make_path(csp->config->confdir, "templates");
1203 if (templates_dir_path == NULL)
1205 return JB_ERR_MEMORY;
1208 full_path = make_path(templates_dir_path, templatename);
1209 free(templates_dir_path);
1210 if (full_path == NULL)
1212 return JB_ERR_MEMORY;
1215 file_buffer = strdup("");
1216 if (file_buffer == NULL)
1219 return JB_ERR_MEMORY;
1222 if (NULL == (fp = fopen(full_path, "r")))
1224 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1232 * Read the file, ignoring comments.
1234 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1235 * This is unlikely in practise.
1237 while (fgets(buf, BUFFER_SIZE, fp))
1239 /* skip lines starting with '#' */
1245 if (string_append(&file_buffer, buf))
1248 return JB_ERR_MEMORY;
1253 *template_ptr = file_buffer;
1259 /*********************************************************************
1261 * Function : template_fill
1263 * Description : CGI support function that fills in a pre-loaded
1264 * HTML template by replacing @name@ with value using
1265 * pcrs, for each item in the output map.
1267 * Note that a leading '$' charachter in the export map's
1268 * values will be stripped and toggle on backreference
1272 * 1 : template_ptr = IN: Template to be filled out.
1274 * OUT: Filled out template.
1275 * Caller must free().
1276 * 2 : exports = map with fill in symbol -> name pairs
1278 * Returns : JB_ERR_OK on success
1279 * JB_ERR_MEMORY on out-of-memory error
1281 *********************************************************************/
1282 jb_err template_fill(char **template_ptr, const struct map *exports)
1284 struct map_entry *m;
1286 char buf[BUFFER_SIZE];
1287 char *tmp_out_buffer;
1293 assert(template_ptr);
1294 assert(*template_ptr);
1297 file_buffer = *template_ptr;
1298 size = strlen(file_buffer) + 1;
1301 * Assemble pcrs joblist from exports map
1303 for (m = exports->first; m != NULL; m = m->next)
1305 if (*m->name == '$')
1308 * First character of name is '$', so remove this flag
1309 * character and allow backreferences ($1 etc) in the
1310 * "replace with" text.
1312 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1318 * Treat the "replace with" text as a literal string -
1319 * no quoting needed, no backreferences allowed.
1320 * ("Trivial" ['T'] flag).
1324 /* Enclose name in @@ */
1325 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1329 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1331 /* Make and run job. */
1332 job = pcrs_compile(buf, m->value, flags, &error);
1335 if (error == PCRS_ERR_NOMEM)
1338 *template_ptr = NULL;
1339 return JB_ERR_MEMORY;
1343 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1344 /* Hope it wasn't important and silently ignore the invalid job */
1349 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1352 if (NULL == tmp_out_buffer)
1354 *template_ptr = NULL;
1355 return JB_ERR_MEMORY;
1357 file_buffer = tmp_out_buffer;
1364 *template_ptr = file_buffer;
1369 /*********************************************************************
1371 * Function : template_fill_for_cgi
1373 * Description : CGI support function that loads a HTML template
1374 * and fills it in. Handles file-not-found errors
1375 * by sending a HTML error message. For convenience,
1376 * this function also frees the passed "exports" map.
1379 * 1 : csp = Client state
1380 * 2 : templatename = name of the HTML template to be used
1381 * 3 : exports = map with fill in symbol -> name pairs.
1382 * Will be freed by this function.
1384 * Returns : JB_ERR_OK on success
1385 * JB_ERR_MEMORY on out-of-memory error
1387 *********************************************************************/
1388 jb_err template_fill_for_cgi(struct client_state *csp,
1389 const char *templatename,
1390 struct map *exports,
1391 struct http_response *rsp)
1396 assert(templatename);
1400 err = template_load(csp, &rsp->body, templatename);
1401 if (err == JB_ERR_FILE)
1404 return cgi_error_no_template(csp, rsp, templatename);
1409 return err; /* JB_ERR_MEMORY */
1411 err = template_fill(&rsp->body, exports);
1417 /*********************************************************************
1419 * Function : default_exports
1421 * Description : returns a struct map list that contains exports
1422 * which are common to all CGI functions.
1425 * 1 : csp = Current client state (buffers, headers, etc...)
1426 * 2 : caller = name of CGI who calls us and which should
1427 * be excluded from the generated menu. May be
1429 * Returns : NULL if no memory, else a new map. Caller frees.
1431 *********************************************************************/
1432 struct map *default_exports(const struct client_state *csp, const char *caller)
1436 struct map * exports;
1437 int local_help_exists = 0;
1441 exports = new_map();
1442 if (exports == NULL)
1447 err = map(exports, "version", 1, html_encode(VERSION), 0);
1448 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1449 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1450 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1451 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1452 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1453 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1454 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1456 snprintf(buf, 20, "%d", csp->config->hport);
1457 if (!err) err = map(exports, "my-port", 1, buf, 1);
1459 if(!strcmp(CODE_STATUS, "stable"))
1461 if (!err) err = map_block_killer(exports, "unstable");
1464 if (csp->config->admin_address != NULL)
1466 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1467 local_help_exists = 1;
1471 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1474 if (csp->config->proxy_info_url != NULL)
1476 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1477 local_help_exists = 1;
1481 if (!err) err = map_block_killer(exports, "have-proxy-info");
1484 if (local_help_exists == 0)
1486 if (!err) err = map_block_killer(exports, "have-help-info");
1499 /*********************************************************************
1501 * Function : map_block_killer
1503 * Description : Convenience function.
1504 * Adds a "killer" for the conditional HTML-template
1505 * block <name>, i.e. a substitution of the regex
1506 * "if-<name>-start.*if-<name>-end" to the given
1510 * 1 : exports = map to extend
1511 * 2 : name = name of conditional block
1513 * Returns : JB_ERR_OK on success
1514 * JB_ERR_MEMORY on out-of-memory error.
1516 *********************************************************************/
1517 jb_err map_block_killer(struct map *exports, const char *name)
1519 char buf[1000]; /* Will do, since the names are hardwired */
1523 assert(strlen(name) < 490);
1525 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1526 return map(exports, buf, 1, "", 1);
1530 /*********************************************************************
1532 * Function : map_block_keep
1534 * Description : Convenience function. Removes the markers used
1535 * by map-block-killer, to save a few bytes.
1536 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1539 * 1 : exports = map to extend
1540 * 2 : name = name of conditional block
1542 * Returns : JB_ERR_OK on success
1543 * JB_ERR_MEMORY on out-of-memory error.
1545 *********************************************************************/
1546 jb_err map_block_keep(struct map *exports, const char *name)
1549 char buf[500]; /* Will do, since the names are hardwired */
1553 assert(strlen(name) < 490);
1555 snprintf(buf, 500, "if-%s-start", name);
1556 err = map(exports, buf, 1, "", 1);
1563 snprintf(buf, 500, "if-%s-end", name);
1564 return map(exports, buf, 1, "", 1);
1568 /*********************************************************************
1570 * Function : map_conditional
1572 * Description : Convenience function.
1573 * Adds an "if-then-else" for the conditional HTML-template
1574 * block <name>, i.e. a substitution of the form:
1581 * The control structure and one of the alternatives
1585 * 1 : exports = map to extend
1586 * 2 : name = name of conditional block
1587 * 3 : choose_first = nonzero for first, zero for second.
1589 * Returns : JB_ERR_OK on success
1590 * JB_ERR_MEMORY on out-of-memory error.
1592 *********************************************************************/
1593 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1595 char buf[1000]; /* Will do, since the names are hardwired */
1600 assert(strlen(name) < 480);
1602 snprintf(buf, 1000, (choose_first
1603 ? "else-not-%s@.*@endif-%s"
1604 : "if-%s-then@.*@else-not-%s"),
1607 err = map(exports, buf, 1, "", 1);
1613 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1614 return map(exports, buf, 1, "", 1);
1618 /*********************************************************************
1620 * Function : make_menu
1622 * Description : Returns an HTML-formatted menu of the available
1623 * unhidden CGIs, excluding the one given in <self>.
1625 * Parameters : self = name of CGI to leave out, can be NULL
1627 * Returns : menu string, or NULL on out-of-memory error.
1629 *********************************************************************/
1630 char *make_menu(const char *self)
1632 const struct cgi_dispatcher *d;
1633 char *result = strdup("");
1637 self = "NO-SUCH-CGI!";
1640 /* List available unhidden CGI's and export as "other-cgis" */
1641 for (d = cgi_dispatchers; d->name; d++)
1643 if (d->description && strcmp(d->name, self))
1645 string_append(&result, "<li><a href=\"" CGI_PREFIX);
1646 string_append(&result, d->name);
1647 string_append(&result, "\">");
1648 string_append(&result, d->description);
1649 string_append(&result, "</a></li>\n");
1657 /*********************************************************************
1659 * Function : dump_map
1661 * Description : HTML-dump a map for debugging
1664 * 1 : the_map = map to dump
1666 * Returns : string with HTML
1668 *********************************************************************/
1669 char *dump_map(const struct map *the_map)
1671 struct map_entry *cur_entry;
1672 char *ret = strdup("");
1674 string_append(&ret, "<table>\n");
1676 for (cur_entry = the_map->first;
1677 (cur_entry != NULL) && (ret != NULL);
1678 cur_entry = cur_entry->next)
1680 string_append(&ret, "<tr><td><b>");
1681 string_join (&ret, html_encode(cur_entry->name));
1682 string_append(&ret, "</b></td><td>");
1683 string_join (&ret, html_encode(cur_entry->value));
1684 string_append(&ret, "</td></tr>\n");
1687 string_append(&ret, "</table>\n");