1 const char cgi_rcs[] = "$Id: cgi.c,v 1.68 2002/05/12 21:36:29 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 * Privoxy team. http://www.privoxy.org/
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.68 2002/05/12 21:36:29 jongfoster
42 * Correcting function comments
44 * Revision 1.67 2002/04/30 12:02:07 oes
45 * Nit: updated a comment
47 * Revision 1.66 2002/04/26 18:32:57 jongfoster
48 * Fixing a memory leak on error
50 * Revision 1.65 2002/04/26 12:53:51 oes
51 * - New function add_help_link
52 * - default_exports now exports links to the user manual
53 * and a prefix for links into the config chapter
55 * Revision 1.64 2002/04/24 02:17:21 oes
56 * - Better descriptions for CGIs
57 * - Hide edit-actions, more shortcuts
58 * - Moved get_char_param, get_string_param and get_number_param here
61 * Revision 1.63 2002/04/15 19:06:43 jongfoster
64 * Revision 1.62 2002/04/10 19:59:46 jongfoster
65 * Fixes to #include in templates:
66 * - Didn't close main file if loading an included template fails.
67 * - I'm paranoid and want to disallow "#include /etc/passwd".
69 * Revision 1.61 2002/04/10 13:37:48 oes
70 * Made templates modular: template_load now recursive with max depth 1
72 * Revision 1.60 2002/04/08 20:50:25 swa
75 * Revision 1.59 2002/04/05 15:51:51 oes
76 * - added send-stylesheet CGI
77 * - bugfix: error-pages now get correct request protocol
79 * - kludged CGI descriptions and menu not to break JS syntax
81 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
82 * Fix Mac OSX compiler warnings
84 * Revision 1.57 2002/03/26 22:29:54 swa
85 * we have a new homepage!
87 * Revision 1.56 2002/03/24 17:50:46 jongfoster
88 * Fixing compile error if actions file editor disabled
90 * Revision 1.55 2002/03/24 16:55:06 oes
91 * Making GIF checkerboard transparent
93 * Revision 1.54 2002/03/24 16:18:15 jongfoster
96 * Revision 1.53 2002/03/24 16:06:00 oes
97 * Correct transparency for checkerboard PNG. Thanks, Magnus!
99 * Revision 1.52 2002/03/24 15:23:33 jongfoster
102 * Revision 1.51 2002/03/24 13:25:43 swa
103 * name change related issues
105 * Revision 1.50 2002/03/16 23:54:06 jongfoster
106 * Adding graceful termination feature, to help look for memory leaks.
107 * If you enable this (which, by design, has to be done by hand
108 * editing config.h) and then go to http://i.j.b/die, then the program
109 * will exit cleanly after the *next* request. It should free all the
110 * memory that was used.
112 * Revision 1.49 2002/03/13 00:27:04 jongfoster
115 * Revision 1.48 2002/03/08 17:47:07 jongfoster
118 * Revision 1.47 2002/03/08 16:41:33 oes
119 * Added GIF images again
121 * Revision 1.46 2002/03/07 03:48:38 oes
122 * - Changed built-in images from GIF to PNG
123 * (with regard to Unisys patent issue)
124 * - Added a 4x4 pattern PNG which is less intrusive
125 * than the logo but also clearly marks the deleted banners
127 * Revision 1.45 2002/03/06 22:54:35 jongfoster
128 * Automated function-comment nitpicking.
130 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
131 * - Better error reporting on OS/2
132 * - Fix double-slash comment (oops)
134 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
135 * - Re-enable OS/2 building after new parms were added
136 * - Fix false out of memory report when resolving CGI templates when no IP
137 * address is available of failed attempt (a la no such domain)
139 * Revision 1.42 2002/01/21 00:33:20 jongfoster
140 * Replacing strsav() with the safer string_append() or string_join().
141 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
142 * Adding missing html_encode() to error message generators.
143 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
145 * Revision 1.41 2002/01/17 20:56:22 jongfoster
146 * Replacing hard references to the URL of the config interface
147 * with #defines from project.h
149 * Revision 1.40 2002/01/09 14:26:46 oes
150 * Added support for thread-safe gmtime_r call.
152 * Revision 1.39 2001/11/16 00:48:13 jongfoster
153 * Fixing a compiler warning
155 * Revision 1.38 2001/11/13 00:31:21 jongfoster
156 * - Adding new CGIs for use by non-JavaScript browsers:
157 * edit-actions-url-form
158 * edit-actions-add-url-form
159 * edit-actions-remove-url-form
160 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
163 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
164 * Show enablement/disablement status in almost all templates.
165 * There is a little trickiness here: apparent recursive resolution of
166 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
167 * the actual enablement status. So a similar construct,
168 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
171 * Revision 1.36 2001/10/26 17:33:27 oes
174 * Revision 1.35 2001/10/23 21:48:19 jongfoster
175 * Cleaning up error handling in CGI functions - they now send back
176 * a HTML error page and should never cause a FATAL error. (Fixes one
177 * potential source of "denial of service" attacks).
179 * CGI actions file editor that works and is actually useful.
181 * Ability to toggle Junkbuster remotely using a CGI call.
183 * You can turn off both the above features in the main configuration
184 * file, e.g. if you are running a multi-user proxy.
186 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
187 * Only show "Local support" on templates conditionally:
188 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
189 * - if not, no Local support section appears
191 * Revision 1.33 2001/10/14 22:28:41 jongfoster
192 * Fixing stupid typo.
194 * Revision 1.32 2001/10/14 22:20:18 jongfoster
195 * - Changes to CGI dispatching method to match CGI names exactly,
196 * rather than doing a prefix match.
197 * - No longer need to count the length of the CGI handler names by hand.
198 * - Adding new handler for 404 error when disptching a CGI, if none of
199 * the handlers match.
200 * - Adding new handlers for CGI actionsfile editor.
202 * Revision 1.31 2001/10/10 10:56:39 oes
203 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
205 * Revision 1.30 2001/10/02 15:30:57 oes
206 * Introduced show-request cgi
208 * Revision 1.29 2001/09/20 15:47:44 steudten
210 * Fix BUG: Modify int size to size_t size in fill_template()
211 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
213 * Revision 1.28 2001/09/19 18:00:37 oes
214 * - Deletef time() FIXME (Can't fail under Linux either, if
215 * the argument is guaranteed to be in out address space,
218 * - Pointer notation cosmetics
219 * - Fixed a minor bug in template_fill(): Failiure of
220 * pcrs_execute() now secure.
222 * Revision 1.27 2001/09/16 17:08:54 jongfoster
223 * Moving simple CGI functions from cgi.c to new file cgisimple.c
225 * Revision 1.26 2001/09/16 15:47:37 jongfoster
226 * First version of CGI-based edit interface. This is very much a
227 * work-in-progress, and you can't actually use it to edit anything
228 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
229 * to have any effect.
231 * Revision 1.25 2001/09/16 15:02:35 jongfoster
232 * Adding i.j.b/robots.txt.
233 * Inlining add_stats() since it's only ever called from one place.
235 * Revision 1.24 2001/09/16 11:38:01 jongfoster
236 * Splitting fill_template() into 2 functions:
237 * template_load() loads the file
238 * template_fill() performs the PCRS regexps.
239 * This is because the CGI edit interface has a "table row"
240 * template which is used many times in the page - this
241 * change means it's only loaded from disk once.
243 * Revision 1.23 2001/09/16 11:16:05 jongfoster
244 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
246 * Revision 1.22 2001/09/16 11:00:10 jongfoster
247 * New function alloc_http_response, for symmetry with free_http_response
249 * Revision 1.21 2001/09/13 23:53:03 jongfoster
250 * Support for both static and dynamically generated CGI pages.
251 * Correctly setting Last-Modified: and Expires: HTTP headers.
253 * Revision 1.20 2001/09/13 23:40:36 jongfoster
254 * (Cosmetic only) Indentation correction
256 * Revision 1.19 2001/09/13 23:31:25 jongfoster
257 * Moving image data to cgi.c rather than cgi.h.
259 * Revision 1.18 2001/08/05 16:06:20 jongfoster
260 * Modifiying "struct map" so that there are now separate header and
261 * "map_entry" structures. This means that functions which modify a
262 * map no longer need to return a pointer to the modified map.
263 * Also, it no longer reverses the order of the entries (which may be
264 * important with some advanced template substitutions).
266 * Revision 1.17 2001/08/05 15:57:38 oes
267 * Adapted finish_http_response to new list_to_text
269 * Revision 1.16 2001/08/01 21:33:18 jongfoster
270 * Changes to fill_template() that reduce memory usage without having
271 * an impact on performance. I also renamed some variables so as not
272 * to clash with the C++ keywords "new" and "template".
274 * Revision 1.15 2001/08/01 21:19:22 jongfoster
275 * Moving file version information to a separate CGI page.
277 * Revision 1.14 2001/08/01 00:19:03 jongfoster
278 * New function: map_conditional() for an if-then-else syntax.
279 * Changing to use new version of show_defines()
281 * Revision 1.13 2001/07/30 22:08:36 jongfoster
282 * Tidying up #defines:
283 * - All feature #defines are now of the form FEATURE_xxx
284 * - Permanently turned off WIN_GUI_EDIT
285 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
287 * Revision 1.12 2001/07/29 18:47:05 jongfoster
288 * Adding missing #include "loadcfg.h"
290 * Revision 1.11 2001/07/18 17:24:37 oes
291 * Changed to conform to new pcrs interface
293 * Revision 1.10 2001/07/13 13:53:13 oes
294 * Removed all #ifdef PCRS and related code
296 * Revision 1.9 2001/06/29 21:45:41 oes
297 * Indentation, CRLF->LF, Tab-> Space
299 * Revision 1.8 2001/06/29 13:21:46 oes
300 * - Cosmetics: renamed and reordered functions, variables,
301 * texts, improved comments etc
303 * - Removed ij_untrusted_url() The relevant
304 * info is now part of the "untrusted" page,
305 * which is generated by filters.c:trust_url()
307 * - Generators of content now call finish_http_response()
308 * themselves, making jcc.c:chat() a little less
311 * - Removed obsolete "Pragma: no-cache" from our headers
313 * - http_responses now know their head length
315 * - fill_template now uses the new interface to pcrs, so that
316 * - long jobs (like whole files) no longer have to be assembled
317 * in a fixed size buffer
318 * - the new T (trivial) option is used, and the replacement may
319 * contain Perl syntax backrefs without confusing pcrs
321 * - Introduced default_exports() which generates a set of exports
322 * common to all CGIs and other content generators
324 * - Introduced convenience function map_block_killer()
326 * - Introduced convenience function make_menu()
328 * - Introduced CGI-like function error_response() which generates
329 * the "No such domain" and "Connect failed" messages using the
332 * - cgi_show_url_info:
333 * - adapted to new CGI features
334 * - form and answers now generated from same template
335 * - http:// prefix in URL now OK
338 * - adapted to new CGI features
339 * - no longer uses csp->init_proxy_args
342 * - moved menu generation to make_menu()
344 * - add_stats now writes single export map entries instead
347 * - Moved redirect_url() to filters.c
349 * - Fixed mem leak in free_http_response(), map_block_killer(),
351 * - Removed logentry from cancelled commit
353 * Revision 1.7 2001/06/09 10:51:58 jongfoster
354 * Changing "show URL info" handler to new style.
355 * Changing BUFSIZ ==> BUFFER_SIZE
357 * Revision 1.6 2001/06/07 23:05:19 jongfoster
358 * Removing code related to old forward and ACL files.
360 * Revision 1.5 2001/06/05 19:59:16 jongfoster
361 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
363 * Revision 1.4 2001/06/04 10:41:52 swa
364 * show version string of cgi.h and cgi.c
366 * Revision 1.3 2001/06/03 19:12:16 oes
367 * introduced new cgi handling
369 * No revisions before 1.3
371 **********************************************************************/
377 #include <sys/types.h>
385 #define snprintf _snprintf
386 #endif /* def _WIN32 */
394 #include "miscutil.h"
395 #include "cgisimple.h"
396 #ifdef FEATURE_CGI_EDIT_ACTIONS
398 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
400 /* loadcfg.h is for g_bToggleIJB only */
402 const char cgi_h_rcs[] = CGI_H_VERSION;
405 * List of CGI functions: name, handler, description
406 * Note: Do NOT use single quotes in the description;
407 * this will break the dynamic "blocked" template!
409 static const struct cgi_dispatcher cgi_dispatchers[] = {
412 "Privoxy main page" },
413 #ifdef FEATURE_GRACEFUL_TERMINATION
416 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
417 "this is a one click Denial Of Service attack!!!</em>" },
421 "View & change the current configuration" },
424 "View the source code version numbers" },
427 "View the request headers." },
430 "Look up which actions apply to a URL and why" },
431 #ifdef FEATURE_CGI_EDIT_ACTIONS
434 "Toggle Privoxy on or off" },
436 { "edit-actions", /* Edit the actions list */
439 { "eaa", /* Shortcut for edit-actions-add-url-form */
440 cgi_edit_actions_add_url_form,
442 { "eau", /* Shortcut for edit-actions-url-form */
443 cgi_edit_actions_url_form,
445 { "ear", /* Shortcut for edit-actions-remove-url-form */
446 cgi_edit_actions_remove_url_form,
448 { "eafu", /* Shortcut for edit-actions-for-url */
449 cgi_edit_actions_for_url,
451 { "eas", /* Shortcut for edit-actions-submit */
452 cgi_edit_actions_submit,
454 { "easa", /* Shortcut for edit-actions-section-add */
455 cgi_edit_actions_section_add,
457 { "easr", /* Shortcut for edit-actions-section-remove */
458 cgi_edit_actions_section_remove,
460 { "eass", /* Shortcut for edit-actions-section-swap */
461 cgi_edit_actions_section_swap,
463 { "edit-actions-for-url",
464 cgi_edit_actions_for_url,
465 NULL /* Edit the actions for (a) specified URL(s) */ },
466 { "edit-actions-list",
467 cgi_edit_actions_list,
468 NULL /* Edit the actions list */ },
469 { "edit-actions-submit",
470 cgi_edit_actions_submit,
471 NULL /* Change the actions for (a) specified URL(s) */ },
472 { "edit-actions-url",
473 cgi_edit_actions_url,
474 NULL /* Change a URL pattern in the actionsfile */ },
475 { "edit-actions-url-form",
476 cgi_edit_actions_url_form,
477 NULL /* Form to change a URL pattern in the actionsfile */ },
478 { "edit-actions-add-url",
479 cgi_edit_actions_add_url,
480 NULL /* Add a URL pattern to the actionsfile */ },
481 { "edit-actions-add-url-form",
482 cgi_edit_actions_add_url_form,
483 NULL /* Form to add a URL pattern to the actionsfile */ },
484 { "edit-actions-remove-url",
485 cgi_edit_actions_remove_url,
486 NULL /* Remove a URL pattern from the actionsfile */ },
487 { "edit-actions-remove-url-form",
488 cgi_edit_actions_remove_url_form,
489 NULL /* Form to remove a URL pattern from the actionsfile */ },
490 { "edit-actions-section-add",
491 cgi_edit_actions_section_add,
492 NULL /* Remove a section from the actionsfile */ },
493 { "edit-actions-section-remove",
494 cgi_edit_actions_section_remove,
495 NULL /* Remove a section from the actionsfile */ },
496 { "edit-actions-section-swap",
497 cgi_edit_actions_section_swap,
498 NULL /* Swap two sections in the actionsfile */ },
499 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
502 NULL /* Sends a robots.txt file to tell robots to go away. */ },
505 NULL /* Send a built-in image */ },
508 NULL /* Send templates/cgi-style.css */ },
510 cgi_transparent_image,
511 NULL /* Send a transparent image (short name) */ },
512 { NULL, /* NULL Indicates end of list and default page */
514 NULL /* Unknown CGI page */ }
519 * Bulit-in images for ad replacement
521 * Hint: You can encode your own images like this:
522 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
525 #ifdef FEATURE_NO_GIFS
528 * Checkerboard pattern, as a PNG.
530 const char image_pattern_data[] =
531 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
532 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
533 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
534 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
535 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
536 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
537 "\000\000\000\111\105\116\104\256\102\140\202";
540 * 1x1 transparant PNG.
542 const char image_blank_data[] =
543 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
544 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
545 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
546 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
547 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
548 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
549 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
550 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
551 "\000\000\000\000\111\105\116\104\256\102\140\202";
555 * Checkerboard pattern, as a GIF.
557 const char image_pattern_data[] =
558 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
559 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
560 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
561 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
565 * 1x1 transparant GIF.
567 const char image_blank_data[] =
568 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
569 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
570 "\000\001\000\000\002\002D\001\000;";
573 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
574 const size_t image_blank_length = sizeof(image_blank_data) - 1;
577 static struct http_response cgi_error_memory_response[1];
579 static struct http_response *dispatch_known_cgi(struct client_state * csp,
581 static struct map *parse_cgi_parameters(char *argstring);
584 /*********************************************************************
586 * Function : dispatch_cgi
588 * Description : Checks if a request URL has either the magical
589 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
590 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
591 * http://config.privoxy.org/). If so, it passes
592 * the (rest of the) path onto dispatch_known_cgi, which
593 * calls the relevant CGI handler function.
596 * 1 : csp = Current client state (buffers, headers, etc...)
598 * Returns : http_response if match, NULL if nonmatch or handler fail
600 *********************************************************************/
601 struct http_response *dispatch_cgi(struct client_state *csp)
603 const char *host = csp->http->host;
604 const char *path = csp->http->path;
607 * Should we intercept ?
610 /* Note: "example.com" and "example.com." are equivalent hostnames. */
612 /* Either the host matches CGI_SITE_1_HOST ..*/
613 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
614 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
615 && (path[0] == '/') )
617 /* ..then the path will all be for us. Remove leading '/' */
620 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
621 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
622 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
623 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
625 /* take everything following CGI_SITE_2_PATH */
626 path += strlen(CGI_SITE_2_PATH);
629 /* skip the forward slash after CGI_SITE_2_PATH */
632 else if (*path != '\0')
635 * wierdness: URL is /configXXX, where XXX is some string
636 * Do *NOT* intercept.
648 * This is a CGI call.
651 return dispatch_known_cgi(csp, path);
655 /*********************************************************************
657 * Function : dispatch_known_cgi
659 * Description : Processes a CGI once dispatch_cgi has determined that
660 * it matches one of the magic prefixes. Parses the path
661 * as a cgi name plus query string, prepares a map that
662 * maps CGI parameter names to their values, initializes
663 * the http_response struct, and calls the relevant CGI
667 * 1 : csp = Current client state (buffers, headers, etc...)
668 * 2 : path = Path of CGI, with the CGI prefix removed.
669 * Should not have a leading "/".
671 * Returns : http_response, or NULL on handler failure or out of
674 *********************************************************************/
675 static struct http_response *dispatch_known_cgi(struct client_state * csp,
678 const struct cgi_dispatcher *d;
679 struct map *param_list;
680 struct http_response *rsp;
681 char *query_args_start;
685 if (NULL == (path_copy = strdup(path)))
687 return cgi_error_memory();
690 query_args_start = path_copy;
691 while (*query_args_start && *query_args_start != '?')
695 if (*query_args_start == '?')
697 *query_args_start++ = '\0';
700 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
703 return cgi_error_memory();
709 * path_copy = CGI call name
710 * param_list = CGI params, as map
713 /* Get mem for response or fail*/
714 if (NULL == (rsp = alloc_http_response()))
717 free_map(param_list);
718 return cgi_error_memory();
721 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
722 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
723 csp->ip_addr_str, csp->http->cmd);
725 /* Find and start the right CGI function*/
729 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
731 err = (d->handler)(csp, rsp, param_list);
733 free_map(param_list);
734 if (err == JB_ERR_CGI_PARAMS)
736 err = cgi_error_bad_param(csp, rsp);
741 return finish_http_response(rsp);
745 /* Error in handler, probably out-of-memory */
746 free_http_response(rsp);
747 return cgi_error_memory();
755 /*********************************************************************
757 * Function : parse_cgi_parameters
759 * Description : Parse a URL-encoded argument string into name/value
760 * pairs and store them in a struct map list.
763 * 1 : argstring = string to be parsed. Will be trashed.
765 * Returns : pointer to param list, or NULL if out of memory.
767 *********************************************************************/
768 static struct map *parse_cgi_parameters(char *argstring)
771 char *vector[BUFFER_SIZE];
773 struct map *cgi_params;
775 if (NULL == (cgi_params = new_map()))
780 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
782 for (i = 0; i < pairs; i++)
784 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
787 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
789 free_map(cgi_params);
800 /*********************************************************************
802 * Function : get_char_param
804 * Description : Get a single-character parameter passed to a CGI
808 * 1 : parameters = map of cgi parameters
809 * 2 : param_name = The name of the parameter to read
811 * Returns : Uppercase character on success, '\0' on error.
813 *********************************************************************/
814 char get_char_param(const struct map *parameters,
815 const char *param_name)
822 ch = *(lookup(parameters, param_name));
823 if ((ch >= 'a') && (ch <= 'z'))
832 /*********************************************************************
834 * Function : get_string_param
836 * Description : Get a string paramater, to be used as an
837 * ACTION_STRING or ACTION_MULTI paramater.
838 * Validates the input to prevent stupid/malicious
839 * users from corrupting their action file.
842 * 1 : parameters = map of cgi parameters
843 * 2 : param_name = The name of the parameter to read
844 * 3 : pparam = destination for paramater. Allocated as
845 * part of the map "parameters", so don't free it.
846 * Set to NULL if not specified.
848 * Returns : JB_ERR_OK on success, or if the paramater
850 * JB_ERR_MEMORY on out-of-memory.
851 * JB_ERR_CGI_PARAMS if the paramater is not valid.
853 *********************************************************************/
854 jb_err get_string_param(const struct map *parameters,
855 const char *param_name,
868 param = lookup(parameters, param_name);
874 if (strlen(param) >= CGI_PARAM_LEN_MAX)
879 * Note that the length limit is arbitrary, it just seems
880 * sensible to limit it to *something*. There's no
881 * technical reason for any limit at all.
883 return JB_ERR_CGI_PARAMS;
886 /* Check every character to see if it's legal */
888 while ((ch = *s++) != '\0')
890 if ( ((unsigned char)ch < (unsigned char)' ')
893 /* Probable hack attempt, or user accidentally used '}'. */
894 return JB_ERR_CGI_PARAMS;
905 /*********************************************************************
907 * Function : get_number_param
909 * Description : Get a non-negative integer from the parameters
910 * passed to a CGI function.
913 * 1 : csp = Current client state (buffers, headers, etc...)
914 * 2 : parameters = map of cgi parameters
915 * 3 : name = Name of CGI parameter to read
916 * 4 : pvalue = destination for value.
917 * Set to -1 on error.
919 * Returns : JB_ERR_OK on success
920 * JB_ERR_MEMORY on out-of-memory
921 * JB_ERR_CGI_PARAMS if the parameter was not specified
924 *********************************************************************/
925 jb_err get_number_param(struct client_state *csp,
926 const struct map *parameters,
941 param = lookup(parameters, name);
944 return JB_ERR_CGI_PARAMS;
947 /* We don't use atoi because I want to check this carefully... */
950 while ((ch = *param++) != '\0')
952 if ((ch < '0') || (ch > '9'))
954 return JB_ERR_CGI_PARAMS;
961 * <limits.h> defines UINT_MAX
963 * (UINT_MAX - ch) / 10 is the largest number that
964 * can be safely multiplied by 10 then have ch added.
966 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
968 return JB_ERR_CGI_PARAMS;
971 value = value * 10 + ch;
982 /*********************************************************************
984 * Function : error_response
986 * Description : returns an http_response that explains the reason
987 * why a request failed.
990 * 1 : csp = Current client state (buffers, headers, etc...)
991 * 2 : templatename = Which template should be used for the answer
992 * 3 : sys_err = system error number
994 * Returns : A http_response. If we run out of memory, this
995 * will be cgi_error_memory().
997 *********************************************************************/
998 struct http_response *error_response(struct client_state *csp,
999 const char *templatename,
1003 struct http_response *rsp;
1004 struct map * exports = default_exports(csp, NULL);
1005 if (exports == NULL)
1007 return cgi_error_memory();
1010 if (NULL == (rsp = alloc_http_response()))
1013 return cgi_error_memory();
1016 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1017 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1018 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1019 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1020 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1023 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1026 /* Some failures, like "404 no such domain", don't have an IP address. */
1027 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1035 free_http_response(rsp);
1036 return cgi_error_memory();
1039 if (!strcmp(templatename, "no-such-domain"))
1041 rsp->status = strdup("404 No such domain");
1042 if (rsp->status == NULL)
1045 free_http_response(rsp);
1046 return cgi_error_memory();
1049 else if (!strcmp(templatename, "connect-failed"))
1051 rsp->status = strdup("503 Connect failed");
1052 if (rsp->status == NULL)
1055 free_http_response(rsp);
1056 return cgi_error_memory();
1060 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1063 free_http_response(rsp);
1064 return cgi_error_memory();
1067 return finish_http_response(rsp);
1071 /*********************************************************************
1073 * Function : cgi_init_error_messages
1075 * Description : Call at the start of the program to initialize
1076 * the error message used by cgi_error_memory().
1082 *********************************************************************/
1083 void cgi_init_error_messages(void)
1085 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1086 cgi_error_memory_response->head =
1087 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1088 "Content-Type: text/html\r\n"
1090 cgi_error_memory_response->body =
1092 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1094 "<h1>500 Internal Privoxy Error</h1>\r\n"
1095 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1096 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1100 cgi_error_memory_response->head_length =
1101 strlen(cgi_error_memory_response->head);
1102 cgi_error_memory_response->content_length =
1103 strlen(cgi_error_memory_response->body);
1107 /*********************************************************************
1109 * Function : cgi_error_memory
1111 * Description : Called if a CGI function runs out of memory.
1112 * Returns a statically-allocated error response.
1116 * Returns : http_response data structure for output. This is
1117 * statically allocated, for obvious reasons.
1119 *********************************************************************/
1120 struct http_response *cgi_error_memory(void)
1122 /* assert that it's been initialized. */
1123 assert(cgi_error_memory_response->head);
1125 return cgi_error_memory_response;
1129 /*********************************************************************
1131 * Function : cgi_error_no_template
1133 * Description : Almost-CGI function that is called if a templae
1134 * cannot be loaded. Note this is not a true CGI,
1135 * it takes a template name rather than a map of
1139 * 1 : csp = Current client state (buffers, headers, etc...)
1140 * 2 : rsp = http_response data structure for output
1141 * 3 : template_name = Name of template that could not
1144 * Returns : JB_ERR_OK on success
1145 * JB_ERR_MEMORY on out-of-memory error.
1147 *********************************************************************/
1148 jb_err cgi_error_no_template(struct client_state *csp,
1149 struct http_response *rsp,
1150 const char *template_name)
1152 static const char status[] =
1153 "500 Internal Privoxy Error";
1154 static const char body_prefix[] =
1156 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1158 "<h1>500 Internal Privoxy Error</h1>\r\n"
1159 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1160 "<p><b>Could not load template file <code>";
1161 static const char body_suffix[] =
1162 "</code> or one of it's included components.</b></p>\r\n"
1163 "<p>Please contact your proxy administrator.</p>\r\n"
1164 "<p>If you are the proxy administrator, please put the required file(s)"
1165 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1166 "location of the <code><i>(confdir)</i></code> directory "
1167 "is specified in the main Privoxy <code>config</code> "
1168 "file. (It's typically the Privoxy install directory"
1170 ", or <code>/etc/privoxy/</code>"
1171 #endif /* ndef _WIN32 */
1178 assert(template_name);
1180 /* Reset rsp, if needed */
1184 rsp->content_length = 0;
1185 rsp->head_length = 0;
1188 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1189 if (rsp->body == NULL)
1191 return JB_ERR_MEMORY;
1193 strcpy(rsp->body, body_prefix);
1194 strcat(rsp->body, template_name);
1195 strcat(rsp->body, body_suffix);
1197 rsp->status = strdup(status);
1198 if (rsp->body == NULL)
1200 return JB_ERR_MEMORY;
1207 /*********************************************************************
1209 * Function : cgi_error_bad_param
1211 * Description : CGI function that is called if the parameters
1212 * (query string) for a CGI were wrong.
1215 * 1 : csp = Current client state (buffers, headers, etc...)
1216 * 2 : rsp = http_response data structure for output
1218 * CGI Parameters : none
1220 * Returns : JB_ERR_OK on success
1221 * JB_ERR_MEMORY on out-of-memory error.
1223 *********************************************************************/
1224 jb_err cgi_error_bad_param(struct client_state *csp,
1225 struct http_response *rsp)
1227 struct map *exports;
1232 if (NULL == (exports = default_exports(csp, NULL)))
1234 return JB_ERR_MEMORY;
1237 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1241 /*********************************************************************
1243 * Function : add_help_link
1245 * Description : Produce a copy of the string given as item,
1246 * embedded in an HTML link to its corresponding
1247 * section (item name in uppercase) in the actions
1248 * chapter of the user manual, (whose URL is given in
1249 * the config and defaults to our web site).
1251 * FIXME: I currently only work for actions, and would
1252 * like to be generalized for other topics.
1255 * 1 : item = item (will NOT be free()d.)
1256 * It is assumed to be HTML-safe.
1257 * 2 : config = The current configuration.
1259 * Returns : String with item embedded in link, or NULL on
1262 *********************************************************************/
1263 char *add_help_link(const char *item,
1264 struct configuration_spec *config)
1268 if (!item) return NULL;
1270 result = strdup("<a href=\"");
1271 string_append(&result, config->usermanual);
1272 string_append(&result, ACTIONS_HELP_PREFIX);
1273 string_join (&result, string_toupper(item));
1274 string_append(&result, "\">");
1275 string_append(&result, item);
1276 string_append(&result, "</a> ");
1282 /*********************************************************************
1284 * Function : get_http_time
1286 * Description : Get the time in a format suitable for use in a
1287 * HTTP header - e.g.:
1288 * "Sun, 06 Nov 1994 08:49:37 GMT"
1291 * 1 : time_offset = Time returned will be current time
1292 * plus this number of seconds.
1293 * 2 : buf = Destination for result. Must be long enough
1294 * to hold 29 characters plus a trailing zero.
1298 *********************************************************************/
1299 void get_http_time(int time_offset, char *buf)
1301 static const char day_names[7][4] =
1302 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1303 static const char month_names[12][4] =
1304 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1305 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1308 time_t current_time;
1312 time(¤t_time); /* get current time */
1314 current_time += time_offset;
1316 /* get and save the gmt */
1318 #ifdef HAVE_GMTIME_R
1320 t = gmtime_r(¤t_time, &dummy);
1322 t = gmtime(¤t_time);
1326 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1328 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1329 day_names[t->tm_wday],
1331 month_names[t->tm_mon],
1341 /*********************************************************************
1343 * Function : finish_http_response
1345 * Description : Fill in the missing headers in an http response,
1346 * and flatten the headers to an http head.
1349 * 1 : rsp = pointer to http_response to be processed
1351 * Returns : A http_response, usually the rsp parameter.
1352 * On error, free()s rsp and returns cgi_error_memory()
1354 *********************************************************************/
1355 struct http_response *finish_http_response(struct http_response *rsp)
1357 char buf[BUFFER_SIZE];
1360 /* Special case - do NOT change this statically allocated response,
1361 * which is ready for output anyway.
1363 if (rsp == cgi_error_memory_response)
1369 * Fill in the HTTP Status
1371 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1372 err = enlist_first(rsp->headers, buf);
1375 * Set the Content-Length
1377 if (rsp->content_length == 0)
1379 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1383 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1384 err = enlist(rsp->headers, buf);
1388 * Fill in the default headers:
1390 * Content-Type: default to text/html if not already specified.
1391 * Date: set to current date/time.
1392 * Last-Modified: set to date/time the page was last changed.
1393 * Expires: set to date/time page next needs reloading.
1394 * Cache-Control: set to "no-cache" if applicable.
1396 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1398 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1403 * Set Expires to about 10 min into the future so it'll get reloaded
1404 * occasionally, e.g. if Privoxy gets upgraded.
1409 get_http_time(0, buf);
1410 err = enlist_unique_header(rsp->headers, "Date", buf);
1413 /* Some date in the past. */
1414 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1418 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1419 err = enlist_unique_header(rsp->headers, "Expires", buf);
1425 * Compliant browsers should not cache this due to the "Cache-Control"
1426 * setting. However, to be certain, we also set both "Last-Modified"
1427 * and "Expires" to the current time.
1429 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1431 get_http_time(0, buf);
1432 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1433 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1434 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1441 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1443 free_http_response(rsp);
1444 return cgi_error_memory();
1446 rsp->head_length = strlen(rsp->head);
1453 /*********************************************************************
1455 * Function : alloc_http_response
1457 * Description : Allocates a new http_response structure.
1461 * Returns : pointer to a new http_response, or NULL.
1463 *********************************************************************/
1464 struct http_response *alloc_http_response(void)
1466 return (struct http_response *) zalloc(sizeof(struct http_response));
1471 /*********************************************************************
1473 * Function : free_http_response
1475 * Description : Free the memory occupied by an http_response
1476 * and its depandant structures.
1479 * 1 : rsp = pointer to http_response to be freed
1483 *********************************************************************/
1484 void free_http_response(struct http_response *rsp)
1487 * Must special case cgi_error_memory_response, which is never freed.
1489 if (rsp && (rsp != cgi_error_memory_response))
1494 destroy_list(rsp->headers);
1501 /*********************************************************************
1503 * Function : template_load
1505 * Description : CGI support function that loads a given HTML
1506 * template from the confdir, ignoring comment
1507 * lines and following #include statements up to
1511 * 1 : csp = Current client state (buffers, headers, etc...)
1512 * 2 : template_ptr = Destination for pointer to loaded
1514 * 3 : templatename = name of the HTML template to be used
1515 * 4 : recursive = Flag set if this function calls itself
1516 * following an #include statament
1518 * Returns : JB_ERR_OK on success
1519 * JB_ERR_MEMORY on out-of-memory error.
1520 * JB_ERR_FILE if the template file cannot be read
1522 *********************************************************************/
1523 jb_err template_load(struct client_state *csp, char **template_ptr,
1524 const char *templatename, int recursive)
1527 char *templates_dir_path;
1530 char *included_module;
1533 char buf[BUFFER_SIZE];
1536 assert(template_ptr);
1537 assert(templatename);
1539 *template_ptr = NULL;
1541 /* Validate template name. Paranoia. */
1542 for (p = templatename; *p != 0; p++)
1544 if ( ((*p < 'a') || (*p > 'z'))
1545 && ((*p < 'A') || (*p > 'Z'))
1546 && ((*p < '0') || (*p > '9'))
1550 /* Illegal character */
1555 /* Generate full path */
1557 templates_dir_path = make_path(csp->config->confdir, "templates");
1558 if (templates_dir_path == NULL)
1560 return JB_ERR_MEMORY;
1563 full_path = make_path(templates_dir_path, templatename);
1564 free(templates_dir_path);
1565 if (full_path == NULL)
1567 return JB_ERR_MEMORY;
1570 /* Allocate buffer */
1572 file_buffer = strdup("");
1573 if (file_buffer == NULL)
1576 return JB_ERR_MEMORY;
1579 /* Open template file */
1581 if (NULL == (fp = fopen(full_path, "r")))
1583 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1591 * Read the file, ignoring comments, and honoring #include
1592 * statements, unless we're already called recursively.
1594 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1595 * This is unlikely in practise.
1597 while (fgets(buf, BUFFER_SIZE, fp))
1599 if (!recursive && !strncmp(buf, "#include ", 9))
1601 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1608 if (string_join(&file_buffer, included_module))
1611 return JB_ERR_MEMORY;
1617 /* skip lines starting with '#' */
1623 if (string_append(&file_buffer, buf))
1626 return JB_ERR_MEMORY;
1631 *template_ptr = file_buffer;
1637 /*********************************************************************
1639 * Function : template_fill
1641 * Description : CGI support function that fills in a pre-loaded
1642 * HTML template by replacing @name@ with value using
1643 * pcrs, for each item in the output map.
1645 * Note that a leading '$' charachter in the export map's
1646 * values will be stripped and toggle on backreference
1650 * 1 : template_ptr = IN: Template to be filled out.
1652 * OUT: Filled out template.
1653 * Caller must free().
1654 * 2 : exports = map with fill in symbol -> name pairs
1656 * Returns : JB_ERR_OK on success
1657 * JB_ERR_MEMORY on out-of-memory error
1659 *********************************************************************/
1660 jb_err template_fill(char **template_ptr, const struct map *exports)
1662 struct map_entry *m;
1664 char buf[BUFFER_SIZE];
1665 char *tmp_out_buffer;
1671 assert(template_ptr);
1672 assert(*template_ptr);
1675 file_buffer = *template_ptr;
1676 size = strlen(file_buffer) + 1;
1679 * Assemble pcrs joblist from exports map
1681 for (m = exports->first; m != NULL; m = m->next)
1683 if (*m->name == '$')
1686 * First character of name is '$', so remove this flag
1687 * character and allow backreferences ($1 etc) in the
1688 * "replace with" text.
1690 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1696 * Treat the "replace with" text as a literal string -
1697 * no quoting needed, no backreferences allowed.
1698 * ("Trivial" ['T'] flag).
1702 /* Enclose name in @@ */
1703 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1707 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1709 /* Make and run job. */
1710 job = pcrs_compile(buf, m->value, flags, &error);
1713 if (error == PCRS_ERR_NOMEM)
1716 *template_ptr = NULL;
1717 return JB_ERR_MEMORY;
1721 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1722 /* Hope it wasn't important and silently ignore the invalid job */
1727 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1730 if (NULL == tmp_out_buffer)
1732 *template_ptr = NULL;
1733 return JB_ERR_MEMORY;
1735 file_buffer = tmp_out_buffer;
1742 *template_ptr = file_buffer;
1747 /*********************************************************************
1749 * Function : template_fill_for_cgi
1751 * Description : CGI support function that loads a HTML template
1752 * and fills it in. Handles file-not-found errors
1753 * by sending a HTML error message. For convenience,
1754 * this function also frees the passed "exports" map.
1757 * 1 : csp = Client state
1758 * 2 : templatename = name of the HTML template to be used
1759 * 3 : exports = map with fill in symbol -> name pairs.
1760 * Will be freed by this function.
1761 * 4 : rsp = Response structure to fill in.
1763 * Returns : JB_ERR_OK on success
1764 * JB_ERR_MEMORY on out-of-memory error
1766 *********************************************************************/
1767 jb_err template_fill_for_cgi(struct client_state *csp,
1768 const char *templatename,
1769 struct map *exports,
1770 struct http_response *rsp)
1775 assert(templatename);
1779 err = template_load(csp, &rsp->body, templatename, 0);
1780 if (err == JB_ERR_FILE)
1783 return cgi_error_no_template(csp, rsp, templatename);
1788 return err; /* JB_ERR_MEMORY */
1790 err = template_fill(&rsp->body, exports);
1796 /*********************************************************************
1798 * Function : default_exports
1800 * Description : returns a struct map list that contains exports
1801 * which are common to all CGI functions.
1804 * 1 : csp = Current client state (buffers, headers, etc...)
1805 * 2 : caller = name of CGI who calls us and which should
1806 * be excluded from the generated menu. May be
1808 * Returns : NULL if no memory, else a new map. Caller frees.
1810 *********************************************************************/
1811 struct map *default_exports(const struct client_state *csp, const char *caller)
1815 struct map * exports;
1816 int local_help_exists = 0;
1820 exports = new_map();
1821 if (exports == NULL)
1826 err = map(exports, "version", 1, html_encode(VERSION), 0);
1827 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1828 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1829 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1830 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1831 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1832 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1833 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
1834 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
1835 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1837 snprintf(buf, 20, "%d", csp->config->hport);
1838 if (!err) err = map(exports, "my-port", 1, buf, 1);
1840 if(!strcmp(CODE_STATUS, "stable"))
1842 if (!err) err = map_block_killer(exports, "unstable");
1845 if (csp->config->admin_address != NULL)
1847 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1848 local_help_exists = 1;
1852 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1855 if (csp->config->proxy_info_url != NULL)
1857 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1858 local_help_exists = 1;
1862 if (!err) err = map_block_killer(exports, "have-proxy-info");
1865 if (local_help_exists == 0)
1867 if (!err) err = map_block_killer(exports, "have-help-info");
1880 /*********************************************************************
1882 * Function : map_block_killer
1884 * Description : Convenience function.
1885 * Adds a "killer" for the conditional HTML-template
1886 * block <name>, i.e. a substitution of the regex
1887 * "if-<name>-start.*if-<name>-end" to the given
1891 * 1 : exports = map to extend
1892 * 2 : name = name of conditional block
1894 * Returns : JB_ERR_OK on success
1895 * JB_ERR_MEMORY on out-of-memory error.
1897 *********************************************************************/
1898 jb_err map_block_killer(struct map *exports, const char *name)
1900 char buf[1000]; /* Will do, since the names are hardwired */
1904 assert(strlen(name) < 490);
1906 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1907 return map(exports, buf, 1, "", 1);
1911 /*********************************************************************
1913 * Function : map_block_keep
1915 * Description : Convenience function. Removes the markers used
1916 * by map-block-killer, to save a few bytes.
1917 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1920 * 1 : exports = map to extend
1921 * 2 : name = name of conditional block
1923 * Returns : JB_ERR_OK on success
1924 * JB_ERR_MEMORY on out-of-memory error.
1926 *********************************************************************/
1927 jb_err map_block_keep(struct map *exports, const char *name)
1930 char buf[500]; /* Will do, since the names are hardwired */
1934 assert(strlen(name) < 490);
1936 snprintf(buf, 500, "if-%s-start", name);
1937 err = map(exports, buf, 1, "", 1);
1944 snprintf(buf, 500, "if-%s-end", name);
1945 return map(exports, buf, 1, "", 1);
1949 /*********************************************************************
1951 * Function : map_conditional
1953 * Description : Convenience function.
1954 * Adds an "if-then-else" for the conditional HTML-template
1955 * block <name>, i.e. a substitution of the form:
1962 * The control structure and one of the alternatives
1966 * 1 : exports = map to extend
1967 * 2 : name = name of conditional block
1968 * 3 : choose_first = nonzero for first, zero for second.
1970 * Returns : JB_ERR_OK on success
1971 * JB_ERR_MEMORY on out-of-memory error.
1973 *********************************************************************/
1974 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1976 char buf[1000]; /* Will do, since the names are hardwired */
1981 assert(strlen(name) < 480);
1983 snprintf(buf, 1000, (choose_first
1984 ? "else-not-%s@.*@endif-%s"
1985 : "if-%s-then@.*@else-not-%s"),
1988 err = map(exports, buf, 1, "", 1);
1994 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1995 return map(exports, buf, 1, "", 1);
1999 /*********************************************************************
2001 * Function : make_menu
2003 * Description : Returns an HTML-formatted menu of the available
2004 * unhidden CGIs, excluding the one given in <self>
2006 * Parameters : self = name of CGI to leave out, can be NULL for
2009 * Returns : menu string, or NULL on out-of-memory error.
2011 *********************************************************************/
2012 char *make_menu(const char *self)
2014 const struct cgi_dispatcher *d;
2015 char *result = strdup("");
2019 self = "NO-SUCH-CGI!";
2022 /* List available unhidden CGI's and export as "other-cgis" */
2023 for (d = cgi_dispatchers; d->name; d++)
2025 if (d->description && strcmp(d->name, self))
2027 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2028 string_append(&result, d->name);
2029 string_append(&result, "\">");
2030 string_append(&result, d->description);
2031 string_append(&result, "</a></li>");
2039 /*********************************************************************
2041 * Function : dump_map
2043 * Description : HTML-dump a map for debugging (as table)
2046 * 1 : the_map = map to dump
2048 * Returns : string with HTML
2050 *********************************************************************/
2051 char *dump_map(const struct map *the_map)
2053 struct map_entry *cur_entry;
2054 char *ret = strdup("");
2056 string_append(&ret, "<table>\n");
2058 for (cur_entry = the_map->first;
2059 (cur_entry != NULL) && (ret != NULL);
2060 cur_entry = cur_entry->next)
2062 string_append(&ret, "<tr><td><b>");
2063 string_join (&ret, html_encode(cur_entry->name));
2064 string_append(&ret, "</b></td><td>");
2065 string_join (&ret, html_encode(cur_entry->value));
2066 string_append(&ret, "</td></tr>\n");
2069 string_append(&ret, "</table>\n");