1 const char cgi_rcs[] = "$Id: cgi.c,v 1.91 2007/01/27 13:09:16 fabiankeil 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-2004, 2006-2007
15 * the SourceForge 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.91 2007/01/27 13:09:16 fabiankeil
42 * Add new config option "templdir" to
43 * change the templates directory.
45 * Revision 1.90 2007/01/25 13:47:26 fabiankeil
46 * Added "forwarding-failed" template support for error_response().
48 * Revision 1.89 2007/01/23 15:51:16 fabiankeil
49 * Add favicon delivery functions.
51 * Revision 1.88 2007/01/23 13:14:32 fabiankeil
52 * - Map variables that aren't guaranteed to be
53 * pure ASCII html_encoded.
54 * - Use CGI_PREFIX to generate URL for user manual
55 * CGI page to make sure CGI_SITE_2_PATH is included.
57 * Revision 1.87 2007/01/22 15:34:13 fabiankeil
58 * - "Protect" against a rather lame JavaScript-based
59 * Privoxy detection "attack" and check the referrer
60 * before delivering the CGI style sheet.
61 * - Move referrer check for unsafe CGI pages into
62 * referrer_is_safe() and log the result.
63 * - Map @url@ in cgi-error-disabled page.
64 * It's required for the "go there anyway" link.
65 * - Mark *csp as immutable for grep_cgi_referrer().
67 * Revision 1.86 2007/01/09 11:54:26 fabiankeil
68 * Fix strdup() error handling in cgi_error_unknown()
69 * and cgi_error_no_template(). Reported by Markus Elfring.
71 * Revision 1.85 2007/01/05 14:19:02 fabiankeil
72 * Handle pcrs_execute() errors in template_fill() properly.
74 * Revision 1.84 2006/12/28 17:54:22 fabiankeil
75 * Fixed gcc43 conversion warnings and replaced sprintf
76 * calls with snprintf to give OpenBSD's gcc one less reason
79 * Revision 1.83 2006/12/17 19:35:19 fabiankeil
80 * Escape ampersand in Privoxy menu.
82 * Revision 1.82 2006/12/17 17:53:39 fabiankeil
83 * Suppress the toggle link if remote toggling is disabled.
85 * Revision 1.81 2006/12/09 13:49:16 fabiankeil
86 * Fix configure option --disable-toggle.
87 * Thanks to Peter Thoenen for reporting this.
89 * Revision 1.80 2006/12/08 14:45:32 fabiankeil
90 * Don't lose the FORCE_PREFIX in case of
91 * connection problems. Fixes #612235.
93 * Revision 1.79 2006/11/13 19:05:50 fabiankeil
94 * Make pthread mutex locking more generic. Instead of
95 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
96 * and use mutex locking unless there is an _r function
97 * available. Better safe than sorry.
99 * Fixes "./configure --disable-pthread" and should result
100 * in less threading-related problems on pthread-using platforms,
101 * but it still doesn't fix BR#1122404.
103 * Revision 1.78 2006/09/21 19:22:07 fabiankeil
104 * Use CGI_PREFIX to check the referrer.
105 * The check for "http://config.privoxy.org/" fails
106 * if the user modified CGI_SITE_2_HOST.
108 * Revision 1.77 2006/09/21 15:17:23 fabiankeil
109 * Adjusted headers for Privoxy's cgi responses:
110 * Don't set Last-Modified, Expires and Cache-Control
111 * headers for redirects; always set "Connection: close".
113 * Revision 1.76 2006/09/07 14:06:38 fabiankeil
114 * Only predate the Last-Modified header for cgi responses
115 * that are delivered with status code 404 or 503.
117 * Revision 1.75 2006/09/07 11:56:39 fabiankeil
118 * Mark cgi_send_user_manual as harmless,
119 * to fix the access denied problem Hal spotted.
120 * The manual has no secret content, therefore we
121 * don't have to care about "secure" referrers.
123 * Revision 1.74 2006/09/06 18:45:03 fabiankeil
124 * Incorporate modified version of Roland Rosenfeld's patch to
125 * optionally access the user-manual via Privoxy. Closes patch 679075.
127 * Formatting changed to Privoxy style, added call to
128 * cgi_error_no_template if the requested file doesn't
129 * exist and modified check whether or not Privoxy itself
130 * should serve the manual. Should work cross-platform now.
132 * Revision 1.73 2006/08/03 02:46:41 david__schmidt
133 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
135 * Revision 1.72 2006/07/18 14:48:45 david__schmidt
136 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
137 * with what was really the latest development (the v_3_0_branch branch)
139 * Revision 1.70.2.13 2004/02/17 13:30:23 oes
140 * Moved cgi_error_disabled() from cgiedit.c to
141 * cgi.c to re-enable build with --disable-editor.
142 * Fixes Bug #892744. Thanks to Matthew Fischer
145 * Revision 1.70.2.12 2003/12/17 16:33:16 oes
146 * - Added new function cgi_redirect to handle creation of
147 * HTTP redirect messages formerly repeated in the code.
148 * - Send cgi_error_disabled instead of cgi_error_404 when
149 * referrer check fails
150 * - Dynamic content now gets Expires header field with date
153 * Revision 1.70.2.11 2003/10/23 12:29:26 oes
154 * Bugfix: Transparent PNG was not transparent. Thanks to
155 * Dan Razzell of Starfish Systems for notice and new PNG.
157 * Revision 1.70.2.10 2003/06/06 07:54:25 oes
158 * Security fix: dspatch_known_cgi no longer considers an empty
159 * referrer safe for critical CGIs, since malicious links could
160 * reside on https:// locations which browsers don't advertize as
161 * referrers. Closes bug #749916, thanks to Jeff Epler for the
162 * hint. Goodbye One-Click[tm] toggling :-(
164 * Revision 1.70.2.9 2003/05/08 15:11:31 oes
167 * Revision 1.70.2.8 2003/04/29 13:33:51 oes
168 * Killed a compiler warning on OSX
170 * Revision 1.70.2.7 2003/04/03 13:50:58 oes
171 * - Don't call cgi_error_disabled ifndef FEATURE_CGI_EDIT_ACTIONS
172 * (fixes bug #710056)
173 * - Show toggle info only if we have it
175 * Revision 1.70.2.6 2003/03/12 01:26:25 david__schmidt
176 * Move declaration of struct tm dummy outside of a control block so it is
177 * accessible later on during snprintf in get_http_time.
179 * Revision 1.70.2.5 2003/03/11 11:53:58 oes
180 * Cosmetic: Renamed cryptic variable
182 * Revision 1.70.2.4 2003/03/07 03:41:03 david__schmidt
183 * Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX. Hopefully this will take care of all of those pesky crash reports.
185 * Revision 1.70.2.3 2002/11/28 18:14:32 oes
186 * Disable access to critical CGIs via untrusted referrers.
187 * This prevents users from being tricked by malicious websites
188 * into making unintentional configuration changes:
190 * - Added flag to each cgi_dispatcher that allows or denies
192 * - Introduced proviorical function that greps for the
193 * referrer header before regular header parsing happens
194 * - Added safety check to dispatch_known_cgi. CGI is called
195 * if (cgi harmless || no referrer || we are referrer).
196 * Else a) toggle calls are modified not to change status and
197 * b) all other calls are denied.
199 * Revision 1.70.2.2 2002/11/12 16:20:37 oes
200 * Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
202 * Revision 1.70.2.1 2002/08/05 11:17:46 oes
203 * Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
205 * Revision 1.70 2002/05/19 11:33:20 jongfoster
206 * If a CGI error was not handled, and propogated back to
207 * dispatch_known_cgi(), then it was assumed to be "out of memory".
208 * This gave a very misleading error message.
210 * Now other errors will cause a simple message giving the error
211 * number and asking the user to report a bug.
214 * http://sourceforge.net/tracker/index.php?func=detail
215 * &aid=557905&group_id=11118&atid=111118
217 * Revision 1.69 2002/05/14 21:28:40 oes
218 * - Fixed add_help_link to link to the (now split) actions
219 * part of the config chapter
220 * - Renamed helplink export to actions-help-prefix
222 * Revision 1.68 2002/05/12 21:36:29 jongfoster
223 * Correcting function comments
225 * Revision 1.67 2002/04/30 12:02:07 oes
226 * Nit: updated a comment
228 * Revision 1.66 2002/04/26 18:32:57 jongfoster
229 * Fixing a memory leak on error
231 * Revision 1.65 2002/04/26 12:53:51 oes
232 * - New function add_help_link
233 * - default_exports now exports links to the user manual
234 * and a prefix for links into the config chapter
236 * Revision 1.64 2002/04/24 02:17:21 oes
237 * - Better descriptions for CGIs
238 * - Hide edit-actions, more shortcuts
239 * - Moved get_char_param, get_string_param and get_number_param here
242 * Revision 1.63 2002/04/15 19:06:43 jongfoster
245 * Revision 1.62 2002/04/10 19:59:46 jongfoster
246 * Fixes to #include in templates:
247 * - Didn't close main file if loading an included template fails.
248 * - I'm paranoid and want to disallow "#include /etc/passwd".
250 * Revision 1.61 2002/04/10 13:37:48 oes
251 * Made templates modular: template_load now recursive with max depth 1
253 * Revision 1.60 2002/04/08 20:50:25 swa
256 * Revision 1.59 2002/04/05 15:51:51 oes
257 * - added send-stylesheet CGI
258 * - bugfix: error-pages now get correct request protocol
260 * - kludged CGI descriptions and menu not to break JS syntax
262 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
263 * Fix Mac OSX compiler warnings
265 * Revision 1.57 2002/03/26 22:29:54 swa
266 * we have a new homepage!
268 * Revision 1.56 2002/03/24 17:50:46 jongfoster
269 * Fixing compile error if actions file editor disabled
271 * Revision 1.55 2002/03/24 16:55:06 oes
272 * Making GIF checkerboard transparent
274 * Revision 1.54 2002/03/24 16:18:15 jongfoster
277 * Revision 1.53 2002/03/24 16:06:00 oes
278 * Correct transparency for checkerboard PNG. Thanks, Magnus!
280 * Revision 1.52 2002/03/24 15:23:33 jongfoster
283 * Revision 1.51 2002/03/24 13:25:43 swa
284 * name change related issues
286 * Revision 1.50 2002/03/16 23:54:06 jongfoster
287 * Adding graceful termination feature, to help look for memory leaks.
288 * If you enable this (which, by design, has to be done by hand
289 * editing config.h) and then go to http://i.j.b/die, then the program
290 * will exit cleanly after the *next* request. It should free all the
291 * memory that was used.
293 * Revision 1.49 2002/03/13 00:27:04 jongfoster
296 * Revision 1.48 2002/03/08 17:47:07 jongfoster
299 * Revision 1.47 2002/03/08 16:41:33 oes
300 * Added GIF images again
302 * Revision 1.46 2002/03/07 03:48:38 oes
303 * - Changed built-in images from GIF to PNG
304 * (with regard to Unisys patent issue)
305 * - Added a 4x4 pattern PNG which is less intrusive
306 * than the logo but also clearly marks the deleted banners
308 * Revision 1.45 2002/03/06 22:54:35 jongfoster
309 * Automated function-comment nitpicking.
311 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
312 * - Better error reporting on OS/2
313 * - Fix double-slash comment (oops)
315 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
316 * - Re-enable OS/2 building after new parms were added
317 * - Fix false out of memory report when resolving CGI templates when no IP
318 * address is available of failed attempt (a la no such domain)
320 * Revision 1.42 2002/01/21 00:33:20 jongfoster
321 * Replacing strsav() with the safer string_append() or string_join().
322 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
323 * Adding missing html_encode() to error message generators.
324 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
326 * Revision 1.41 2002/01/17 20:56:22 jongfoster
327 * Replacing hard references to the URL of the config interface
328 * with #defines from project.h
330 * Revision 1.40 2002/01/09 14:26:46 oes
331 * Added support for thread-safe gmtime_r call.
333 * Revision 1.39 2001/11/16 00:48:13 jongfoster
334 * Fixing a compiler warning
336 * Revision 1.38 2001/11/13 00:31:21 jongfoster
337 * - Adding new CGIs for use by non-JavaScript browsers:
338 * edit-actions-url-form
339 * edit-actions-add-url-form
340 * edit-actions-remove-url-form
341 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
344 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
345 * Show enablement/disablement status in almost all templates.
346 * There is a little trickiness here: apparent recursive resolution of
347 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
348 * the actual enablement status. So a similar construct,
349 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
352 * Revision 1.36 2001/10/26 17:33:27 oes
355 * Revision 1.35 2001/10/23 21:48:19 jongfoster
356 * Cleaning up error handling in CGI functions - they now send back
357 * a HTML error page and should never cause a FATAL error. (Fixes one
358 * potential source of "denial of service" attacks).
360 * CGI actions file editor that works and is actually useful.
362 * Ability to toggle Junkbuster remotely using a CGI call.
364 * You can turn off both the above features in the main configuration
365 * file, e.g. if you are running a multi-user proxy.
367 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
368 * Only show "Local support" on templates conditionally:
369 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
370 * - if not, no Local support section appears
372 * Revision 1.33 2001/10/14 22:28:41 jongfoster
373 * Fixing stupid typo.
375 * Revision 1.32 2001/10/14 22:20:18 jongfoster
376 * - Changes to CGI dispatching method to match CGI names exactly,
377 * rather than doing a prefix match.
378 * - No longer need to count the length of the CGI handler names by hand.
379 * - Adding new handler for 404 error when disptching a CGI, if none of
380 * the handlers match.
381 * - Adding new handlers for CGI actionsfile editor.
383 * Revision 1.31 2001/10/10 10:56:39 oes
384 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
386 * Revision 1.30 2001/10/02 15:30:57 oes
387 * Introduced show-request cgi
389 * Revision 1.29 2001/09/20 15:47:44 steudten
391 * Fix BUG: Modify int size to size_t size in fill_template()
392 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
394 * Revision 1.28 2001/09/19 18:00:37 oes
395 * - Deletef time() FIXME (Can't fail under Linux either, if
396 * the argument is guaranteed to be in out address space,
399 * - Pointer notation cosmetics
400 * - Fixed a minor bug in template_fill(): Failiure of
401 * pcrs_execute() now secure.
403 * Revision 1.27 2001/09/16 17:08:54 jongfoster
404 * Moving simple CGI functions from cgi.c to new file cgisimple.c
406 * Revision 1.26 2001/09/16 15:47:37 jongfoster
407 * First version of CGI-based edit interface. This is very much a
408 * work-in-progress, and you can't actually use it to edit anything
409 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
410 * to have any effect.
412 * Revision 1.25 2001/09/16 15:02:35 jongfoster
413 * Adding i.j.b/robots.txt.
414 * Inlining add_stats() since it's only ever called from one place.
416 * Revision 1.24 2001/09/16 11:38:01 jongfoster
417 * Splitting fill_template() into 2 functions:
418 * template_load() loads the file
419 * template_fill() performs the PCRS regexps.
420 * This is because the CGI edit interface has a "table row"
421 * template which is used many times in the page - this
422 * change means it's only loaded from disk once.
424 * Revision 1.23 2001/09/16 11:16:05 jongfoster
425 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
427 * Revision 1.22 2001/09/16 11:00:10 jongfoster
428 * New function alloc_http_response, for symmetry with free_http_response
430 * Revision 1.21 2001/09/13 23:53:03 jongfoster
431 * Support for both static and dynamically generated CGI pages.
432 * Correctly setting Last-Modified: and Expires: HTTP headers.
434 * Revision 1.20 2001/09/13 23:40:36 jongfoster
435 * (Cosmetic only) Indentation correction
437 * Revision 1.19 2001/09/13 23:31:25 jongfoster
438 * Moving image data to cgi.c rather than cgi.h.
440 * Revision 1.18 2001/08/05 16:06:20 jongfoster
441 * Modifiying "struct map" so that there are now separate header and
442 * "map_entry" structures. This means that functions which modify a
443 * map no longer need to return a pointer to the modified map.
444 * Also, it no longer reverses the order of the entries (which may be
445 * important with some advanced template substitutions).
447 * Revision 1.17 2001/08/05 15:57:38 oes
448 * Adapted finish_http_response to new list_to_text
450 * Revision 1.16 2001/08/01 21:33:18 jongfoster
451 * Changes to fill_template() that reduce memory usage without having
452 * an impact on performance. I also renamed some variables so as not
453 * to clash with the C++ keywords "new" and "template".
455 * Revision 1.15 2001/08/01 21:19:22 jongfoster
456 * Moving file version information to a separate CGI page.
458 * Revision 1.14 2001/08/01 00:19:03 jongfoster
459 * New function: map_conditional() for an if-then-else syntax.
460 * Changing to use new version of show_defines()
462 * Revision 1.13 2001/07/30 22:08:36 jongfoster
463 * Tidying up #defines:
464 * - All feature #defines are now of the form FEATURE_xxx
465 * - Permanently turned off WIN_GUI_EDIT
466 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
468 * Revision 1.12 2001/07/29 18:47:05 jongfoster
469 * Adding missing #include "loadcfg.h"
471 * Revision 1.11 2001/07/18 17:24:37 oes
472 * Changed to conform to new pcrs interface
474 * Revision 1.10 2001/07/13 13:53:13 oes
475 * Removed all #ifdef PCRS and related code
477 * Revision 1.9 2001/06/29 21:45:41 oes
478 * Indentation, CRLF->LF, Tab-> Space
480 * Revision 1.8 2001/06/29 13:21:46 oes
481 * - Cosmetics: renamed and reordered functions, variables,
482 * texts, improved comments etc
484 * - Removed ij_untrusted_url() The relevant
485 * info is now part of the "untrusted" page,
486 * which is generated by filters.c:trust_url()
488 * - Generators of content now call finish_http_response()
489 * themselves, making jcc.c:chat() a little less
492 * - Removed obsolete "Pragma: no-cache" from our headers
494 * - http_responses now know their head length
496 * - fill_template now uses the new interface to pcrs, so that
497 * - long jobs (like whole files) no longer have to be assembled
498 * in a fixed size buffer
499 * - the new T (trivial) option is used, and the replacement may
500 * contain Perl syntax backrefs without confusing pcrs
502 * - Introduced default_exports() which generates a set of exports
503 * common to all CGIs and other content generators
505 * - Introduced convenience function map_block_killer()
507 * - Introduced convenience function make_menu()
509 * - Introduced CGI-like function error_response() which generates
510 * the "No such domain" and "Connect failed" messages using the
513 * - cgi_show_url_info:
514 * - adapted to new CGI features
515 * - form and answers now generated from same template
516 * - http:// prefix in URL now OK
519 * - adapted to new CGI features
520 * - no longer uses csp->init_proxy_args
523 * - moved menu generation to make_menu()
525 * - add_stats now writes single export map entries instead
528 * - Moved redirect_url() to filters.c
530 * - Fixed mem leak in free_http_response(), map_block_killer(),
532 * - Removed logentry from cancelled commit
534 * Revision 1.7 2001/06/09 10:51:58 jongfoster
535 * Changing "show URL info" handler to new style.
536 * Changing BUFSIZ ==> BUFFER_SIZE
538 * Revision 1.6 2001/06/07 23:05:19 jongfoster
539 * Removing code related to old forward and ACL files.
541 * Revision 1.5 2001/06/05 19:59:16 jongfoster
542 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
544 * Revision 1.4 2001/06/04 10:41:52 swa
545 * show version string of cgi.h and cgi.c
547 * Revision 1.3 2001/06/03 19:12:16 oes
548 * introduced new cgi handling
550 * No revisions before 1.3
552 **********************************************************************/
558 #include <sys/types.h>
566 #define snprintf _snprintf
567 #endif /* def _WIN32 */
576 #include "miscutil.h"
577 #include "cgisimple.h"
578 #ifdef FEATURE_CGI_EDIT_ACTIONS
580 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
582 /* loadcfg.h is for global_toggle_state only */
583 #ifdef FEATURE_PTHREAD
585 /* jcc.h is for mutex semaphore globals only */
586 #endif /* def FEATURE_PTHREAD */
587 const char cgi_h_rcs[] = CGI_H_VERSION;
590 * List of CGI functions: name, handler, description
591 * Note: Do NOT use single quotes in the description;
592 * this will break the dynamic "blocked" template!
594 static const struct cgi_dispatcher cgi_dispatchers[] = {
599 #ifdef FEATURE_GRACEFUL_TERMINATION
602 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
603 "this is a one click Denial Of Service attack!!!</em>",
608 #ifdef FEATURE_CGI_EDIT_ACTIONS
609 "View & change the current configuration",
611 "View the current configuration",
616 "View the source code version numbers",
620 "View the request headers.",
624 "Look up which actions apply to a URL and why",
626 #ifdef FEATURE_CGI_EDIT_ACTIONS
627 #ifdef FEATURE_TOGGLE
630 "Toggle Privoxy on or off",
632 #endif /* def FEATURE_TOGGLE */
633 { "edit-actions", /* Edit the actions list */
636 { "eaa", /* Shortcut for edit-actions-add-url-form */
637 cgi_edit_actions_add_url_form,
639 { "eau", /* Shortcut for edit-actions-url-form */
640 cgi_edit_actions_url_form,
642 { "ear", /* Shortcut for edit-actions-remove-url-form */
643 cgi_edit_actions_remove_url_form,
645 { "eal", /* Shortcut for edit-actions-list */
646 cgi_edit_actions_list,
648 { "eafu", /* Shortcut for edit-actions-for-url */
649 cgi_edit_actions_for_url,
651 { "eas", /* Shortcut for edit-actions-submit */
652 cgi_edit_actions_submit,
654 { "easa", /* Shortcut for edit-actions-section-add */
655 cgi_edit_actions_section_add,
657 { "easr", /* Shortcut for edit-actions-section-remove */
658 cgi_edit_actions_section_remove,
660 { "eass", /* Shortcut for edit-actions-section-swap */
661 cgi_edit_actions_section_swap,
663 { "edit-actions-for-url",
664 cgi_edit_actions_for_url,
665 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
666 { "edit-actions-list",
667 cgi_edit_actions_list,
668 NULL, TRUE /* Edit the actions list */ },
669 { "edit-actions-submit",
670 cgi_edit_actions_submit,
671 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
672 { "edit-actions-url",
673 cgi_edit_actions_url,
674 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
675 { "edit-actions-url-form",
676 cgi_edit_actions_url_form,
677 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
678 { "edit-actions-add-url",
679 cgi_edit_actions_add_url,
680 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
681 { "edit-actions-add-url-form",
682 cgi_edit_actions_add_url_form,
683 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
684 { "edit-actions-remove-url",
685 cgi_edit_actions_remove_url,
686 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
687 { "edit-actions-remove-url-form",
688 cgi_edit_actions_remove_url_form,
689 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
690 { "edit-actions-section-add",
691 cgi_edit_actions_section_add,
692 NULL, FALSE /* Remove a section from the actionsfile */ },
693 { "edit-actions-section-remove",
694 cgi_edit_actions_section_remove,
695 NULL, FALSE /* Remove a section from the actionsfile */ },
696 { "edit-actions-section-swap",
697 cgi_edit_actions_section_swap,
698 NULL, FALSE /* Swap two sections in the actionsfile */ },
699 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
700 { "error-favicon.ico",
701 cgi_send_error_favicon,
702 NULL, TRUE /* Sends the favicon image for error pages. */ },
704 cgi_send_default_favicon,
705 NULL, TRUE /* Sends the default favicon image. */ },
708 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
711 NULL, TRUE /* Send a built-in image */ },
714 NULL, FALSE /* Send templates/cgi-style.css */ },
716 cgi_transparent_image,
717 NULL, TRUE /* Send a transparent image (short name) */ },
719 cgi_send_user_manual,
720 NULL, TRUE /* Send user-manual */ },
721 { NULL, /* NULL Indicates end of list and default page */
723 NULL, TRUE /* Unknown CGI page */ }
728 * Built-in images for ad replacement
730 * Hint: You can encode your own images like this:
731 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
734 #ifdef FEATURE_NO_GIFS
737 * Checkerboard pattern, as a PNG.
739 const char image_pattern_data[] =
740 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
741 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
742 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
743 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
744 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
745 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
746 "\000\000\000\111\105\116\104\256\102\140\202";
749 * 1x1 transparant PNG.
751 const char image_blank_data[] =
752 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
753 "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
754 "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
755 "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
756 "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
757 "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
758 "\000\000\000\000\111\105\116\104\256\102\140\202";
762 * Checkerboard pattern, as a GIF.
764 const char image_pattern_data[] =
765 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
766 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
767 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
768 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
772 * 1x1 transparant GIF.
774 const char image_blank_data[] =
775 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
776 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
777 "\000\001\000\000\002\002D\001\000;";
780 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
781 const size_t image_blank_length = sizeof(image_blank_data) - 1;
784 static struct http_response cgi_error_memory_response[1];
786 static struct http_response *dispatch_known_cgi(struct client_state * csp,
788 static struct map *parse_cgi_parameters(char *argstring);
791 /*********************************************************************
793 * Function : dispatch_cgi
795 * Description : Checks if a request URL has either the magical
796 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
797 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
798 * http://config.privoxy.org/). If so, it passes
799 * the (rest of the) path onto dispatch_known_cgi, which
800 * calls the relevant CGI handler function.
803 * 1 : csp = Current client state (buffers, headers, etc...)
805 * Returns : http_response if match, NULL if nonmatch or handler fail
807 *********************************************************************/
808 struct http_response *dispatch_cgi(struct client_state *csp)
810 const char *host = csp->http->host;
811 const char *path = csp->http->path;
814 * Should we intercept ?
817 /* Note: "example.com" and "example.com." are equivalent hostnames. */
819 /* Either the host matches CGI_SITE_1_HOST ..*/
820 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
821 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
822 && (path[0] == '/') )
824 /* ..then the path will all be for us. Remove leading '/' */
827 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
828 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
829 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
830 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
832 /* take everything following CGI_SITE_2_PATH */
833 path += strlen(CGI_SITE_2_PATH);
836 /* skip the forward slash after CGI_SITE_2_PATH */
839 else if (*path != '\0')
842 * weirdness: URL is /configXXX, where XXX is some string
843 * Do *NOT* intercept.
855 * This is a CGI call.
858 return dispatch_known_cgi(csp, path);
862 /*********************************************************************
864 * Function : grep_cgi_referrer
866 * Description : Ugly provisorical fix that greps the value of the
867 * referer HTTP header field out of a linked list of
868 * strings like found at csp->headers. Will disappear
871 * FIXME: csp->headers ought to be csp->http->headers
872 * FIXME: Parsing all client header lines should
873 * happen right after the request is received!
876 * 1 : csp = Current client state (buffers, headers, etc...)
878 * Returns : pointer to value (no copy!), or NULL if none found.
880 *********************************************************************/
881 char *grep_cgi_referrer(const struct client_state *csp)
883 struct list_entry *p;
885 for (p = csp->headers->first; p != NULL; p = p->next)
887 if (p->str == NULL) continue;
888 if (strncmpic(p->str, "Referer: ", 9) == 0)
890 return ((p->str) + 9);
898 /*********************************************************************
900 * Function : referrer_is_safe
902 * Description : Decides whether we trust the Referer for
903 * CGI pages which are only meant to be reachable
904 * through Privoxy's web interface directly.
907 * 1 : csp = Current client state (buffers, headers, etc...)
909 * Returns : TRUE if the referrer is safe, or
910 * FALSE if the referrer is unsafe or not set.
912 *********************************************************************/
913 int referrer_is_safe (const struct client_state *csp)
916 const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
918 referrer = grep_cgi_referrer(csp);
920 if (NULL == referrer)
922 /* No referrer, no access */
923 log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
926 else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)
927 || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix)))))
929 /* Trustworthy referrer */
930 log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
931 csp->http->url, referrer);
937 /* Untrustworthy referrer */
938 log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
939 csp->http->url, referrer);
946 /*********************************************************************
948 * Function : dispatch_known_cgi
950 * Description : Processes a CGI once dispatch_cgi has determined that
951 * it matches one of the magic prefixes. Parses the path
952 * as a cgi name plus query string, prepares a map that
953 * maps CGI parameter names to their values, initializes
954 * the http_response struct, and calls the relevant CGI
958 * 1 : csp = Current client state (buffers, headers, etc...)
959 * 2 : path = Path of CGI, with the CGI prefix removed.
960 * Should not have a leading "/".
962 * Returns : http_response, or NULL on handler failure or out of
965 *********************************************************************/
966 static struct http_response *dispatch_known_cgi(struct client_state * csp,
969 const struct cgi_dispatcher *d;
970 struct map *param_list;
971 struct http_response *rsp;
972 char *query_args_start;
976 if (NULL == (path_copy = strdup(path)))
978 return cgi_error_memory();
980 query_args_start = path_copy;
981 while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
985 if (*query_args_start == '/')
987 *query_args_start++ = '\0';
988 if ((param_list = new_map()))
990 map(param_list, "file", 1, url_decode(query_args_start), 0);
995 if (*query_args_start == '?')
997 *query_args_start++ = '\0';
999 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
1002 return cgi_error_memory();
1008 * path_copy = CGI call name
1009 * param_list = CGI params, as map
1012 /* Get mem for response or fail*/
1013 if (NULL == (rsp = alloc_http_response()))
1016 free_map(param_list);
1017 return cgi_error_memory();
1020 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
1021 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
1022 csp->ip_addr_str, csp->http->cmd);
1025 * Find and start the right CGI function
1027 d = cgi_dispatchers;
1030 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
1033 * If the called CGI is either harmless, or referred
1034 * from a trusted source, start it.
1036 if (d->harmless || referrer_is_safe(csp))
1038 err = (d->handler)(csp, rsp, param_list);
1043 * Else, modify toggle calls so that they only display
1044 * the status, and deny all other calls.
1046 if (0 == strcmp(path_copy, "toggle"))
1048 unmap(param_list, "set");
1049 err = (d->handler)(csp, rsp, param_list);
1053 err = cgi_error_disabled(csp, rsp);
1058 free_map(param_list);
1060 if (err == JB_ERR_CGI_PARAMS)
1062 err = cgi_error_bad_param(csp, rsp);
1064 if (err && (err != JB_ERR_MEMORY))
1066 /* Unexpected error! Shouldn't get here */
1067 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
1068 err = cgi_error_unknown(csp, rsp, err);
1073 return finish_http_response(csp, rsp);
1077 /* Error in handler, probably out-of-memory */
1078 free_http_response(rsp);
1079 return cgi_error_memory();
1087 /*********************************************************************
1089 * Function : parse_cgi_parameters
1091 * Description : Parse a URL-encoded argument string into name/value
1092 * pairs and store them in a struct map list.
1095 * 1 : argstring = string to be parsed. Will be trashed.
1097 * Returns : pointer to param list, or NULL if out of memory.
1099 *********************************************************************/
1100 static struct map *parse_cgi_parameters(char *argstring)
1103 char *vector[BUFFER_SIZE];
1105 struct map *cgi_params;
1107 if (NULL == (cgi_params = new_map()))
1113 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
1114 * the fragment identifier along with the request, so we must
1115 * cut it off here, so it won't pollute the CGI params:
1117 if (NULL != (p = strchr(argstring, '#')))
1122 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
1124 for (i = 0; i < pairs; i++)
1126 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
1129 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
1131 free_map(cgi_params);
1142 /*********************************************************************
1144 * Function : get_char_param
1146 * Description : Get a single-character parameter passed to a CGI
1150 * 1 : parameters = map of cgi parameters
1151 * 2 : param_name = The name of the parameter to read
1153 * Returns : Uppercase character on success, '\0' on error.
1155 *********************************************************************/
1156 char get_char_param(const struct map *parameters,
1157 const char *param_name)
1164 ch = *(lookup(parameters, param_name));
1165 if ((ch >= 'a') && (ch <= 'z'))
1167 ch = (char)(ch - 'a' + 'A');
1174 /*********************************************************************
1176 * Function : get_string_param
1178 * Description : Get a string paramater, to be used as an
1179 * ACTION_STRING or ACTION_MULTI paramater.
1180 * Validates the input to prevent stupid/malicious
1181 * users from corrupting their action file.
1184 * 1 : parameters = map of cgi parameters
1185 * 2 : param_name = The name of the parameter to read
1186 * 3 : pparam = destination for paramater. Allocated as
1187 * part of the map "parameters", so don't free it.
1188 * Set to NULL if not specified.
1190 * Returns : JB_ERR_OK on success, or if the paramater
1191 * was not specified.
1192 * JB_ERR_MEMORY on out-of-memory.
1193 * JB_ERR_CGI_PARAMS if the paramater is not valid.
1195 *********************************************************************/
1196 jb_err get_string_param(const struct map *parameters,
1197 const char *param_name,
1198 const char **pparam)
1210 param = lookup(parameters, param_name);
1216 if (strlen(param) >= CGI_PARAM_LEN_MAX)
1221 * Note that the length limit is arbitrary, it just seems
1222 * sensible to limit it to *something*. There's no
1223 * technical reason for any limit at all.
1225 return JB_ERR_CGI_PARAMS;
1228 /* Check every character to see if it's legal */
1230 while ((ch = *s++) != '\0')
1232 if ( ((unsigned char)ch < (unsigned char)' ')
1235 /* Probable hack attempt, or user accidentally used '}'. */
1236 return JB_ERR_CGI_PARAMS;
1247 /*********************************************************************
1249 * Function : get_number_param
1251 * Description : Get a non-negative integer from the parameters
1252 * passed to a CGI function.
1255 * 1 : csp = Current client state (buffers, headers, etc...)
1256 * 2 : parameters = map of cgi parameters
1257 * 3 : name = Name of CGI parameter to read
1258 * 4 : pvalue = destination for value.
1259 * Set to -1 on error.
1261 * Returns : JB_ERR_OK on success
1262 * JB_ERR_MEMORY on out-of-memory
1263 * JB_ERR_CGI_PARAMS if the parameter was not specified
1266 *********************************************************************/
1267 jb_err get_number_param(struct client_state *csp,
1268 const struct map *parameters,
1283 param = lookup(parameters, name);
1286 return JB_ERR_CGI_PARAMS;
1289 /* We don't use atoi because I want to check this carefully... */
1292 while ((ch = *param++) != '\0')
1294 if ((ch < '0') || (ch > '9'))
1296 return JB_ERR_CGI_PARAMS;
1299 ch = (char)(ch - '0');
1303 * <limits.h> defines UINT_MAX
1305 * (UINT_MAX - ch) / 10 is the largest number that
1306 * can be safely multiplied by 10 then have ch added.
1308 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1310 return JB_ERR_CGI_PARAMS;
1313 value = value * 10 + (unsigned)ch;
1324 /*********************************************************************
1326 * Function : error_response
1328 * Description : returns an http_response that explains the reason
1329 * why a request failed.
1332 * 1 : csp = Current client state (buffers, headers, etc...)
1333 * 2 : templatename = Which template should be used for the answer
1334 * 3 : sys_err = system error number
1336 * Returns : A http_response. If we run out of memory, this
1337 * will be cgi_error_memory().
1339 *********************************************************************/
1340 struct http_response *error_response(struct client_state *csp,
1341 const char *templatename,
1345 struct http_response *rsp;
1346 struct map *exports = default_exports(csp, NULL);
1349 if (exports == NULL)
1351 return cgi_error_memory();
1354 if (NULL == (rsp = alloc_http_response()))
1357 return cgi_error_memory();
1360 if (csp->flags & CSP_FLAG_FORCED)
1362 path = strdup(FORCE_PREFIX);
1368 err = string_append(&path, csp->http->path);
1370 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1371 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1372 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
1373 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1374 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1377 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1380 /* Some failures, like "404 no such domain", don't have an IP address. */
1381 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1389 free_http_response(rsp);
1390 return cgi_error_memory();
1393 if (!strcmp(templatename, "no-such-domain"))
1395 rsp->status = strdup("404 No such domain");
1396 if (rsp->status == NULL)
1399 free_http_response(rsp);
1400 return cgi_error_memory();
1403 else if (!strcmp(templatename, "forwarding-failed"))
1405 const struct forward_spec * fwd = forward_url(csp->http, csp);
1408 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
1409 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1413 * XXX: While the template is called forwarding-failed,
1414 * it currently only handles socks forwarding failures.
1416 assert(fwd->type != SOCKS_NONE);
1419 * Map failure reason, forwarding type and forwarder.
1421 if (NULL == csp->error_message)
1424 * Either we forgot to record the failure reason,
1425 * or the memory allocation failed.
1427 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
1428 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
1430 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
1431 if (!err) map(exports, "forwarding-type", 1, (fwd->type == SOCKS_4) ?
1432 "socks4-" : "socks4a-", 1);
1433 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
1435 if (!err) rsp->status = strdup("503 Forwarding failure");
1436 if ((rsp->status == NULL) || (NULL == csp->error_message) || err)
1439 free_http_response(rsp);
1440 return cgi_error_memory();
1443 else if (!strcmp(templatename, "connect-failed"))
1445 rsp->status = strdup("503 Connect failed");
1446 if (rsp->status == NULL)
1449 free_http_response(rsp);
1450 return cgi_error_memory();
1454 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1457 free_http_response(rsp);
1458 return cgi_error_memory();
1461 return finish_http_response(csp, rsp);
1465 /*********************************************************************
1467 * Function : cgi_error_disabled
1469 * Description : CGI function that is called to generate an error
1470 * response if the actions editor or toggle CGI are
1471 * accessed despite having being disabled at compile-
1472 * or run-time, or if the user followed an untrusted link
1473 * to access a unsafe CGI feature that is only reachable
1474 * through Privoxy directly.
1477 * 1 : csp = Current client state (buffers, headers, etc...)
1478 * 2 : rsp = http_response data structure for output
1480 * CGI Parameters : none
1482 * Returns : JB_ERR_OK on success
1483 * JB_ERR_MEMORY on out-of-memory error.
1485 *********************************************************************/
1486 jb_err cgi_error_disabled(struct client_state *csp,
1487 struct http_response *rsp)
1489 struct map *exports;
1494 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1496 return JB_ERR_MEMORY;
1498 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1500 /* Not important enough to do anything */
1501 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1504 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1508 /*********************************************************************
1510 * Function : cgi_init_error_messages
1512 * Description : Call at the start of the program to initialize
1513 * the error message used by cgi_error_memory().
1519 *********************************************************************/
1520 void cgi_init_error_messages(void)
1522 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1523 cgi_error_memory_response->head =
1524 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1525 "Content-Type: text/html\r\n"
1527 cgi_error_memory_response->body =
1530 " <title>500 Internal Privoxy Error</title>\r\n"
1531 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1534 "<h1>500 Internal Privoxy Error</h1>\r\n"
1535 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1536 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1540 cgi_error_memory_response->head_length =
1541 strlen(cgi_error_memory_response->head);
1542 cgi_error_memory_response->content_length =
1543 strlen(cgi_error_memory_response->body);
1547 /*********************************************************************
1549 * Function : cgi_error_memory
1551 * Description : Called if a CGI function runs out of memory.
1552 * Returns a statically-allocated error response.
1556 * Returns : http_response data structure for output. This is
1557 * statically allocated, for obvious reasons.
1559 *********************************************************************/
1560 struct http_response *cgi_error_memory(void)
1562 /* assert that it's been initialized. */
1563 assert(cgi_error_memory_response->head);
1565 return cgi_error_memory_response;
1569 /*********************************************************************
1571 * Function : cgi_error_no_template
1573 * Description : Almost-CGI function that is called if a template
1574 * cannot be loaded. Note this is not a true CGI,
1575 * it takes a template name rather than a map of
1579 * 1 : csp = Current client state (buffers, headers, etc...)
1580 * 2 : rsp = http_response data structure for output
1581 * 3 : template_name = Name of template that could not
1584 * Returns : JB_ERR_OK on success
1585 * JB_ERR_MEMORY on out-of-memory error.
1587 *********************************************************************/
1588 jb_err cgi_error_no_template(struct client_state *csp,
1589 struct http_response *rsp,
1590 const char *template_name)
1592 static const char status[] =
1593 "500 Internal Privoxy Error";
1594 static const char body_prefix[] =
1597 " <title>500 Internal Privoxy Error</title>\r\n"
1598 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1601 "<h1>500 Internal Privoxy Error</h1>\r\n"
1602 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1603 "<p><b>Could not load template file <code>";
1604 static const char body_suffix[] =
1605 "</code> or one of it's included components.</b></p>\r\n"
1606 "<p>Please contact your proxy administrator.</p>\r\n"
1607 "<p>If you are the proxy administrator, please put the required file(s)"
1608 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1609 "location of the <code><i>(confdir)</i></code> directory "
1610 "is specified in the main Privoxy <code>config</code> "
1611 "file. (It's typically the Privoxy install directory"
1613 ", or <code>/etc/privoxy/</code>"
1614 #endif /* ndef _WIN32 */
1621 assert(template_name);
1623 /* Reset rsp, if needed */
1627 rsp->content_length = 0;
1628 rsp->head_length = 0;
1631 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1632 if (rsp->body == NULL)
1634 return JB_ERR_MEMORY;
1636 strcpy(rsp->body, body_prefix);
1637 strcat(rsp->body, template_name);
1638 strcat(rsp->body, body_suffix);
1640 rsp->status = strdup(status);
1641 if (rsp->status == NULL)
1643 return JB_ERR_MEMORY;
1650 /*********************************************************************
1652 * Function : cgi_error_unknown
1654 * Description : Almost-CGI function that is called if an unexpected
1655 * error occurs in the top-level CGI dispatcher.
1656 * In this context, "unexpected" means "anything other
1657 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1658 * expected to handle all other errors internally,
1659 * since they can give more relavent error messages
1662 * Note this is not a true CGI, it takes an error
1663 * code rather than a map of parameters.
1666 * 1 : csp = Current client state (buffers, headers, etc...)
1667 * 2 : rsp = http_response data structure for output
1668 * 3 : error_to_report = Error code to report.
1670 * Returns : JB_ERR_OK on success
1671 * JB_ERR_MEMORY on out-of-memory error.
1673 *********************************************************************/
1674 jb_err cgi_error_unknown(struct client_state *csp,
1675 struct http_response *rsp,
1676 jb_err error_to_report)
1678 static const char status[] =
1679 "500 Internal Privoxy Error";
1680 static const char body_prefix[] =
1683 " <title>500 Internal Privoxy Error</title>\r\n"
1684 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1687 "<h1>500 Internal Privoxy Error</h1>\r\n"
1688 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1689 "<p><b>Unexpected internal error: ";
1690 static const char body_suffix[] =
1693 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1694 "file a bug report</a>.</p>\r\n"
1701 /* Reset rsp, if needed */
1705 rsp->content_length = 0;
1706 rsp->head_length = 0;
1709 snprintf(errnumbuf, sizeof(errnumbuf), "%d", error_to_report);
1711 rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1712 if (rsp->body == NULL)
1714 return JB_ERR_MEMORY;
1716 strcpy(rsp->body, body_prefix);
1717 strcat(rsp->body, errnumbuf);
1718 strcat(rsp->body, body_suffix);
1720 rsp->status = strdup(status);
1721 if (rsp->status == NULL)
1723 return JB_ERR_MEMORY;
1730 /*********************************************************************
1732 * Function : cgi_error_bad_param
1734 * Description : CGI function that is called if the parameters
1735 * (query string) for a CGI were wrong.
1738 * 1 : csp = Current client state (buffers, headers, etc...)
1739 * 2 : rsp = http_response data structure for output
1741 * CGI Parameters : none
1743 * Returns : JB_ERR_OK on success
1744 * JB_ERR_MEMORY on out-of-memory error.
1746 *********************************************************************/
1747 jb_err cgi_error_bad_param(struct client_state *csp,
1748 struct http_response *rsp)
1750 struct map *exports;
1755 if (NULL == (exports = default_exports(csp, NULL)))
1757 return JB_ERR_MEMORY;
1760 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1764 /*********************************************************************
1766 * Function : cgi_redirect
1768 * Description : CGI support function to generate a HTTP redirect
1772 * 1 : rsp = http_response data structure for output
1773 * 2 : target = string with the target URL
1775 * CGI Parameters : None
1777 * Returns : JB_ERR_OK on success
1778 * JB_ERR_MEMORY on out-of-memory error.
1780 *********************************************************************/
1781 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1788 err = enlist_unique_header(rsp->headers, "Location", target);
1790 rsp->status = strdup("302 Local Redirect from Privoxy");
1791 if (rsp->status == NULL)
1793 return JB_ERR_MEMORY;
1800 /*********************************************************************
1802 * Function : add_help_link
1804 * Description : Produce a copy of the string given as item,
1805 * embedded in an HTML link to its corresponding
1806 * section (item name in uppercase) in the actions
1807 * chapter of the user manual, (whose URL is given in
1808 * the config and defaults to our web site).
1810 * FIXME: I currently only work for actions, and would
1811 * like to be generalized for other topics.
1814 * 1 : item = item (will NOT be free()d.)
1815 * It is assumed to be HTML-safe.
1816 * 2 : config = The current configuration.
1818 * Returns : String with item embedded in link, or NULL on
1821 *********************************************************************/
1822 char *add_help_link(const char *item,
1823 struct configuration_spec *config)
1827 if (!item) return NULL;
1829 result = strdup("<a href=\"");
1830 if (!strncmpic(config->usermanual, "file://", 7) ||
1831 !strncmpic(config->usermanual, "http", 4))
1833 string_append(&result, config->usermanual);
1837 string_append(&result, "http://");
1838 string_append(&result, CGI_SITE_2_HOST);
1839 string_append(&result, "/user-manual/");
1841 string_append(&result, ACTIONS_HELP_PREFIX);
1842 string_join (&result, string_toupper(item));
1843 string_append(&result, "\">");
1844 string_append(&result, item);
1845 string_append(&result, "</a> ");
1851 /*********************************************************************
1853 * Function : get_http_time
1855 * Description : Get the time in a format suitable for use in a
1856 * HTTP header - e.g.:
1857 * "Sun, 06 Nov 1994 08:49:37 GMT"
1860 * 1 : time_offset = Time returned will be current time
1861 * plus this number of seconds.
1862 * 2 : buf = Destination for result. Must be long enough
1863 * to hold 29 characters plus a trailing zero.
1867 *********************************************************************/
1868 void get_http_time(int time_offset, char *buf)
1870 static const char day_names[7][4] =
1871 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1872 static const char month_names[12][4] =
1873 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1874 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1877 time_t current_time;
1878 #if defined(HAVE_GMTIME_R)
1880 * Declare dummy up here (instead of inside get/set gmt block) so it
1881 * doesn't go out of scope before it's potentially used in snprintf later.
1882 * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1883 * !defined HAVE_GMTIME_R.
1890 time(¤t_time); /* get current time */
1892 current_time += time_offset;
1894 /* get and save the gmt */
1897 t = gmtime_r(¤t_time, &dummy);
1898 #elif FEATURE_PTHREAD
1899 pthread_mutex_lock(&gmtime_mutex);
1900 t = gmtime(¤t_time);
1901 pthread_mutex_unlock(&gmtime_mutex);
1903 t = gmtime(¤t_time);
1907 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1909 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1910 day_names[t->tm_wday],
1912 month_names[t->tm_mon],
1922 /*********************************************************************
1924 * Function : finish_http_response
1926 * Description : Fill in the missing headers in an http response,
1927 * and flatten the headers to an http head.
1928 * For HEAD requests the body is freed once
1929 * the Content-Length header is set.
1932 * 1 : rsp = pointer to http_response to be processed
1934 * Returns : A http_response, usually the rsp parameter.
1935 * On error, free()s rsp and returns cgi_error_memory()
1937 *********************************************************************/
1938 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1940 char buf[BUFFER_SIZE];
1943 /* Special case - do NOT change this statically allocated response,
1944 * which is ready for output anyway.
1946 if (rsp == cgi_error_memory_response)
1952 * Fill in the HTTP Status
1954 snprintf(buf, sizeof(buf), "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1955 err = enlist_first(rsp->headers, buf);
1958 * Set the Content-Length
1960 if (rsp->content_length == 0)
1962 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1966 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1967 err = enlist(rsp->headers, buf);
1970 if (0 == strcmpic(csp->http->gpc, "head"))
1973 * The client only asked for the head. Dispose
1974 * the body and log an offensive message.
1976 * While it may seem to be a bit inefficient to
1977 * prepare the body if it isn't needed, it's the
1978 * only way to get the Content-Length right for
1979 * dynamic pages. We could have disposed the body
1980 * earlier, but not without duplicating the
1981 * Content-Length setting code above.
1983 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1985 rsp->content_length = 0;
1988 if ((rsp->status != NULL) && strncmpic(rsp->status, "302", 3))
1991 * If it's not a redirect without any content,
1992 * set the Content-Type to text/html if it's
1993 * not already specified.
1995 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1999 * Fill in the rest of the default headers:
2001 * Date: set to current date/time.
2002 * Last-Modified: set to date/time the page was last changed.
2003 * Expires: set to date/time page next needs reloading.
2004 * Cache-Control: set to "no-cache" if applicable.
2006 * See http://www.w3.org/Protocols/rfc2068/rfc2068
2011 * Set Expires to about 10 min into the future so it'll get reloaded
2012 * occasionally, e.g. if Privoxy gets upgraded.
2017 get_http_time(0, buf);
2018 err = enlist_unique_header(rsp->headers, "Date", buf);
2021 /* Some date in the past. */
2022 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
2026 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
2027 err = enlist_unique_header(rsp->headers, "Expires", buf);
2030 else if (!strncmpic(rsp->status, "302", 3))
2032 get_http_time(0, buf);
2033 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
2038 * Setting "Cache-Control" to "no-cache" and "Expires" to
2039 * the current time doesn't exactly forbid caching, it just
2040 * requires the client to revalidate the cached copy.
2042 * If a temporary problem occurs and the user tries again after
2043 * getting Privoxy's error message, a compliant browser may set the
2044 * If-Modified-Since header with the content of the error page's
2045 * Last-Modified header. More often than not, the document on the server
2046 * is older than Privoxy's error message, the server would send status code
2047 * 304 and the browser would display the outdated error message again and again.
2049 * For documents delivered with status code 404 or 503 we set "Last-Modified"
2050 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
2051 * and can be safely used to "revalidate" without getting a status code 304.
2053 * There is no need to let the useless If-Modified-Since header reach the
2054 * server, it is therefore stripped by client_if_modified_since in parsers.c.
2056 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
2058 get_http_time(0, buf);
2059 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
2060 if (!strncmpic(rsp->status, "404", 3) || !strncmpic(rsp->status, "503", 3))
2062 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
2066 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
2068 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
2069 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
2075 * HTTP/1.1 applications that do not support persistent connections MUST
2076 * include the "close" connection option in every message.
2078 if (!err) err = enlist_unique_header(rsp->headers, "Connection", "close");
2083 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
2085 free_http_response(rsp);
2086 return cgi_error_memory();
2088 rsp->head_length = strlen(rsp->head);
2095 /*********************************************************************
2097 * Function : alloc_http_response
2099 * Description : Allocates a new http_response structure.
2103 * Returns : pointer to a new http_response, or NULL.
2105 *********************************************************************/
2106 struct http_response *alloc_http_response(void)
2108 return (struct http_response *) zalloc(sizeof(struct http_response));
2113 /*********************************************************************
2115 * Function : free_http_response
2117 * Description : Free the memory occupied by an http_response
2118 * and its depandant structures.
2121 * 1 : rsp = pointer to http_response to be freed
2125 *********************************************************************/
2126 void free_http_response(struct http_response *rsp)
2129 * Must special case cgi_error_memory_response, which is never freed.
2131 if (rsp && (rsp != cgi_error_memory_response))
2136 destroy_list(rsp->headers);
2143 /*********************************************************************
2145 * Function : template_load
2147 * Description : CGI support function that loads a given HTML
2148 * template, ignoring comment lines and following
2149 * #include statements up to a depth of 1.
2152 * 1 : csp = Current client state (buffers, headers, etc...)
2153 * 2 : template_ptr = Destination for pointer to loaded
2155 * 3 : templatename = name of the HTML template to be used
2156 * 4 : recursive = Flag set if this function calls itself
2157 * following an #include statament
2159 * Returns : JB_ERR_OK on success
2160 * JB_ERR_MEMORY on out-of-memory error.
2161 * JB_ERR_FILE if the template file cannot be read
2163 *********************************************************************/
2164 jb_err template_load(struct client_state *csp, char **template_ptr,
2165 const char *templatename, int recursive)
2168 char *templates_dir_path;
2171 char *included_module;
2174 char buf[BUFFER_SIZE];
2177 assert(template_ptr);
2178 assert(templatename);
2180 *template_ptr = NULL;
2182 /* Validate template name. Paranoia. */
2183 for (p = templatename; *p != 0; p++)
2185 if ( ((*p < 'a') || (*p > 'z'))
2186 && ((*p < 'A') || (*p > 'Z'))
2187 && ((*p < '0') || (*p > '9'))
2191 /* Illegal character */
2197 * Generate full path using either templdir
2198 * or confdir/templates as base directory.
2200 if (NULL != csp->config->templdir)
2202 templates_dir_path = strdup(csp->config->templdir);
2206 templates_dir_path = make_path(csp->config->confdir, "templates");
2209 if (templates_dir_path == NULL)
2211 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
2213 return JB_ERR_MEMORY;
2216 full_path = make_path(templates_dir_path, templatename);
2217 free(templates_dir_path);
2218 if (full_path == NULL)
2220 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
2222 return JB_ERR_MEMORY;
2225 /* Allocate buffer */
2227 file_buffer = strdup("");
2228 if (file_buffer == NULL)
2230 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
2232 return JB_ERR_MEMORY;
2235 /* Open template file */
2237 if (NULL == (fp = fopen(full_path, "r")))
2239 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
2247 * Read the file, ignoring comments, and honoring #include
2248 * statements, unless we're already called recursively.
2250 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
2251 * This is unlikely in practise.
2253 while (fgets(buf, BUFFER_SIZE, fp))
2255 if (!recursive && !strncmp(buf, "#include ", 9))
2257 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
2264 if (string_join(&file_buffer, included_module))
2267 return JB_ERR_MEMORY;
2273 /* skip lines starting with '#' */
2279 if (string_append(&file_buffer, buf))
2282 return JB_ERR_MEMORY;
2287 *template_ptr = file_buffer;
2293 /*********************************************************************
2295 * Function : template_fill
2297 * Description : CGI support function that fills in a pre-loaded
2298 * HTML template by replacing @name@ with value using
2299 * pcrs, for each item in the output map.
2301 * Note that a leading '$' charachter in the export map's
2302 * values will be stripped and toggle on backreference
2306 * 1 : template_ptr = IN: Template to be filled out.
2308 * OUT: Filled out template.
2309 * Caller must free().
2310 * 2 : exports = map with fill in symbol -> name pairs
2312 * Returns : JB_ERR_OK on success (and for uncritical errors)
2313 * JB_ERR_MEMORY on out-of-memory error
2315 *********************************************************************/
2316 jb_err template_fill(char **template_ptr, const struct map *exports)
2318 struct map_entry *m;
2320 char buf[BUFFER_SIZE];
2321 char *tmp_out_buffer;
2327 assert(template_ptr);
2328 assert(*template_ptr);
2331 file_buffer = *template_ptr;
2332 size = strlen(file_buffer) + 1;
2335 * Assemble pcrs joblist from exports map
2337 for (m = exports->first; m != NULL; m = m->next)
2339 if (*m->name == '$')
2342 * First character of name is '$', so remove this flag
2343 * character and allow backreferences ($1 etc) in the
2344 * "replace with" text.
2346 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
2352 * Treat the "replace with" text as a literal string -
2353 * no quoting needed, no backreferences allowed.
2354 * ("Trivial" ['T'] flag).
2358 /* Enclose name in @@ */
2359 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
2363 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
2365 /* Make and run job. */
2366 job = pcrs_compile(buf, m->value, flags, &error);
2369 if (error == PCRS_ERR_NOMEM)
2372 *template_ptr = NULL;
2373 return JB_ERR_MEMORY;
2377 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2378 /* Hope it wasn't important and silently ignore the invalid job */
2383 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2386 if (NULL == tmp_out_buffer)
2388 *template_ptr = NULL;
2389 return JB_ERR_MEMORY;
2395 * Substitution failed, keep the original buffer,
2396 * log the problem and ignore it.
2398 * The user might see some unresolved @CGI_VARIABLES@,
2399 * but returning a special CGI error page seems unreasonable
2400 * and could mask more important error messages.
2402 free(tmp_out_buffer);
2403 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
2404 buf, m->value, flags, pcrs_strerror(error));
2408 /* Substitution succeeded, use modified buffer. */
2410 file_buffer = tmp_out_buffer;
2418 *template_ptr = file_buffer;
2423 /*********************************************************************
2425 * Function : template_fill_for_cgi
2427 * Description : CGI support function that loads a HTML template
2428 * and fills it in. Handles file-not-found errors
2429 * by sending a HTML error message. For convenience,
2430 * this function also frees the passed "exports" map.
2433 * 1 : csp = Client state
2434 * 2 : templatename = name of the HTML template to be used
2435 * 3 : exports = map with fill in symbol -> name pairs.
2436 * Will be freed by this function.
2437 * 4 : rsp = Response structure to fill in.
2439 * Returns : JB_ERR_OK on success
2440 * JB_ERR_MEMORY on out-of-memory error
2442 *********************************************************************/
2443 jb_err template_fill_for_cgi(struct client_state *csp,
2444 const char *templatename,
2445 struct map *exports,
2446 struct http_response *rsp)
2451 assert(templatename);
2455 err = template_load(csp, &rsp->body, templatename, 0);
2456 if (err == JB_ERR_FILE)
2459 return cgi_error_no_template(csp, rsp, templatename);
2464 return err; /* JB_ERR_MEMORY */
2466 err = template_fill(&rsp->body, exports);
2472 /*********************************************************************
2474 * Function : default_exports
2476 * Description : returns a struct map list that contains exports
2477 * which are common to all CGI functions.
2480 * 1 : csp = Current client state (buffers, headers, etc...)
2481 * 2 : caller = name of CGI who calls us and which should
2482 * be excluded from the generated menu. May be
2484 * Returns : NULL if no memory, else a new map. Caller frees.
2486 *********************************************************************/
2487 struct map *default_exports(const struct client_state *csp, const char *caller)
2491 struct map * exports;
2492 int local_help_exists = 0;
2496 exports = new_map();
2497 if (exports == NULL)
2502 err = map(exports, "version", 1, html_encode(VERSION), 0);
2503 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2504 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2505 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2506 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2507 if (!err) err = map(exports, "menu", 1, make_menu(caller, csp->config->feature_flags), 0);
2508 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2509 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2510 !strncmpic(csp->config->usermanual, "http", 4))
2512 /* Manual is located somewhere else, just link to it. */
2513 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2517 /* Manual is delivered by Privoxy. */
2518 if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2520 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2521 #ifdef FEATURE_TOGGLE
2522 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2524 if (!err) err = map_block_killer(exports, "can-toggle");
2527 snprintf(buf, 20, "%d", csp->config->hport);
2528 if (!err) err = map(exports, "my-port", 1, buf, 1);
2530 if(!strcmp(CODE_STATUS, "stable"))
2532 if (!err) err = map_block_killer(exports, "unstable");
2535 if (csp->config->admin_address != NULL)
2537 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2538 local_help_exists = 1;
2542 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2545 if (csp->config->proxy_info_url != NULL)
2547 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2548 local_help_exists = 1;
2552 if (!err) err = map_block_killer(exports, "have-proxy-info");
2555 if (local_help_exists == 0)
2557 if (!err) err = map_block_killer(exports, "have-help-info");
2570 /*********************************************************************
2572 * Function : map_block_killer
2574 * Description : Convenience function.
2575 * Adds a "killer" for the conditional HTML-template
2576 * block <name>, i.e. a substitution of the regex
2577 * "if-<name>-start.*if-<name>-end" to the given
2581 * 1 : exports = map to extend
2582 * 2 : name = name of conditional block
2584 * Returns : JB_ERR_OK on success
2585 * JB_ERR_MEMORY on out-of-memory error.
2587 *********************************************************************/
2588 jb_err map_block_killer(struct map *exports, const char *name)
2590 char buf[1000]; /* Will do, since the names are hardwired */
2594 assert(strlen(name) < 490);
2596 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2597 return map(exports, buf, 1, "", 1);
2601 /*********************************************************************
2603 * Function : map_block_keep
2605 * Description : Convenience function. Removes the markers used
2606 * by map-block-killer, to save a few bytes.
2607 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2610 * 1 : exports = map to extend
2611 * 2 : name = name of conditional block
2613 * Returns : JB_ERR_OK on success
2614 * JB_ERR_MEMORY on out-of-memory error.
2616 *********************************************************************/
2617 jb_err map_block_keep(struct map *exports, const char *name)
2620 char buf[500]; /* Will do, since the names are hardwired */
2624 assert(strlen(name) < 490);
2626 snprintf(buf, 500, "if-%s-start", name);
2627 err = map(exports, buf, 1, "", 1);
2634 snprintf(buf, 500, "if-%s-end", name);
2635 return map(exports, buf, 1, "", 1);
2639 /*********************************************************************
2641 * Function : map_conditional
2643 * Description : Convenience function.
2644 * Adds an "if-then-else" for the conditional HTML-template
2645 * block <name>, i.e. a substitution of the form:
2652 * The control structure and one of the alternatives
2656 * 1 : exports = map to extend
2657 * 2 : name = name of conditional block
2658 * 3 : choose_first = nonzero for first, zero for second.
2660 * Returns : JB_ERR_OK on success
2661 * JB_ERR_MEMORY on out-of-memory error.
2663 *********************************************************************/
2664 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2666 char buf[1000]; /* Will do, since the names are hardwired */
2671 assert(strlen(name) < 480);
2673 snprintf(buf, 1000, (choose_first
2674 ? "else-not-%s@.*@endif-%s"
2675 : "if-%s-then@.*@else-not-%s"),
2678 err = map(exports, buf, 1, "", 1);
2684 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2685 return map(exports, buf, 1, "", 1);
2689 /*********************************************************************
2691 * Function : make_menu
2693 * Description : Returns an HTML-formatted menu of the available
2694 * unhidden CGIs, excluding the one given in <self>
2695 * and the toggle CGI if toggling is disabled.
2698 * 1 : self = name of CGI to leave out, can be NULL for
2700 * 2 : feature_flags = feature bitmap from csp->config
2703 * Returns : menu string, or NULL on out-of-memory error.
2705 *********************************************************************/
2706 char *make_menu(const char *self, const unsigned feature_flags)
2708 const struct cgi_dispatcher *d;
2709 char *result = strdup("");
2713 self = "NO-SUCH-CGI!";
2716 /* List available unhidden CGI's and export as "other-cgis" */
2717 for (d = cgi_dispatchers; d->name; d++)
2720 #ifdef FEATURE_TOGGLE
2721 if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2724 * Suppress the toggle link if remote toggling is disabled.
2728 #endif /* def FEATURE_TOGGLE */
2730 if (d->description && strcmp(d->name, self))
2732 char *html_encoded_prefix;
2734 string_append(&result, "<li><a href=\"");
2735 html_encoded_prefix = html_encode(CGI_PREFIX);
2736 if (html_encoded_prefix == NULL)
2742 string_append(&result, html_encoded_prefix);
2743 free(html_encoded_prefix);
2745 string_append(&result, d->name);
2746 string_append(&result, "\">");
2747 string_append(&result, d->description);
2748 string_append(&result, "</a></li>\n");
2756 /*********************************************************************
2758 * Function : dump_map
2760 * Description : HTML-dump a map for debugging (as table)
2763 * 1 : the_map = map to dump
2765 * Returns : string with HTML
2767 *********************************************************************/
2768 char *dump_map(const struct map *the_map)
2770 struct map_entry *cur_entry;
2771 char *ret = strdup("");
2773 string_append(&ret, "<table>\n");
2775 for (cur_entry = the_map->first;
2776 (cur_entry != NULL) && (ret != NULL);
2777 cur_entry = cur_entry->next)
2779 string_append(&ret, "<tr><td><b>");
2780 string_join (&ret, html_encode(cur_entry->name));
2781 string_append(&ret, "</b></td><td>");
2782 string_join (&ret, html_encode(cur_entry->value));
2783 string_append(&ret, "</td></tr>\n");
2786 string_append(&ret, "</table>\n");