1 const char cgi_rcs[] = "$Id: cgi.c,v 1.63 2002/04/15 19:06:43 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.63 2002/04/15 19:06:43 jongfoster
44 * Revision 1.62 2002/04/10 19:59:46 jongfoster
45 * Fixes to #include in templates:
46 * - Didn't close main file if loading an included template fails.
47 * - I'm paranoid and want to disallow "#include /etc/passwd".
49 * Revision 1.61 2002/04/10 13:37:48 oes
50 * Made templates modular: template_load now recursive with max depth 1
52 * Revision 1.60 2002/04/08 20:50:25 swa
55 * Revision 1.59 2002/04/05 15:51:51 oes
56 * - added send-stylesheet CGI
57 * - bugfix: error-pages now get correct request protocol
59 * - kludged CGI descriptions and menu not to break JS syntax
61 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
62 * Fix Mac OSX compiler warnings
64 * Revision 1.57 2002/03/26 22:29:54 swa
65 * we have a new homepage!
67 * Revision 1.56 2002/03/24 17:50:46 jongfoster
68 * Fixing compile error if actions file editor disabled
70 * Revision 1.55 2002/03/24 16:55:06 oes
71 * Making GIF checkerboard transparent
73 * Revision 1.54 2002/03/24 16:18:15 jongfoster
76 * Revision 1.53 2002/03/24 16:06:00 oes
77 * Correct transparency for checkerboard PNG. Thanks, Magnus!
79 * Revision 1.52 2002/03/24 15:23:33 jongfoster
82 * Revision 1.51 2002/03/24 13:25:43 swa
83 * name change related issues
85 * Revision 1.50 2002/03/16 23:54:06 jongfoster
86 * Adding graceful termination feature, to help look for memory leaks.
87 * If you enable this (which, by design, has to be done by hand
88 * editing config.h) and then go to http://i.j.b/die, then the program
89 * will exit cleanly after the *next* request. It should free all the
90 * memory that was used.
92 * Revision 1.49 2002/03/13 00:27:04 jongfoster
95 * Revision 1.48 2002/03/08 17:47:07 jongfoster
98 * Revision 1.47 2002/03/08 16:41:33 oes
99 * Added GIF images again
101 * Revision 1.46 2002/03/07 03:48:38 oes
102 * - Changed built-in images from GIF to PNG
103 * (with regard to Unisys patent issue)
104 * - Added a 4x4 pattern PNG which is less intrusive
105 * than the logo but also clearly marks the deleted banners
107 * Revision 1.45 2002/03/06 22:54:35 jongfoster
108 * Automated function-comment nitpicking.
110 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
111 * - Better error reporting on OS/2
112 * - Fix double-slash comment (oops)
114 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
115 * - Re-enable OS/2 building after new parms were added
116 * - Fix false out of memory report when resolving CGI templates when no IP
117 * address is available of failed attempt (a la no such domain)
119 * Revision 1.42 2002/01/21 00:33:20 jongfoster
120 * Replacing strsav() with the safer string_append() or string_join().
121 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
122 * Adding missing html_encode() to error message generators.
123 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
125 * Revision 1.41 2002/01/17 20:56:22 jongfoster
126 * Replacing hard references to the URL of the config interface
127 * with #defines from project.h
129 * Revision 1.40 2002/01/09 14:26:46 oes
130 * Added support for thread-safe gmtime_r call.
132 * Revision 1.39 2001/11/16 00:48:13 jongfoster
133 * Fixing a compiler warning
135 * Revision 1.38 2001/11/13 00:31:21 jongfoster
136 * - Adding new CGIs for use by non-JavaScript browsers:
137 * edit-actions-url-form
138 * edit-actions-add-url-form
139 * edit-actions-remove-url-form
140 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
143 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
144 * Show enablement/disablement status in almost all templates.
145 * There is a little trickiness here: apparent recursive resolution of
146 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
147 * the actual enablement status. So a similar construct,
148 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
151 * Revision 1.36 2001/10/26 17:33:27 oes
154 * Revision 1.35 2001/10/23 21:48:19 jongfoster
155 * Cleaning up error handling in CGI functions - they now send back
156 * a HTML error page and should never cause a FATAL error. (Fixes one
157 * potential source of "denial of service" attacks).
159 * CGI actions file editor that works and is actually useful.
161 * Ability to toggle Junkbuster remotely using a CGI call.
163 * You can turn off both the above features in the main configuration
164 * file, e.g. if you are running a multi-user proxy.
166 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
167 * Only show "Local support" on templates conditionally:
168 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
169 * - if not, no Local support section appears
171 * Revision 1.33 2001/10/14 22:28:41 jongfoster
172 * Fixing stupid typo.
174 * Revision 1.32 2001/10/14 22:20:18 jongfoster
175 * - Changes to CGI dispatching method to match CGI names exactly,
176 * rather than doing a prefix match.
177 * - No longer need to count the length of the CGI handler names by hand.
178 * - Adding new handler for 404 error when disptching a CGI, if none of
179 * the handlers match.
180 * - Adding new handlers for CGI actionsfile editor.
182 * Revision 1.31 2001/10/10 10:56:39 oes
183 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
185 * Revision 1.30 2001/10/02 15:30:57 oes
186 * Introduced show-request cgi
188 * Revision 1.29 2001/09/20 15:47:44 steudten
190 * Fix BUG: Modify int size to size_t size in fill_template()
191 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
193 * Revision 1.28 2001/09/19 18:00:37 oes
194 * - Deletef time() FIXME (Can't fail under Linux either, if
195 * the argument is guaranteed to be in out address space,
198 * - Pointer notation cosmetics
199 * - Fixed a minor bug in template_fill(): Failiure of
200 * pcrs_execute() now secure.
202 * Revision 1.27 2001/09/16 17:08:54 jongfoster
203 * Moving simple CGI functions from cgi.c to new file cgisimple.c
205 * Revision 1.26 2001/09/16 15:47:37 jongfoster
206 * First version of CGI-based edit interface. This is very much a
207 * work-in-progress, and you can't actually use it to edit anything
208 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
209 * to have any effect.
211 * Revision 1.25 2001/09/16 15:02:35 jongfoster
212 * Adding i.j.b/robots.txt.
213 * Inlining add_stats() since it's only ever called from one place.
215 * Revision 1.24 2001/09/16 11:38:01 jongfoster
216 * Splitting fill_template() into 2 functions:
217 * template_load() loads the file
218 * template_fill() performs the PCRS regexps.
219 * This is because the CGI edit interface has a "table row"
220 * template which is used many times in the page - this
221 * change means it's only loaded from disk once.
223 * Revision 1.23 2001/09/16 11:16:05 jongfoster
224 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
226 * Revision 1.22 2001/09/16 11:00:10 jongfoster
227 * New function alloc_http_response, for symmetry with free_http_response
229 * Revision 1.21 2001/09/13 23:53:03 jongfoster
230 * Support for both static and dynamically generated CGI pages.
231 * Correctly setting Last-Modified: and Expires: HTTP headers.
233 * Revision 1.20 2001/09/13 23:40:36 jongfoster
234 * (Cosmetic only) Indentation correction
236 * Revision 1.19 2001/09/13 23:31:25 jongfoster
237 * Moving image data to cgi.c rather than cgi.h.
239 * Revision 1.18 2001/08/05 16:06:20 jongfoster
240 * Modifiying "struct map" so that there are now separate header and
241 * "map_entry" structures. This means that functions which modify a
242 * map no longer need to return a pointer to the modified map.
243 * Also, it no longer reverses the order of the entries (which may be
244 * important with some advanced template substitutions).
246 * Revision 1.17 2001/08/05 15:57:38 oes
247 * Adapted finish_http_response to new list_to_text
249 * Revision 1.16 2001/08/01 21:33:18 jongfoster
250 * Changes to fill_template() that reduce memory usage without having
251 * an impact on performance. I also renamed some variables so as not
252 * to clash with the C++ keywords "new" and "template".
254 * Revision 1.15 2001/08/01 21:19:22 jongfoster
255 * Moving file version information to a separate CGI page.
257 * Revision 1.14 2001/08/01 00:19:03 jongfoster
258 * New function: map_conditional() for an if-then-else syntax.
259 * Changing to use new version of show_defines()
261 * Revision 1.13 2001/07/30 22:08:36 jongfoster
262 * Tidying up #defines:
263 * - All feature #defines are now of the form FEATURE_xxx
264 * - Permanently turned off WIN_GUI_EDIT
265 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
267 * Revision 1.12 2001/07/29 18:47:05 jongfoster
268 * Adding missing #include "loadcfg.h"
270 * Revision 1.11 2001/07/18 17:24:37 oes
271 * Changed to conform to new pcrs interface
273 * Revision 1.10 2001/07/13 13:53:13 oes
274 * Removed all #ifdef PCRS and related code
276 * Revision 1.9 2001/06/29 21:45:41 oes
277 * Indentation, CRLF->LF, Tab-> Space
279 * Revision 1.8 2001/06/29 13:21:46 oes
280 * - Cosmetics: renamed and reordered functions, variables,
281 * texts, improved comments etc
283 * - Removed ij_untrusted_url() The relevant
284 * info is now part of the "untrusted" page,
285 * which is generated by filters.c:trust_url()
287 * - Generators of content now call finish_http_response()
288 * themselves, making jcc.c:chat() a little less
291 * - Removed obsolete "Pragma: no-cache" from our headers
293 * - http_responses now know their head length
295 * - fill_template now uses the new interface to pcrs, so that
296 * - long jobs (like whole files) no longer have to be assembled
297 * in a fixed size buffer
298 * - the new T (trivial) option is used, and the replacement may
299 * contain Perl syntax backrefs without confusing pcrs
301 * - Introduced default_exports() which generates a set of exports
302 * common to all CGIs and other content generators
304 * - Introduced convenience function map_block_killer()
306 * - Introduced convenience function make_menu()
308 * - Introduced CGI-like function error_response() which generates
309 * the "No such domain" and "Connect failed" messages using the
312 * - cgi_show_url_info:
313 * - adapted to new CGI features
314 * - form and answers now generated from same template
315 * - http:// prefix in URL now OK
318 * - adapted to new CGI features
319 * - no longer uses csp->init_proxy_args
322 * - moved menu generation to make_menu()
324 * - add_stats now writes single export map entries instead
327 * - Moved redirect_url() to filters.c
329 * - Fixed mem leak in free_http_response(), map_block_killer(),
331 * - Removed logentry from cancelled commit
333 * Revision 1.7 2001/06/09 10:51:58 jongfoster
334 * Changing "show URL info" handler to new style.
335 * Changing BUFSIZ ==> BUFFER_SIZE
337 * Revision 1.6 2001/06/07 23:05:19 jongfoster
338 * Removing code related to old forward and ACL files.
340 * Revision 1.5 2001/06/05 19:59:16 jongfoster
341 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
343 * Revision 1.4 2001/06/04 10:41:52 swa
344 * show version string of cgi.h and cgi.c
346 * Revision 1.3 2001/06/03 19:12:16 oes
347 * introduced new cgi handling
349 * No revisions before 1.3
351 **********************************************************************/
357 #include <sys/types.h>
365 #define snprintf _snprintf
366 #endif /* def _WIN32 */
374 #include "miscutil.h"
375 #include "cgisimple.h"
376 #ifdef FEATURE_CGI_EDIT_ACTIONS
378 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
380 /* loadcfg.h is for g_bToggleIJB only */
382 const char cgi_h_rcs[] = CGI_H_VERSION;
385 * List of CGI functions: name, handler, description
386 * Note: Do NOT use single quotes in the description;
387 * this will break the dynamic "blocked" template!
389 static const struct cgi_dispatcher cgi_dispatchers[] = {
392 "Privoxy main page" },
393 #ifdef FEATURE_GRACEFUL_TERMINATION
396 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
397 "this is a one click Denial Of Service attack!!!</em>" },
401 "View & change the current configuration" },
404 "View the source code version numbers" },
407 "View the request headers." },
410 "Look up which actions apply to a URL and why" },
411 #ifdef FEATURE_CGI_EDIT_ACTIONS
414 "Toggle Privoxy on or off" },
416 { "edit-actions", /* Edit the actions list */
419 { "eaa", /* Shortcut for edit-actions-add-url-form */
420 cgi_edit_actions_add_url_form,
422 { "eau", /* Shortcut for edit-actions-url-form */
423 cgi_edit_actions_url_form,
425 { "ear", /* Shortcut for edit-actions-remove-url-form */
426 cgi_edit_actions_remove_url_form,
428 { "eafu", /* Shortcut for edit-actions-for-url */
429 cgi_edit_actions_for_url,
431 { "eas", /* Shortcut for edit-actions-submit */
432 cgi_edit_actions_submit,
434 { "easa", /* Shortcut for edit-actions-section-add */
435 cgi_edit_actions_section_add,
437 { "easr", /* Shortcut for edit-actions-section-remove */
438 cgi_edit_actions_section_remove,
440 { "eass", /* Shortcut for edit-actions-section-swap */
441 cgi_edit_actions_section_swap,
443 { "edit-actions-for-url",
444 cgi_edit_actions_for_url,
445 NULL /* Edit the actions for (a) specified URL(s) */ },
446 { "edit-actions-list",
447 cgi_edit_actions_list,
448 NULL /* Edit the actions list */ },
449 { "edit-actions-submit",
450 cgi_edit_actions_submit,
451 NULL /* Change the actions for (a) specified URL(s) */ },
452 { "edit-actions-url",
453 cgi_edit_actions_url,
454 NULL /* Change a URL pattern in the actionsfile */ },
455 { "edit-actions-url-form",
456 cgi_edit_actions_url_form,
457 NULL /* Form to change a URL pattern in the actionsfile */ },
458 { "edit-actions-add-url",
459 cgi_edit_actions_add_url,
460 NULL /* Add a URL pattern to the actionsfile */ },
461 { "edit-actions-add-url-form",
462 cgi_edit_actions_add_url_form,
463 NULL /* Form to add a URL pattern to the actionsfile */ },
464 { "edit-actions-remove-url",
465 cgi_edit_actions_remove_url,
466 NULL /* Remove a URL pattern from the actionsfile */ },
467 { "edit-actions-remove-url-form",
468 cgi_edit_actions_remove_url_form,
469 NULL /* Form to remove a URL pattern from the actionsfile */ },
470 { "edit-actions-section-add",
471 cgi_edit_actions_section_add,
472 NULL /* Remove a section from the actionsfile */ },
473 { "edit-actions-section-remove",
474 cgi_edit_actions_section_remove,
475 NULL /* Remove a section from the actionsfile */ },
476 { "edit-actions-section-swap",
477 cgi_edit_actions_section_swap,
478 NULL /* Swap two sections in the actionsfile */ },
479 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
482 NULL /* Sends a robots.txt file to tell robots to go away. */ },
485 NULL /* Send a built-in image */ },
488 NULL /* Send templates/cgi-style.css */ },
490 cgi_transparent_image,
491 NULL /* Send a transparent image (short name) */ },
492 { NULL, /* NULL Indicates end of list and default page */
494 NULL /* Unknown CGI page */ }
499 * Bulit-in images for ad replacement
501 * Hint: You can encode your own images like this:
502 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
505 #ifdef FEATURE_NO_GIFS
508 * Checkerboard pattern, as a PNG.
510 const char image_pattern_data[] =
511 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
512 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
513 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
514 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
515 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
516 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
517 "\000\000\000\111\105\116\104\256\102\140\202";
520 * 1x1 transparant PNG.
522 const char image_blank_data[] =
523 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
524 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
525 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
526 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
527 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
528 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
529 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
530 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
531 "\000\000\000\000\111\105\116\104\256\102\140\202";
535 * Checkerboard pattern, as a GIF.
537 const char image_pattern_data[] =
538 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
539 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
540 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
541 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
545 * 1x1 transparant GIF.
547 const char image_blank_data[] =
548 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
549 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
550 "\000\001\000\000\002\002D\001\000;";
553 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
554 const size_t image_blank_length = sizeof(image_blank_data) - 1;
557 static struct http_response cgi_error_memory_response[1];
559 static struct http_response *dispatch_known_cgi(struct client_state * csp,
561 static struct map *parse_cgi_parameters(char *argstring);
564 /*********************************************************************
566 * Function : dispatch_cgi
568 * Description : Checks if a request URL has either the magical
569 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
570 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
571 * http://ijbswa.sourceforge.net/config). If so, it passes
572 * the (rest of the) path onto dispatch_known_cgi, which
573 * calls the relevant CGI handler function.
576 * 1 : csp = Current client state (buffers, headers, etc...)
578 * Returns : http_response if match, NULL if nonmatch or handler fail
580 *********************************************************************/
581 struct http_response *dispatch_cgi(struct client_state *csp)
583 const char *host = csp->http->host;
584 const char *path = csp->http->path;
587 * Should we intercept ?
590 /* Note: "example.com" and "example.com." are equivalent hostnames. */
592 /* Either the host matches CGI_SITE_1_HOST ..*/
593 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
594 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
595 && (path[0] == '/') )
597 /* ..then the path will all be for us. Remove leading '/' */
600 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
601 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
602 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
603 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
605 /* take everything following CGI_SITE_2_PATH */
606 path += strlen(CGI_SITE_2_PATH);
609 /* skip the forward slash after CGI_SITE_2_PATH */
612 else if (*path != '\0')
615 * wierdness: URL is /configXXX, where XXX is some string
616 * Do *NOT* intercept.
628 * This is a CGI call.
631 return dispatch_known_cgi(csp, path);
635 /*********************************************************************
637 * Function : dispatch_known_cgi
639 * Description : Processes a CGI once dispatch_cgi has determined that
640 * it matches one of the magic prefixes. Parses the path
641 * as a cgi name plus query string, prepares a map that
642 * maps CGI parameter names to their values, initializes
643 * the http_response struct, and calls the relevant CGI
647 * 1 : csp = Current client state (buffers, headers, etc...)
648 * 2 : path = Path of CGI, with the CGI prefix removed.
649 * Should not have a leading "/".
651 * Returns : http_response, or NULL on handler failure or out of
654 *********************************************************************/
655 static struct http_response *dispatch_known_cgi(struct client_state * csp,
658 const struct cgi_dispatcher *d;
659 struct map *param_list;
660 struct http_response *rsp;
661 char *query_args_start;
665 if (NULL == (path_copy = strdup(path)))
667 return cgi_error_memory();
670 query_args_start = path_copy;
671 while (*query_args_start && *query_args_start != '?')
675 if (*query_args_start == '?')
677 *query_args_start++ = '\0';
680 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
683 return cgi_error_memory();
689 * path_copy = CGI call name
690 * param_list = CGI params, as map
693 /* Get mem for response or fail*/
694 if (NULL == (rsp = alloc_http_response()))
697 free_map(param_list);
698 return cgi_error_memory();
701 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
702 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
703 csp->ip_addr_str, csp->http->cmd);
705 /* Find and start the right CGI function*/
709 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
711 err = (d->handler)(csp, rsp, param_list);
713 free_map(param_list);
714 if (err == JB_ERR_CGI_PARAMS)
716 err = cgi_error_bad_param(csp, rsp);
721 return finish_http_response(rsp);
725 /* Error in handler, probably out-of-memory */
726 free_http_response(rsp);
727 return cgi_error_memory();
735 /*********************************************************************
737 * Function : parse_cgi_parameters
739 * Description : Parse a URL-encoded argument string into name/value
740 * pairs and store them in a struct map list.
743 * 1 : string = string to be parsed. Will be trashed.
745 * Returns : pointer to param list, or NULL if out of memory.
747 *********************************************************************/
748 static struct map *parse_cgi_parameters(char *argstring)
751 char *vector[BUFFER_SIZE];
753 struct map *cgi_params;
755 if (NULL == (cgi_params = new_map()))
760 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
762 for (i = 0; i < pairs; i++)
764 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
767 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
769 free_map(cgi_params);
780 /*********************************************************************
782 * Function : get_char_param
784 * Description : Get a single-character parameter passed to a CGI
788 * 1 : parameters = map of cgi parameters
789 * 2 : param_name = The name of the parameter to read
791 * Returns : Uppercase character on success, '\0' on error.
793 *********************************************************************/
794 char get_char_param(const struct map *parameters,
795 const char *param_name)
802 ch = *(lookup(parameters, param_name));
803 if ((ch >= 'a') && (ch <= 'z'))
812 /*********************************************************************
814 * Function : get_string_param
816 * Description : Get a string paramater, to be used as an
817 * ACTION_STRING or ACTION_MULTI paramater.
818 * Validates the input to prevent stupid/malicious
819 * users from corrupting their action file.
822 * 1 : parameters = map of cgi parameters
823 * 2 : param_name = The name of the parameter to read
824 * 3 : pparam = destination for paramater. Allocated as
825 * part of the map "parameters", so don't free it.
826 * Set to NULL if not specified.
828 * Returns : JB_ERR_OK on success, or if the paramater
830 * JB_ERR_MEMORY on out-of-memory.
831 * JB_ERR_CGI_PARAMS if the paramater is not valid.
833 *********************************************************************/
834 jb_err get_string_param(const struct map *parameters,
835 const char *param_name,
848 param = lookup(parameters, param_name);
854 if (strlen(param) >= CGI_PARAM_LEN_MAX)
859 * Note that the length limit is arbitrary, it just seems
860 * sensible to limit it to *something*. There's no
861 * technical reason for any limit at all.
863 return JB_ERR_CGI_PARAMS;
866 /* Check every character to see if it's legal */
868 while ((ch = *s++) != '\0')
870 if ( ((unsigned char)ch < (unsigned char)' ')
873 /* Probable hack attempt, or user accidentally used '}'. */
874 return JB_ERR_CGI_PARAMS;
885 /*********************************************************************
887 * Function : get_number_param
889 * Description : Get a non-negative integer from the parameters
890 * passed to a CGI function.
893 * 1 : csp = Current client state (buffers, headers, etc...)
894 * 2 : parameters = map of cgi parameters
895 * 3 : name = Name of CGI parameter to read
896 * 4 : pvalue = destination for value.
897 * Set to -1 on error.
899 * Returns : JB_ERR_OK on success
900 * JB_ERR_MEMORY on out-of-memory
901 * JB_ERR_CGI_PARAMS if the parameter was not specified
904 *********************************************************************/
905 jb_err get_number_param(struct client_state *csp,
906 const struct map *parameters,
921 param = lookup(parameters, name);
924 return JB_ERR_CGI_PARAMS;
927 /* We don't use atoi because I want to check this carefully... */
930 while ((ch = *param++) != '\0')
932 if ((ch < '0') || (ch > '9'))
934 return JB_ERR_CGI_PARAMS;
941 * <limits.h> defines UINT_MAX
943 * (UINT_MAX - ch) / 10 is the largest number that
944 * can be safely multiplied by 10 then have ch added.
946 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
948 return JB_ERR_CGI_PARAMS;
951 value = value * 10 + ch;
962 /*********************************************************************
964 * Function : error_response
966 * Description : returns an http_response that explains the reason
967 * why a request failed.
970 * 1 : csp = Current client state (buffers, headers, etc...)
971 * 2 : templatename = Which template should be used for the answer
972 * 3 : sys_err = system error number
974 * Returns : A http_response. If we run out of memory, this
975 * will be cgi_error_memory().
977 *********************************************************************/
978 struct http_response *error_response(struct client_state *csp,
979 const char *templatename,
983 struct http_response *rsp;
984 struct map * exports = default_exports(csp, NULL);
987 return cgi_error_memory();
990 if (NULL == (rsp = alloc_http_response()))
993 return cgi_error_memory();
996 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
997 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
998 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
999 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1000 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1003 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1006 /* Some failures, like "404 no such domain", don't have an IP address. */
1007 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1015 free_http_response(rsp);
1016 return cgi_error_memory();
1019 if (!strcmp(templatename, "no-such-domain"))
1021 rsp->status = strdup("404 No such domain");
1022 if (rsp->status == NULL)
1025 free_http_response(rsp);
1026 return cgi_error_memory();
1029 else if (!strcmp(templatename, "connect-failed"))
1031 rsp->status = strdup("503 Connect failed");
1032 if (rsp->status == NULL)
1035 free_http_response(rsp);
1036 return cgi_error_memory();
1040 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1043 free_http_response(rsp);
1044 return cgi_error_memory();
1047 return finish_http_response(rsp);
1051 /*********************************************************************
1053 * Function : cgi_init_error_messages
1055 * Description : Call at the start of the program to initialize
1056 * the error message used by cgi_error_memory().
1062 *********************************************************************/
1063 void cgi_init_error_messages(void)
1065 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1066 cgi_error_memory_response->head =
1067 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1068 "Content-Type: text/html\r\n"
1070 cgi_error_memory_response->body =
1072 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1074 "<h1>500 Internal Privoxy Error</h1>\r\n"
1075 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1076 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1080 cgi_error_memory_response->head_length =
1081 strlen(cgi_error_memory_response->head);
1082 cgi_error_memory_response->content_length =
1083 strlen(cgi_error_memory_response->body);
1087 /*********************************************************************
1089 * Function : cgi_error_memory
1091 * Description : Called if a CGI function runs out of memory.
1092 * Returns a statically-allocated error response.
1095 * 1 : csp = Current client state (buffers, headers, etc...)
1096 * 2 : rsp = http_response data structure for output
1097 * 3 : template_name = Name of template that could not
1100 * Returns : JB_ERR_OK on success
1101 * JB_ERR_MEMORY on out-of-memory error.
1103 *********************************************************************/
1104 struct http_response *cgi_error_memory(void)
1106 /* assert that it's been initialized. */
1107 assert(cgi_error_memory_response->head);
1109 return cgi_error_memory_response;
1113 /*********************************************************************
1115 * Function : cgi_error_no_template
1117 * Description : Almost-CGI function that is called if a templae
1118 * cannot be loaded. Note this is not a true CGI,
1119 * it takes a template name rather than a map of
1123 * 1 : csp = Current client state (buffers, headers, etc...)
1124 * 2 : rsp = http_response data structure for output
1125 * 3 : template_name = Name of template that could not
1128 * Returns : JB_ERR_OK on success
1129 * JB_ERR_MEMORY on out-of-memory error.
1131 *********************************************************************/
1132 jb_err cgi_error_no_template(struct client_state *csp,
1133 struct http_response *rsp,
1134 const char *template_name)
1136 static const char status[] =
1137 "500 Internal Privoxy Error";
1138 static const char body_prefix[] =
1140 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1142 "<h1>500 Internal Privoxy Error</h1>\r\n"
1143 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1144 "<p><b>Could not load template file <code>";
1145 static const char body_suffix[] =
1146 "</code> or one of it's included components.</b></p>\r\n"
1147 "<p>Please contact your proxy administrator.</p>\r\n"
1148 "<p>If you are the proxy administrator, please put the required file(s)"
1149 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1150 "location of the <code><i>(confdir)</i></code> directory "
1151 "is specified in the main Privoxy <code>config</code> "
1152 "file. (It's typically the Privoxy install directory"
1154 ", or <code>/etc/privoxy/</code>"
1155 #endif /* ndef _WIN32 */
1162 assert(template_name);
1164 /* Reset rsp, if needed */
1168 rsp->content_length = 0;
1169 rsp->head_length = 0;
1172 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1173 if (rsp->body == NULL)
1175 return JB_ERR_MEMORY;
1177 strcpy(rsp->body, body_prefix);
1178 strcat(rsp->body, template_name);
1179 strcat(rsp->body, body_suffix);
1181 rsp->status = strdup(status);
1182 if (rsp->body == NULL)
1184 return JB_ERR_MEMORY;
1191 /*********************************************************************
1193 * Function : cgi_error_bad_param
1195 * Description : CGI function that is called if the parameters
1196 * (query string) for a CGI were wrong.
1199 * 1 : csp = Current client state (buffers, headers, etc...)
1200 * 2 : rsp = http_response data structure for output
1202 * CGI Parameters : none
1204 * Returns : JB_ERR_OK on success
1205 * JB_ERR_MEMORY on out-of-memory error.
1207 *********************************************************************/
1208 jb_err cgi_error_bad_param(struct client_state *csp,
1209 struct http_response *rsp)
1211 struct map *exports;
1216 if (NULL == (exports = default_exports(csp, NULL)))
1218 return JB_ERR_MEMORY;
1221 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1225 /*********************************************************************
1227 * Function : get_http_time
1229 * Description : Get the time in a format suitable for use in a
1230 * HTTP header - e.g.:
1231 * "Sun, 06 Nov 1994 08:49:37 GMT"
1234 * 1 : time_offset = Time returned will be current time
1235 * plus this number of seconds.
1236 * 2 : buf = Destination for result. Must be long enough
1237 * to hold 29 characters plus a trailing zero.
1241 *********************************************************************/
1242 void get_http_time(int time_offset, char *buf)
1244 static const char day_names[7][4] =
1245 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1246 static const char month_names[12][4] =
1247 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1248 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1251 time_t current_time;
1255 time(¤t_time); /* get current time */
1257 current_time += time_offset;
1259 /* get and save the gmt */
1261 #ifdef HAVE_GMTIME_R
1263 t = gmtime_r(¤t_time, &dummy);
1265 t = gmtime(¤t_time);
1269 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1271 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1272 day_names[t->tm_wday],
1274 month_names[t->tm_mon],
1284 /*********************************************************************
1286 * Function : finish_http_response
1288 * Description : Fill in the missing headers in an http response,
1289 * and flatten the headers to an http head.
1292 * 1 : rsp = pointer to http_response to be processed
1294 * Returns : A http_response, usually the rsp parameter.
1295 * On error, free()s rsp and returns cgi_error_memory()
1297 *********************************************************************/
1298 struct http_response *finish_http_response(struct http_response *rsp)
1300 char buf[BUFFER_SIZE];
1303 /* Special case - do NOT change this statically allocated response,
1304 * which is ready for output anyway.
1306 if (rsp == cgi_error_memory_response)
1312 * Fill in the HTTP Status
1314 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1315 err = enlist_first(rsp->headers, buf);
1318 * Set the Content-Length
1320 if (rsp->content_length == 0)
1322 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1326 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1327 err = enlist(rsp->headers, buf);
1331 * Fill in the default headers:
1333 * Content-Type: default to text/html if not already specified.
1334 * Date: set to current date/time.
1335 * Last-Modified: set to date/time the page was last changed.
1336 * Expires: set to date/time page next needs reloading.
1337 * Cache-Control: set to "no-cache" if applicable.
1339 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1341 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1346 * Set Expires to about 10 min into the future so it'll get reloaded
1347 * occasionally, e.g. if Privoxy gets upgraded.
1352 get_http_time(0, buf);
1353 err = enlist_unique_header(rsp->headers, "Date", buf);
1356 /* Some date in the past. */
1357 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1361 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1362 err = enlist_unique_header(rsp->headers, "Expires", buf);
1368 * Compliant browsers should not cache this due to the "Cache-Control"
1369 * setting. However, to be certain, we also set both "Last-Modified"
1370 * and "Expires" to the current time.
1372 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1374 get_http_time(0, buf);
1375 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1376 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1377 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1384 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1386 free_http_response(rsp);
1387 return cgi_error_memory();
1389 rsp->head_length = strlen(rsp->head);
1396 /*********************************************************************
1398 * Function : alloc_http_response
1400 * Description : Allocates a new http_response structure.
1404 * Returns : pointer to a new http_response, or NULL.
1406 *********************************************************************/
1407 struct http_response *alloc_http_response(void)
1409 return (struct http_response *) zalloc(sizeof(struct http_response));
1414 /*********************************************************************
1416 * Function : free_http_response
1418 * Description : Free the memory occupied by an http_response
1419 * and its depandant structures.
1422 * 1 : rsp = pointer to http_response to be freed
1426 *********************************************************************/
1427 void free_http_response(struct http_response *rsp)
1430 * Must special case cgi_error_memory_response, which is never freed.
1432 if (rsp && (rsp != cgi_error_memory_response))
1437 destroy_list(rsp->headers);
1444 /*********************************************************************
1446 * Function : template_load
1448 * Description : CGI support function that loads a given HTML
1449 * template from the confdir, ignoring comment
1450 * lines and following #include statements up to
1454 * 1 : csp = Current client state (buffers, headers, etc...)
1455 * 2 : template_ptr = Destination for pointer to loaded
1457 * 3 : template = name of the HTML template to be used
1458 * 4 : recursive = Flag set if this function calls itself
1459 * following an #include statament
1461 * Returns : JB_ERR_OK on success
1462 * JB_ERR_MEMORY on out-of-memory error.
1463 * JB_ERR_FILE if the template file cannot be read
1465 *********************************************************************/
1466 jb_err template_load(struct client_state *csp, char **template_ptr,
1467 const char *templatename, int recursive)
1470 char *templates_dir_path;
1473 char *included_module;
1476 char buf[BUFFER_SIZE];
1479 assert(template_ptr);
1480 assert(templatename);
1482 *template_ptr = NULL;
1484 /* Validate template name. Paranoia. */
1485 for (p = templatename; *p != 0; p++)
1487 if ( ((*p < 'a') || (*p > 'z'))
1488 && ((*p < 'A') || (*p > 'Z'))
1489 && ((*p < '0') || (*p > '9'))
1493 /* Illegal character */
1498 /* Generate full path */
1500 templates_dir_path = make_path(csp->config->confdir, "templates");
1501 if (templates_dir_path == NULL)
1503 return JB_ERR_MEMORY;
1506 full_path = make_path(templates_dir_path, templatename);
1507 free(templates_dir_path);
1508 if (full_path == NULL)
1510 return JB_ERR_MEMORY;
1513 /* Allocate buffer */
1515 file_buffer = strdup("");
1516 if (file_buffer == NULL)
1519 return JB_ERR_MEMORY;
1522 /* Open template file */
1524 if (NULL == (fp = fopen(full_path, "r")))
1526 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1534 * Read the file, ignoring comments, and honoring #include
1535 * statements, unless we're already called recursively.
1537 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1538 * This is unlikely in practise.
1540 while (fgets(buf, BUFFER_SIZE, fp))
1542 if (!recursive && !strncmp(buf, "#include ", 9))
1544 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1551 if (string_join(&file_buffer, included_module))
1554 return JB_ERR_MEMORY;
1560 /* skip lines starting with '#' */
1566 if (string_append(&file_buffer, buf))
1569 return JB_ERR_MEMORY;
1574 *template_ptr = file_buffer;
1580 /*********************************************************************
1582 * Function : template_fill
1584 * Description : CGI support function that fills in a pre-loaded
1585 * HTML template by replacing @name@ with value using
1586 * pcrs, for each item in the output map.
1588 * Note that a leading '$' charachter in the export map's
1589 * values will be stripped and toggle on backreference
1593 * 1 : template_ptr = IN: Template to be filled out.
1595 * OUT: Filled out template.
1596 * Caller must free().
1597 * 2 : exports = map with fill in symbol -> name pairs
1599 * Returns : JB_ERR_OK on success
1600 * JB_ERR_MEMORY on out-of-memory error
1602 *********************************************************************/
1603 jb_err template_fill(char **template_ptr, const struct map *exports)
1605 struct map_entry *m;
1607 char buf[BUFFER_SIZE];
1608 char *tmp_out_buffer;
1614 assert(template_ptr);
1615 assert(*template_ptr);
1618 file_buffer = *template_ptr;
1619 size = strlen(file_buffer) + 1;
1622 * Assemble pcrs joblist from exports map
1624 for (m = exports->first; m != NULL; m = m->next)
1626 if (*m->name == '$')
1629 * First character of name is '$', so remove this flag
1630 * character and allow backreferences ($1 etc) in the
1631 * "replace with" text.
1633 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1639 * Treat the "replace with" text as a literal string -
1640 * no quoting needed, no backreferences allowed.
1641 * ("Trivial" ['T'] flag).
1645 /* Enclose name in @@ */
1646 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1650 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1652 /* Make and run job. */
1653 job = pcrs_compile(buf, m->value, flags, &error);
1656 if (error == PCRS_ERR_NOMEM)
1659 *template_ptr = NULL;
1660 return JB_ERR_MEMORY;
1664 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1665 /* Hope it wasn't important and silently ignore the invalid job */
1670 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1673 if (NULL == tmp_out_buffer)
1675 *template_ptr = NULL;
1676 return JB_ERR_MEMORY;
1678 file_buffer = tmp_out_buffer;
1685 *template_ptr = file_buffer;
1690 /*********************************************************************
1692 * Function : template_fill_for_cgi
1694 * Description : CGI support function that loads a HTML template
1695 * and fills it in. Handles file-not-found errors
1696 * by sending a HTML error message. For convenience,
1697 * this function also frees the passed "exports" map.
1700 * 1 : csp = Client state
1701 * 2 : templatename = name of the HTML template to be used
1702 * 3 : exports = map with fill in symbol -> name pairs.
1703 * Will be freed by this function.
1705 * Returns : JB_ERR_OK on success
1706 * JB_ERR_MEMORY on out-of-memory error
1708 *********************************************************************/
1709 jb_err template_fill_for_cgi(struct client_state *csp,
1710 const char *templatename,
1711 struct map *exports,
1712 struct http_response *rsp)
1717 assert(templatename);
1721 err = template_load(csp, &rsp->body, templatename, 0);
1722 if (err == JB_ERR_FILE)
1725 return cgi_error_no_template(csp, rsp, templatename);
1730 return err; /* JB_ERR_MEMORY */
1732 err = template_fill(&rsp->body, exports);
1738 /*********************************************************************
1740 * Function : default_exports
1742 * Description : returns a struct map list that contains exports
1743 * which are common to all CGI functions.
1746 * 1 : csp = Current client state (buffers, headers, etc...)
1747 * 2 : caller = name of CGI who calls us and which should
1748 * be excluded from the generated menu. May be
1750 * Returns : NULL if no memory, else a new map. Caller frees.
1752 *********************************************************************/
1753 struct map *default_exports(const struct client_state *csp, const char *caller)
1757 struct map * exports;
1758 int local_help_exists = 0;
1762 exports = new_map();
1763 if (exports == NULL)
1768 err = map(exports, "version", 1, html_encode(VERSION), 0);
1769 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1770 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1771 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1772 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1773 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1774 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1775 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1777 snprintf(buf, 20, "%d", csp->config->hport);
1778 if (!err) err = map(exports, "my-port", 1, buf, 1);
1780 if(!strcmp(CODE_STATUS, "stable"))
1782 if (!err) err = map_block_killer(exports, "unstable");
1785 if (csp->config->admin_address != NULL)
1787 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1788 local_help_exists = 1;
1792 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1795 if (csp->config->proxy_info_url != NULL)
1797 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1798 local_help_exists = 1;
1802 if (!err) err = map_block_killer(exports, "have-proxy-info");
1805 if (local_help_exists == 0)
1807 if (!err) err = map_block_killer(exports, "have-help-info");
1820 /*********************************************************************
1822 * Function : map_block_killer
1824 * Description : Convenience function.
1825 * Adds a "killer" for the conditional HTML-template
1826 * block <name>, i.e. a substitution of the regex
1827 * "if-<name>-start.*if-<name>-end" to the given
1831 * 1 : exports = map to extend
1832 * 2 : name = name of conditional block
1834 * Returns : JB_ERR_OK on success
1835 * JB_ERR_MEMORY on out-of-memory error.
1837 *********************************************************************/
1838 jb_err map_block_killer(struct map *exports, const char *name)
1840 char buf[1000]; /* Will do, since the names are hardwired */
1844 assert(strlen(name) < 490);
1846 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1847 return map(exports, buf, 1, "", 1);
1851 /*********************************************************************
1853 * Function : map_block_keep
1855 * Description : Convenience function. Removes the markers used
1856 * by map-block-killer, to save a few bytes.
1857 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1860 * 1 : exports = map to extend
1861 * 2 : name = name of conditional block
1863 * Returns : JB_ERR_OK on success
1864 * JB_ERR_MEMORY on out-of-memory error.
1866 *********************************************************************/
1867 jb_err map_block_keep(struct map *exports, const char *name)
1870 char buf[500]; /* Will do, since the names are hardwired */
1874 assert(strlen(name) < 490);
1876 snprintf(buf, 500, "if-%s-start", name);
1877 err = map(exports, buf, 1, "", 1);
1884 snprintf(buf, 500, "if-%s-end", name);
1885 return map(exports, buf, 1, "", 1);
1889 /*********************************************************************
1891 * Function : map_conditional
1893 * Description : Convenience function.
1894 * Adds an "if-then-else" for the conditional HTML-template
1895 * block <name>, i.e. a substitution of the form:
1902 * The control structure and one of the alternatives
1906 * 1 : exports = map to extend
1907 * 2 : name = name of conditional block
1908 * 3 : choose_first = nonzero for first, zero for second.
1910 * Returns : JB_ERR_OK on success
1911 * JB_ERR_MEMORY on out-of-memory error.
1913 *********************************************************************/
1914 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1916 char buf[1000]; /* Will do, since the names are hardwired */
1921 assert(strlen(name) < 480);
1923 snprintf(buf, 1000, (choose_first
1924 ? "else-not-%s@.*@endif-%s"
1925 : "if-%s-then@.*@else-not-%s"),
1928 err = map(exports, buf, 1, "", 1);
1934 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1935 return map(exports, buf, 1, "", 1);
1939 /*********************************************************************
1941 * Function : make_menu
1943 * Description : Returns an HTML-formatted menu of the available
1944 * unhidden CGIs, excluding the one given in <self>.
1946 * Parameters : self = name of CGI to leave out, can be NULL
1948 * Returns : menu string, or NULL on out-of-memory error.
1950 *********************************************************************/
1951 char *make_menu(const char *self)
1953 const struct cgi_dispatcher *d;
1954 char *result = strdup("");
1958 self = "NO-SUCH-CGI!";
1961 /* List available unhidden CGI's and export as "other-cgis" */
1962 for (d = cgi_dispatchers; d->name; d++)
1964 if (d->description && strcmp(d->name, self))
1966 string_append(&result, "<li><a href=\"" CGI_PREFIX);
1967 string_append(&result, d->name);
1968 string_append(&result, "\">");
1969 string_append(&result, d->description);
1970 string_append(&result, "</a></li>");
1978 /*********************************************************************
1980 * Function : dump_map
1982 * Description : HTML-dump a map for debugging
1985 * 1 : the_map = map to dump
1987 * Returns : string with HTML
1989 *********************************************************************/
1990 char *dump_map(const struct map *the_map)
1992 struct map_entry *cur_entry;
1993 char *ret = strdup("");
1995 string_append(&ret, "<table>\n");
1997 for (cur_entry = the_map->first;
1998 (cur_entry != NULL) && (ret != NULL);
1999 cur_entry = cur_entry->next)
2001 string_append(&ret, "<tr><td><b>");
2002 string_join (&ret, html_encode(cur_entry->name));
2003 string_append(&ret, "</b></td><td>");
2004 string_join (&ret, html_encode(cur_entry->value));
2005 string_append(&ret, "</td></tr>\n");
2008 string_append(&ret, "</table>\n");