1 const char cgi_rcs[] = "$Id: cgi.c,v 1.66 2002/04/26 18:32:57 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.66 2002/04/26 18:32:57 jongfoster
42 * Fixing a memory leak on error
44 * Revision 1.65 2002/04/26 12:53:51 oes
45 * - New function add_help_link
46 * - default_exports now exports links to the user manual
47 * and a prefix for links into the config chapter
49 * Revision 1.64 2002/04/24 02:17:21 oes
50 * - Better descriptions for CGIs
51 * - Hide edit-actions, more shortcuts
52 * - Moved get_char_param, get_string_param and get_number_param here
55 * Revision 1.63 2002/04/15 19:06:43 jongfoster
58 * Revision 1.62 2002/04/10 19:59:46 jongfoster
59 * Fixes to #include in templates:
60 * - Didn't close main file if loading an included template fails.
61 * - I'm paranoid and want to disallow "#include /etc/passwd".
63 * Revision 1.61 2002/04/10 13:37:48 oes
64 * Made templates modular: template_load now recursive with max depth 1
66 * Revision 1.60 2002/04/08 20:50:25 swa
69 * Revision 1.59 2002/04/05 15:51:51 oes
70 * - added send-stylesheet CGI
71 * - bugfix: error-pages now get correct request protocol
73 * - kludged CGI descriptions and menu not to break JS syntax
75 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
76 * Fix Mac OSX compiler warnings
78 * Revision 1.57 2002/03/26 22:29:54 swa
79 * we have a new homepage!
81 * Revision 1.56 2002/03/24 17:50:46 jongfoster
82 * Fixing compile error if actions file editor disabled
84 * Revision 1.55 2002/03/24 16:55:06 oes
85 * Making GIF checkerboard transparent
87 * Revision 1.54 2002/03/24 16:18:15 jongfoster
90 * Revision 1.53 2002/03/24 16:06:00 oes
91 * Correct transparency for checkerboard PNG. Thanks, Magnus!
93 * Revision 1.52 2002/03/24 15:23:33 jongfoster
96 * Revision 1.51 2002/03/24 13:25:43 swa
97 * name change related issues
99 * Revision 1.50 2002/03/16 23:54:06 jongfoster
100 * Adding graceful termination feature, to help look for memory leaks.
101 * If you enable this (which, by design, has to be done by hand
102 * editing config.h) and then go to http://i.j.b/die, then the program
103 * will exit cleanly after the *next* request. It should free all the
104 * memory that was used.
106 * Revision 1.49 2002/03/13 00:27:04 jongfoster
109 * Revision 1.48 2002/03/08 17:47:07 jongfoster
112 * Revision 1.47 2002/03/08 16:41:33 oes
113 * Added GIF images again
115 * Revision 1.46 2002/03/07 03:48:38 oes
116 * - Changed built-in images from GIF to PNG
117 * (with regard to Unisys patent issue)
118 * - Added a 4x4 pattern PNG which is less intrusive
119 * than the logo but also clearly marks the deleted banners
121 * Revision 1.45 2002/03/06 22:54:35 jongfoster
122 * Automated function-comment nitpicking.
124 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
125 * - Better error reporting on OS/2
126 * - Fix double-slash comment (oops)
128 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
129 * - Re-enable OS/2 building after new parms were added
130 * - Fix false out of memory report when resolving CGI templates when no IP
131 * address is available of failed attempt (a la no such domain)
133 * Revision 1.42 2002/01/21 00:33:20 jongfoster
134 * Replacing strsav() with the safer string_append() or string_join().
135 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
136 * Adding missing html_encode() to error message generators.
137 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
139 * Revision 1.41 2002/01/17 20:56:22 jongfoster
140 * Replacing hard references to the URL of the config interface
141 * with #defines from project.h
143 * Revision 1.40 2002/01/09 14:26:46 oes
144 * Added support for thread-safe gmtime_r call.
146 * Revision 1.39 2001/11/16 00:48:13 jongfoster
147 * Fixing a compiler warning
149 * Revision 1.38 2001/11/13 00:31:21 jongfoster
150 * - Adding new CGIs for use by non-JavaScript browsers:
151 * edit-actions-url-form
152 * edit-actions-add-url-form
153 * edit-actions-remove-url-form
154 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
157 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
158 * Show enablement/disablement status in almost all templates.
159 * There is a little trickiness here: apparent recursive resolution of
160 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
161 * the actual enablement status. So a similar construct,
162 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
165 * Revision 1.36 2001/10/26 17:33:27 oes
168 * Revision 1.35 2001/10/23 21:48:19 jongfoster
169 * Cleaning up error handling in CGI functions - they now send back
170 * a HTML error page and should never cause a FATAL error. (Fixes one
171 * potential source of "denial of service" attacks).
173 * CGI actions file editor that works and is actually useful.
175 * Ability to toggle Junkbuster remotely using a CGI call.
177 * You can turn off both the above features in the main configuration
178 * file, e.g. if you are running a multi-user proxy.
180 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
181 * Only show "Local support" on templates conditionally:
182 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
183 * - if not, no Local support section appears
185 * Revision 1.33 2001/10/14 22:28:41 jongfoster
186 * Fixing stupid typo.
188 * Revision 1.32 2001/10/14 22:20:18 jongfoster
189 * - Changes to CGI dispatching method to match CGI names exactly,
190 * rather than doing a prefix match.
191 * - No longer need to count the length of the CGI handler names by hand.
192 * - Adding new handler for 404 error when disptching a CGI, if none of
193 * the handlers match.
194 * - Adding new handlers for CGI actionsfile editor.
196 * Revision 1.31 2001/10/10 10:56:39 oes
197 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
199 * Revision 1.30 2001/10/02 15:30:57 oes
200 * Introduced show-request cgi
202 * Revision 1.29 2001/09/20 15:47:44 steudten
204 * Fix BUG: Modify int size to size_t size in fill_template()
205 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
207 * Revision 1.28 2001/09/19 18:00:37 oes
208 * - Deletef time() FIXME (Can't fail under Linux either, if
209 * the argument is guaranteed to be in out address space,
212 * - Pointer notation cosmetics
213 * - Fixed a minor bug in template_fill(): Failiure of
214 * pcrs_execute() now secure.
216 * Revision 1.27 2001/09/16 17:08:54 jongfoster
217 * Moving simple CGI functions from cgi.c to new file cgisimple.c
219 * Revision 1.26 2001/09/16 15:47:37 jongfoster
220 * First version of CGI-based edit interface. This is very much a
221 * work-in-progress, and you can't actually use it to edit anything
222 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
223 * to have any effect.
225 * Revision 1.25 2001/09/16 15:02:35 jongfoster
226 * Adding i.j.b/robots.txt.
227 * Inlining add_stats() since it's only ever called from one place.
229 * Revision 1.24 2001/09/16 11:38:01 jongfoster
230 * Splitting fill_template() into 2 functions:
231 * template_load() loads the file
232 * template_fill() performs the PCRS regexps.
233 * This is because the CGI edit interface has a "table row"
234 * template which is used many times in the page - this
235 * change means it's only loaded from disk once.
237 * Revision 1.23 2001/09/16 11:16:05 jongfoster
238 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
240 * Revision 1.22 2001/09/16 11:00:10 jongfoster
241 * New function alloc_http_response, for symmetry with free_http_response
243 * Revision 1.21 2001/09/13 23:53:03 jongfoster
244 * Support for both static and dynamically generated CGI pages.
245 * Correctly setting Last-Modified: and Expires: HTTP headers.
247 * Revision 1.20 2001/09/13 23:40:36 jongfoster
248 * (Cosmetic only) Indentation correction
250 * Revision 1.19 2001/09/13 23:31:25 jongfoster
251 * Moving image data to cgi.c rather than cgi.h.
253 * Revision 1.18 2001/08/05 16:06:20 jongfoster
254 * Modifiying "struct map" so that there are now separate header and
255 * "map_entry" structures. This means that functions which modify a
256 * map no longer need to return a pointer to the modified map.
257 * Also, it no longer reverses the order of the entries (which may be
258 * important with some advanced template substitutions).
260 * Revision 1.17 2001/08/05 15:57:38 oes
261 * Adapted finish_http_response to new list_to_text
263 * Revision 1.16 2001/08/01 21:33:18 jongfoster
264 * Changes to fill_template() that reduce memory usage without having
265 * an impact on performance. I also renamed some variables so as not
266 * to clash with the C++ keywords "new" and "template".
268 * Revision 1.15 2001/08/01 21:19:22 jongfoster
269 * Moving file version information to a separate CGI page.
271 * Revision 1.14 2001/08/01 00:19:03 jongfoster
272 * New function: map_conditional() for an if-then-else syntax.
273 * Changing to use new version of show_defines()
275 * Revision 1.13 2001/07/30 22:08:36 jongfoster
276 * Tidying up #defines:
277 * - All feature #defines are now of the form FEATURE_xxx
278 * - Permanently turned off WIN_GUI_EDIT
279 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
281 * Revision 1.12 2001/07/29 18:47:05 jongfoster
282 * Adding missing #include "loadcfg.h"
284 * Revision 1.11 2001/07/18 17:24:37 oes
285 * Changed to conform to new pcrs interface
287 * Revision 1.10 2001/07/13 13:53:13 oes
288 * Removed all #ifdef PCRS and related code
290 * Revision 1.9 2001/06/29 21:45:41 oes
291 * Indentation, CRLF->LF, Tab-> Space
293 * Revision 1.8 2001/06/29 13:21:46 oes
294 * - Cosmetics: renamed and reordered functions, variables,
295 * texts, improved comments etc
297 * - Removed ij_untrusted_url() The relevant
298 * info is now part of the "untrusted" page,
299 * which is generated by filters.c:trust_url()
301 * - Generators of content now call finish_http_response()
302 * themselves, making jcc.c:chat() a little less
305 * - Removed obsolete "Pragma: no-cache" from our headers
307 * - http_responses now know their head length
309 * - fill_template now uses the new interface to pcrs, so that
310 * - long jobs (like whole files) no longer have to be assembled
311 * in a fixed size buffer
312 * - the new T (trivial) option is used, and the replacement may
313 * contain Perl syntax backrefs without confusing pcrs
315 * - Introduced default_exports() which generates a set of exports
316 * common to all CGIs and other content generators
318 * - Introduced convenience function map_block_killer()
320 * - Introduced convenience function make_menu()
322 * - Introduced CGI-like function error_response() which generates
323 * the "No such domain" and "Connect failed" messages using the
326 * - cgi_show_url_info:
327 * - adapted to new CGI features
328 * - form and answers now generated from same template
329 * - http:// prefix in URL now OK
332 * - adapted to new CGI features
333 * - no longer uses csp->init_proxy_args
336 * - moved menu generation to make_menu()
338 * - add_stats now writes single export map entries instead
341 * - Moved redirect_url() to filters.c
343 * - Fixed mem leak in free_http_response(), map_block_killer(),
345 * - Removed logentry from cancelled commit
347 * Revision 1.7 2001/06/09 10:51:58 jongfoster
348 * Changing "show URL info" handler to new style.
349 * Changing BUFSIZ ==> BUFFER_SIZE
351 * Revision 1.6 2001/06/07 23:05:19 jongfoster
352 * Removing code related to old forward and ACL files.
354 * Revision 1.5 2001/06/05 19:59:16 jongfoster
355 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
357 * Revision 1.4 2001/06/04 10:41:52 swa
358 * show version string of cgi.h and cgi.c
360 * Revision 1.3 2001/06/03 19:12:16 oes
361 * introduced new cgi handling
363 * No revisions before 1.3
365 **********************************************************************/
371 #include <sys/types.h>
379 #define snprintf _snprintf
380 #endif /* def _WIN32 */
388 #include "miscutil.h"
389 #include "cgisimple.h"
390 #ifdef FEATURE_CGI_EDIT_ACTIONS
392 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
394 /* loadcfg.h is for g_bToggleIJB only */
396 const char cgi_h_rcs[] = CGI_H_VERSION;
399 * List of CGI functions: name, handler, description
400 * Note: Do NOT use single quotes in the description;
401 * this will break the dynamic "blocked" template!
403 static const struct cgi_dispatcher cgi_dispatchers[] = {
406 "Privoxy main page" },
407 #ifdef FEATURE_GRACEFUL_TERMINATION
410 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
411 "this is a one click Denial Of Service attack!!!</em>" },
415 "View & change the current configuration" },
418 "View the source code version numbers" },
421 "View the request headers." },
424 "Look up which actions apply to a URL and why" },
425 #ifdef FEATURE_CGI_EDIT_ACTIONS
428 "Toggle Privoxy on or off" },
430 { "edit-actions", /* Edit the actions list */
433 { "eaa", /* Shortcut for edit-actions-add-url-form */
434 cgi_edit_actions_add_url_form,
436 { "eau", /* Shortcut for edit-actions-url-form */
437 cgi_edit_actions_url_form,
439 { "ear", /* Shortcut for edit-actions-remove-url-form */
440 cgi_edit_actions_remove_url_form,
442 { "eafu", /* Shortcut for edit-actions-for-url */
443 cgi_edit_actions_for_url,
445 { "eas", /* Shortcut for edit-actions-submit */
446 cgi_edit_actions_submit,
448 { "easa", /* Shortcut for edit-actions-section-add */
449 cgi_edit_actions_section_add,
451 { "easr", /* Shortcut for edit-actions-section-remove */
452 cgi_edit_actions_section_remove,
454 { "eass", /* Shortcut for edit-actions-section-swap */
455 cgi_edit_actions_section_swap,
457 { "edit-actions-for-url",
458 cgi_edit_actions_for_url,
459 NULL /* Edit the actions for (a) specified URL(s) */ },
460 { "edit-actions-list",
461 cgi_edit_actions_list,
462 NULL /* Edit the actions list */ },
463 { "edit-actions-submit",
464 cgi_edit_actions_submit,
465 NULL /* Change the actions for (a) specified URL(s) */ },
466 { "edit-actions-url",
467 cgi_edit_actions_url,
468 NULL /* Change a URL pattern in the actionsfile */ },
469 { "edit-actions-url-form",
470 cgi_edit_actions_url_form,
471 NULL /* Form to change a URL pattern in the actionsfile */ },
472 { "edit-actions-add-url",
473 cgi_edit_actions_add_url,
474 NULL /* Add a URL pattern to the actionsfile */ },
475 { "edit-actions-add-url-form",
476 cgi_edit_actions_add_url_form,
477 NULL /* Form to add a URL pattern to the actionsfile */ },
478 { "edit-actions-remove-url",
479 cgi_edit_actions_remove_url,
480 NULL /* Remove a URL pattern from the actionsfile */ },
481 { "edit-actions-remove-url-form",
482 cgi_edit_actions_remove_url_form,
483 NULL /* Form to remove a URL pattern from the actionsfile */ },
484 { "edit-actions-section-add",
485 cgi_edit_actions_section_add,
486 NULL /* Remove a section from the actionsfile */ },
487 { "edit-actions-section-remove",
488 cgi_edit_actions_section_remove,
489 NULL /* Remove a section from the actionsfile */ },
490 { "edit-actions-section-swap",
491 cgi_edit_actions_section_swap,
492 NULL /* Swap two sections in the actionsfile */ },
493 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
496 NULL /* Sends a robots.txt file to tell robots to go away. */ },
499 NULL /* Send a built-in image */ },
502 NULL /* Send templates/cgi-style.css */ },
504 cgi_transparent_image,
505 NULL /* Send a transparent image (short name) */ },
506 { NULL, /* NULL Indicates end of list and default page */
508 NULL /* Unknown CGI page */ }
513 * Bulit-in images for ad replacement
515 * Hint: You can encode your own images like this:
516 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
519 #ifdef FEATURE_NO_GIFS
522 * Checkerboard pattern, as a PNG.
524 const char image_pattern_data[] =
525 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
526 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
527 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
528 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
529 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
530 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
531 "\000\000\000\111\105\116\104\256\102\140\202";
534 * 1x1 transparant PNG.
536 const char image_blank_data[] =
537 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
538 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
539 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
540 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
541 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
542 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
543 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
544 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
545 "\000\000\000\000\111\105\116\104\256\102\140\202";
549 * Checkerboard pattern, as a GIF.
551 const char image_pattern_data[] =
552 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
553 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
554 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
555 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
559 * 1x1 transparant GIF.
561 const char image_blank_data[] =
562 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
563 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
564 "\000\001\000\000\002\002D\001\000;";
567 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
568 const size_t image_blank_length = sizeof(image_blank_data) - 1;
571 static struct http_response cgi_error_memory_response[1];
573 static struct http_response *dispatch_known_cgi(struct client_state * csp,
575 static struct map *parse_cgi_parameters(char *argstring);
578 /*********************************************************************
580 * Function : dispatch_cgi
582 * Description : Checks if a request URL has either the magical
583 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
584 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
585 * http://config.privoxy.org/). If so, it passes
586 * the (rest of the) path onto dispatch_known_cgi, which
587 * calls the relevant CGI handler function.
590 * 1 : csp = Current client state (buffers, headers, etc...)
592 * Returns : http_response if match, NULL if nonmatch or handler fail
594 *********************************************************************/
595 struct http_response *dispatch_cgi(struct client_state *csp)
597 const char *host = csp->http->host;
598 const char *path = csp->http->path;
601 * Should we intercept ?
604 /* Note: "example.com" and "example.com." are equivalent hostnames. */
606 /* Either the host matches CGI_SITE_1_HOST ..*/
607 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
608 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
609 && (path[0] == '/') )
611 /* ..then the path will all be for us. Remove leading '/' */
614 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
615 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
616 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
617 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
619 /* take everything following CGI_SITE_2_PATH */
620 path += strlen(CGI_SITE_2_PATH);
623 /* skip the forward slash after CGI_SITE_2_PATH */
626 else if (*path != '\0')
629 * wierdness: URL is /configXXX, where XXX is some string
630 * Do *NOT* intercept.
642 * This is a CGI call.
645 return dispatch_known_cgi(csp, path);
649 /*********************************************************************
651 * Function : dispatch_known_cgi
653 * Description : Processes a CGI once dispatch_cgi has determined that
654 * it matches one of the magic prefixes. Parses the path
655 * as a cgi name plus query string, prepares a map that
656 * maps CGI parameter names to their values, initializes
657 * the http_response struct, and calls the relevant CGI
661 * 1 : csp = Current client state (buffers, headers, etc...)
662 * 2 : path = Path of CGI, with the CGI prefix removed.
663 * Should not have a leading "/".
665 * Returns : http_response, or NULL on handler failure or out of
668 *********************************************************************/
669 static struct http_response *dispatch_known_cgi(struct client_state * csp,
672 const struct cgi_dispatcher *d;
673 struct map *param_list;
674 struct http_response *rsp;
675 char *query_args_start;
679 if (NULL == (path_copy = strdup(path)))
681 return cgi_error_memory();
684 query_args_start = path_copy;
685 while (*query_args_start && *query_args_start != '?')
689 if (*query_args_start == '?')
691 *query_args_start++ = '\0';
694 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
697 return cgi_error_memory();
703 * path_copy = CGI call name
704 * param_list = CGI params, as map
707 /* Get mem for response or fail*/
708 if (NULL == (rsp = alloc_http_response()))
711 free_map(param_list);
712 return cgi_error_memory();
715 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
716 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
717 csp->ip_addr_str, csp->http->cmd);
719 /* Find and start the right CGI function*/
723 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
725 err = (d->handler)(csp, rsp, param_list);
727 free_map(param_list);
728 if (err == JB_ERR_CGI_PARAMS)
730 err = cgi_error_bad_param(csp, rsp);
735 return finish_http_response(rsp);
739 /* Error in handler, probably out-of-memory */
740 free_http_response(rsp);
741 return cgi_error_memory();
749 /*********************************************************************
751 * Function : parse_cgi_parameters
753 * Description : Parse a URL-encoded argument string into name/value
754 * pairs and store them in a struct map list.
757 * 1 : string = string to be parsed. Will be trashed.
759 * Returns : pointer to param list, or NULL if out of memory.
761 *********************************************************************/
762 static struct map *parse_cgi_parameters(char *argstring)
765 char *vector[BUFFER_SIZE];
767 struct map *cgi_params;
769 if (NULL == (cgi_params = new_map()))
774 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
776 for (i = 0; i < pairs; i++)
778 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
781 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
783 free_map(cgi_params);
794 /*********************************************************************
796 * Function : get_char_param
798 * Description : Get a single-character parameter passed to a CGI
802 * 1 : parameters = map of cgi parameters
803 * 2 : param_name = The name of the parameter to read
805 * Returns : Uppercase character on success, '\0' on error.
807 *********************************************************************/
808 char get_char_param(const struct map *parameters,
809 const char *param_name)
816 ch = *(lookup(parameters, param_name));
817 if ((ch >= 'a') && (ch <= 'z'))
826 /*********************************************************************
828 * Function : get_string_param
830 * Description : Get a string paramater, to be used as an
831 * ACTION_STRING or ACTION_MULTI paramater.
832 * Validates the input to prevent stupid/malicious
833 * users from corrupting their action file.
836 * 1 : parameters = map of cgi parameters
837 * 2 : param_name = The name of the parameter to read
838 * 3 : pparam = destination for paramater. Allocated as
839 * part of the map "parameters", so don't free it.
840 * Set to NULL if not specified.
842 * Returns : JB_ERR_OK on success, or if the paramater
844 * JB_ERR_MEMORY on out-of-memory.
845 * JB_ERR_CGI_PARAMS if the paramater is not valid.
847 *********************************************************************/
848 jb_err get_string_param(const struct map *parameters,
849 const char *param_name,
862 param = lookup(parameters, param_name);
868 if (strlen(param) >= CGI_PARAM_LEN_MAX)
873 * Note that the length limit is arbitrary, it just seems
874 * sensible to limit it to *something*. There's no
875 * technical reason for any limit at all.
877 return JB_ERR_CGI_PARAMS;
880 /* Check every character to see if it's legal */
882 while ((ch = *s++) != '\0')
884 if ( ((unsigned char)ch < (unsigned char)' ')
887 /* Probable hack attempt, or user accidentally used '}'. */
888 return JB_ERR_CGI_PARAMS;
899 /*********************************************************************
901 * Function : get_number_param
903 * Description : Get a non-negative integer from the parameters
904 * passed to a CGI function.
907 * 1 : csp = Current client state (buffers, headers, etc...)
908 * 2 : parameters = map of cgi parameters
909 * 3 : name = Name of CGI parameter to read
910 * 4 : pvalue = destination for value.
911 * Set to -1 on error.
913 * Returns : JB_ERR_OK on success
914 * JB_ERR_MEMORY on out-of-memory
915 * JB_ERR_CGI_PARAMS if the parameter was not specified
918 *********************************************************************/
919 jb_err get_number_param(struct client_state *csp,
920 const struct map *parameters,
935 param = lookup(parameters, name);
938 return JB_ERR_CGI_PARAMS;
941 /* We don't use atoi because I want to check this carefully... */
944 while ((ch = *param++) != '\0')
946 if ((ch < '0') || (ch > '9'))
948 return JB_ERR_CGI_PARAMS;
955 * <limits.h> defines UINT_MAX
957 * (UINT_MAX - ch) / 10 is the largest number that
958 * can be safely multiplied by 10 then have ch added.
960 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
962 return JB_ERR_CGI_PARAMS;
965 value = value * 10 + ch;
976 /*********************************************************************
978 * Function : error_response
980 * Description : returns an http_response that explains the reason
981 * why a request failed.
984 * 1 : csp = Current client state (buffers, headers, etc...)
985 * 2 : templatename = Which template should be used for the answer
986 * 3 : sys_err = system error number
988 * Returns : A http_response. If we run out of memory, this
989 * will be cgi_error_memory().
991 *********************************************************************/
992 struct http_response *error_response(struct client_state *csp,
993 const char *templatename,
997 struct http_response *rsp;
998 struct map * exports = default_exports(csp, NULL);
1001 return cgi_error_memory();
1004 if (NULL == (rsp = alloc_http_response()))
1007 return cgi_error_memory();
1010 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1011 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1012 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1013 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1014 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1017 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1020 /* Some failures, like "404 no such domain", don't have an IP address. */
1021 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1029 free_http_response(rsp);
1030 return cgi_error_memory();
1033 if (!strcmp(templatename, "no-such-domain"))
1035 rsp->status = strdup("404 No such domain");
1036 if (rsp->status == NULL)
1039 free_http_response(rsp);
1040 return cgi_error_memory();
1043 else if (!strcmp(templatename, "connect-failed"))
1045 rsp->status = strdup("503 Connect failed");
1046 if (rsp->status == NULL)
1049 free_http_response(rsp);
1050 return cgi_error_memory();
1054 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1057 free_http_response(rsp);
1058 return cgi_error_memory();
1061 return finish_http_response(rsp);
1065 /*********************************************************************
1067 * Function : cgi_init_error_messages
1069 * Description : Call at the start of the program to initialize
1070 * the error message used by cgi_error_memory().
1076 *********************************************************************/
1077 void cgi_init_error_messages(void)
1079 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1080 cgi_error_memory_response->head =
1081 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1082 "Content-Type: text/html\r\n"
1084 cgi_error_memory_response->body =
1086 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1088 "<h1>500 Internal Privoxy Error</h1>\r\n"
1089 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1090 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1094 cgi_error_memory_response->head_length =
1095 strlen(cgi_error_memory_response->head);
1096 cgi_error_memory_response->content_length =
1097 strlen(cgi_error_memory_response->body);
1101 /*********************************************************************
1103 * Function : cgi_error_memory
1105 * Description : Called if a CGI function runs out of memory.
1106 * Returns a statically-allocated error response.
1109 * 1 : csp = Current client state (buffers, headers, etc...)
1110 * 2 : rsp = http_response data structure for output
1111 * 3 : template_name = Name of template that could not
1114 * Returns : JB_ERR_OK on success
1115 * JB_ERR_MEMORY on out-of-memory error.
1117 *********************************************************************/
1118 struct http_response *cgi_error_memory(void)
1120 /* assert that it's been initialized. */
1121 assert(cgi_error_memory_response->head);
1123 return cgi_error_memory_response;
1127 /*********************************************************************
1129 * Function : cgi_error_no_template
1131 * Description : Almost-CGI function that is called if a templae
1132 * cannot be loaded. Note this is not a true CGI,
1133 * it takes a template name rather than a map of
1137 * 1 : csp = Current client state (buffers, headers, etc...)
1138 * 2 : rsp = http_response data structure for output
1139 * 3 : template_name = Name of template that could not
1142 * Returns : JB_ERR_OK on success
1143 * JB_ERR_MEMORY on out-of-memory error.
1145 *********************************************************************/
1146 jb_err cgi_error_no_template(struct client_state *csp,
1147 struct http_response *rsp,
1148 const char *template_name)
1150 static const char status[] =
1151 "500 Internal Privoxy Error";
1152 static const char body_prefix[] =
1154 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1156 "<h1>500 Internal Privoxy Error</h1>\r\n"
1157 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1158 "<p><b>Could not load template file <code>";
1159 static const char body_suffix[] =
1160 "</code> or one of it's included components.</b></p>\r\n"
1161 "<p>Please contact your proxy administrator.</p>\r\n"
1162 "<p>If you are the proxy administrator, please put the required file(s)"
1163 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1164 "location of the <code><i>(confdir)</i></code> directory "
1165 "is specified in the main Privoxy <code>config</code> "
1166 "file. (It's typically the Privoxy install directory"
1168 ", or <code>/etc/privoxy/</code>"
1169 #endif /* ndef _WIN32 */
1176 assert(template_name);
1178 /* Reset rsp, if needed */
1182 rsp->content_length = 0;
1183 rsp->head_length = 0;
1186 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1187 if (rsp->body == NULL)
1189 return JB_ERR_MEMORY;
1191 strcpy(rsp->body, body_prefix);
1192 strcat(rsp->body, template_name);
1193 strcat(rsp->body, body_suffix);
1195 rsp->status = strdup(status);
1196 if (rsp->body == NULL)
1198 return JB_ERR_MEMORY;
1205 /*********************************************************************
1207 * Function : cgi_error_bad_param
1209 * Description : CGI function that is called if the parameters
1210 * (query string) for a CGI were wrong.
1213 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * 2 : rsp = http_response data structure for output
1216 * CGI Parameters : none
1218 * Returns : JB_ERR_OK on success
1219 * JB_ERR_MEMORY on out-of-memory error.
1221 *********************************************************************/
1222 jb_err cgi_error_bad_param(struct client_state *csp,
1223 struct http_response *rsp)
1225 struct map *exports;
1230 if (NULL == (exports = default_exports(csp, NULL)))
1232 return JB_ERR_MEMORY;
1235 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1239 /*********************************************************************
1241 * Function : add_help_link
1243 * Description : Produce a copy of the string given as item,
1244 * embedded in an HTML link to its corresponding
1245 * section (item name in uppercase) in the configuration
1246 * chapter of the user manual, (whose URL is given in
1247 * the config and defaults to our web site).
1250 * 1 : item = item (will NOT be free()d.)
1251 * It is assumed to be HTML-safe.
1253 * Returns : String with item embedded in link, or NULL on
1256 *********************************************************************/
1257 char *add_help_link(const char *item,
1258 struct configuration_spec *config)
1262 if (!item) return NULL;
1264 result = strdup("<a href=\"");
1265 string_append(&result, config->usermanual);
1266 string_append(&result, HELP_LINK_PREFIX);
1267 string_join (&result, string_toupper(item));
1268 string_append(&result, "\">");
1269 string_append(&result, item);
1270 string_append(&result, "</a> ");
1276 /*********************************************************************
1278 * Function : get_http_time
1280 * Description : Get the time in a format suitable for use in a
1281 * HTTP header - e.g.:
1282 * "Sun, 06 Nov 1994 08:49:37 GMT"
1285 * 1 : time_offset = Time returned will be current time
1286 * plus this number of seconds.
1287 * 2 : buf = Destination for result. Must be long enough
1288 * to hold 29 characters plus a trailing zero.
1292 *********************************************************************/
1293 void get_http_time(int time_offset, char *buf)
1295 static const char day_names[7][4] =
1296 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1297 static const char month_names[12][4] =
1298 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1299 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1302 time_t current_time;
1306 time(¤t_time); /* get current time */
1308 current_time += time_offset;
1310 /* get and save the gmt */
1312 #ifdef HAVE_GMTIME_R
1314 t = gmtime_r(¤t_time, &dummy);
1316 t = gmtime(¤t_time);
1320 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1322 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1323 day_names[t->tm_wday],
1325 month_names[t->tm_mon],
1335 /*********************************************************************
1337 * Function : finish_http_response
1339 * Description : Fill in the missing headers in an http response,
1340 * and flatten the headers to an http head.
1343 * 1 : rsp = pointer to http_response to be processed
1345 * Returns : A http_response, usually the rsp parameter.
1346 * On error, free()s rsp and returns cgi_error_memory()
1348 *********************************************************************/
1349 struct http_response *finish_http_response(struct http_response *rsp)
1351 char buf[BUFFER_SIZE];
1354 /* Special case - do NOT change this statically allocated response,
1355 * which is ready for output anyway.
1357 if (rsp == cgi_error_memory_response)
1363 * Fill in the HTTP Status
1365 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1366 err = enlist_first(rsp->headers, buf);
1369 * Set the Content-Length
1371 if (rsp->content_length == 0)
1373 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1377 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1378 err = enlist(rsp->headers, buf);
1382 * Fill in the default headers:
1384 * Content-Type: default to text/html if not already specified.
1385 * Date: set to current date/time.
1386 * Last-Modified: set to date/time the page was last changed.
1387 * Expires: set to date/time page next needs reloading.
1388 * Cache-Control: set to "no-cache" if applicable.
1390 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1392 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1397 * Set Expires to about 10 min into the future so it'll get reloaded
1398 * occasionally, e.g. if Privoxy gets upgraded.
1403 get_http_time(0, buf);
1404 err = enlist_unique_header(rsp->headers, "Date", buf);
1407 /* Some date in the past. */
1408 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1412 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1413 err = enlist_unique_header(rsp->headers, "Expires", buf);
1419 * Compliant browsers should not cache this due to the "Cache-Control"
1420 * setting. However, to be certain, we also set both "Last-Modified"
1421 * and "Expires" to the current time.
1423 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1425 get_http_time(0, buf);
1426 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1427 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1428 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1435 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1437 free_http_response(rsp);
1438 return cgi_error_memory();
1440 rsp->head_length = strlen(rsp->head);
1447 /*********************************************************************
1449 * Function : alloc_http_response
1451 * Description : Allocates a new http_response structure.
1455 * Returns : pointer to a new http_response, or NULL.
1457 *********************************************************************/
1458 struct http_response *alloc_http_response(void)
1460 return (struct http_response *) zalloc(sizeof(struct http_response));
1465 /*********************************************************************
1467 * Function : free_http_response
1469 * Description : Free the memory occupied by an http_response
1470 * and its depandant structures.
1473 * 1 : rsp = pointer to http_response to be freed
1477 *********************************************************************/
1478 void free_http_response(struct http_response *rsp)
1481 * Must special case cgi_error_memory_response, which is never freed.
1483 if (rsp && (rsp != cgi_error_memory_response))
1488 destroy_list(rsp->headers);
1495 /*********************************************************************
1497 * Function : template_load
1499 * Description : CGI support function that loads a given HTML
1500 * template from the confdir, ignoring comment
1501 * lines and following #include statements up to
1505 * 1 : csp = Current client state (buffers, headers, etc...)
1506 * 2 : template_ptr = Destination for pointer to loaded
1508 * 3 : template = name of the HTML template to be used
1509 * 4 : recursive = Flag set if this function calls itself
1510 * following an #include statament
1512 * Returns : JB_ERR_OK on success
1513 * JB_ERR_MEMORY on out-of-memory error.
1514 * JB_ERR_FILE if the template file cannot be read
1516 *********************************************************************/
1517 jb_err template_load(struct client_state *csp, char **template_ptr,
1518 const char *templatename, int recursive)
1521 char *templates_dir_path;
1524 char *included_module;
1527 char buf[BUFFER_SIZE];
1530 assert(template_ptr);
1531 assert(templatename);
1533 *template_ptr = NULL;
1535 /* Validate template name. Paranoia. */
1536 for (p = templatename; *p != 0; p++)
1538 if ( ((*p < 'a') || (*p > 'z'))
1539 && ((*p < 'A') || (*p > 'Z'))
1540 && ((*p < '0') || (*p > '9'))
1544 /* Illegal character */
1549 /* Generate full path */
1551 templates_dir_path = make_path(csp->config->confdir, "templates");
1552 if (templates_dir_path == NULL)
1554 return JB_ERR_MEMORY;
1557 full_path = make_path(templates_dir_path, templatename);
1558 free(templates_dir_path);
1559 if (full_path == NULL)
1561 return JB_ERR_MEMORY;
1564 /* Allocate buffer */
1566 file_buffer = strdup("");
1567 if (file_buffer == NULL)
1570 return JB_ERR_MEMORY;
1573 /* Open template file */
1575 if (NULL == (fp = fopen(full_path, "r")))
1577 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1585 * Read the file, ignoring comments, and honoring #include
1586 * statements, unless we're already called recursively.
1588 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1589 * This is unlikely in practise.
1591 while (fgets(buf, BUFFER_SIZE, fp))
1593 if (!recursive && !strncmp(buf, "#include ", 9))
1595 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1602 if (string_join(&file_buffer, included_module))
1605 return JB_ERR_MEMORY;
1611 /* skip lines starting with '#' */
1617 if (string_append(&file_buffer, buf))
1620 return JB_ERR_MEMORY;
1625 *template_ptr = file_buffer;
1631 /*********************************************************************
1633 * Function : template_fill
1635 * Description : CGI support function that fills in a pre-loaded
1636 * HTML template by replacing @name@ with value using
1637 * pcrs, for each item in the output map.
1639 * Note that a leading '$' charachter in the export map's
1640 * values will be stripped and toggle on backreference
1644 * 1 : template_ptr = IN: Template to be filled out.
1646 * OUT: Filled out template.
1647 * Caller must free().
1648 * 2 : exports = map with fill in symbol -> name pairs
1650 * Returns : JB_ERR_OK on success
1651 * JB_ERR_MEMORY on out-of-memory error
1653 *********************************************************************/
1654 jb_err template_fill(char **template_ptr, const struct map *exports)
1656 struct map_entry *m;
1658 char buf[BUFFER_SIZE];
1659 char *tmp_out_buffer;
1665 assert(template_ptr);
1666 assert(*template_ptr);
1669 file_buffer = *template_ptr;
1670 size = strlen(file_buffer) + 1;
1673 * Assemble pcrs joblist from exports map
1675 for (m = exports->first; m != NULL; m = m->next)
1677 if (*m->name == '$')
1680 * First character of name is '$', so remove this flag
1681 * character and allow backreferences ($1 etc) in the
1682 * "replace with" text.
1684 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1690 * Treat the "replace with" text as a literal string -
1691 * no quoting needed, no backreferences allowed.
1692 * ("Trivial" ['T'] flag).
1696 /* Enclose name in @@ */
1697 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1701 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1703 /* Make and run job. */
1704 job = pcrs_compile(buf, m->value, flags, &error);
1707 if (error == PCRS_ERR_NOMEM)
1710 *template_ptr = NULL;
1711 return JB_ERR_MEMORY;
1715 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1716 /* Hope it wasn't important and silently ignore the invalid job */
1721 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1724 if (NULL == tmp_out_buffer)
1726 *template_ptr = NULL;
1727 return JB_ERR_MEMORY;
1729 file_buffer = tmp_out_buffer;
1736 *template_ptr = file_buffer;
1741 /*********************************************************************
1743 * Function : template_fill_for_cgi
1745 * Description : CGI support function that loads a HTML template
1746 * and fills it in. Handles file-not-found errors
1747 * by sending a HTML error message. For convenience,
1748 * this function also frees the passed "exports" map.
1751 * 1 : csp = Client state
1752 * 2 : templatename = name of the HTML template to be used
1753 * 3 : exports = map with fill in symbol -> name pairs.
1754 * Will be freed by this function.
1756 * Returns : JB_ERR_OK on success
1757 * JB_ERR_MEMORY on out-of-memory error
1759 *********************************************************************/
1760 jb_err template_fill_for_cgi(struct client_state *csp,
1761 const char *templatename,
1762 struct map *exports,
1763 struct http_response *rsp)
1768 assert(templatename);
1772 err = template_load(csp, &rsp->body, templatename, 0);
1773 if (err == JB_ERR_FILE)
1776 return cgi_error_no_template(csp, rsp, templatename);
1781 return err; /* JB_ERR_MEMORY */
1783 err = template_fill(&rsp->body, exports);
1789 /*********************************************************************
1791 * Function : default_exports
1793 * Description : returns a struct map list that contains exports
1794 * which are common to all CGI functions.
1797 * 1 : csp = Current client state (buffers, headers, etc...)
1798 * 2 : caller = name of CGI who calls us and which should
1799 * be excluded from the generated menu. May be
1801 * Returns : NULL if no memory, else a new map. Caller frees.
1803 *********************************************************************/
1804 struct map *default_exports(const struct client_state *csp, const char *caller)
1808 struct map * exports;
1809 int local_help_exists = 0;
1813 exports = new_map();
1814 if (exports == NULL)
1819 err = map(exports, "version", 1, html_encode(VERSION), 0);
1820 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1821 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1822 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1823 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1824 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1825 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1826 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
1827 if (!err) err = map(exports, "helplink", 1, HELP_LINK_PREFIX ,1);
1828 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1830 snprintf(buf, 20, "%d", csp->config->hport);
1831 if (!err) err = map(exports, "my-port", 1, buf, 1);
1833 if(!strcmp(CODE_STATUS, "stable"))
1835 if (!err) err = map_block_killer(exports, "unstable");
1838 if (csp->config->admin_address != NULL)
1840 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1841 local_help_exists = 1;
1845 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1848 if (csp->config->proxy_info_url != NULL)
1850 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1851 local_help_exists = 1;
1855 if (!err) err = map_block_killer(exports, "have-proxy-info");
1858 if (local_help_exists == 0)
1860 if (!err) err = map_block_killer(exports, "have-help-info");
1873 /*********************************************************************
1875 * Function : map_block_killer
1877 * Description : Convenience function.
1878 * Adds a "killer" for the conditional HTML-template
1879 * block <name>, i.e. a substitution of the regex
1880 * "if-<name>-start.*if-<name>-end" to the given
1884 * 1 : exports = map to extend
1885 * 2 : name = name of conditional block
1887 * Returns : JB_ERR_OK on success
1888 * JB_ERR_MEMORY on out-of-memory error.
1890 *********************************************************************/
1891 jb_err map_block_killer(struct map *exports, const char *name)
1893 char buf[1000]; /* Will do, since the names are hardwired */
1897 assert(strlen(name) < 490);
1899 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1900 return map(exports, buf, 1, "", 1);
1904 /*********************************************************************
1906 * Function : map_block_keep
1908 * Description : Convenience function. Removes the markers used
1909 * by map-block-killer, to save a few bytes.
1910 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1913 * 1 : exports = map to extend
1914 * 2 : name = name of conditional block
1916 * Returns : JB_ERR_OK on success
1917 * JB_ERR_MEMORY on out-of-memory error.
1919 *********************************************************************/
1920 jb_err map_block_keep(struct map *exports, const char *name)
1923 char buf[500]; /* Will do, since the names are hardwired */
1927 assert(strlen(name) < 490);
1929 snprintf(buf, 500, "if-%s-start", name);
1930 err = map(exports, buf, 1, "", 1);
1937 snprintf(buf, 500, "if-%s-end", name);
1938 return map(exports, buf, 1, "", 1);
1942 /*********************************************************************
1944 * Function : map_conditional
1946 * Description : Convenience function.
1947 * Adds an "if-then-else" for the conditional HTML-template
1948 * block <name>, i.e. a substitution of the form:
1955 * The control structure and one of the alternatives
1959 * 1 : exports = map to extend
1960 * 2 : name = name of conditional block
1961 * 3 : choose_first = nonzero for first, zero for second.
1963 * Returns : JB_ERR_OK on success
1964 * JB_ERR_MEMORY on out-of-memory error.
1966 *********************************************************************/
1967 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1969 char buf[1000]; /* Will do, since the names are hardwired */
1974 assert(strlen(name) < 480);
1976 snprintf(buf, 1000, (choose_first
1977 ? "else-not-%s@.*@endif-%s"
1978 : "if-%s-then@.*@else-not-%s"),
1981 err = map(exports, buf, 1, "", 1);
1987 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1988 return map(exports, buf, 1, "", 1);
1992 /*********************************************************************
1994 * Function : make_menu
1996 * Description : Returns an HTML-formatted menu of the available
1997 * unhidden CGIs, excluding the one given in <self>
1999 * Parameters : self = name of CGI to leave out, can be NULL for
2002 * Returns : menu string, or NULL on out-of-memory error.
2004 *********************************************************************/
2005 char *make_menu(const char *self)
2007 const struct cgi_dispatcher *d;
2008 char *result = strdup("");
2012 self = "NO-SUCH-CGI!";
2015 /* List available unhidden CGI's and export as "other-cgis" */
2016 for (d = cgi_dispatchers; d->name; d++)
2018 if (d->description && strcmp(d->name, self))
2020 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2021 string_append(&result, d->name);
2022 string_append(&result, "\">");
2023 string_append(&result, d->description);
2024 string_append(&result, "</a></li>");
2032 /*********************************************************************
2034 * Function : dump_map
2036 * Description : HTML-dump a map for debugging (as table)
2039 * 1 : the_map = map to dump
2041 * Returns : string with HTML
2043 *********************************************************************/
2044 char *dump_map(const struct map *the_map)
2046 struct map_entry *cur_entry;
2047 char *ret = strdup("");
2049 string_append(&ret, "<table>\n");
2051 for (cur_entry = the_map->first;
2052 (cur_entry != NULL) && (ret != NULL);
2053 cur_entry = cur_entry->next)
2055 string_append(&ret, "<tr><td><b>");
2056 string_join (&ret, html_encode(cur_entry->name));
2057 string_append(&ret, "</b></td><td>");
2058 string_join (&ret, html_encode(cur_entry->value));
2059 string_append(&ret, "</td></tr>\n");
2062 string_append(&ret, "</table>\n");