1 const char cgi_rcs[] = "$Id: cgi.c,v 1.65 2002/04/26 12:53:51 oes 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.65 2002/04/26 12:53:51 oes
42 * - New function add_help_link
43 * - default_exports now exports links to the user manual
44 * and a prefix for links into the config chapter
46 * Revision 1.64 2002/04/24 02:17:21 oes
47 * - Better descriptions for CGIs
48 * - Hide edit-actions, more shortcuts
49 * - Moved get_char_param, get_string_param and get_number_param here
52 * Revision 1.63 2002/04/15 19:06:43 jongfoster
55 * Revision 1.62 2002/04/10 19:59:46 jongfoster
56 * Fixes to #include in templates:
57 * - Didn't close main file if loading an included template fails.
58 * - I'm paranoid and want to disallow "#include /etc/passwd".
60 * Revision 1.61 2002/04/10 13:37:48 oes
61 * Made templates modular: template_load now recursive with max depth 1
63 * Revision 1.60 2002/04/08 20:50:25 swa
66 * Revision 1.59 2002/04/05 15:51:51 oes
67 * - added send-stylesheet CGI
68 * - bugfix: error-pages now get correct request protocol
70 * - kludged CGI descriptions and menu not to break JS syntax
72 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
73 * Fix Mac OSX compiler warnings
75 * Revision 1.57 2002/03/26 22:29:54 swa
76 * we have a new homepage!
78 * Revision 1.56 2002/03/24 17:50:46 jongfoster
79 * Fixing compile error if actions file editor disabled
81 * Revision 1.55 2002/03/24 16:55:06 oes
82 * Making GIF checkerboard transparent
84 * Revision 1.54 2002/03/24 16:18:15 jongfoster
87 * Revision 1.53 2002/03/24 16:06:00 oes
88 * Correct transparency for checkerboard PNG. Thanks, Magnus!
90 * Revision 1.52 2002/03/24 15:23:33 jongfoster
93 * Revision 1.51 2002/03/24 13:25:43 swa
94 * name change related issues
96 * Revision 1.50 2002/03/16 23:54:06 jongfoster
97 * Adding graceful termination feature, to help look for memory leaks.
98 * If you enable this (which, by design, has to be done by hand
99 * editing config.h) and then go to http://i.j.b/die, then the program
100 * will exit cleanly after the *next* request. It should free all the
101 * memory that was used.
103 * Revision 1.49 2002/03/13 00:27:04 jongfoster
106 * Revision 1.48 2002/03/08 17:47:07 jongfoster
109 * Revision 1.47 2002/03/08 16:41:33 oes
110 * Added GIF images again
112 * Revision 1.46 2002/03/07 03:48:38 oes
113 * - Changed built-in images from GIF to PNG
114 * (with regard to Unisys patent issue)
115 * - Added a 4x4 pattern PNG which is less intrusive
116 * than the logo but also clearly marks the deleted banners
118 * Revision 1.45 2002/03/06 22:54:35 jongfoster
119 * Automated function-comment nitpicking.
121 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
122 * - Better error reporting on OS/2
123 * - Fix double-slash comment (oops)
125 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
126 * - Re-enable OS/2 building after new parms were added
127 * - Fix false out of memory report when resolving CGI templates when no IP
128 * address is available of failed attempt (a la no such domain)
130 * Revision 1.42 2002/01/21 00:33:20 jongfoster
131 * Replacing strsav() with the safer string_append() or string_join().
132 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
133 * Adding missing html_encode() to error message generators.
134 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
136 * Revision 1.41 2002/01/17 20:56:22 jongfoster
137 * Replacing hard references to the URL of the config interface
138 * with #defines from project.h
140 * Revision 1.40 2002/01/09 14:26:46 oes
141 * Added support for thread-safe gmtime_r call.
143 * Revision 1.39 2001/11/16 00:48:13 jongfoster
144 * Fixing a compiler warning
146 * Revision 1.38 2001/11/13 00:31:21 jongfoster
147 * - Adding new CGIs for use by non-JavaScript browsers:
148 * edit-actions-url-form
149 * edit-actions-add-url-form
150 * edit-actions-remove-url-form
151 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
154 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
155 * Show enablement/disablement status in almost all templates.
156 * There is a little trickiness here: apparent recursive resolution of
157 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
158 * the actual enablement status. So a similar construct,
159 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
162 * Revision 1.36 2001/10/26 17:33:27 oes
165 * Revision 1.35 2001/10/23 21:48:19 jongfoster
166 * Cleaning up error handling in CGI functions - they now send back
167 * a HTML error page and should never cause a FATAL error. (Fixes one
168 * potential source of "denial of service" attacks).
170 * CGI actions file editor that works and is actually useful.
172 * Ability to toggle Junkbuster remotely using a CGI call.
174 * You can turn off both the above features in the main configuration
175 * file, e.g. if you are running a multi-user proxy.
177 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
178 * Only show "Local support" on templates conditionally:
179 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
180 * - if not, no Local support section appears
182 * Revision 1.33 2001/10/14 22:28:41 jongfoster
183 * Fixing stupid typo.
185 * Revision 1.32 2001/10/14 22:20:18 jongfoster
186 * - Changes to CGI dispatching method to match CGI names exactly,
187 * rather than doing a prefix match.
188 * - No longer need to count the length of the CGI handler names by hand.
189 * - Adding new handler for 404 error when disptching a CGI, if none of
190 * the handlers match.
191 * - Adding new handlers for CGI actionsfile editor.
193 * Revision 1.31 2001/10/10 10:56:39 oes
194 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
196 * Revision 1.30 2001/10/02 15:30:57 oes
197 * Introduced show-request cgi
199 * Revision 1.29 2001/09/20 15:47:44 steudten
201 * Fix BUG: Modify int size to size_t size in fill_template()
202 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
204 * Revision 1.28 2001/09/19 18:00:37 oes
205 * - Deletef time() FIXME (Can't fail under Linux either, if
206 * the argument is guaranteed to be in out address space,
209 * - Pointer notation cosmetics
210 * - Fixed a minor bug in template_fill(): Failiure of
211 * pcrs_execute() now secure.
213 * Revision 1.27 2001/09/16 17:08:54 jongfoster
214 * Moving simple CGI functions from cgi.c to new file cgisimple.c
216 * Revision 1.26 2001/09/16 15:47:37 jongfoster
217 * First version of CGI-based edit interface. This is very much a
218 * work-in-progress, and you can't actually use it to edit anything
219 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
220 * to have any effect.
222 * Revision 1.25 2001/09/16 15:02:35 jongfoster
223 * Adding i.j.b/robots.txt.
224 * Inlining add_stats() since it's only ever called from one place.
226 * Revision 1.24 2001/09/16 11:38:01 jongfoster
227 * Splitting fill_template() into 2 functions:
228 * template_load() loads the file
229 * template_fill() performs the PCRS regexps.
230 * This is because the CGI edit interface has a "table row"
231 * template which is used many times in the page - this
232 * change means it's only loaded from disk once.
234 * Revision 1.23 2001/09/16 11:16:05 jongfoster
235 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
237 * Revision 1.22 2001/09/16 11:00:10 jongfoster
238 * New function alloc_http_response, for symmetry with free_http_response
240 * Revision 1.21 2001/09/13 23:53:03 jongfoster
241 * Support for both static and dynamically generated CGI pages.
242 * Correctly setting Last-Modified: and Expires: HTTP headers.
244 * Revision 1.20 2001/09/13 23:40:36 jongfoster
245 * (Cosmetic only) Indentation correction
247 * Revision 1.19 2001/09/13 23:31:25 jongfoster
248 * Moving image data to cgi.c rather than cgi.h.
250 * Revision 1.18 2001/08/05 16:06:20 jongfoster
251 * Modifiying "struct map" so that there are now separate header and
252 * "map_entry" structures. This means that functions which modify a
253 * map no longer need to return a pointer to the modified map.
254 * Also, it no longer reverses the order of the entries (which may be
255 * important with some advanced template substitutions).
257 * Revision 1.17 2001/08/05 15:57:38 oes
258 * Adapted finish_http_response to new list_to_text
260 * Revision 1.16 2001/08/01 21:33:18 jongfoster
261 * Changes to fill_template() that reduce memory usage without having
262 * an impact on performance. I also renamed some variables so as not
263 * to clash with the C++ keywords "new" and "template".
265 * Revision 1.15 2001/08/01 21:19:22 jongfoster
266 * Moving file version information to a separate CGI page.
268 * Revision 1.14 2001/08/01 00:19:03 jongfoster
269 * New function: map_conditional() for an if-then-else syntax.
270 * Changing to use new version of show_defines()
272 * Revision 1.13 2001/07/30 22:08:36 jongfoster
273 * Tidying up #defines:
274 * - All feature #defines are now of the form FEATURE_xxx
275 * - Permanently turned off WIN_GUI_EDIT
276 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
278 * Revision 1.12 2001/07/29 18:47:05 jongfoster
279 * Adding missing #include "loadcfg.h"
281 * Revision 1.11 2001/07/18 17:24:37 oes
282 * Changed to conform to new pcrs interface
284 * Revision 1.10 2001/07/13 13:53:13 oes
285 * Removed all #ifdef PCRS and related code
287 * Revision 1.9 2001/06/29 21:45:41 oes
288 * Indentation, CRLF->LF, Tab-> Space
290 * Revision 1.8 2001/06/29 13:21:46 oes
291 * - Cosmetics: renamed and reordered functions, variables,
292 * texts, improved comments etc
294 * - Removed ij_untrusted_url() The relevant
295 * info is now part of the "untrusted" page,
296 * which is generated by filters.c:trust_url()
298 * - Generators of content now call finish_http_response()
299 * themselves, making jcc.c:chat() a little less
302 * - Removed obsolete "Pragma: no-cache" from our headers
304 * - http_responses now know their head length
306 * - fill_template now uses the new interface to pcrs, so that
307 * - long jobs (like whole files) no longer have to be assembled
308 * in a fixed size buffer
309 * - the new T (trivial) option is used, and the replacement may
310 * contain Perl syntax backrefs without confusing pcrs
312 * - Introduced default_exports() which generates a set of exports
313 * common to all CGIs and other content generators
315 * - Introduced convenience function map_block_killer()
317 * - Introduced convenience function make_menu()
319 * - Introduced CGI-like function error_response() which generates
320 * the "No such domain" and "Connect failed" messages using the
323 * - cgi_show_url_info:
324 * - adapted to new CGI features
325 * - form and answers now generated from same template
326 * - http:// prefix in URL now OK
329 * - adapted to new CGI features
330 * - no longer uses csp->init_proxy_args
333 * - moved menu generation to make_menu()
335 * - add_stats now writes single export map entries instead
338 * - Moved redirect_url() to filters.c
340 * - Fixed mem leak in free_http_response(), map_block_killer(),
342 * - Removed logentry from cancelled commit
344 * Revision 1.7 2001/06/09 10:51:58 jongfoster
345 * Changing "show URL info" handler to new style.
346 * Changing BUFSIZ ==> BUFFER_SIZE
348 * Revision 1.6 2001/06/07 23:05:19 jongfoster
349 * Removing code related to old forward and ACL files.
351 * Revision 1.5 2001/06/05 19:59:16 jongfoster
352 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
354 * Revision 1.4 2001/06/04 10:41:52 swa
355 * show version string of cgi.h and cgi.c
357 * Revision 1.3 2001/06/03 19:12:16 oes
358 * introduced new cgi handling
360 * No revisions before 1.3
362 **********************************************************************/
368 #include <sys/types.h>
376 #define snprintf _snprintf
377 #endif /* def _WIN32 */
385 #include "miscutil.h"
386 #include "cgisimple.h"
387 #ifdef FEATURE_CGI_EDIT_ACTIONS
389 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
391 /* loadcfg.h is for g_bToggleIJB only */
393 const char cgi_h_rcs[] = CGI_H_VERSION;
396 * List of CGI functions: name, handler, description
397 * Note: Do NOT use single quotes in the description;
398 * this will break the dynamic "blocked" template!
400 static const struct cgi_dispatcher cgi_dispatchers[] = {
403 "Privoxy main page" },
404 #ifdef FEATURE_GRACEFUL_TERMINATION
407 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
408 "this is a one click Denial Of Service attack!!!</em>" },
412 "View & change the current configuration" },
415 "View the source code version numbers" },
418 "View the request headers." },
421 "Look up which actions apply to a URL and why" },
422 #ifdef FEATURE_CGI_EDIT_ACTIONS
425 "Toggle Privoxy on or off" },
427 { "edit-actions", /* Edit the actions list */
430 { "eaa", /* Shortcut for edit-actions-add-url-form */
431 cgi_edit_actions_add_url_form,
433 { "eau", /* Shortcut for edit-actions-url-form */
434 cgi_edit_actions_url_form,
436 { "ear", /* Shortcut for edit-actions-remove-url-form */
437 cgi_edit_actions_remove_url_form,
439 { "eafu", /* Shortcut for edit-actions-for-url */
440 cgi_edit_actions_for_url,
442 { "eas", /* Shortcut for edit-actions-submit */
443 cgi_edit_actions_submit,
445 { "easa", /* Shortcut for edit-actions-section-add */
446 cgi_edit_actions_section_add,
448 { "easr", /* Shortcut for edit-actions-section-remove */
449 cgi_edit_actions_section_remove,
451 { "eass", /* Shortcut for edit-actions-section-swap */
452 cgi_edit_actions_section_swap,
454 { "edit-actions-for-url",
455 cgi_edit_actions_for_url,
456 NULL /* Edit the actions for (a) specified URL(s) */ },
457 { "edit-actions-list",
458 cgi_edit_actions_list,
459 NULL /* Edit the actions list */ },
460 { "edit-actions-submit",
461 cgi_edit_actions_submit,
462 NULL /* Change the actions for (a) specified URL(s) */ },
463 { "edit-actions-url",
464 cgi_edit_actions_url,
465 NULL /* Change a URL pattern in the actionsfile */ },
466 { "edit-actions-url-form",
467 cgi_edit_actions_url_form,
468 NULL /* Form to change a URL pattern in the actionsfile */ },
469 { "edit-actions-add-url",
470 cgi_edit_actions_add_url,
471 NULL /* Add a URL pattern to the actionsfile */ },
472 { "edit-actions-add-url-form",
473 cgi_edit_actions_add_url_form,
474 NULL /* Form to add a URL pattern to the actionsfile */ },
475 { "edit-actions-remove-url",
476 cgi_edit_actions_remove_url,
477 NULL /* Remove a URL pattern from the actionsfile */ },
478 { "edit-actions-remove-url-form",
479 cgi_edit_actions_remove_url_form,
480 NULL /* Form to remove a URL pattern from the actionsfile */ },
481 { "edit-actions-section-add",
482 cgi_edit_actions_section_add,
483 NULL /* Remove a section from the actionsfile */ },
484 { "edit-actions-section-remove",
485 cgi_edit_actions_section_remove,
486 NULL /* Remove a section from the actionsfile */ },
487 { "edit-actions-section-swap",
488 cgi_edit_actions_section_swap,
489 NULL /* Swap two sections in the actionsfile */ },
490 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
493 NULL /* Sends a robots.txt file to tell robots to go away. */ },
496 NULL /* Send a built-in image */ },
499 NULL /* Send templates/cgi-style.css */ },
501 cgi_transparent_image,
502 NULL /* Send a transparent image (short name) */ },
503 { NULL, /* NULL Indicates end of list and default page */
505 NULL /* Unknown CGI page */ }
510 * Bulit-in images for ad replacement
512 * Hint: You can encode your own images like this:
513 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
516 #ifdef FEATURE_NO_GIFS
519 * Checkerboard pattern, as a PNG.
521 const char image_pattern_data[] =
522 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
523 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
524 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
525 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
526 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
527 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
528 "\000\000\000\111\105\116\104\256\102\140\202";
531 * 1x1 transparant PNG.
533 const char image_blank_data[] =
534 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
535 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
536 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
537 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
538 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
539 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
540 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
541 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
542 "\000\000\000\000\111\105\116\104\256\102\140\202";
546 * Checkerboard pattern, as a GIF.
548 const char image_pattern_data[] =
549 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
550 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
551 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
552 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
556 * 1x1 transparant GIF.
558 const char image_blank_data[] =
559 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
560 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
561 "\000\001\000\000\002\002D\001\000;";
564 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
565 const size_t image_blank_length = sizeof(image_blank_data) - 1;
568 static struct http_response cgi_error_memory_response[1];
570 static struct http_response *dispatch_known_cgi(struct client_state * csp,
572 static struct map *parse_cgi_parameters(char *argstring);
575 /*********************************************************************
577 * Function : dispatch_cgi
579 * Description : Checks if a request URL has either the magical
580 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
581 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
582 * http://ijbswa.sourceforge.net/config). If so, it passes
583 * the (rest of the) path onto dispatch_known_cgi, which
584 * calls the relevant CGI handler function.
587 * 1 : csp = Current client state (buffers, headers, etc...)
589 * Returns : http_response if match, NULL if nonmatch or handler fail
591 *********************************************************************/
592 struct http_response *dispatch_cgi(struct client_state *csp)
594 const char *host = csp->http->host;
595 const char *path = csp->http->path;
598 * Should we intercept ?
601 /* Note: "example.com" and "example.com." are equivalent hostnames. */
603 /* Either the host matches CGI_SITE_1_HOST ..*/
604 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
605 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
606 && (path[0] == '/') )
608 /* ..then the path will all be for us. Remove leading '/' */
611 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
612 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
613 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
614 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
616 /* take everything following CGI_SITE_2_PATH */
617 path += strlen(CGI_SITE_2_PATH);
620 /* skip the forward slash after CGI_SITE_2_PATH */
623 else if (*path != '\0')
626 * wierdness: URL is /configXXX, where XXX is some string
627 * Do *NOT* intercept.
639 * This is a CGI call.
642 return dispatch_known_cgi(csp, path);
646 /*********************************************************************
648 * Function : dispatch_known_cgi
650 * Description : Processes a CGI once dispatch_cgi has determined that
651 * it matches one of the magic prefixes. Parses the path
652 * as a cgi name plus query string, prepares a map that
653 * maps CGI parameter names to their values, initializes
654 * the http_response struct, and calls the relevant CGI
658 * 1 : csp = Current client state (buffers, headers, etc...)
659 * 2 : path = Path of CGI, with the CGI prefix removed.
660 * Should not have a leading "/".
662 * Returns : http_response, or NULL on handler failure or out of
665 *********************************************************************/
666 static struct http_response *dispatch_known_cgi(struct client_state * csp,
669 const struct cgi_dispatcher *d;
670 struct map *param_list;
671 struct http_response *rsp;
672 char *query_args_start;
676 if (NULL == (path_copy = strdup(path)))
678 return cgi_error_memory();
681 query_args_start = path_copy;
682 while (*query_args_start && *query_args_start != '?')
686 if (*query_args_start == '?')
688 *query_args_start++ = '\0';
691 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
694 return cgi_error_memory();
700 * path_copy = CGI call name
701 * param_list = CGI params, as map
704 /* Get mem for response or fail*/
705 if (NULL == (rsp = alloc_http_response()))
708 free_map(param_list);
709 return cgi_error_memory();
712 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
713 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
714 csp->ip_addr_str, csp->http->cmd);
716 /* Find and start the right CGI function*/
720 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
722 err = (d->handler)(csp, rsp, param_list);
724 free_map(param_list);
725 if (err == JB_ERR_CGI_PARAMS)
727 err = cgi_error_bad_param(csp, rsp);
732 return finish_http_response(rsp);
736 /* Error in handler, probably out-of-memory */
737 free_http_response(rsp);
738 return cgi_error_memory();
746 /*********************************************************************
748 * Function : parse_cgi_parameters
750 * Description : Parse a URL-encoded argument string into name/value
751 * pairs and store them in a struct map list.
754 * 1 : string = string to be parsed. Will be trashed.
756 * Returns : pointer to param list, or NULL if out of memory.
758 *********************************************************************/
759 static struct map *parse_cgi_parameters(char *argstring)
762 char *vector[BUFFER_SIZE];
764 struct map *cgi_params;
766 if (NULL == (cgi_params = new_map()))
771 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
773 for (i = 0; i < pairs; i++)
775 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
778 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
780 free_map(cgi_params);
791 /*********************************************************************
793 * Function : get_char_param
795 * Description : Get a single-character parameter passed to a CGI
799 * 1 : parameters = map of cgi parameters
800 * 2 : param_name = The name of the parameter to read
802 * Returns : Uppercase character on success, '\0' on error.
804 *********************************************************************/
805 char get_char_param(const struct map *parameters,
806 const char *param_name)
813 ch = *(lookup(parameters, param_name));
814 if ((ch >= 'a') && (ch <= 'z'))
823 /*********************************************************************
825 * Function : get_string_param
827 * Description : Get a string paramater, to be used as an
828 * ACTION_STRING or ACTION_MULTI paramater.
829 * Validates the input to prevent stupid/malicious
830 * users from corrupting their action file.
833 * 1 : parameters = map of cgi parameters
834 * 2 : param_name = The name of the parameter to read
835 * 3 : pparam = destination for paramater. Allocated as
836 * part of the map "parameters", so don't free it.
837 * Set to NULL if not specified.
839 * Returns : JB_ERR_OK on success, or if the paramater
841 * JB_ERR_MEMORY on out-of-memory.
842 * JB_ERR_CGI_PARAMS if the paramater is not valid.
844 *********************************************************************/
845 jb_err get_string_param(const struct map *parameters,
846 const char *param_name,
859 param = lookup(parameters, param_name);
865 if (strlen(param) >= CGI_PARAM_LEN_MAX)
870 * Note that the length limit is arbitrary, it just seems
871 * sensible to limit it to *something*. There's no
872 * technical reason for any limit at all.
874 return JB_ERR_CGI_PARAMS;
877 /* Check every character to see if it's legal */
879 while ((ch = *s++) != '\0')
881 if ( ((unsigned char)ch < (unsigned char)' ')
884 /* Probable hack attempt, or user accidentally used '}'. */
885 return JB_ERR_CGI_PARAMS;
896 /*********************************************************************
898 * Function : get_number_param
900 * Description : Get a non-negative integer from the parameters
901 * passed to a CGI function.
904 * 1 : csp = Current client state (buffers, headers, etc...)
905 * 2 : parameters = map of cgi parameters
906 * 3 : name = Name of CGI parameter to read
907 * 4 : pvalue = destination for value.
908 * Set to -1 on error.
910 * Returns : JB_ERR_OK on success
911 * JB_ERR_MEMORY on out-of-memory
912 * JB_ERR_CGI_PARAMS if the parameter was not specified
915 *********************************************************************/
916 jb_err get_number_param(struct client_state *csp,
917 const struct map *parameters,
932 param = lookup(parameters, name);
935 return JB_ERR_CGI_PARAMS;
938 /* We don't use atoi because I want to check this carefully... */
941 while ((ch = *param++) != '\0')
943 if ((ch < '0') || (ch > '9'))
945 return JB_ERR_CGI_PARAMS;
952 * <limits.h> defines UINT_MAX
954 * (UINT_MAX - ch) / 10 is the largest number that
955 * can be safely multiplied by 10 then have ch added.
957 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
959 return JB_ERR_CGI_PARAMS;
962 value = value * 10 + ch;
973 /*********************************************************************
975 * Function : error_response
977 * Description : returns an http_response that explains the reason
978 * why a request failed.
981 * 1 : csp = Current client state (buffers, headers, etc...)
982 * 2 : templatename = Which template should be used for the answer
983 * 3 : sys_err = system error number
985 * Returns : A http_response. If we run out of memory, this
986 * will be cgi_error_memory().
988 *********************************************************************/
989 struct http_response *error_response(struct client_state *csp,
990 const char *templatename,
994 struct http_response *rsp;
995 struct map * exports = default_exports(csp, NULL);
998 return cgi_error_memory();
1001 if (NULL == (rsp = alloc_http_response()))
1004 return cgi_error_memory();
1007 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1008 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1009 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1010 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1011 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1014 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1017 /* Some failures, like "404 no such domain", don't have an IP address. */
1018 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1026 free_http_response(rsp);
1027 return cgi_error_memory();
1030 if (!strcmp(templatename, "no-such-domain"))
1032 rsp->status = strdup("404 No such domain");
1033 if (rsp->status == NULL)
1036 free_http_response(rsp);
1037 return cgi_error_memory();
1040 else if (!strcmp(templatename, "connect-failed"))
1042 rsp->status = strdup("503 Connect failed");
1043 if (rsp->status == NULL)
1046 free_http_response(rsp);
1047 return cgi_error_memory();
1051 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1054 free_http_response(rsp);
1055 return cgi_error_memory();
1058 return finish_http_response(rsp);
1062 /*********************************************************************
1064 * Function : cgi_init_error_messages
1066 * Description : Call at the start of the program to initialize
1067 * the error message used by cgi_error_memory().
1073 *********************************************************************/
1074 void cgi_init_error_messages(void)
1076 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1077 cgi_error_memory_response->head =
1078 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1079 "Content-Type: text/html\r\n"
1081 cgi_error_memory_response->body =
1083 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1085 "<h1>500 Internal Privoxy Error</h1>\r\n"
1086 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1087 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1091 cgi_error_memory_response->head_length =
1092 strlen(cgi_error_memory_response->head);
1093 cgi_error_memory_response->content_length =
1094 strlen(cgi_error_memory_response->body);
1098 /*********************************************************************
1100 * Function : cgi_error_memory
1102 * Description : Called if a CGI function runs out of memory.
1103 * Returns a statically-allocated error response.
1106 * 1 : csp = Current client state (buffers, headers, etc...)
1107 * 2 : rsp = http_response data structure for output
1108 * 3 : template_name = Name of template that could not
1111 * Returns : JB_ERR_OK on success
1112 * JB_ERR_MEMORY on out-of-memory error.
1114 *********************************************************************/
1115 struct http_response *cgi_error_memory(void)
1117 /* assert that it's been initialized. */
1118 assert(cgi_error_memory_response->head);
1120 return cgi_error_memory_response;
1124 /*********************************************************************
1126 * Function : cgi_error_no_template
1128 * Description : Almost-CGI function that is called if a templae
1129 * cannot be loaded. Note this is not a true CGI,
1130 * it takes a template name rather than a map of
1134 * 1 : csp = Current client state (buffers, headers, etc...)
1135 * 2 : rsp = http_response data structure for output
1136 * 3 : template_name = Name of template that could not
1139 * Returns : JB_ERR_OK on success
1140 * JB_ERR_MEMORY on out-of-memory error.
1142 *********************************************************************/
1143 jb_err cgi_error_no_template(struct client_state *csp,
1144 struct http_response *rsp,
1145 const char *template_name)
1147 static const char status[] =
1148 "500 Internal Privoxy Error";
1149 static const char body_prefix[] =
1151 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1153 "<h1>500 Internal Privoxy Error</h1>\r\n"
1154 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1155 "<p><b>Could not load template file <code>";
1156 static const char body_suffix[] =
1157 "</code> or one of it's included components.</b></p>\r\n"
1158 "<p>Please contact your proxy administrator.</p>\r\n"
1159 "<p>If you are the proxy administrator, please put the required file(s)"
1160 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1161 "location of the <code><i>(confdir)</i></code> directory "
1162 "is specified in the main Privoxy <code>config</code> "
1163 "file. (It's typically the Privoxy install directory"
1165 ", or <code>/etc/privoxy/</code>"
1166 #endif /* ndef _WIN32 */
1173 assert(template_name);
1175 /* Reset rsp, if needed */
1179 rsp->content_length = 0;
1180 rsp->head_length = 0;
1183 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1184 if (rsp->body == NULL)
1186 return JB_ERR_MEMORY;
1188 strcpy(rsp->body, body_prefix);
1189 strcat(rsp->body, template_name);
1190 strcat(rsp->body, body_suffix);
1192 rsp->status = strdup(status);
1193 if (rsp->body == NULL)
1195 return JB_ERR_MEMORY;
1202 /*********************************************************************
1204 * Function : cgi_error_bad_param
1206 * Description : CGI function that is called if the parameters
1207 * (query string) for a CGI were wrong.
1210 * 1 : csp = Current client state (buffers, headers, etc...)
1211 * 2 : rsp = http_response data structure for output
1213 * CGI Parameters : none
1215 * Returns : JB_ERR_OK on success
1216 * JB_ERR_MEMORY on out-of-memory error.
1218 *********************************************************************/
1219 jb_err cgi_error_bad_param(struct client_state *csp,
1220 struct http_response *rsp)
1222 struct map *exports;
1227 if (NULL == (exports = default_exports(csp, NULL)))
1229 return JB_ERR_MEMORY;
1232 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1236 /*********************************************************************
1238 * Function : add_help_link
1240 * Description : Produce a copy of the string given as item,
1241 * embedded in an HTML link to its corresponding
1242 * section (item name in uppercase) in the configuration
1243 * chapter of the user manual, (whose URL is given in
1244 * the config and defaults to our web site).
1247 * 1 : item = item (will NOT be free()d.)
1248 * It is assumed to be HTML-safe.
1250 * Returns : String with item embedded in link, or NULL on
1253 *********************************************************************/
1254 char *add_help_link(const char *item,
1255 struct configuration_spec *config)
1259 if (!item) return NULL;
1261 result = strdup("<a href=\"");
1262 string_append(&result, config->usermanual);
1263 string_append(&result, HELP_LINK_PREFIX);
1264 string_join (&result, string_toupper(item));
1265 string_append(&result, "\">");
1266 string_append(&result, item);
1267 string_append(&result, "</a> ");
1273 /*********************************************************************
1275 * Function : get_http_time
1277 * Description : Get the time in a format suitable for use in a
1278 * HTTP header - e.g.:
1279 * "Sun, 06 Nov 1994 08:49:37 GMT"
1282 * 1 : time_offset = Time returned will be current time
1283 * plus this number of seconds.
1284 * 2 : buf = Destination for result. Must be long enough
1285 * to hold 29 characters plus a trailing zero.
1289 *********************************************************************/
1290 void get_http_time(int time_offset, char *buf)
1292 static const char day_names[7][4] =
1293 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1294 static const char month_names[12][4] =
1295 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1296 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1299 time_t current_time;
1303 time(¤t_time); /* get current time */
1305 current_time += time_offset;
1307 /* get and save the gmt */
1309 #ifdef HAVE_GMTIME_R
1311 t = gmtime_r(¤t_time, &dummy);
1313 t = gmtime(¤t_time);
1317 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1319 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1320 day_names[t->tm_wday],
1322 month_names[t->tm_mon],
1332 /*********************************************************************
1334 * Function : finish_http_response
1336 * Description : Fill in the missing headers in an http response,
1337 * and flatten the headers to an http head.
1340 * 1 : rsp = pointer to http_response to be processed
1342 * Returns : A http_response, usually the rsp parameter.
1343 * On error, free()s rsp and returns cgi_error_memory()
1345 *********************************************************************/
1346 struct http_response *finish_http_response(struct http_response *rsp)
1348 char buf[BUFFER_SIZE];
1351 /* Special case - do NOT change this statically allocated response,
1352 * which is ready for output anyway.
1354 if (rsp == cgi_error_memory_response)
1360 * Fill in the HTTP Status
1362 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1363 err = enlist_first(rsp->headers, buf);
1366 * Set the Content-Length
1368 if (rsp->content_length == 0)
1370 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1374 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1375 err = enlist(rsp->headers, buf);
1379 * Fill in the default headers:
1381 * Content-Type: default to text/html if not already specified.
1382 * Date: set to current date/time.
1383 * Last-Modified: set to date/time the page was last changed.
1384 * Expires: set to date/time page next needs reloading.
1385 * Cache-Control: set to "no-cache" if applicable.
1387 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1389 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1394 * Set Expires to about 10 min into the future so it'll get reloaded
1395 * occasionally, e.g. if Privoxy gets upgraded.
1400 get_http_time(0, buf);
1401 err = enlist_unique_header(rsp->headers, "Date", buf);
1404 /* Some date in the past. */
1405 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1409 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1410 err = enlist_unique_header(rsp->headers, "Expires", buf);
1416 * Compliant browsers should not cache this due to the "Cache-Control"
1417 * setting. However, to be certain, we also set both "Last-Modified"
1418 * and "Expires" to the current time.
1420 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1422 get_http_time(0, buf);
1423 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1424 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1425 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1432 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1434 free_http_response(rsp);
1435 return cgi_error_memory();
1437 rsp->head_length = strlen(rsp->head);
1444 /*********************************************************************
1446 * Function : alloc_http_response
1448 * Description : Allocates a new http_response structure.
1452 * Returns : pointer to a new http_response, or NULL.
1454 *********************************************************************/
1455 struct http_response *alloc_http_response(void)
1457 return (struct http_response *) zalloc(sizeof(struct http_response));
1462 /*********************************************************************
1464 * Function : free_http_response
1466 * Description : Free the memory occupied by an http_response
1467 * and its depandant structures.
1470 * 1 : rsp = pointer to http_response to be freed
1474 *********************************************************************/
1475 void free_http_response(struct http_response *rsp)
1478 * Must special case cgi_error_memory_response, which is never freed.
1480 if (rsp && (rsp != cgi_error_memory_response))
1485 destroy_list(rsp->headers);
1492 /*********************************************************************
1494 * Function : template_load
1496 * Description : CGI support function that loads a given HTML
1497 * template from the confdir, ignoring comment
1498 * lines and following #include statements up to
1502 * 1 : csp = Current client state (buffers, headers, etc...)
1503 * 2 : template_ptr = Destination for pointer to loaded
1505 * 3 : template = name of the HTML template to be used
1506 * 4 : recursive = Flag set if this function calls itself
1507 * following an #include statament
1509 * Returns : JB_ERR_OK on success
1510 * JB_ERR_MEMORY on out-of-memory error.
1511 * JB_ERR_FILE if the template file cannot be read
1513 *********************************************************************/
1514 jb_err template_load(struct client_state *csp, char **template_ptr,
1515 const char *templatename, int recursive)
1518 char *templates_dir_path;
1521 char *included_module;
1524 char buf[BUFFER_SIZE];
1527 assert(template_ptr);
1528 assert(templatename);
1530 *template_ptr = NULL;
1532 /* Validate template name. Paranoia. */
1533 for (p = templatename; *p != 0; p++)
1535 if ( ((*p < 'a') || (*p > 'z'))
1536 && ((*p < 'A') || (*p > 'Z'))
1537 && ((*p < '0') || (*p > '9'))
1541 /* Illegal character */
1546 /* Generate full path */
1548 templates_dir_path = make_path(csp->config->confdir, "templates");
1549 if (templates_dir_path == NULL)
1551 return JB_ERR_MEMORY;
1554 full_path = make_path(templates_dir_path, templatename);
1555 free(templates_dir_path);
1556 if (full_path == NULL)
1558 return JB_ERR_MEMORY;
1561 /* Allocate buffer */
1563 file_buffer = strdup("");
1564 if (file_buffer == NULL)
1567 return JB_ERR_MEMORY;
1570 /* Open template file */
1572 if (NULL == (fp = fopen(full_path, "r")))
1574 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1582 * Read the file, ignoring comments, and honoring #include
1583 * statements, unless we're already called recursively.
1585 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1586 * This is unlikely in practise.
1588 while (fgets(buf, BUFFER_SIZE, fp))
1590 if (!recursive && !strncmp(buf, "#include ", 9))
1592 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1599 if (string_join(&file_buffer, included_module))
1602 return JB_ERR_MEMORY;
1608 /* skip lines starting with '#' */
1614 if (string_append(&file_buffer, buf))
1617 return JB_ERR_MEMORY;
1622 *template_ptr = file_buffer;
1628 /*********************************************************************
1630 * Function : template_fill
1632 * Description : CGI support function that fills in a pre-loaded
1633 * HTML template by replacing @name@ with value using
1634 * pcrs, for each item in the output map.
1636 * Note that a leading '$' charachter in the export map's
1637 * values will be stripped and toggle on backreference
1641 * 1 : template_ptr = IN: Template to be filled out.
1643 * OUT: Filled out template.
1644 * Caller must free().
1645 * 2 : exports = map with fill in symbol -> name pairs
1647 * Returns : JB_ERR_OK on success
1648 * JB_ERR_MEMORY on out-of-memory error
1650 *********************************************************************/
1651 jb_err template_fill(char **template_ptr, const struct map *exports)
1653 struct map_entry *m;
1655 char buf[BUFFER_SIZE];
1656 char *tmp_out_buffer;
1662 assert(template_ptr);
1663 assert(*template_ptr);
1666 file_buffer = *template_ptr;
1667 size = strlen(file_buffer) + 1;
1670 * Assemble pcrs joblist from exports map
1672 for (m = exports->first; m != NULL; m = m->next)
1674 if (*m->name == '$')
1677 * First character of name is '$', so remove this flag
1678 * character and allow backreferences ($1 etc) in the
1679 * "replace with" text.
1681 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1687 * Treat the "replace with" text as a literal string -
1688 * no quoting needed, no backreferences allowed.
1689 * ("Trivial" ['T'] flag).
1693 /* Enclose name in @@ */
1694 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1698 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1700 /* Make and run job. */
1701 job = pcrs_compile(buf, m->value, flags, &error);
1704 if (error == PCRS_ERR_NOMEM)
1707 *template_ptr = NULL;
1708 return JB_ERR_MEMORY;
1712 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1713 /* Hope it wasn't important and silently ignore the invalid job */
1718 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1721 if (NULL == tmp_out_buffer)
1723 *template_ptr = NULL;
1724 return JB_ERR_MEMORY;
1726 file_buffer = tmp_out_buffer;
1733 *template_ptr = file_buffer;
1738 /*********************************************************************
1740 * Function : template_fill_for_cgi
1742 * Description : CGI support function that loads a HTML template
1743 * and fills it in. Handles file-not-found errors
1744 * by sending a HTML error message. For convenience,
1745 * this function also frees the passed "exports" map.
1748 * 1 : csp = Client state
1749 * 2 : templatename = name of the HTML template to be used
1750 * 3 : exports = map with fill in symbol -> name pairs.
1751 * Will be freed by this function.
1753 * Returns : JB_ERR_OK on success
1754 * JB_ERR_MEMORY on out-of-memory error
1756 *********************************************************************/
1757 jb_err template_fill_for_cgi(struct client_state *csp,
1758 const char *templatename,
1759 struct map *exports,
1760 struct http_response *rsp)
1765 assert(templatename);
1769 err = template_load(csp, &rsp->body, templatename, 0);
1770 if (err == JB_ERR_FILE)
1773 return cgi_error_no_template(csp, rsp, templatename);
1778 return err; /* JB_ERR_MEMORY */
1780 err = template_fill(&rsp->body, exports);
1786 /*********************************************************************
1788 * Function : default_exports
1790 * Description : returns a struct map list that contains exports
1791 * which are common to all CGI functions.
1794 * 1 : csp = Current client state (buffers, headers, etc...)
1795 * 2 : caller = name of CGI who calls us and which should
1796 * be excluded from the generated menu. May be
1798 * Returns : NULL if no memory, else a new map. Caller frees.
1800 *********************************************************************/
1801 struct map *default_exports(const struct client_state *csp, const char *caller)
1805 struct map * exports;
1806 int local_help_exists = 0;
1810 exports = new_map();
1811 if (exports == NULL)
1816 err = map(exports, "version", 1, html_encode(VERSION), 0);
1817 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1818 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1819 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1820 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1821 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1822 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1823 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
1824 if (!err) err = map(exports, "helplink", 1, HELP_LINK_PREFIX ,1);
1825 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1827 snprintf(buf, 20, "%d", csp->config->hport);
1828 if (!err) err = map(exports, "my-port", 1, buf, 1);
1830 if(!strcmp(CODE_STATUS, "stable"))
1832 if (!err) err = map_block_killer(exports, "unstable");
1835 if (csp->config->admin_address != NULL)
1837 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1838 local_help_exists = 1;
1842 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1845 if (csp->config->proxy_info_url != NULL)
1847 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1848 local_help_exists = 1;
1852 if (!err) err = map_block_killer(exports, "have-proxy-info");
1855 if (local_help_exists == 0)
1857 if (!err) err = map_block_killer(exports, "have-help-info");
1870 /*********************************************************************
1872 * Function : map_block_killer
1874 * Description : Convenience function.
1875 * Adds a "killer" for the conditional HTML-template
1876 * block <name>, i.e. a substitution of the regex
1877 * "if-<name>-start.*if-<name>-end" to the given
1881 * 1 : exports = map to extend
1882 * 2 : name = name of conditional block
1884 * Returns : JB_ERR_OK on success
1885 * JB_ERR_MEMORY on out-of-memory error.
1887 *********************************************************************/
1888 jb_err map_block_killer(struct map *exports, const char *name)
1890 char buf[1000]; /* Will do, since the names are hardwired */
1894 assert(strlen(name) < 490);
1896 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1897 return map(exports, buf, 1, "", 1);
1901 /*********************************************************************
1903 * Function : map_block_keep
1905 * Description : Convenience function. Removes the markers used
1906 * by map-block-killer, to save a few bytes.
1907 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1910 * 1 : exports = map to extend
1911 * 2 : name = name of conditional block
1913 * Returns : JB_ERR_OK on success
1914 * JB_ERR_MEMORY on out-of-memory error.
1916 *********************************************************************/
1917 jb_err map_block_keep(struct map *exports, const char *name)
1920 char buf[500]; /* Will do, since the names are hardwired */
1924 assert(strlen(name) < 490);
1926 snprintf(buf, 500, "if-%s-start", name);
1927 err = map(exports, buf, 1, "", 1);
1934 snprintf(buf, 500, "if-%s-end", name);
1935 return map(exports, buf, 1, "", 1);
1939 /*********************************************************************
1941 * Function : map_conditional
1943 * Description : Convenience function.
1944 * Adds an "if-then-else" for the conditional HTML-template
1945 * block <name>, i.e. a substitution of the form:
1952 * The control structure and one of the alternatives
1956 * 1 : exports = map to extend
1957 * 2 : name = name of conditional block
1958 * 3 : choose_first = nonzero for first, zero for second.
1960 * Returns : JB_ERR_OK on success
1961 * JB_ERR_MEMORY on out-of-memory error.
1963 *********************************************************************/
1964 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1966 char buf[1000]; /* Will do, since the names are hardwired */
1971 assert(strlen(name) < 480);
1973 snprintf(buf, 1000, (choose_first
1974 ? "else-not-%s@.*@endif-%s"
1975 : "if-%s-then@.*@else-not-%s"),
1978 err = map(exports, buf, 1, "", 1);
1984 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1985 return map(exports, buf, 1, "", 1);
1989 /*********************************************************************
1991 * Function : make_menu
1993 * Description : Returns an HTML-formatted menu of the available
1994 * unhidden CGIs, excluding the one given in <self>
1996 * Parameters : self = name of CGI to leave out, can be NULL for
1999 * Returns : menu string, or NULL on out-of-memory error.
2001 *********************************************************************/
2002 char *make_menu(const char *self)
2004 const struct cgi_dispatcher *d;
2005 char *result = strdup("");
2009 self = "NO-SUCH-CGI!";
2012 /* List available unhidden CGI's and export as "other-cgis" */
2013 for (d = cgi_dispatchers; d->name; d++)
2015 if (d->description && strcmp(d->name, self))
2017 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2018 string_append(&result, d->name);
2019 string_append(&result, "\">");
2020 string_append(&result, d->description);
2021 string_append(&result, "</a></li>");
2029 /*********************************************************************
2031 * Function : dump_map
2033 * Description : HTML-dump a map for debugging (as table)
2036 * 1 : the_map = map to dump
2038 * Returns : string with HTML
2040 *********************************************************************/
2041 char *dump_map(const struct map *the_map)
2043 struct map_entry *cur_entry;
2044 char *ret = strdup("");
2046 string_append(&ret, "<table>\n");
2048 for (cur_entry = the_map->first;
2049 (cur_entry != NULL) && (ret != NULL);
2050 cur_entry = cur_entry->next)
2052 string_append(&ret, "<tr><td><b>");
2053 string_join (&ret, html_encode(cur_entry->name));
2054 string_append(&ret, "</b></td><td>");
2055 string_join (&ret, html_encode(cur_entry->value));
2056 string_append(&ret, "</td></tr>\n");
2059 string_append(&ret, "</table>\n");