1 const char cgi_rcs[] = "$Id: cgi.c,v 1.69 2002/05/14 21:28:40 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.69 2002/05/14 21:28:40 oes
42 * - Fixed add_help_link to link to the (now split) actions
43 * part of the config chapter
44 * - Renamed helplink export to actions-help-prefix
46 * Revision 1.68 2002/05/12 21:36:29 jongfoster
47 * Correcting function comments
49 * Revision 1.67 2002/04/30 12:02:07 oes
50 * Nit: updated a comment
52 * Revision 1.66 2002/04/26 18:32:57 jongfoster
53 * Fixing a memory leak on error
55 * Revision 1.65 2002/04/26 12:53:51 oes
56 * - New function add_help_link
57 * - default_exports now exports links to the user manual
58 * and a prefix for links into the config chapter
60 * Revision 1.64 2002/04/24 02:17:21 oes
61 * - Better descriptions for CGIs
62 * - Hide edit-actions, more shortcuts
63 * - Moved get_char_param, get_string_param and get_number_param here
66 * Revision 1.63 2002/04/15 19:06:43 jongfoster
69 * Revision 1.62 2002/04/10 19:59:46 jongfoster
70 * Fixes to #include in templates:
71 * - Didn't close main file if loading an included template fails.
72 * - I'm paranoid and want to disallow "#include /etc/passwd".
74 * Revision 1.61 2002/04/10 13:37:48 oes
75 * Made templates modular: template_load now recursive with max depth 1
77 * Revision 1.60 2002/04/08 20:50:25 swa
80 * Revision 1.59 2002/04/05 15:51:51 oes
81 * - added send-stylesheet CGI
82 * - bugfix: error-pages now get correct request protocol
84 * - kludged CGI descriptions and menu not to break JS syntax
86 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
87 * Fix Mac OSX compiler warnings
89 * Revision 1.57 2002/03/26 22:29:54 swa
90 * we have a new homepage!
92 * Revision 1.56 2002/03/24 17:50:46 jongfoster
93 * Fixing compile error if actions file editor disabled
95 * Revision 1.55 2002/03/24 16:55:06 oes
96 * Making GIF checkerboard transparent
98 * Revision 1.54 2002/03/24 16:18:15 jongfoster
101 * Revision 1.53 2002/03/24 16:06:00 oes
102 * Correct transparency for checkerboard PNG. Thanks, Magnus!
104 * Revision 1.52 2002/03/24 15:23:33 jongfoster
107 * Revision 1.51 2002/03/24 13:25:43 swa
108 * name change related issues
110 * Revision 1.50 2002/03/16 23:54:06 jongfoster
111 * Adding graceful termination feature, to help look for memory leaks.
112 * If you enable this (which, by design, has to be done by hand
113 * editing config.h) and then go to http://i.j.b/die, then the program
114 * will exit cleanly after the *next* request. It should free all the
115 * memory that was used.
117 * Revision 1.49 2002/03/13 00:27:04 jongfoster
120 * Revision 1.48 2002/03/08 17:47:07 jongfoster
123 * Revision 1.47 2002/03/08 16:41:33 oes
124 * Added GIF images again
126 * Revision 1.46 2002/03/07 03:48:38 oes
127 * - Changed built-in images from GIF to PNG
128 * (with regard to Unisys patent issue)
129 * - Added a 4x4 pattern PNG which is less intrusive
130 * than the logo but also clearly marks the deleted banners
132 * Revision 1.45 2002/03/06 22:54:35 jongfoster
133 * Automated function-comment nitpicking.
135 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
136 * - Better error reporting on OS/2
137 * - Fix double-slash comment (oops)
139 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
140 * - Re-enable OS/2 building after new parms were added
141 * - Fix false out of memory report when resolving CGI templates when no IP
142 * address is available of failed attempt (a la no such domain)
144 * Revision 1.42 2002/01/21 00:33:20 jongfoster
145 * Replacing strsav() with the safer string_append() or string_join().
146 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
147 * Adding missing html_encode() to error message generators.
148 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
150 * Revision 1.41 2002/01/17 20:56:22 jongfoster
151 * Replacing hard references to the URL of the config interface
152 * with #defines from project.h
154 * Revision 1.40 2002/01/09 14:26:46 oes
155 * Added support for thread-safe gmtime_r call.
157 * Revision 1.39 2001/11/16 00:48:13 jongfoster
158 * Fixing a compiler warning
160 * Revision 1.38 2001/11/13 00:31:21 jongfoster
161 * - Adding new CGIs for use by non-JavaScript browsers:
162 * edit-actions-url-form
163 * edit-actions-add-url-form
164 * edit-actions-remove-url-form
165 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
168 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
169 * Show enablement/disablement status in almost all templates.
170 * There is a little trickiness here: apparent recursive resolution of
171 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
172 * the actual enablement status. So a similar construct,
173 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
176 * Revision 1.36 2001/10/26 17:33:27 oes
179 * Revision 1.35 2001/10/23 21:48:19 jongfoster
180 * Cleaning up error handling in CGI functions - they now send back
181 * a HTML error page and should never cause a FATAL error. (Fixes one
182 * potential source of "denial of service" attacks).
184 * CGI actions file editor that works and is actually useful.
186 * Ability to toggle Junkbuster remotely using a CGI call.
188 * You can turn off both the above features in the main configuration
189 * file, e.g. if you are running a multi-user proxy.
191 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
192 * Only show "Local support" on templates conditionally:
193 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
194 * - if not, no Local support section appears
196 * Revision 1.33 2001/10/14 22:28:41 jongfoster
197 * Fixing stupid typo.
199 * Revision 1.32 2001/10/14 22:20:18 jongfoster
200 * - Changes to CGI dispatching method to match CGI names exactly,
201 * rather than doing a prefix match.
202 * - No longer need to count the length of the CGI handler names by hand.
203 * - Adding new handler for 404 error when disptching a CGI, if none of
204 * the handlers match.
205 * - Adding new handlers for CGI actionsfile editor.
207 * Revision 1.31 2001/10/10 10:56:39 oes
208 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
210 * Revision 1.30 2001/10/02 15:30:57 oes
211 * Introduced show-request cgi
213 * Revision 1.29 2001/09/20 15:47:44 steudten
215 * Fix BUG: Modify int size to size_t size in fill_template()
216 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
218 * Revision 1.28 2001/09/19 18:00:37 oes
219 * - Deletef time() FIXME (Can't fail under Linux either, if
220 * the argument is guaranteed to be in out address space,
223 * - Pointer notation cosmetics
224 * - Fixed a minor bug in template_fill(): Failiure of
225 * pcrs_execute() now secure.
227 * Revision 1.27 2001/09/16 17:08:54 jongfoster
228 * Moving simple CGI functions from cgi.c to new file cgisimple.c
230 * Revision 1.26 2001/09/16 15:47:37 jongfoster
231 * First version of CGI-based edit interface. This is very much a
232 * work-in-progress, and you can't actually use it to edit anything
233 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
234 * to have any effect.
236 * Revision 1.25 2001/09/16 15:02:35 jongfoster
237 * Adding i.j.b/robots.txt.
238 * Inlining add_stats() since it's only ever called from one place.
240 * Revision 1.24 2001/09/16 11:38:01 jongfoster
241 * Splitting fill_template() into 2 functions:
242 * template_load() loads the file
243 * template_fill() performs the PCRS regexps.
244 * This is because the CGI edit interface has a "table row"
245 * template which is used many times in the page - this
246 * change means it's only loaded from disk once.
248 * Revision 1.23 2001/09/16 11:16:05 jongfoster
249 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
251 * Revision 1.22 2001/09/16 11:00:10 jongfoster
252 * New function alloc_http_response, for symmetry with free_http_response
254 * Revision 1.21 2001/09/13 23:53:03 jongfoster
255 * Support for both static and dynamically generated CGI pages.
256 * Correctly setting Last-Modified: and Expires: HTTP headers.
258 * Revision 1.20 2001/09/13 23:40:36 jongfoster
259 * (Cosmetic only) Indentation correction
261 * Revision 1.19 2001/09/13 23:31:25 jongfoster
262 * Moving image data to cgi.c rather than cgi.h.
264 * Revision 1.18 2001/08/05 16:06:20 jongfoster
265 * Modifiying "struct map" so that there are now separate header and
266 * "map_entry" structures. This means that functions which modify a
267 * map no longer need to return a pointer to the modified map.
268 * Also, it no longer reverses the order of the entries (which may be
269 * important with some advanced template substitutions).
271 * Revision 1.17 2001/08/05 15:57:38 oes
272 * Adapted finish_http_response to new list_to_text
274 * Revision 1.16 2001/08/01 21:33:18 jongfoster
275 * Changes to fill_template() that reduce memory usage without having
276 * an impact on performance. I also renamed some variables so as not
277 * to clash with the C++ keywords "new" and "template".
279 * Revision 1.15 2001/08/01 21:19:22 jongfoster
280 * Moving file version information to a separate CGI page.
282 * Revision 1.14 2001/08/01 00:19:03 jongfoster
283 * New function: map_conditional() for an if-then-else syntax.
284 * Changing to use new version of show_defines()
286 * Revision 1.13 2001/07/30 22:08:36 jongfoster
287 * Tidying up #defines:
288 * - All feature #defines are now of the form FEATURE_xxx
289 * - Permanently turned off WIN_GUI_EDIT
290 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
292 * Revision 1.12 2001/07/29 18:47:05 jongfoster
293 * Adding missing #include "loadcfg.h"
295 * Revision 1.11 2001/07/18 17:24:37 oes
296 * Changed to conform to new pcrs interface
298 * Revision 1.10 2001/07/13 13:53:13 oes
299 * Removed all #ifdef PCRS and related code
301 * Revision 1.9 2001/06/29 21:45:41 oes
302 * Indentation, CRLF->LF, Tab-> Space
304 * Revision 1.8 2001/06/29 13:21:46 oes
305 * - Cosmetics: renamed and reordered functions, variables,
306 * texts, improved comments etc
308 * - Removed ij_untrusted_url() The relevant
309 * info is now part of the "untrusted" page,
310 * which is generated by filters.c:trust_url()
312 * - Generators of content now call finish_http_response()
313 * themselves, making jcc.c:chat() a little less
316 * - Removed obsolete "Pragma: no-cache" from our headers
318 * - http_responses now know their head length
320 * - fill_template now uses the new interface to pcrs, so that
321 * - long jobs (like whole files) no longer have to be assembled
322 * in a fixed size buffer
323 * - the new T (trivial) option is used, and the replacement may
324 * contain Perl syntax backrefs without confusing pcrs
326 * - Introduced default_exports() which generates a set of exports
327 * common to all CGIs and other content generators
329 * - Introduced convenience function map_block_killer()
331 * - Introduced convenience function make_menu()
333 * - Introduced CGI-like function error_response() which generates
334 * the "No such domain" and "Connect failed" messages using the
337 * - cgi_show_url_info:
338 * - adapted to new CGI features
339 * - form and answers now generated from same template
340 * - http:// prefix in URL now OK
343 * - adapted to new CGI features
344 * - no longer uses csp->init_proxy_args
347 * - moved menu generation to make_menu()
349 * - add_stats now writes single export map entries instead
352 * - Moved redirect_url() to filters.c
354 * - Fixed mem leak in free_http_response(), map_block_killer(),
356 * - Removed logentry from cancelled commit
358 * Revision 1.7 2001/06/09 10:51:58 jongfoster
359 * Changing "show URL info" handler to new style.
360 * Changing BUFSIZ ==> BUFFER_SIZE
362 * Revision 1.6 2001/06/07 23:05:19 jongfoster
363 * Removing code related to old forward and ACL files.
365 * Revision 1.5 2001/06/05 19:59:16 jongfoster
366 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
368 * Revision 1.4 2001/06/04 10:41:52 swa
369 * show version string of cgi.h and cgi.c
371 * Revision 1.3 2001/06/03 19:12:16 oes
372 * introduced new cgi handling
374 * No revisions before 1.3
376 **********************************************************************/
382 #include <sys/types.h>
390 #define snprintf _snprintf
391 #endif /* def _WIN32 */
399 #include "miscutil.h"
400 #include "cgisimple.h"
401 #ifdef FEATURE_CGI_EDIT_ACTIONS
403 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
405 /* loadcfg.h is for g_bToggleIJB only */
407 const char cgi_h_rcs[] = CGI_H_VERSION;
410 * List of CGI functions: name, handler, description
411 * Note: Do NOT use single quotes in the description;
412 * this will break the dynamic "blocked" template!
414 static const struct cgi_dispatcher cgi_dispatchers[] = {
417 "Privoxy main page" },
418 #ifdef FEATURE_GRACEFUL_TERMINATION
421 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
422 "this is a one click Denial Of Service attack!!!</em>" },
426 "View & change the current configuration" },
429 "View the source code version numbers" },
432 "View the request headers." },
435 "Look up which actions apply to a URL and why" },
436 #ifdef FEATURE_CGI_EDIT_ACTIONS
439 "Toggle Privoxy on or off" },
441 { "edit-actions", /* Edit the actions list */
444 { "eaa", /* Shortcut for edit-actions-add-url-form */
445 cgi_edit_actions_add_url_form,
447 { "eau", /* Shortcut for edit-actions-url-form */
448 cgi_edit_actions_url_form,
450 { "ear", /* Shortcut for edit-actions-remove-url-form */
451 cgi_edit_actions_remove_url_form,
453 { "eafu", /* Shortcut for edit-actions-for-url */
454 cgi_edit_actions_for_url,
456 { "eas", /* Shortcut for edit-actions-submit */
457 cgi_edit_actions_submit,
459 { "easa", /* Shortcut for edit-actions-section-add */
460 cgi_edit_actions_section_add,
462 { "easr", /* Shortcut for edit-actions-section-remove */
463 cgi_edit_actions_section_remove,
465 { "eass", /* Shortcut for edit-actions-section-swap */
466 cgi_edit_actions_section_swap,
468 { "edit-actions-for-url",
469 cgi_edit_actions_for_url,
470 NULL /* Edit the actions for (a) specified URL(s) */ },
471 { "edit-actions-list",
472 cgi_edit_actions_list,
473 NULL /* Edit the actions list */ },
474 { "edit-actions-submit",
475 cgi_edit_actions_submit,
476 NULL /* Change the actions for (a) specified URL(s) */ },
477 { "edit-actions-url",
478 cgi_edit_actions_url,
479 NULL /* Change a URL pattern in the actionsfile */ },
480 { "edit-actions-url-form",
481 cgi_edit_actions_url_form,
482 NULL /* Form to change a URL pattern in the actionsfile */ },
483 { "edit-actions-add-url",
484 cgi_edit_actions_add_url,
485 NULL /* Add a URL pattern to the actionsfile */ },
486 { "edit-actions-add-url-form",
487 cgi_edit_actions_add_url_form,
488 NULL /* Form to add a URL pattern to the actionsfile */ },
489 { "edit-actions-remove-url",
490 cgi_edit_actions_remove_url,
491 NULL /* Remove a URL pattern from the actionsfile */ },
492 { "edit-actions-remove-url-form",
493 cgi_edit_actions_remove_url_form,
494 NULL /* Form to remove a URL pattern from the actionsfile */ },
495 { "edit-actions-section-add",
496 cgi_edit_actions_section_add,
497 NULL /* Remove a section from the actionsfile */ },
498 { "edit-actions-section-remove",
499 cgi_edit_actions_section_remove,
500 NULL /* Remove a section from the actionsfile */ },
501 { "edit-actions-section-swap",
502 cgi_edit_actions_section_swap,
503 NULL /* Swap two sections in the actionsfile */ },
504 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
507 NULL /* Sends a robots.txt file to tell robots to go away. */ },
510 NULL /* Send a built-in image */ },
513 NULL /* Send templates/cgi-style.css */ },
515 cgi_transparent_image,
516 NULL /* Send a transparent image (short name) */ },
517 { NULL, /* NULL Indicates end of list and default page */
519 NULL /* Unknown CGI page */ }
524 * Bulit-in images for ad replacement
526 * Hint: You can encode your own images like this:
527 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
530 #ifdef FEATURE_NO_GIFS
533 * Checkerboard pattern, as a PNG.
535 const char image_pattern_data[] =
536 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
537 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
538 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
539 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
540 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
541 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
542 "\000\000\000\111\105\116\104\256\102\140\202";
545 * 1x1 transparant PNG.
547 const char image_blank_data[] =
548 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
549 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
550 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
551 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
552 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
553 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
554 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
555 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
556 "\000\000\000\000\111\105\116\104\256\102\140\202";
560 * Checkerboard pattern, as a GIF.
562 const char image_pattern_data[] =
563 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
564 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
565 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
566 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
570 * 1x1 transparant GIF.
572 const char image_blank_data[] =
573 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
574 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
575 "\000\001\000\000\002\002D\001\000;";
578 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
579 const size_t image_blank_length = sizeof(image_blank_data) - 1;
582 static struct http_response cgi_error_memory_response[1];
584 static struct http_response *dispatch_known_cgi(struct client_state * csp,
586 static struct map *parse_cgi_parameters(char *argstring);
589 /*********************************************************************
591 * Function : dispatch_cgi
593 * Description : Checks if a request URL has either the magical
594 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
595 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
596 * http://config.privoxy.org/). If so, it passes
597 * the (rest of the) path onto dispatch_known_cgi, which
598 * calls the relevant CGI handler function.
601 * 1 : csp = Current client state (buffers, headers, etc...)
603 * Returns : http_response if match, NULL if nonmatch or handler fail
605 *********************************************************************/
606 struct http_response *dispatch_cgi(struct client_state *csp)
608 const char *host = csp->http->host;
609 const char *path = csp->http->path;
612 * Should we intercept ?
615 /* Note: "example.com" and "example.com." are equivalent hostnames. */
617 /* Either the host matches CGI_SITE_1_HOST ..*/
618 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
619 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
620 && (path[0] == '/') )
622 /* ..then the path will all be for us. Remove leading '/' */
625 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
626 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
627 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
628 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
630 /* take everything following CGI_SITE_2_PATH */
631 path += strlen(CGI_SITE_2_PATH);
634 /* skip the forward slash after CGI_SITE_2_PATH */
637 else if (*path != '\0')
640 * wierdness: URL is /configXXX, where XXX is some string
641 * Do *NOT* intercept.
653 * This is a CGI call.
656 return dispatch_known_cgi(csp, path);
660 /*********************************************************************
662 * Function : dispatch_known_cgi
664 * Description : Processes a CGI once dispatch_cgi has determined that
665 * it matches one of the magic prefixes. Parses the path
666 * as a cgi name plus query string, prepares a map that
667 * maps CGI parameter names to their values, initializes
668 * the http_response struct, and calls the relevant CGI
672 * 1 : csp = Current client state (buffers, headers, etc...)
673 * 2 : path = Path of CGI, with the CGI prefix removed.
674 * Should not have a leading "/".
676 * Returns : http_response, or NULL on handler failure or out of
679 *********************************************************************/
680 static struct http_response *dispatch_known_cgi(struct client_state * csp,
683 const struct cgi_dispatcher *d;
684 struct map *param_list;
685 struct http_response *rsp;
686 char *query_args_start;
690 if (NULL == (path_copy = strdup(path)))
692 return cgi_error_memory();
695 query_args_start = path_copy;
696 while (*query_args_start && *query_args_start != '?')
700 if (*query_args_start == '?')
702 *query_args_start++ = '\0';
705 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
708 return cgi_error_memory();
714 * path_copy = CGI call name
715 * param_list = CGI params, as map
718 /* Get mem for response or fail*/
719 if (NULL == (rsp = alloc_http_response()))
722 free_map(param_list);
723 return cgi_error_memory();
726 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
727 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
728 csp->ip_addr_str, csp->http->cmd);
730 /* Find and start the right CGI function*/
734 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
736 err = (d->handler)(csp, rsp, param_list);
738 free_map(param_list);
739 if (err == JB_ERR_CGI_PARAMS)
741 err = cgi_error_bad_param(csp, rsp);
743 if (err && (err != JB_ERR_MEMORY))
745 /* Unexpected error! Shouldn't get here */
746 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
747 err = cgi_error_unknown(csp, rsp, err);
752 return finish_http_response(rsp);
756 /* Error in handler, probably out-of-memory */
757 free_http_response(rsp);
758 return cgi_error_memory();
766 /*********************************************************************
768 * Function : parse_cgi_parameters
770 * Description : Parse a URL-encoded argument string into name/value
771 * pairs and store them in a struct map list.
774 * 1 : argstring = string to be parsed. Will be trashed.
776 * Returns : pointer to param list, or NULL if out of memory.
778 *********************************************************************/
779 static struct map *parse_cgi_parameters(char *argstring)
782 char *vector[BUFFER_SIZE];
784 struct map *cgi_params;
786 if (NULL == (cgi_params = new_map()))
791 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
793 for (i = 0; i < pairs; i++)
795 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
798 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
800 free_map(cgi_params);
811 /*********************************************************************
813 * Function : get_char_param
815 * Description : Get a single-character parameter passed to a CGI
819 * 1 : parameters = map of cgi parameters
820 * 2 : param_name = The name of the parameter to read
822 * Returns : Uppercase character on success, '\0' on error.
824 *********************************************************************/
825 char get_char_param(const struct map *parameters,
826 const char *param_name)
833 ch = *(lookup(parameters, param_name));
834 if ((ch >= 'a') && (ch <= 'z'))
843 /*********************************************************************
845 * Function : get_string_param
847 * Description : Get a string paramater, to be used as an
848 * ACTION_STRING or ACTION_MULTI paramater.
849 * Validates the input to prevent stupid/malicious
850 * users from corrupting their action file.
853 * 1 : parameters = map of cgi parameters
854 * 2 : param_name = The name of the parameter to read
855 * 3 : pparam = destination for paramater. Allocated as
856 * part of the map "parameters", so don't free it.
857 * Set to NULL if not specified.
859 * Returns : JB_ERR_OK on success, or if the paramater
861 * JB_ERR_MEMORY on out-of-memory.
862 * JB_ERR_CGI_PARAMS if the paramater is not valid.
864 *********************************************************************/
865 jb_err get_string_param(const struct map *parameters,
866 const char *param_name,
879 param = lookup(parameters, param_name);
885 if (strlen(param) >= CGI_PARAM_LEN_MAX)
890 * Note that the length limit is arbitrary, it just seems
891 * sensible to limit it to *something*. There's no
892 * technical reason for any limit at all.
894 return JB_ERR_CGI_PARAMS;
897 /* Check every character to see if it's legal */
899 while ((ch = *s++) != '\0')
901 if ( ((unsigned char)ch < (unsigned char)' ')
904 /* Probable hack attempt, or user accidentally used '}'. */
905 return JB_ERR_CGI_PARAMS;
916 /*********************************************************************
918 * Function : get_number_param
920 * Description : Get a non-negative integer from the parameters
921 * passed to a CGI function.
924 * 1 : csp = Current client state (buffers, headers, etc...)
925 * 2 : parameters = map of cgi parameters
926 * 3 : name = Name of CGI parameter to read
927 * 4 : pvalue = destination for value.
928 * Set to -1 on error.
930 * Returns : JB_ERR_OK on success
931 * JB_ERR_MEMORY on out-of-memory
932 * JB_ERR_CGI_PARAMS if the parameter was not specified
935 *********************************************************************/
936 jb_err get_number_param(struct client_state *csp,
937 const struct map *parameters,
952 param = lookup(parameters, name);
955 return JB_ERR_CGI_PARAMS;
958 /* We don't use atoi because I want to check this carefully... */
961 while ((ch = *param++) != '\0')
963 if ((ch < '0') || (ch > '9'))
965 return JB_ERR_CGI_PARAMS;
972 * <limits.h> defines UINT_MAX
974 * (UINT_MAX - ch) / 10 is the largest number that
975 * can be safely multiplied by 10 then have ch added.
977 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
979 return JB_ERR_CGI_PARAMS;
982 value = value * 10 + ch;
993 /*********************************************************************
995 * Function : error_response
997 * Description : returns an http_response that explains the reason
998 * why a request failed.
1001 * 1 : csp = Current client state (buffers, headers, etc...)
1002 * 2 : templatename = Which template should be used for the answer
1003 * 3 : sys_err = system error number
1005 * Returns : A http_response. If we run out of memory, this
1006 * will be cgi_error_memory().
1008 *********************************************************************/
1009 struct http_response *error_response(struct client_state *csp,
1010 const char *templatename,
1014 struct http_response *rsp;
1015 struct map * exports = default_exports(csp, NULL);
1016 if (exports == NULL)
1018 return cgi_error_memory();
1021 if (NULL == (rsp = alloc_http_response()))
1024 return cgi_error_memory();
1027 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1028 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1029 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1030 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1031 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1034 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1037 /* Some failures, like "404 no such domain", don't have an IP address. */
1038 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1046 free_http_response(rsp);
1047 return cgi_error_memory();
1050 if (!strcmp(templatename, "no-such-domain"))
1052 rsp->status = strdup("404 No such domain");
1053 if (rsp->status == NULL)
1056 free_http_response(rsp);
1057 return cgi_error_memory();
1060 else if (!strcmp(templatename, "connect-failed"))
1062 rsp->status = strdup("503 Connect failed");
1063 if (rsp->status == NULL)
1066 free_http_response(rsp);
1067 return cgi_error_memory();
1071 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1074 free_http_response(rsp);
1075 return cgi_error_memory();
1078 return finish_http_response(rsp);
1082 /*********************************************************************
1084 * Function : cgi_init_error_messages
1086 * Description : Call at the start of the program to initialize
1087 * the error message used by cgi_error_memory().
1093 *********************************************************************/
1094 void cgi_init_error_messages(void)
1096 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1097 cgi_error_memory_response->head =
1098 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1099 "Content-Type: text/html\r\n"
1101 cgi_error_memory_response->body =
1103 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1105 "<h1>500 Internal Privoxy Error</h1>\r\n"
1106 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1107 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1111 cgi_error_memory_response->head_length =
1112 strlen(cgi_error_memory_response->head);
1113 cgi_error_memory_response->content_length =
1114 strlen(cgi_error_memory_response->body);
1118 /*********************************************************************
1120 * Function : cgi_error_memory
1122 * Description : Called if a CGI function runs out of memory.
1123 * Returns a statically-allocated error response.
1127 * Returns : http_response data structure for output. This is
1128 * statically allocated, for obvious reasons.
1130 *********************************************************************/
1131 struct http_response *cgi_error_memory(void)
1133 /* assert that it's been initialized. */
1134 assert(cgi_error_memory_response->head);
1136 return cgi_error_memory_response;
1140 /*********************************************************************
1142 * Function : cgi_error_no_template
1144 * Description : Almost-CGI function that is called if a template
1145 * cannot be loaded. Note this is not a true CGI,
1146 * it takes a template name rather than a map of
1150 * 1 : csp = Current client state (buffers, headers, etc...)
1151 * 2 : rsp = http_response data structure for output
1152 * 3 : template_name = Name of template that could not
1155 * Returns : JB_ERR_OK on success
1156 * JB_ERR_MEMORY on out-of-memory error.
1158 *********************************************************************/
1159 jb_err cgi_error_no_template(struct client_state *csp,
1160 struct http_response *rsp,
1161 const char *template_name)
1163 static const char status[] =
1164 "500 Internal Privoxy Error";
1165 static const char body_prefix[] =
1167 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1169 "<h1>500 Internal Privoxy Error</h1>\r\n"
1170 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1171 "<p><b>Could not load template file <code>";
1172 static const char body_suffix[] =
1173 "</code> or one of it's included components.</b></p>\r\n"
1174 "<p>Please contact your proxy administrator.</p>\r\n"
1175 "<p>If you are the proxy administrator, please put the required file(s)"
1176 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1177 "location of the <code><i>(confdir)</i></code> directory "
1178 "is specified in the main Privoxy <code>config</code> "
1179 "file. (It's typically the Privoxy install directory"
1181 ", or <code>/etc/privoxy/</code>"
1182 #endif /* ndef _WIN32 */
1189 assert(template_name);
1191 /* Reset rsp, if needed */
1195 rsp->content_length = 0;
1196 rsp->head_length = 0;
1199 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1200 if (rsp->body == NULL)
1202 return JB_ERR_MEMORY;
1204 strcpy(rsp->body, body_prefix);
1205 strcat(rsp->body, template_name);
1206 strcat(rsp->body, body_suffix);
1208 rsp->status = strdup(status);
1209 if (rsp->body == NULL)
1211 return JB_ERR_MEMORY;
1218 /*********************************************************************
1220 * Function : cgi_error_unknown
1222 * Description : Almost-CGI function that is called if an unexpected
1223 * error occurs in the top-level CGI dispatcher.
1224 * In this context, "unexpected" means "anything other
1225 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1226 * expected to handle all other errors internally,
1227 * since they can give more relavent error messages
1230 * Note this is not a true CGI, it takes an error
1231 * code rather than a map of parameters.
1234 * 1 : csp = Current client state (buffers, headers, etc...)
1235 * 2 : rsp = http_response data structure for output
1236 * 3 : error_to_report = Error code to report.
1238 * Returns : JB_ERR_OK on success
1239 * JB_ERR_MEMORY on out-of-memory error.
1241 *********************************************************************/
1242 jb_err cgi_error_unknown(struct client_state *csp,
1243 struct http_response *rsp,
1244 jb_err error_to_report)
1246 static const char status[] =
1247 "500 Internal Privoxy Error";
1248 static const char body_prefix[] =
1250 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1252 "<h1>500 Internal Privoxy Error</h1>\r\n"
1253 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1254 "<p><b>Unexpected internal error: ";
1255 static const char body_suffix[] =
1258 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1259 "file a bug report</a>.</p>\r\n"
1266 /* Reset rsp, if needed */
1270 rsp->content_length = 0;
1271 rsp->head_length = 0;
1274 sprintf(errnumbuf, "%d", error_to_report);
1276 rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1277 if (rsp->body == NULL)
1279 return JB_ERR_MEMORY;
1281 strcpy(rsp->body, body_prefix);
1282 strcat(rsp->body, errnumbuf);
1283 strcat(rsp->body, body_suffix);
1285 rsp->status = strdup(status);
1286 if (rsp->body == NULL)
1288 return JB_ERR_MEMORY;
1295 /*********************************************************************
1297 * Function : cgi_error_bad_param
1299 * Description : CGI function that is called if the parameters
1300 * (query string) for a CGI were wrong.
1303 * 1 : csp = Current client state (buffers, headers, etc...)
1304 * 2 : rsp = http_response data structure for output
1306 * CGI Parameters : none
1308 * Returns : JB_ERR_OK on success
1309 * JB_ERR_MEMORY on out-of-memory error.
1311 *********************************************************************/
1312 jb_err cgi_error_bad_param(struct client_state *csp,
1313 struct http_response *rsp)
1315 struct map *exports;
1320 if (NULL == (exports = default_exports(csp, NULL)))
1322 return JB_ERR_MEMORY;
1325 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1329 /*********************************************************************
1331 * Function : add_help_link
1333 * Description : Produce a copy of the string given as item,
1334 * embedded in an HTML link to its corresponding
1335 * section (item name in uppercase) in the actions
1336 * chapter of the user manual, (whose URL is given in
1337 * the config and defaults to our web site).
1339 * FIXME: I currently only work for actions, and would
1340 * like to be generalized for other topics.
1343 * 1 : item = item (will NOT be free()d.)
1344 * It is assumed to be HTML-safe.
1345 * 2 : config = The current configuration.
1347 * Returns : String with item embedded in link, or NULL on
1350 *********************************************************************/
1351 char *add_help_link(const char *item,
1352 struct configuration_spec *config)
1356 if (!item) return NULL;
1358 result = strdup("<a href=\"");
1359 string_append(&result, config->usermanual);
1360 string_append(&result, ACTIONS_HELP_PREFIX);
1361 string_join (&result, string_toupper(item));
1362 string_append(&result, "\">");
1363 string_append(&result, item);
1364 string_append(&result, "</a> ");
1370 /*********************************************************************
1372 * Function : get_http_time
1374 * Description : Get the time in a format suitable for use in a
1375 * HTTP header - e.g.:
1376 * "Sun, 06 Nov 1994 08:49:37 GMT"
1379 * 1 : time_offset = Time returned will be current time
1380 * plus this number of seconds.
1381 * 2 : buf = Destination for result. Must be long enough
1382 * to hold 29 characters plus a trailing zero.
1386 *********************************************************************/
1387 void get_http_time(int time_offset, char *buf)
1389 static const char day_names[7][4] =
1390 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1391 static const char month_names[12][4] =
1392 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1393 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1396 time_t current_time;
1400 time(¤t_time); /* get current time */
1402 current_time += time_offset;
1404 /* get and save the gmt */
1406 #ifdef HAVE_GMTIME_R
1408 t = gmtime_r(¤t_time, &dummy);
1410 t = gmtime(¤t_time);
1414 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1416 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1417 day_names[t->tm_wday],
1419 month_names[t->tm_mon],
1429 /*********************************************************************
1431 * Function : finish_http_response
1433 * Description : Fill in the missing headers in an http response,
1434 * and flatten the headers to an http head.
1437 * 1 : rsp = pointer to http_response to be processed
1439 * Returns : A http_response, usually the rsp parameter.
1440 * On error, free()s rsp and returns cgi_error_memory()
1442 *********************************************************************/
1443 struct http_response *finish_http_response(struct http_response *rsp)
1445 char buf[BUFFER_SIZE];
1448 /* Special case - do NOT change this statically allocated response,
1449 * which is ready for output anyway.
1451 if (rsp == cgi_error_memory_response)
1457 * Fill in the HTTP Status
1459 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1460 err = enlist_first(rsp->headers, buf);
1463 * Set the Content-Length
1465 if (rsp->content_length == 0)
1467 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1471 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1472 err = enlist(rsp->headers, buf);
1476 * Fill in the default headers:
1478 * Content-Type: default to text/html if not already specified.
1479 * Date: set to current date/time.
1480 * Last-Modified: set to date/time the page was last changed.
1481 * Expires: set to date/time page next needs reloading.
1482 * Cache-Control: set to "no-cache" if applicable.
1484 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1486 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1491 * Set Expires to about 10 min into the future so it'll get reloaded
1492 * occasionally, e.g. if Privoxy gets upgraded.
1497 get_http_time(0, buf);
1498 err = enlist_unique_header(rsp->headers, "Date", buf);
1501 /* Some date in the past. */
1502 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1506 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1507 err = enlist_unique_header(rsp->headers, "Expires", buf);
1513 * Compliant browsers should not cache this due to the "Cache-Control"
1514 * setting. However, to be certain, we also set both "Last-Modified"
1515 * and "Expires" to the current time.
1517 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1519 get_http_time(0, buf);
1520 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1521 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1522 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1529 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1531 free_http_response(rsp);
1532 return cgi_error_memory();
1534 rsp->head_length = strlen(rsp->head);
1541 /*********************************************************************
1543 * Function : alloc_http_response
1545 * Description : Allocates a new http_response structure.
1549 * Returns : pointer to a new http_response, or NULL.
1551 *********************************************************************/
1552 struct http_response *alloc_http_response(void)
1554 return (struct http_response *) zalloc(sizeof(struct http_response));
1559 /*********************************************************************
1561 * Function : free_http_response
1563 * Description : Free the memory occupied by an http_response
1564 * and its depandant structures.
1567 * 1 : rsp = pointer to http_response to be freed
1571 *********************************************************************/
1572 void free_http_response(struct http_response *rsp)
1575 * Must special case cgi_error_memory_response, which is never freed.
1577 if (rsp && (rsp != cgi_error_memory_response))
1582 destroy_list(rsp->headers);
1589 /*********************************************************************
1591 * Function : template_load
1593 * Description : CGI support function that loads a given HTML
1594 * template from the confdir, ignoring comment
1595 * lines and following #include statements up to
1599 * 1 : csp = Current client state (buffers, headers, etc...)
1600 * 2 : template_ptr = Destination for pointer to loaded
1602 * 3 : templatename = name of the HTML template to be used
1603 * 4 : recursive = Flag set if this function calls itself
1604 * following an #include statament
1606 * Returns : JB_ERR_OK on success
1607 * JB_ERR_MEMORY on out-of-memory error.
1608 * JB_ERR_FILE if the template file cannot be read
1610 *********************************************************************/
1611 jb_err template_load(struct client_state *csp, char **template_ptr,
1612 const char *templatename, int recursive)
1615 char *templates_dir_path;
1618 char *included_module;
1621 char buf[BUFFER_SIZE];
1624 assert(template_ptr);
1625 assert(templatename);
1627 *template_ptr = NULL;
1629 /* Validate template name. Paranoia. */
1630 for (p = templatename; *p != 0; p++)
1632 if ( ((*p < 'a') || (*p > 'z'))
1633 && ((*p < 'A') || (*p > 'Z'))
1634 && ((*p < '0') || (*p > '9'))
1638 /* Illegal character */
1643 /* Generate full path */
1645 templates_dir_path = make_path(csp->config->confdir, "templates");
1646 if (templates_dir_path == NULL)
1648 return JB_ERR_MEMORY;
1651 full_path = make_path(templates_dir_path, templatename);
1652 free(templates_dir_path);
1653 if (full_path == NULL)
1655 return JB_ERR_MEMORY;
1658 /* Allocate buffer */
1660 file_buffer = strdup("");
1661 if (file_buffer == NULL)
1664 return JB_ERR_MEMORY;
1667 /* Open template file */
1669 if (NULL == (fp = fopen(full_path, "r")))
1671 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1679 * Read the file, ignoring comments, and honoring #include
1680 * statements, unless we're already called recursively.
1682 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1683 * This is unlikely in practise.
1685 while (fgets(buf, BUFFER_SIZE, fp))
1687 if (!recursive && !strncmp(buf, "#include ", 9))
1689 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1696 if (string_join(&file_buffer, included_module))
1699 return JB_ERR_MEMORY;
1705 /* skip lines starting with '#' */
1711 if (string_append(&file_buffer, buf))
1714 return JB_ERR_MEMORY;
1719 *template_ptr = file_buffer;
1725 /*********************************************************************
1727 * Function : template_fill
1729 * Description : CGI support function that fills in a pre-loaded
1730 * HTML template by replacing @name@ with value using
1731 * pcrs, for each item in the output map.
1733 * Note that a leading '$' charachter in the export map's
1734 * values will be stripped and toggle on backreference
1738 * 1 : template_ptr = IN: Template to be filled out.
1740 * OUT: Filled out template.
1741 * Caller must free().
1742 * 2 : exports = map with fill in symbol -> name pairs
1744 * Returns : JB_ERR_OK on success
1745 * JB_ERR_MEMORY on out-of-memory error
1747 *********************************************************************/
1748 jb_err template_fill(char **template_ptr, const struct map *exports)
1750 struct map_entry *m;
1752 char buf[BUFFER_SIZE];
1753 char *tmp_out_buffer;
1759 assert(template_ptr);
1760 assert(*template_ptr);
1763 file_buffer = *template_ptr;
1764 size = strlen(file_buffer) + 1;
1767 * Assemble pcrs joblist from exports map
1769 for (m = exports->first; m != NULL; m = m->next)
1771 if (*m->name == '$')
1774 * First character of name is '$', so remove this flag
1775 * character and allow backreferences ($1 etc) in the
1776 * "replace with" text.
1778 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1784 * Treat the "replace with" text as a literal string -
1785 * no quoting needed, no backreferences allowed.
1786 * ("Trivial" ['T'] flag).
1790 /* Enclose name in @@ */
1791 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1795 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1797 /* Make and run job. */
1798 job = pcrs_compile(buf, m->value, flags, &error);
1801 if (error == PCRS_ERR_NOMEM)
1804 *template_ptr = NULL;
1805 return JB_ERR_MEMORY;
1809 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1810 /* Hope it wasn't important and silently ignore the invalid job */
1815 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1818 if (NULL == tmp_out_buffer)
1820 *template_ptr = NULL;
1821 return JB_ERR_MEMORY;
1823 file_buffer = tmp_out_buffer;
1830 *template_ptr = file_buffer;
1835 /*********************************************************************
1837 * Function : template_fill_for_cgi
1839 * Description : CGI support function that loads a HTML template
1840 * and fills it in. Handles file-not-found errors
1841 * by sending a HTML error message. For convenience,
1842 * this function also frees the passed "exports" map.
1845 * 1 : csp = Client state
1846 * 2 : templatename = name of the HTML template to be used
1847 * 3 : exports = map with fill in symbol -> name pairs.
1848 * Will be freed by this function.
1849 * 4 : rsp = Response structure to fill in.
1851 * Returns : JB_ERR_OK on success
1852 * JB_ERR_MEMORY on out-of-memory error
1854 *********************************************************************/
1855 jb_err template_fill_for_cgi(struct client_state *csp,
1856 const char *templatename,
1857 struct map *exports,
1858 struct http_response *rsp)
1863 assert(templatename);
1867 err = template_load(csp, &rsp->body, templatename, 0);
1868 if (err == JB_ERR_FILE)
1871 return cgi_error_no_template(csp, rsp, templatename);
1876 return err; /* JB_ERR_MEMORY */
1878 err = template_fill(&rsp->body, exports);
1884 /*********************************************************************
1886 * Function : default_exports
1888 * Description : returns a struct map list that contains exports
1889 * which are common to all CGI functions.
1892 * 1 : csp = Current client state (buffers, headers, etc...)
1893 * 2 : caller = name of CGI who calls us and which should
1894 * be excluded from the generated menu. May be
1896 * Returns : NULL if no memory, else a new map. Caller frees.
1898 *********************************************************************/
1899 struct map *default_exports(const struct client_state *csp, const char *caller)
1903 struct map * exports;
1904 int local_help_exists = 0;
1908 exports = new_map();
1909 if (exports == NULL)
1914 err = map(exports, "version", 1, html_encode(VERSION), 0);
1915 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1916 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1917 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1918 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1919 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1920 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1921 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
1922 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
1923 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1925 snprintf(buf, 20, "%d", csp->config->hport);
1926 if (!err) err = map(exports, "my-port", 1, buf, 1);
1928 if(!strcmp(CODE_STATUS, "stable"))
1930 if (!err) err = map_block_killer(exports, "unstable");
1933 if (csp->config->admin_address != NULL)
1935 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1936 local_help_exists = 1;
1940 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1943 if (csp->config->proxy_info_url != NULL)
1945 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1946 local_help_exists = 1;
1950 if (!err) err = map_block_killer(exports, "have-proxy-info");
1953 if (local_help_exists == 0)
1955 if (!err) err = map_block_killer(exports, "have-help-info");
1968 /*********************************************************************
1970 * Function : map_block_killer
1972 * Description : Convenience function.
1973 * Adds a "killer" for the conditional HTML-template
1974 * block <name>, i.e. a substitution of the regex
1975 * "if-<name>-start.*if-<name>-end" to the given
1979 * 1 : exports = map to extend
1980 * 2 : name = name of conditional block
1982 * Returns : JB_ERR_OK on success
1983 * JB_ERR_MEMORY on out-of-memory error.
1985 *********************************************************************/
1986 jb_err map_block_killer(struct map *exports, const char *name)
1988 char buf[1000]; /* Will do, since the names are hardwired */
1992 assert(strlen(name) < 490);
1994 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1995 return map(exports, buf, 1, "", 1);
1999 /*********************************************************************
2001 * Function : map_block_keep
2003 * Description : Convenience function. Removes the markers used
2004 * by map-block-killer, to save a few bytes.
2005 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2008 * 1 : exports = map to extend
2009 * 2 : name = name of conditional block
2011 * Returns : JB_ERR_OK on success
2012 * JB_ERR_MEMORY on out-of-memory error.
2014 *********************************************************************/
2015 jb_err map_block_keep(struct map *exports, const char *name)
2018 char buf[500]; /* Will do, since the names are hardwired */
2022 assert(strlen(name) < 490);
2024 snprintf(buf, 500, "if-%s-start", name);
2025 err = map(exports, buf, 1, "", 1);
2032 snprintf(buf, 500, "if-%s-end", name);
2033 return map(exports, buf, 1, "", 1);
2037 /*********************************************************************
2039 * Function : map_conditional
2041 * Description : Convenience function.
2042 * Adds an "if-then-else" for the conditional HTML-template
2043 * block <name>, i.e. a substitution of the form:
2050 * The control structure and one of the alternatives
2054 * 1 : exports = map to extend
2055 * 2 : name = name of conditional block
2056 * 3 : choose_first = nonzero for first, zero for second.
2058 * Returns : JB_ERR_OK on success
2059 * JB_ERR_MEMORY on out-of-memory error.
2061 *********************************************************************/
2062 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2064 char buf[1000]; /* Will do, since the names are hardwired */
2069 assert(strlen(name) < 480);
2071 snprintf(buf, 1000, (choose_first
2072 ? "else-not-%s@.*@endif-%s"
2073 : "if-%s-then@.*@else-not-%s"),
2076 err = map(exports, buf, 1, "", 1);
2082 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2083 return map(exports, buf, 1, "", 1);
2087 /*********************************************************************
2089 * Function : make_menu
2091 * Description : Returns an HTML-formatted menu of the available
2092 * unhidden CGIs, excluding the one given in <self>
2094 * Parameters : self = name of CGI to leave out, can be NULL for
2097 * Returns : menu string, or NULL on out-of-memory error.
2099 *********************************************************************/
2100 char *make_menu(const char *self)
2102 const struct cgi_dispatcher *d;
2103 char *result = strdup("");
2107 self = "NO-SUCH-CGI!";
2110 /* List available unhidden CGI's and export as "other-cgis" */
2111 for (d = cgi_dispatchers; d->name; d++)
2113 if (d->description && strcmp(d->name, self))
2115 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2116 string_append(&result, d->name);
2117 string_append(&result, "\">");
2118 string_append(&result, d->description);
2119 string_append(&result, "</a></li>");
2127 /*********************************************************************
2129 * Function : dump_map
2131 * Description : HTML-dump a map for debugging (as table)
2134 * 1 : the_map = map to dump
2136 * Returns : string with HTML
2138 *********************************************************************/
2139 char *dump_map(const struct map *the_map)
2141 struct map_entry *cur_entry;
2142 char *ret = strdup("");
2144 string_append(&ret, "<table>\n");
2146 for (cur_entry = the_map->first;
2147 (cur_entry != NULL) && (ret != NULL);
2148 cur_entry = cur_entry->next)
2150 string_append(&ret, "<tr><td><b>");
2151 string_join (&ret, html_encode(cur_entry->name));
2152 string_append(&ret, "</b></td><td>");
2153 string_join (&ret, html_encode(cur_entry->value));
2154 string_append(&ret, "</td></tr>\n");
2157 string_append(&ret, "</table>\n");