Install man page as privoxy(8) instead of privoxy(1), because this is
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.70.2.10 2003/06/06 07:54:25 oes Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/Attic/cgi.c,v $
5  *
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.
10  *                
11  *                Functions declared include:
12  * 
13  *
14  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
15  *                Privoxy team. http://www.privoxy.org/
16  *
17  *                Based on the Internet Junkbuster originally written
18  *                by and Copyright (C) 1997 Anonymous Coders and 
19  *                Junkbusters Corporation.  http://www.junkbusters.com
20  *
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.
26  *
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.
32  *
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.
38  *
39  * Revisions   :
40  *    $Log: cgi.c,v $
41  *    Revision 1.70.2.10  2003/06/06 07:54:25  oes
42  *    Security fix: dspatch_known_cgi no longer considers an empty
43  *    referrer safe for critical CGIs, since malicious links could
44  *    reside on https:// locations which browsers don't advertize as
45  *    referrers. Closes bug #749916, thanks to Jeff Epler for the
46  *    hint. Goodbye One-Click[tm] toggling :-(
47  *
48  *    Revision 1.70.2.9  2003/05/08 15:11:31  oes
49  *    Nit
50  *
51  *    Revision 1.70.2.8  2003/04/29 13:33:51  oes
52  *    Killed a compiler warning on OSX
53  *
54  *    Revision 1.70.2.7  2003/04/03 13:50:58  oes
55  *    - Don't call cgi_error_disabled ifndef FEATURE_CGI_EDIT_ACTIONS
56  *      (fixes bug #710056)
57  *    - Show toggle info only if we have it
58  *
59  *    Revision 1.70.2.6  2003/03/12 01:26:25  david__schmidt
60  *    Move declaration of struct tm dummy outside of a control block so it is
61  *    accessible later on during snprintf in get_http_time.
62  *
63  *    Revision 1.70.2.5  2003/03/11 11:53:58  oes
64  *    Cosmetic: Renamed cryptic variable
65  *
66  *    Revision 1.70.2.4  2003/03/07 03:41:03  david__schmidt
67  *    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.
68  *
69  *    Revision 1.70.2.3  2002/11/28 18:14:32  oes
70  *    Disable access to critical CGIs via untrusted referrers.
71  *    This prevents users from being tricked by malicious websites
72  *    into making unintentional configuration changes:
73  *
74  *     - Added flag to each cgi_dispatcher that allows or denies
75  *       external linking
76  *     - Introduced proviorical function that greps for the
77  *       referrer header before regular header parsing happens
78  *     - Added safety check to dispatch_known_cgi. CGI is called
79  *       if (cgi harmless || no referrer || we are referrer).
80  *       Else a) toggle calls are modified not to change status and
81  *       b) all other calls are denied.
82  *
83  *    Revision 1.70.2.2  2002/11/12 16:20:37  oes
84  *    Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
85  *
86  *    Revision 1.70.2.1  2002/08/05 11:17:46  oes
87  *    Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
88  *
89  *    Revision 1.70  2002/05/19 11:33:20  jongfoster
90  *    If a CGI error was not handled, and propogated back to
91  *    dispatch_known_cgi(), then it was assumed to be "out of memory".
92  *    This gave a very misleading error message.
93  *
94  *    Now other errors will cause a simple message giving the error
95  *    number and asking the user to report a bug.
96  *
97  *    Bug report:
98  *    http://sourceforge.net/tracker/index.php?func=detail
99  *    &aid=557905&group_id=11118&atid=111118
100  *
101  *    Revision 1.69  2002/05/14 21:28:40  oes
102  *     - Fixed add_help_link to link to the (now split) actions
103  *       part of the config chapter
104  *     - Renamed helplink export to actions-help-prefix
105  *
106  *    Revision 1.68  2002/05/12 21:36:29  jongfoster
107  *    Correcting function comments
108  *
109  *    Revision 1.67  2002/04/30 12:02:07  oes
110  *    Nit: updated a comment
111  *
112  *    Revision 1.66  2002/04/26 18:32:57  jongfoster
113  *    Fixing a memory leak on error
114  *
115  *    Revision 1.65  2002/04/26 12:53:51  oes
116  *     - New function add_help_link
117  *     - default_exports now exports links to the user manual
118  *       and a prefix for links into the config chapter
119  *
120  *    Revision 1.64  2002/04/24 02:17:21  oes
121  *     - Better descriptions for CGIs
122  *     - Hide edit-actions, more shortcuts
123  *     - Moved get_char_param, get_string_param and get_number_param here
124  *       from cgiedit.c
125  *
126  *    Revision 1.63  2002/04/15 19:06:43  jongfoster
127  *    Typos
128  *
129  *    Revision 1.62  2002/04/10 19:59:46  jongfoster
130  *    Fixes to #include in templates:
131  *    - Didn't close main file if loading an included template fails.
132  *    - I'm paranoid and want to disallow "#include /etc/passwd".
133  *
134  *    Revision 1.61  2002/04/10 13:37:48  oes
135  *    Made templates modular: template_load now recursive with max depth 1
136  *
137  *    Revision 1.60  2002/04/08 20:50:25  swa
138  *    fixed JB spelling
139  *
140  *    Revision 1.59  2002/04/05 15:51:51  oes
141  *     - added send-stylesheet CGI
142  *     - bugfix: error-pages now get correct request protocol
143  *     - fixed
144  *     - kludged CGI descriptions and menu not to break JS syntax
145  *
146  *    Revision 1.58  2002/03/29 03:33:13  david__schmidt
147  *    Fix Mac OSX compiler warnings
148  *
149  *    Revision 1.57  2002/03/26 22:29:54  swa
150  *    we have a new homepage!
151  *
152  *    Revision 1.56  2002/03/24 17:50:46  jongfoster
153  *    Fixing compile error if actions file editor disabled
154  *
155  *    Revision 1.55  2002/03/24 16:55:06  oes
156  *    Making GIF checkerboard transparent
157  *
158  *    Revision 1.54  2002/03/24 16:18:15  jongfoster
159  *    Removing old logo
160  *
161  *    Revision 1.53  2002/03/24 16:06:00  oes
162  *    Correct transparency for checkerboard PNG. Thanks, Magnus!
163  *
164  *    Revision 1.52  2002/03/24 15:23:33  jongfoster
165  *    Name changes
166  *
167  *    Revision 1.51  2002/03/24 13:25:43  swa
168  *    name change related issues
169  *
170  *    Revision 1.50  2002/03/16 23:54:06  jongfoster
171  *    Adding graceful termination feature, to help look for memory leaks.
172  *    If you enable this (which, by design, has to be done by hand
173  *    editing config.h) and then go to http://i.j.b/die, then the program
174  *    will exit cleanly after the *next* request.  It should free all the
175  *    memory that was used.
176  *
177  *    Revision 1.49  2002/03/13 00:27:04  jongfoster
178  *    Killing warnings
179  *
180  *    Revision 1.48  2002/03/08 17:47:07  jongfoster
181  *    Adding comments
182  *
183  *    Revision 1.47  2002/03/08 16:41:33  oes
184  *    Added GIF images again
185  *
186  *    Revision 1.46  2002/03/07 03:48:38  oes
187  *     - Changed built-in images from GIF to PNG
188  *       (with regard to Unisys patent issue)
189  *     - Added a 4x4 pattern PNG which is less intrusive
190  *       than the logo but also clearly marks the deleted banners
191  *
192  *    Revision 1.45  2002/03/06 22:54:35  jongfoster
193  *    Automated function-comment nitpicking.
194  *
195  *    Revision 1.44  2002/03/05 22:43:45  david__schmidt
196  *    - Better error reporting on OS/2
197  *    - Fix double-slash comment (oops)
198  *
199  *    Revision 1.43  2002/03/05 21:33:45  david__schmidt
200  *    - Re-enable OS/2 building after new parms were added
201  *    - Fix false out of memory report when resolving CGI templates when no IP
202  *      address is available of failed attempt (a la no such domain)
203  *
204  *    Revision 1.42  2002/01/21 00:33:20  jongfoster
205  *    Replacing strsav() with the safer string_append() or string_join().
206  *    Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
207  *    Adding missing html_encode() to error message generators.
208  *    Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
209  *
210  *    Revision 1.41  2002/01/17 20:56:22  jongfoster
211  *    Replacing hard references to the URL of the config interface
212  *    with #defines from project.h
213  *
214  *    Revision 1.40  2002/01/09 14:26:46  oes
215  *    Added support for thread-safe gmtime_r call.
216  *
217  *    Revision 1.39  2001/11/16 00:48:13  jongfoster
218  *    Fixing a compiler warning
219  *
220  *    Revision 1.38  2001/11/13 00:31:21  jongfoster
221  *    - Adding new CGIs for use by non-JavaScript browsers:
222  *        edit-actions-url-form
223  *        edit-actions-add-url-form
224  *        edit-actions-remove-url-form
225  *    - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
226  *    - Fixing || bug.
227  *
228  *    Revision 1.37  2001/11/01 14:28:47  david__schmidt
229  *    Show enablement/disablement status in almost all templates.
230  *    There is a little trickiness here: apparent recursive resolution of
231  *    @if-enabled-then@ caused the toggle template to show status out-of-phase with
232  *    the actual enablement status.  So a similar construct,
233  *    @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
234  *    templates.
235  *
236  *    Revision 1.36  2001/10/26 17:33:27  oes
237  *    marginal bugfix
238  *
239  *    Revision 1.35  2001/10/23 21:48:19  jongfoster
240  *    Cleaning up error handling in CGI functions - they now send back
241  *    a HTML error page and should never cause a FATAL error.  (Fixes one
242  *    potential source of "denial of service" attacks).
243  *
244  *    CGI actions file editor that works and is actually useful.
245  *
246  *    Ability to toggle Junkbuster remotely using a CGI call.
247  *
248  *    You can turn off both the above features in the main configuration
249  *    file, e.g. if you are running a multi-user proxy.
250  *
251  *    Revision 1.34  2001/10/18 22:22:09  david__schmidt
252  *    Only show "Local support" on templates conditionally:
253  *      - if either 'admin-address' or 'proxy-info-url' are uncommented in config
254  *      - if not, no Local support section appears
255  *
256  *    Revision 1.33  2001/10/14 22:28:41  jongfoster
257  *    Fixing stupid typo.
258  *
259  *    Revision 1.32  2001/10/14 22:20:18  jongfoster
260  *    - Changes to CGI dispatching method to match CGI names exactly,
261  *      rather than doing a prefix match.
262  *    - No longer need to count the length of the CGI handler names by hand.
263  *    - Adding new handler for 404 error when disptching a CGI, if none of
264  *      the handlers match.
265  *    - Adding new handlers for CGI actionsfile editor.
266  *
267  *    Revision 1.31  2001/10/10 10:56:39  oes
268  *    Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
269  *
270  *    Revision 1.30  2001/10/02 15:30:57  oes
271  *    Introduced show-request cgi
272  *
273  *    Revision 1.29  2001/09/20 15:47:44  steudten
274  *
275  *    Fix BUG: Modify int size to size_t size in fill_template()
276  *     - removes big trouble on machines where sizeof(int) != sizeof(size_t).
277  *
278  *    Revision 1.28  2001/09/19 18:00:37  oes
279  *     - Deletef time() FIXME (Can't fail under Linux either, if
280  *       the argument is guaranteed to be in out address space,
281  *       which it is.)
282  *     - Fixed comments
283  *     - Pointer notation cosmetics
284  *     - Fixed a minor bug in template_fill(): Failiure of
285  *       pcrs_execute() now secure.
286  *
287  *    Revision 1.27  2001/09/16 17:08:54  jongfoster
288  *    Moving simple CGI functions from cgi.c to new file cgisimple.c
289  *
290  *    Revision 1.26  2001/09/16 15:47:37  jongfoster
291  *    First version of CGI-based edit interface.  This is very much a
292  *    work-in-progress, and you can't actually use it to edit anything
293  *    yet.  You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
294  *    to have any effect.
295  *
296  *    Revision 1.25  2001/09/16 15:02:35  jongfoster
297  *    Adding i.j.b/robots.txt.
298  *    Inlining add_stats() since it's only ever called from one place.
299  *
300  *    Revision 1.24  2001/09/16 11:38:01  jongfoster
301  *    Splitting fill_template() into 2 functions:
302  *    template_load() loads the file
303  *    template_fill() performs the PCRS regexps.
304  *    This is because the CGI edit interface has a "table row"
305  *    template which is used many times in the page - this
306  *    change means it's only loaded from disk once.
307  *
308  *    Revision 1.23  2001/09/16 11:16:05  jongfoster
309  *    Better error handling in dispatch_cgi() and parse_cgi_parameters()
310  *
311  *    Revision 1.22  2001/09/16 11:00:10  jongfoster
312  *    New function alloc_http_response, for symmetry with free_http_response
313  *
314  *    Revision 1.21  2001/09/13 23:53:03  jongfoster
315  *    Support for both static and dynamically generated CGI pages.
316  *    Correctly setting Last-Modified: and Expires: HTTP headers.
317  *
318  *    Revision 1.20  2001/09/13 23:40:36  jongfoster
319  *    (Cosmetic only) Indentation correction
320  *
321  *    Revision 1.19  2001/09/13 23:31:25  jongfoster
322  *    Moving image data to cgi.c rather than cgi.h.
323  *
324  *    Revision 1.18  2001/08/05 16:06:20  jongfoster
325  *    Modifiying "struct map" so that there are now separate header and
326  *    "map_entry" structures.  This means that functions which modify a
327  *    map no longer need to return a pointer to the modified map.
328  *    Also, it no longer reverses the order of the entries (which may be
329  *    important with some advanced template substitutions).
330  *
331  *    Revision 1.17  2001/08/05 15:57:38  oes
332  *    Adapted finish_http_response to new list_to_text
333  *
334  *    Revision 1.16  2001/08/01 21:33:18  jongfoster
335  *    Changes to fill_template() that reduce memory usage without having
336  *    an impact on performance.  I also renamed some variables so as not
337  *    to clash with the C++ keywords "new" and "template".
338  *
339  *    Revision 1.15  2001/08/01 21:19:22  jongfoster
340  *    Moving file version information to a separate CGI page.
341  *
342  *    Revision 1.14  2001/08/01 00:19:03  jongfoster
343  *    New function: map_conditional() for an if-then-else syntax.
344  *    Changing to use new version of show_defines()
345  *
346  *    Revision 1.13  2001/07/30 22:08:36  jongfoster
347  *    Tidying up #defines:
348  *    - All feature #defines are now of the form FEATURE_xxx
349  *    - Permanently turned off WIN_GUI_EDIT
350  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
351  *
352  *    Revision 1.12  2001/07/29 18:47:05  jongfoster
353  *    Adding missing #include "loadcfg.h"
354  *
355  *    Revision 1.11  2001/07/18 17:24:37  oes
356  *    Changed to conform to new pcrs interface
357  *
358  *    Revision 1.10  2001/07/13 13:53:13  oes
359  *    Removed all #ifdef PCRS and related code
360  *
361  *    Revision 1.9  2001/06/29 21:45:41  oes
362  *    Indentation, CRLF->LF, Tab-> Space
363  *
364  *    Revision 1.8  2001/06/29 13:21:46  oes
365  *    - Cosmetics: renamed and reordered functions, variables,
366  *      texts, improved comments  etc
367  *
368  *    - Removed ij_untrusted_url() The relevant
369  *      info is now part of the "untrusted" page,
370  *      which is generated by filters.c:trust_url()
371  *
372  *    - Generators of content now call finish_http_response()
373  *      themselves, making jcc.c:chat() a little less
374  *      cluttered
375  *
376  *    - Removed obsolete "Pragma: no-cache" from our headers
377  *
378  *    - http_responses now know their head length
379  *
380  *    - fill_template now uses the new interface to pcrs, so that
381  *       - long jobs (like whole files) no longer have to be assembled
382  *         in a fixed size buffer
383  *       - the new T (trivial) option is used, and the replacement may
384  *         contain Perl syntax backrefs without confusing pcrs
385  *
386  *    - Introduced default_exports() which generates a set of exports
387  *      common to all CGIs and other content generators
388  *
389  *    - Introduced convenience function map_block_killer()
390  *
391  *    - Introduced convenience function make_menu()
392  *
393  *    - Introduced CGI-like function error_response() which generates
394  *      the "No such domain" and "Connect failed" messages using the
395  *      CGI platform
396  *
397  *    - cgi_show_url_info:
398  *      - adapted to new CGI features
399  *      - form and answers now generated from same template
400  *      - http:// prefix in URL now OK
401  *
402  *    - cgi_show_status:
403  *      - adapted to new CGI features
404  *      - no longer uses csp->init_proxy_args
405  *
406  *    - cgi_default:
407  *      - moved menu generation to make_menu()
408  *
409  *    - add_stats now writes single export map entries instead
410  *      of a fixed string
411  *
412  *    - Moved redirect_url() to filters.c
413  *
414  *    - Fixed mem leak in free_http_response(), map_block_killer(),
415  *
416  *    - Removed logentry from cancelled commit
417  *
418  *    Revision 1.7  2001/06/09 10:51:58  jongfoster
419  *    Changing "show URL info" handler to new style.
420  *    Changing BUFSIZ ==> BUFFER_SIZE
421  *
422  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
423  *    Removing code related to old forward and ACL files.
424  *
425  *    Revision 1.5  2001/06/05 19:59:16  jongfoster
426  *    Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
427  *
428  *    Revision 1.4  2001/06/04 10:41:52  swa
429  *    show version string of cgi.h and cgi.c
430  *
431  *    Revision 1.3  2001/06/03 19:12:16  oes
432  *    introduced new cgi handling
433  *
434  *    No revisions before 1.3
435  *
436  **********************************************************************/
437 \f
438
439 #include "config.h"
440
441 #include <stdio.h>
442 #include <sys/types.h>
443 #include <stdlib.h>
444 #include <ctype.h>
445 #include <string.h>
446 #include <limits.h>
447 #include <assert.h>
448
449 #ifdef _WIN32
450 #define snprintf _snprintf
451 #endif /* def _WIN32 */
452
453 #include "project.h"
454 #include "cgi.h"
455 #include "list.h"
456 #include "encode.h"
457 #include "ssplit.h"
458 #include "errlog.h"
459 #include "miscutil.h"
460 #include "cgisimple.h"
461 #ifdef FEATURE_CGI_EDIT_ACTIONS
462 #include "cgiedit.h"
463 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
464 #include "loadcfg.h"
465 /* loadcfg.h is for global_toggle_state only */
466 #ifdef FEATURE_PTHREAD
467 #include <pthread.h>
468 #include "jcc.h"
469 /* jcc.h is for mutex semaphore globals only */
470 #endif /* def FEATURE_PTHREAD */
471 const char cgi_h_rcs[] = CGI_H_VERSION;
472
473 /*
474  * List of CGI functions: name, handler, description
475  * Note: Do NOT use single quotes in the description;
476  *       this will break the dynamic "blocked" template!
477  */
478 static const struct cgi_dispatcher cgi_dispatchers[] = {
479    { "",
480          cgi_default,
481          "Privoxy main page",
482          TRUE },
483 #ifdef FEATURE_GRACEFUL_TERMINATION
484    { "die", 
485          cgi_die,  
486          "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
487         "this is a one click Denial Of Service attack!!!</em>",
488          FALSE }, 
489 #endif
490    { "show-status", 
491          cgi_show_status,  
492 #ifdef FEATURE_CGI_EDIT_ACTIONS
493         "View & change the current configuration",
494 #else
495         "View the current configuration",
496 #endif
497          TRUE }, 
498    { "show-version", 
499          cgi_show_version,  
500          "View the source code version numbers",
501           TRUE }, 
502    { "show-request", 
503          cgi_show_request,  
504          "View the request headers.",
505          TRUE }, 
506    { "show-url-info",
507          cgi_show_url_info, 
508          "Look up which actions apply to a URL and why",
509          TRUE },
510 #ifdef FEATURE_CGI_EDIT_ACTIONS
511    { "toggle",
512          cgi_toggle, 
513          "Toggle Privoxy on or off",
514          FALSE },
515    { "edit-actions", /* Edit the actions list */
516          cgi_edit_actions, 
517          NULL, FALSE },
518    { "eaa", /* Shortcut for edit-actions-add-url-form */
519          cgi_edit_actions_add_url_form, 
520          NULL, FALSE },
521    { "eau", /* Shortcut for edit-actions-url-form */
522          cgi_edit_actions_url_form, 
523          NULL, FALSE },
524    { "ear", /* Shortcut for edit-actions-remove-url-form */
525          cgi_edit_actions_remove_url_form, 
526          NULL, FALSE },
527    { "eafu", /* Shortcut for edit-actions-for-url */
528          cgi_edit_actions_for_url, 
529          NULL, FALSE },
530    { "eas", /* Shortcut for edit-actions-submit */
531          cgi_edit_actions_submit, 
532          NULL, FALSE },
533    { "easa", /* Shortcut for edit-actions-section-add */
534          cgi_edit_actions_section_add, 
535          NULL, FALSE  },
536    { "easr", /* Shortcut for edit-actions-section-remove */
537          cgi_edit_actions_section_remove, 
538          NULL, FALSE  },
539    { "eass", /* Shortcut for edit-actions-section-swap */
540          cgi_edit_actions_section_swap, 
541          NULL, FALSE  },
542    { "edit-actions-for-url",
543          cgi_edit_actions_for_url, 
544          NULL, FALSE  /* Edit the actions for (a) specified URL(s) */ },
545    { "edit-actions-list",
546          cgi_edit_actions_list, 
547          NULL, TRUE /* Edit the actions list */ },
548    { "edit-actions-submit",
549          cgi_edit_actions_submit, 
550          NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
551    { "edit-actions-url",
552          cgi_edit_actions_url, 
553          NULL, FALSE /* Change a URL pattern in the actionsfile */ },
554    { "edit-actions-url-form",
555          cgi_edit_actions_url_form, 
556          NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
557    { "edit-actions-add-url",
558          cgi_edit_actions_add_url, 
559          NULL, FALSE /* Add a URL pattern to the actionsfile */ },
560    { "edit-actions-add-url-form",
561          cgi_edit_actions_add_url_form, 
562          NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
563    { "edit-actions-remove-url",
564          cgi_edit_actions_remove_url, 
565          NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
566    { "edit-actions-remove-url-form",
567          cgi_edit_actions_remove_url_form, 
568          NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
569    { "edit-actions-section-add",
570          cgi_edit_actions_section_add, 
571          NULL, FALSE /* Remove a section from the actionsfile */ },
572    { "edit-actions-section-remove",
573          cgi_edit_actions_section_remove, 
574          NULL, FALSE /* Remove a section from the actionsfile */ },
575    { "edit-actions-section-swap",
576          cgi_edit_actions_section_swap, 
577          NULL, FALSE /* Swap two sections in the actionsfile */ },
578 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
579    { "robots.txt", 
580          cgi_robots_txt,  
581          NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ }, 
582    { "send-banner",
583          cgi_send_banner, 
584          NULL, TRUE /* Send a built-in image */ },
585    { "send-stylesheet",
586          cgi_send_stylesheet, 
587          NULL, TRUE /* Send templates/cgi-style.css */ },
588    { "t",
589          cgi_transparent_image, 
590          NULL, TRUE /* Send a transparent image (short name) */ },
591    { NULL, /* NULL Indicates end of list and default page */
592          cgi_error_404,
593          NULL, TRUE /* Unknown CGI page */ }
594 };
595
596
597 /*
598  * Built-in images for ad replacement
599  *
600  * Hint: You can encode your own images like this:
601  * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
602  */
603
604 #ifdef FEATURE_NO_GIFS
605
606 /*
607  * Checkerboard pattern, as a PNG.
608  */
609 const char image_pattern_data[] =
610    "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
611    "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
612    "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
613    "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
614    "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
615    "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
616    "\000\000\000\111\105\116\104\256\102\140\202";
617
618 /*
619  * 1x1 transparant PNG.
620  */
621 const char image_blank_data[] =
622  "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
623  "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
624  "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
625  "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
626  "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
627  "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
628  "\000\000\000\000\111\105\116\104\256\102\140\202";
629 #else
630
631 /*
632  * Checkerboard pattern, as a GIF.
633  */
634 const char image_pattern_data[] =
635    "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
636    "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
637    "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
638    "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
639    "\270\005\000\073";
640
641 /*
642  * 1x1 transparant GIF.
643  */
644 const char image_blank_data[] =
645    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
646    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
647    "\000\001\000\000\002\002D\001\000;";
648 #endif
649
650 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
651 const size_t image_blank_length   = sizeof(image_blank_data) - 1;
652
653
654 static struct http_response cgi_error_memory_response[1];
655
656 static struct http_response *dispatch_known_cgi(struct client_state * csp,
657                                                 const char * path);
658 static struct map *parse_cgi_parameters(char *argstring);
659
660
661 /*********************************************************************
662  * 
663  * Function    :  dispatch_cgi
664  *
665  * Description :  Checks if a request URL has either the magical
666  *                hostname CGI_SITE_1_HOST (usually http://p.p/) or
667  *                matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
668  *                http://config.privoxy.org/). If so, it passes
669  *                the (rest of the) path onto dispatch_known_cgi, which
670  *                calls the relevant CGI handler function.
671  *
672  * Parameters  :
673  *          1  :  csp = Current client state (buffers, headers, etc...)
674  *
675  * Returns     :  http_response if match, NULL if nonmatch or handler fail
676  *
677  *********************************************************************/
678 struct http_response *dispatch_cgi(struct client_state *csp)
679 {
680    const char *host = csp->http->host;
681    const char *path = csp->http->path;
682
683    /*
684     * Should we intercept ?
685     */
686
687    /* Note: "example.com" and "example.com." are equivalent hostnames. */
688
689    /* Either the host matches CGI_SITE_1_HOST ..*/
690    if (   ( (0 == strcmpic(host, CGI_SITE_1_HOST))
691          || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
692        && (path[0] == '/') )
693    {
694       /* ..then the path will all be for us.  Remove leading '/' */
695       path++;
696    }
697    /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
698    else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
699             || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
700           && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
701    {
702       /* take everything following CGI_SITE_2_PATH */
703       path += strlen(CGI_SITE_2_PATH);
704       if (*path == '/')
705       {
706          /* skip the forward slash after CGI_SITE_2_PATH */
707          path++;
708       }
709       else if (*path != '\0')
710       {
711          /*
712           * wierdness: URL is /configXXX, where XXX is some string
713           * Do *NOT* intercept.
714           */
715          return NULL;
716       }
717    }
718    else
719    {
720       /* Not a CGI */
721       return NULL;
722    }
723
724    /* 
725     * This is a CGI call.
726     */
727
728    return dispatch_known_cgi(csp, path);
729 }
730
731
732 /*********************************************************************
733  *
734  * Function    :  grep_cgi_referrer
735  *
736  * Description :  Ugly provisorical fix that greps the value of the
737  *                referer HTTP header field out of a linked list of
738  *                strings like found at csp->headers. Will disappear
739  *                in Privoxy 3.1.
740  *
741  *                FIXME: csp->headers ought to be csp->http->headers
742  *                FIXME: Parsing all client header lines should
743  *                       happen right after the request is received!
744  *
745  * Parameters  :
746  *          1  :  csp = Current client state (buffers, headers, etc...)
747  *
748  * Returns     :  pointer to value (no copy!), or NULL if none found.
749  *
750  *********************************************************************/
751 char *grep_cgi_referrer(struct client_state *csp)
752 {
753    struct list_entry *p;
754
755    for (p = csp->headers->first; p != NULL; p = p->next)
756    {
757       if (p->str == NULL) continue;
758       if (strncmpic(p->str, "Referer: ", 9) == 0)
759       {
760          return ((p->str) + 9);
761       }
762    }
763    return NULL;
764
765 }
766
767
768 /*********************************************************************
769  * 
770  * Function    :  dispatch_known_cgi
771  *
772  * Description :  Processes a CGI once dispatch_cgi has determined that
773  *                it matches one of the magic prefixes. Parses the path
774  *                as a cgi name plus query string, prepares a map that
775  *                maps CGI parameter names to their values, initializes
776  *                the http_response struct, and calls the relevant CGI
777  *                handler function.
778  *
779  * Parameters  :
780  *          1  :  csp = Current client state (buffers, headers, etc...)
781  *          2  :  path = Path of CGI, with the CGI prefix removed.
782  *                       Should not have a leading "/".
783  *
784  * Returns     :  http_response, or NULL on handler failure or out of
785  *                memory.
786  *
787  *********************************************************************/
788 static struct http_response *dispatch_known_cgi(struct client_state * csp,
789                                                 const char * path)
790 {
791    const struct cgi_dispatcher *d;
792    struct map *param_list;
793    struct http_response *rsp;
794    char *query_args_start;
795    char *path_copy;
796    char *referrer;
797    jb_err err;
798
799    if (NULL == (path_copy = strdup(path)))
800    {
801       return cgi_error_memory();
802    }
803
804    query_args_start = path_copy;
805    while (*query_args_start && *query_args_start != '?')
806    {
807       query_args_start++;
808    }
809    if (*query_args_start == '?')
810    {
811       *query_args_start++ = '\0';
812    }
813
814    if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
815    {
816       free(path_copy);
817       return cgi_error_memory();
818    }
819
820    /*
821     * At this point:
822     * path_copy        = CGI call name
823     * param_list       = CGI params, as map
824     */
825
826    /* Get mem for response or fail*/
827    if (NULL == (rsp = alloc_http_response()))
828    {
829       free(path_copy);
830       free_map(param_list);
831       return cgi_error_memory();
832    }
833
834    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
835    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
836                             csp->ip_addr_str, csp->http->cmd); 
837
838    /* 
839     * Find and start the right CGI function
840     */
841    d = cgi_dispatchers;
842    for (;;)
843    {
844       if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
845       {
846          /*
847           * If the called CGI is either harmless, or referred
848           * from a trusted source, start it.
849           */
850          if (d->harmless
851              || ((NULL != (referrer = grep_cgi_referrer(csp)))
852                  && (0 == strncmp(referrer, "http://config.privoxy.org/", 26)))
853              )
854          {
855             err = (d->handler)(csp, rsp, param_list);
856          }
857          else
858          {
859             /*
860              * Else, modify toggle calls so that they only display
861              * the status, and deny all other calls.
862              */
863             if (0 == strcmp(path_copy, "toggle"))
864             {
865                unmap(param_list, "set");
866                err = (d->handler)(csp, rsp, param_list);
867             }
868             else
869             {
870                err = cgi_error_404(csp, rsp, param_list);
871             }
872          }
873
874          free(path_copy);
875          free_map(param_list);
876
877          if (err == JB_ERR_CGI_PARAMS)
878          {
879             err = cgi_error_bad_param(csp, rsp);
880          }
881          if (err && (err != JB_ERR_MEMORY))
882          {
883             /* Unexpected error! Shouldn't get here */
884             log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler.  Please file a bug report!", err);
885             err = cgi_error_unknown(csp, rsp, err);
886          }
887          if (!err)
888          {
889             /* It worked */
890             return finish_http_response(rsp);
891          }
892          else
893          {
894             /* Error in handler, probably out-of-memory */
895             free_http_response(rsp);
896             return cgi_error_memory();
897          }
898       }
899       d++;
900    }
901 }
902    
903         
904 /*********************************************************************
905  *
906  * Function    :  parse_cgi_parameters
907  *
908  * Description :  Parse a URL-encoded argument string into name/value
909  *                pairs and store them in a struct map list.
910  *
911  * Parameters  :
912  *          1  :  argstring = string to be parsed.  Will be trashed.
913  *
914  * Returns     :  pointer to param list, or NULL if out of memory.
915  *
916  *********************************************************************/
917 static struct map *parse_cgi_parameters(char *argstring)
918 {
919    char *p;
920    char *vector[BUFFER_SIZE];
921    int pairs, i;
922    struct map *cgi_params;
923
924    if (NULL == (cgi_params = new_map()))
925    {
926       return NULL;
927    }
928
929    /* 
930     * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
931     * the fragment identifier along with the request, so we must
932     * cut it off here, so it won't pollute the CGI params:
933     */
934    if (NULL != (p = strchr(argstring, '#')))
935    {
936       *p = '\0';
937    }
938
939    pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
940
941    for (i = 0; i < pairs; i++)
942    {
943       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
944       {
945          *p = '\0';
946          if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
947          {
948             free_map(cgi_params);
949             return NULL;
950          }
951       }
952    }
953
954    return cgi_params;
955
956 }
957
958
959 /*********************************************************************
960  *
961  * Function    :  get_char_param
962  *
963  * Description :  Get a single-character parameter passed to a CGI
964  *                function.
965  *
966  * Parameters  :
967  *          1  :  parameters = map of cgi parameters
968  *          2  :  param_name = The name of the parameter to read
969  *
970  * Returns     :  Uppercase character on success, '\0' on error.
971  *
972  *********************************************************************/
973 char get_char_param(const struct map *parameters,
974                     const char *param_name)
975 {
976    char ch;
977
978    assert(parameters);
979    assert(param_name);
980
981    ch = *(lookup(parameters, param_name));
982    if ((ch >= 'a') && (ch <= 'z'))
983    {
984       ch = ch - 'a' + 'A';
985    }
986
987    return ch;
988 }
989
990
991 /*********************************************************************
992  *
993  * Function    :  get_string_param
994  *
995  * Description :  Get a string paramater, to be used as an
996  *                ACTION_STRING or ACTION_MULTI paramater.
997  *                Validates the input to prevent stupid/malicious
998  *                users from corrupting their action file.
999  *
1000  * Parameters  :
1001  *          1  :  parameters = map of cgi parameters
1002  *          2  :  param_name = The name of the parameter to read
1003  *          3  :  pparam = destination for paramater.  Allocated as
1004  *                part of the map "parameters", so don't free it.
1005  *                Set to NULL if not specified.
1006  *
1007  * Returns     :  JB_ERR_OK         on success, or if the paramater
1008  *                                  was not specified.
1009  *                JB_ERR_MEMORY     on out-of-memory.
1010  *                JB_ERR_CGI_PARAMS if the paramater is not valid.
1011  *
1012  *********************************************************************/
1013 jb_err get_string_param(const struct map *parameters,
1014                         const char *param_name,
1015                         const char **pparam)
1016 {
1017    const char *param;
1018    const char *s;
1019    char ch;
1020
1021    assert(parameters);
1022    assert(param_name);
1023    assert(pparam);
1024
1025    *pparam = NULL;
1026
1027    param = lookup(parameters, param_name);
1028    if (!*param)
1029    {
1030       return JB_ERR_OK;
1031    }
1032
1033    if (strlen(param) >= CGI_PARAM_LEN_MAX)
1034    {
1035       /*
1036        * Too long.
1037        *
1038        * Note that the length limit is arbitrary, it just seems
1039        * sensible to limit it to *something*.  There's no
1040        * technical reason for any limit at all.
1041        */
1042       return JB_ERR_CGI_PARAMS;
1043    }
1044
1045    /* Check every character to see if it's legal */
1046    s = param;
1047    while ((ch = *s++) != '\0')
1048    {
1049       if ( ((unsigned char)ch < (unsigned char)' ')
1050         || (ch == '}') )
1051       {
1052          /* Probable hack attempt, or user accidentally used '}'. */
1053          return JB_ERR_CGI_PARAMS;
1054       }
1055    }
1056
1057    /* Success */
1058    *pparam = param;
1059
1060    return JB_ERR_OK;
1061 }
1062
1063
1064 /*********************************************************************
1065  *
1066  * Function    :  get_number_param
1067  *
1068  * Description :  Get a non-negative integer from the parameters
1069  *                passed to a CGI function.
1070  *
1071  * Parameters  :
1072  *          1  :  csp = Current client state (buffers, headers, etc...)
1073  *          2  :  parameters = map of cgi parameters
1074  *          3  :  name = Name of CGI parameter to read
1075  *          4  :  pvalue = destination for value.
1076  *                         Set to -1 on error.
1077  *
1078  * Returns     :  JB_ERR_OK         on success
1079  *                JB_ERR_MEMORY     on out-of-memory
1080  *                JB_ERR_CGI_PARAMS if the parameter was not specified
1081  *                                  or is not valid.
1082  *
1083  *********************************************************************/
1084 jb_err get_number_param(struct client_state *csp,
1085                         const struct map *parameters,
1086                         char *name,
1087                         unsigned *pvalue)
1088 {
1089    const char *param;
1090    char ch;
1091    unsigned value;
1092
1093    assert(csp);
1094    assert(parameters);
1095    assert(name);
1096    assert(pvalue);
1097
1098    *pvalue = 0; 
1099
1100    param = lookup(parameters, name);
1101    if (!*param)
1102    {
1103       return JB_ERR_CGI_PARAMS;
1104    }
1105
1106    /* We don't use atoi because I want to check this carefully... */
1107
1108    value = 0;
1109    while ((ch = *param++) != '\0')
1110    {
1111       if ((ch < '0') || (ch > '9'))
1112       {
1113          return JB_ERR_CGI_PARAMS;
1114       }
1115
1116       ch -= '0';
1117
1118       /* Note:
1119        *
1120        * <limits.h> defines UINT_MAX
1121        *
1122        * (UINT_MAX - ch) / 10 is the largest number that
1123        *     can be safely multiplied by 10 then have ch added.
1124        */
1125       if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1126       {
1127          return JB_ERR_CGI_PARAMS;
1128       }
1129
1130       value = value * 10 + ch;
1131    }
1132
1133    /* Success */
1134    *pvalue = value;
1135
1136    return JB_ERR_OK;
1137
1138 }
1139
1140
1141 /*********************************************************************
1142  *
1143  * Function    :  error_response
1144  *
1145  * Description :  returns an http_response that explains the reason
1146  *                why a request failed.
1147  *
1148  * Parameters  :
1149  *          1  :  csp = Current client state (buffers, headers, etc...)
1150  *          2  :  templatename = Which template should be used for the answer
1151  *          3  :  sys_err = system error number
1152  *
1153  * Returns     :  A http_response.  If we run out of memory, this
1154  *                will be cgi_error_memory().
1155  *
1156  *********************************************************************/
1157 struct http_response *error_response(struct client_state *csp,
1158                                      const char *templatename,
1159                                      int sys_err)
1160 {
1161    jb_err err;
1162    struct http_response *rsp;
1163    struct map * exports = default_exports(csp, NULL);
1164    if (exports == NULL)
1165    {
1166       return cgi_error_memory();
1167    }
1168
1169    if (NULL == (rsp = alloc_http_response()))
1170    {
1171       free_map(exports);
1172       return cgi_error_memory();
1173    }
1174
1175    err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1176    if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1177    if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1178    if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1179    if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1); 
1180    if (!err)
1181    {
1182      err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1183      if (err)
1184      {
1185        /* Some failures, like "404 no such domain", don't have an IP address. */
1186        err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1187      }
1188    }
1189
1190
1191    if (err)
1192    {
1193       free_map(exports);
1194       free_http_response(rsp);
1195       return cgi_error_memory();
1196    }
1197
1198    if (!strcmp(templatename, "no-such-domain"))
1199    {
1200       rsp->status = strdup("404 No such domain");
1201       if (rsp->status == NULL)
1202       {
1203          free_map(exports);
1204          free_http_response(rsp);
1205          return cgi_error_memory();
1206       }
1207    }
1208    else if (!strcmp(templatename, "connect-failed"))
1209    {
1210       rsp->status = strdup("503 Connect failed");
1211       if (rsp->status == NULL)
1212       {
1213          free_map(exports);
1214          free_http_response(rsp);
1215          return cgi_error_memory();
1216       }
1217    }
1218
1219    err = template_fill_for_cgi(csp, templatename, exports, rsp);
1220    if (err)
1221    {
1222       free_http_response(rsp);
1223       return cgi_error_memory();
1224    }
1225
1226    return finish_http_response(rsp);
1227 }
1228
1229
1230 /*********************************************************************
1231  *
1232  * Function    :  cgi_init_error_messages
1233  *
1234  * Description :  Call at the start of the program to initialize
1235  *                the error message used by cgi_error_memory().
1236  *
1237  * Parameters  :  N/A
1238  *
1239  * Returns     :  N/A
1240  *
1241  *********************************************************************/
1242 void cgi_init_error_messages(void)
1243 {
1244    memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1245    cgi_error_memory_response->head =
1246       "HTTP/1.0 500 Internal Privoxy Error\r\n"
1247       "Content-Type: text/html\r\n"
1248       "\r\n";
1249    cgi_error_memory_response->body =
1250       "<html>\r\n"
1251       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1252       "<body>\r\n"
1253       "<h1>500 Internal Privoxy Error</h1>\r\n"
1254       "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1255       "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1256       "</body>\r\n"
1257       "</html>\r\n";
1258
1259    cgi_error_memory_response->head_length =
1260       strlen(cgi_error_memory_response->head);
1261    cgi_error_memory_response->content_length =
1262       strlen(cgi_error_memory_response->body);
1263 }
1264
1265
1266 /*********************************************************************
1267  *
1268  * Function    :  cgi_error_memory
1269  *
1270  * Description :  Called if a CGI function runs out of memory.
1271  *                Returns a statically-allocated error response.
1272  *
1273  * Parameters  :  N/A
1274  *
1275  * Returns     :  http_response data structure for output.  This is
1276  *                statically allocated, for obvious reasons.
1277  *
1278  *********************************************************************/
1279 struct http_response *cgi_error_memory(void)
1280 {
1281    /* assert that it's been initialized. */
1282    assert(cgi_error_memory_response->head);
1283
1284    return cgi_error_memory_response;
1285 }
1286
1287
1288 /*********************************************************************
1289  *
1290  * Function    :  cgi_error_no_template
1291  *
1292  * Description :  Almost-CGI function that is called if a template
1293  *                cannot be loaded.  Note this is not a true CGI,
1294  *                it takes a template name rather than a map of 
1295  *                parameters.
1296  *
1297  * Parameters  :
1298  *          1  :  csp = Current client state (buffers, headers, etc...)
1299  *          2  :  rsp = http_response data structure for output
1300  *          3  :  template_name = Name of template that could not
1301  *                                be loaded.
1302  *
1303  * Returns     :  JB_ERR_OK on success
1304  *                JB_ERR_MEMORY on out-of-memory error.  
1305  *
1306  *********************************************************************/
1307 jb_err cgi_error_no_template(struct client_state *csp,
1308                              struct http_response *rsp,
1309                              const char *template_name)
1310 {
1311    static const char status[] =
1312       "500 Internal Privoxy Error";
1313    static const char body_prefix[] =
1314       "<html>\r\n"
1315       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1316       "<body>\r\n"
1317       "<h1>500 Internal Privoxy Error</h1>\r\n"
1318       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1319       "<p><b>Could not load template file <code>";
1320    static const char body_suffix[] =
1321       "</code> or one of it's included components.</b></p>\r\n"
1322       "<p>Please contact your proxy administrator.</p>\r\n"
1323       "<p>If you are the proxy administrator, please put the required file(s)"
1324       "in the <code><i>(confdir)</i>/templates</code> directory.  The "
1325       "location of the <code><i>(confdir)</i></code> directory "
1326       "is specified in the main Privoxy <code>config</code> "
1327       "file.  (It's typically the Privoxy install directory"
1328 #ifndef _WIN32
1329       ", or <code>/etc/privoxy/</code>"
1330 #endif /* ndef _WIN32 */
1331       ").</p>\r\n"
1332       "</body>\r\n"
1333       "</html>\r\n";
1334
1335    assert(csp);
1336    assert(rsp);
1337    assert(template_name);
1338
1339    /* Reset rsp, if needed */
1340    freez(rsp->status);
1341    freez(rsp->head);
1342    freez(rsp->body);
1343    rsp->content_length = 0;
1344    rsp->head_length = 0;
1345    rsp->is_static = 0;
1346
1347    rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1348    if (rsp->body == NULL)
1349    {
1350       return JB_ERR_MEMORY;
1351    }
1352    strcpy(rsp->body, body_prefix);
1353    strcat(rsp->body, template_name);
1354    strcat(rsp->body, body_suffix);
1355
1356    rsp->status = strdup(status);
1357    if (rsp->body == NULL)
1358    {
1359       return JB_ERR_MEMORY;
1360    }
1361
1362    return JB_ERR_OK;
1363 }
1364
1365
1366 /*********************************************************************
1367  *
1368  * Function    :  cgi_error_unknown
1369  *
1370  * Description :  Almost-CGI function that is called if an unexpected
1371  *                error occurs in the top-level CGI dispatcher.
1372  *                In this context, "unexpected" means "anything other
1373  *                than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1374  *                expected to handle all other errors internally,
1375  *                since they can give more relavent error messages
1376  *                that way.
1377  *
1378  *                Note this is not a true CGI, it takes an error
1379  *                code rather than a map of parameters.
1380  *
1381  * Parameters  :
1382  *          1  :  csp = Current client state (buffers, headers, etc...)
1383  *          2  :  rsp = http_response data structure for output
1384  *          3  :  error_to_report = Error code to report.
1385  *
1386  * Returns     :  JB_ERR_OK on success
1387  *                JB_ERR_MEMORY on out-of-memory error.  
1388  *
1389  *********************************************************************/
1390 jb_err cgi_error_unknown(struct client_state *csp,
1391                          struct http_response *rsp,
1392                          jb_err error_to_report)
1393 {
1394    static const char status[] =
1395       "500 Internal Privoxy Error";
1396    static const char body_prefix[] =
1397       "<html>\r\n"
1398       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1399       "<body>\r\n"
1400       "<h1>500 Internal Privoxy Error</h1>\r\n"
1401       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1402       "<p><b>Unexpected internal error: ";
1403    static const char body_suffix[] =
1404       "</b></p>\r\n"
1405       "<p>Please "
1406       "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1407       "file a bug report</a>.</p>\r\n"
1408       "</body>\r\n"
1409       "</html>\r\n";
1410    char errnumbuf[30];
1411    assert(csp);
1412    assert(rsp);
1413
1414    /* Reset rsp, if needed */
1415    freez(rsp->status);
1416    freez(rsp->head);
1417    freez(rsp->body);
1418    rsp->content_length = 0;
1419    rsp->head_length = 0;
1420    rsp->is_static = 0;
1421
1422    sprintf(errnumbuf, "%d", error_to_report);
1423
1424    rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1425    if (rsp->body == NULL)
1426    {
1427       return JB_ERR_MEMORY;
1428    }
1429    strcpy(rsp->body, body_prefix);
1430    strcat(rsp->body, errnumbuf);
1431    strcat(rsp->body, body_suffix);
1432
1433    rsp->status = strdup(status);
1434    if (rsp->body == NULL)
1435    {
1436       return JB_ERR_MEMORY;
1437    }
1438
1439    return JB_ERR_OK;
1440 }
1441
1442
1443 /*********************************************************************
1444  *
1445  * Function    :  cgi_error_bad_param
1446  *
1447  * Description :  CGI function that is called if the parameters
1448  *                (query string) for a CGI were wrong.
1449  *               
1450  * Parameters  :
1451  *          1  :  csp = Current client state (buffers, headers, etc...)
1452  *          2  :  rsp = http_response data structure for output
1453  *
1454  * CGI Parameters : none
1455  *
1456  * Returns     :  JB_ERR_OK on success
1457  *                JB_ERR_MEMORY on out-of-memory error.  
1458  *
1459  *********************************************************************/
1460 jb_err cgi_error_bad_param(struct client_state *csp,
1461                            struct http_response *rsp)
1462 {
1463    struct map *exports;
1464
1465    assert(csp);
1466    assert(rsp);
1467
1468    if (NULL == (exports = default_exports(csp, NULL)))
1469    {
1470       return JB_ERR_MEMORY;
1471    }
1472
1473    return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1474 }
1475
1476
1477 /*********************************************************************
1478  *
1479  * Function    :  add_help_link
1480  *
1481  * Description :  Produce a copy of the string given as item,
1482  *                embedded in an HTML link to its corresponding
1483  *                section (item name in uppercase) in the actions
1484  *                chapter of the user manual, (whose URL is given in
1485  *                the config and defaults to our web site).
1486  *
1487  *                FIXME: I currently only work for actions, and would
1488  *                       like to be generalized for other topics.
1489  *
1490  * Parameters  :  
1491  *          1  :  item = item (will NOT be free()d.) 
1492  *                       It is assumed to be HTML-safe.
1493  *          2  :  config = The current configuration.
1494  *
1495  * Returns     :  String with item embedded in link, or NULL on
1496  *                out-of-memory
1497  *
1498  *********************************************************************/
1499 char *add_help_link(const char *item,
1500                     struct configuration_spec *config)
1501 {
1502    char *result;
1503
1504    if (!item) return NULL;
1505
1506    result = strdup("<a href=\"");
1507    string_append(&result, config->usermanual);
1508    string_append(&result, ACTIONS_HELP_PREFIX);
1509    string_join  (&result, string_toupper(item));
1510    string_append(&result, "\">");
1511    string_append(&result, item);
1512    string_append(&result, "</a> ");
1513
1514    return result;
1515 }
1516
1517
1518 /*********************************************************************
1519  *
1520  * Function    :  get_http_time
1521  *
1522  * Description :  Get the time in a format suitable for use in a
1523  *                HTTP header - e.g.:
1524  *                "Sun, 06 Nov 1994 08:49:37 GMT"
1525  *
1526  * Parameters  :  
1527  *          1  :  time_offset = Time returned will be current time
1528  *                              plus this number of seconds.
1529  *          2  :  buf = Destination for result.  Must be long enough
1530  *                      to hold 29 characters plus a trailing zero.
1531  *
1532  * Returns     :  N/A
1533  *
1534  *********************************************************************/
1535 void get_http_time(int time_offset, char *buf)
1536 {
1537    static const char day_names[7][4] =
1538       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1539    static const char month_names[12][4] =
1540       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1541         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1542
1543    struct tm *t;
1544    time_t current_time;
1545 #if defined(HAVE_GMTIME_R) && !defined(OSX_DARWIN)
1546    /*
1547     * Declare dummy up here (instead of inside get/set gmt block) so it
1548     * doesn't go out of scope before it's potentially used in snprintf later.
1549     * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1550     * !defined HAVE_GMTIME_R.
1551     */
1552    struct tm dummy; 
1553 #endif
1554
1555    assert(buf);
1556
1557    time(&current_time); /* get current time */
1558
1559    current_time += time_offset;
1560
1561    /* get and save the gmt */
1562    {
1563 #ifdef OSX_DARWIN
1564       pthread_mutex_lock(&gmtime_mutex);
1565       t = gmtime(&current_time);
1566       pthread_mutex_unlock(&gmtime_mutex);
1567 #elif HAVE_GMTIME_R
1568       t = gmtime_r(&current_time, &dummy);
1569 #else
1570       t = gmtime(&current_time);
1571 #endif
1572    }
1573
1574    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1575    snprintf(buf, 30,
1576       "%s, %02d %s %4d %02d:%02d:%02d GMT",
1577       day_names[t->tm_wday],
1578       t->tm_mday,
1579       month_names[t->tm_mon],
1580       t->tm_year + 1900,
1581       t->tm_hour,
1582       t->tm_min,
1583       t->tm_sec
1584       );
1585
1586 }
1587
1588
1589 /*********************************************************************
1590  *
1591  * Function    :  finish_http_response
1592  *
1593  * Description :  Fill in the missing headers in an http response,
1594  *                and flatten the headers to an http head.
1595  *
1596  * Parameters  :
1597  *          1  :  rsp = pointer to http_response to be processed
1598  *
1599  * Returns     :  A http_response, usually the rsp parameter.
1600  *                On error, free()s rsp and returns cgi_error_memory()
1601  *
1602  *********************************************************************/
1603 struct http_response *finish_http_response(struct http_response *rsp)
1604 {
1605    char buf[BUFFER_SIZE];
1606    jb_err err;
1607
1608    /* Special case - do NOT change this statically allocated response,
1609     * which is ready for output anyway.
1610     */
1611    if (rsp == cgi_error_memory_response)
1612    {
1613       return rsp;
1614    }
1615
1616    /* 
1617     * Fill in the HTTP Status
1618     */
1619    sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1620    err = enlist_first(rsp->headers, buf);
1621
1622    /* 
1623     * Set the Content-Length
1624     */
1625    if (rsp->content_length == 0)
1626    {
1627       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1628    }
1629    if (!err)
1630    {
1631       sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1632       err = enlist(rsp->headers, buf);
1633    }
1634
1635    /* 
1636     * Fill in the default headers:
1637     *
1638     * Content-Type: default to text/html if not already specified.
1639     * Date: set to current date/time.
1640     * Last-Modified: set to date/time the page was last changed.
1641     * Expires: set to date/time page next needs reloading.
1642     * Cache-Control: set to "no-cache" if applicable.
1643     * 
1644     * See http://www.w3.org/Protocols/rfc2068/rfc2068
1645     */
1646    if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1647
1648    if (rsp->is_static)
1649    {
1650       /*
1651        * Set Expires to about 10 min into the future so it'll get reloaded
1652        * occasionally, e.g. if Privoxy gets upgraded.
1653        */
1654
1655       if (!err)
1656       {
1657          get_http_time(0, buf);
1658          err = enlist_unique_header(rsp->headers, "Date", buf);
1659       }
1660
1661       /* Some date in the past. */
1662       if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1663
1664       if (!err)
1665       {
1666          get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1667          err = enlist_unique_header(rsp->headers, "Expires", buf);
1668       }
1669    }
1670    else
1671    {
1672       /*
1673        * Compliant browsers should not cache this due to the "Cache-Control"
1674        * setting.  However, to be certain, we also set both "Last-Modified"
1675        * and "Expires" to the current time.
1676        */
1677       if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1678
1679       get_http_time(0, buf);
1680       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1681       if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1682       if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1683    }
1684
1685
1686    /* 
1687     * Write the head
1688     */
1689    if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1690    {
1691       free_http_response(rsp);
1692       return cgi_error_memory();
1693    }
1694    rsp->head_length = strlen(rsp->head);
1695
1696    return rsp;
1697
1698 }
1699
1700
1701 /*********************************************************************
1702  *
1703  * Function    :  alloc_http_response
1704  *
1705  * Description :  Allocates a new http_response structure.
1706  *
1707  * Parameters  :  N/A
1708  *
1709  * Returns     :  pointer to a new http_response, or NULL.
1710  *
1711  *********************************************************************/
1712 struct http_response *alloc_http_response(void)
1713 {
1714    return (struct http_response *) zalloc(sizeof(struct http_response));
1715
1716 }
1717
1718
1719 /*********************************************************************
1720  *
1721  * Function    :  free_http_response
1722  *
1723  * Description :  Free the memory occupied by an http_response
1724  *                and its depandant structures.
1725  *
1726  * Parameters  :
1727  *          1  :  rsp = pointer to http_response to be freed
1728  *
1729  * Returns     :  N/A
1730  *
1731  *********************************************************************/
1732 void free_http_response(struct http_response *rsp)
1733 {
1734    /*
1735     * Must special case cgi_error_memory_response, which is never freed.
1736     */
1737    if (rsp && (rsp != cgi_error_memory_response))
1738    {
1739       freez(rsp->status);
1740       freez(rsp->head);
1741       freez(rsp->body);
1742       destroy_list(rsp->headers);
1743       free(rsp);
1744    }
1745
1746 }
1747
1748
1749 /*********************************************************************
1750  *
1751  * Function    :  template_load
1752  *
1753  * Description :  CGI support function that loads a given HTML
1754  *                template from the confdir, ignoring comment
1755  *                lines and following #include statements up to
1756  *                a depth of 1.
1757  *
1758  * Parameters  :
1759  *          1  :  csp = Current client state (buffers, headers, etc...)
1760  *          2  :  template_ptr = Destination for pointer to loaded
1761  *                               template text.
1762  *          3  :  templatename = name of the HTML template to be used
1763  *          4  :  recursive = Flag set if this function calls itself
1764  *                            following an #include statament
1765  *
1766  * Returns     :  JB_ERR_OK on success
1767  *                JB_ERR_MEMORY on out-of-memory error.  
1768  *                JB_ERR_FILE if the template file cannot be read
1769  *
1770  *********************************************************************/
1771 jb_err template_load(struct client_state *csp, char **template_ptr, 
1772                      const char *templatename, int recursive)
1773 {
1774    jb_err err;
1775    char *templates_dir_path;
1776    char *full_path;
1777    char *file_buffer;
1778    char *included_module;
1779    const char *p;
1780    FILE *fp;
1781    char buf[BUFFER_SIZE];
1782
1783    assert(csp);
1784    assert(template_ptr);
1785    assert(templatename);
1786
1787    *template_ptr = NULL;
1788
1789    /* Validate template name.  Paranoia. */
1790    for (p = templatename; *p != 0; p++)
1791    {
1792       if ( ((*p < 'a') || (*p > 'z'))
1793         && ((*p < 'A') || (*p > 'Z'))
1794         && ((*p < '0') || (*p > '9'))
1795         && (*p != '-')
1796         && (*p != '.'))
1797       {
1798          /* Illegal character */
1799          return JB_ERR_FILE;
1800       }
1801    }
1802
1803    /* Generate full path */
1804
1805    templates_dir_path = make_path(csp->config->confdir, "templates");
1806    if (templates_dir_path == NULL)
1807    {
1808       return JB_ERR_MEMORY;
1809    }
1810
1811    full_path = make_path(templates_dir_path, templatename);
1812    free(templates_dir_path);
1813    if (full_path == NULL)
1814    {
1815       return JB_ERR_MEMORY;
1816    }
1817
1818    /* Allocate buffer */
1819
1820    file_buffer = strdup("");
1821    if (file_buffer == NULL)
1822    {
1823       free(full_path);
1824       return JB_ERR_MEMORY;
1825    }
1826
1827    /* Open template file */
1828
1829    if (NULL == (fp = fopen(full_path, "r")))
1830    {
1831       log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1832       free(full_path);
1833       free(file_buffer);
1834       return JB_ERR_FILE;
1835    }
1836    free(full_path);
1837
1838    /* 
1839     * Read the file, ignoring comments, and honoring #include
1840     * statements, unless we're already called recursively.
1841     *
1842     * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1843     *        This is unlikely in practise.
1844     */
1845    while (fgets(buf, BUFFER_SIZE, fp))
1846    {
1847       if (!recursive && !strncmp(buf, "#include ", 9))
1848       {
1849          if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1850          {
1851             free(file_buffer);
1852             fclose(fp);
1853             return err;
1854          }
1855
1856          if (string_join(&file_buffer, included_module))
1857          {
1858             fclose(fp);
1859             return JB_ERR_MEMORY;
1860          }
1861
1862          continue;
1863       }
1864
1865       /* skip lines starting with '#' */
1866       if (*buf == '#')
1867       {
1868          continue;
1869       }
1870
1871       if (string_append(&file_buffer, buf))
1872       {
1873          fclose(fp);
1874          return JB_ERR_MEMORY;
1875       }
1876    }
1877    fclose(fp);
1878
1879    *template_ptr = file_buffer;
1880
1881    return JB_ERR_OK;
1882 }
1883
1884
1885 /*********************************************************************
1886  *
1887  * Function    :  template_fill
1888  *
1889  * Description :  CGI support function that fills in a pre-loaded
1890  *                HTML template by replacing @name@ with value using
1891  *                pcrs, for each item in the output map.
1892  *
1893  *                Note that a leading '$' charachter in the export map's
1894  *                values will be stripped and toggle on backreference
1895  *                interpretation.
1896  *
1897  * Parameters  :
1898  *          1  :  template_ptr = IN: Template to be filled out.
1899  *                                   Will be free()d.
1900  *                               OUT: Filled out template.
1901  *                                    Caller must free().
1902  *          2  :  exports = map with fill in symbol -> name pairs
1903  *
1904  * Returns     :  JB_ERR_OK on success
1905  *                JB_ERR_MEMORY on out-of-memory error
1906  *
1907  *********************************************************************/
1908 jb_err template_fill(char **template_ptr, const struct map *exports)
1909 {
1910    struct map_entry *m;
1911    pcrs_job *job;
1912    char buf[BUFFER_SIZE];
1913    char *tmp_out_buffer;
1914    char *file_buffer;
1915    size_t  size;
1916    int error;
1917    const char *flags;
1918
1919    assert(template_ptr);
1920    assert(*template_ptr);
1921    assert(exports);
1922
1923    file_buffer = *template_ptr;
1924    size = strlen(file_buffer) + 1;
1925
1926    /* 
1927     * Assemble pcrs joblist from exports map
1928     */
1929    for (m = exports->first; m != NULL; m = m->next)
1930    {
1931       if (*m->name == '$')
1932       {
1933          /*
1934           * First character of name is '$', so remove this flag
1935           * character and allow backreferences ($1 etc) in the
1936           * "replace with" text.
1937           */
1938          snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1939          flags = "sigU";
1940       }
1941       else
1942       {
1943          /*
1944           * Treat the "replace with" text as a literal string - 
1945           * no quoting needed, no backreferences allowed.
1946           * ("Trivial" ['T'] flag).
1947           */
1948          flags = "sigTU";
1949
1950          /* Enclose name in @@ */
1951          snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1952       }
1953
1954
1955       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1956
1957       /* Make and run job. */
1958       job = pcrs_compile(buf, m->value, flags,  &error);
1959       if (job == NULL) 
1960       {
1961          if (error == PCRS_ERR_NOMEM)
1962          {
1963             free(file_buffer);
1964             *template_ptr = NULL;
1965             return JB_ERR_MEMORY;
1966          }
1967          else
1968          {
1969             log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1970             /* Hope it wasn't important and silently ignore the invalid job */
1971          }
1972       }
1973       else
1974       {
1975          pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1976          free(file_buffer);
1977          pcrs_free_job(job);
1978          if (NULL == tmp_out_buffer)
1979          {
1980             *template_ptr = NULL;
1981             return JB_ERR_MEMORY;
1982          }
1983          file_buffer = tmp_out_buffer;
1984       }
1985    }
1986
1987    /*
1988     * Return
1989     */
1990    *template_ptr = file_buffer;
1991    return JB_ERR_OK;
1992 }
1993
1994
1995 /*********************************************************************
1996  *
1997  * Function    :  template_fill_for_cgi
1998  *
1999  * Description :  CGI support function that loads a HTML template
2000  *                and fills it in.  Handles file-not-found errors
2001  *                by sending a HTML error message.  For convenience,
2002  *                this function also frees the passed "exports" map.
2003  *
2004  * Parameters  :
2005  *          1  :  csp = Client state
2006  *          2  :  templatename = name of the HTML template to be used
2007  *          3  :  exports = map with fill in symbol -> name pairs.
2008  *                          Will be freed by this function.
2009  *          4  :  rsp = Response structure to fill in.
2010  *
2011  * Returns     :  JB_ERR_OK on success
2012  *                JB_ERR_MEMORY on out-of-memory error
2013  *
2014  *********************************************************************/
2015 jb_err template_fill_for_cgi(struct client_state *csp,
2016                              const char *templatename,
2017                              struct map *exports,
2018                              struct http_response *rsp)
2019 {
2020    jb_err err;
2021    
2022    assert(csp);
2023    assert(templatename);
2024    assert(exports);
2025    assert(rsp);
2026
2027    err = template_load(csp, &rsp->body, templatename, 0);
2028    if (err == JB_ERR_FILE)
2029    {
2030       free_map(exports);
2031       return cgi_error_no_template(csp, rsp, templatename);
2032    }
2033    else if (err)
2034    {
2035       free_map(exports);
2036       return err; /* JB_ERR_MEMORY */
2037    }
2038    err = template_fill(&rsp->body, exports);
2039    free_map(exports);
2040    return err;
2041 }
2042
2043
2044 /*********************************************************************
2045  *
2046  * Function    :  default_exports
2047  *
2048  * Description :  returns a struct map list that contains exports
2049  *                which are common to all CGI functions.
2050  *
2051  * Parameters  :
2052  *          1  :  csp = Current client state (buffers, headers, etc...)
2053  *          2  :  caller = name of CGI who calls us and which should
2054  *                         be excluded from the generated menu. May be
2055  *                         NULL.
2056  * Returns     :  NULL if no memory, else a new map.  Caller frees.
2057  *
2058  *********************************************************************/
2059 struct map *default_exports(const struct client_state *csp, const char *caller)
2060 {
2061    char buf[20];
2062    jb_err err;
2063    struct map * exports;
2064    int local_help_exists = 0;
2065
2066    assert(csp);
2067
2068    exports = new_map();
2069    if (exports == NULL)
2070    {
2071       return NULL;
2072    }
2073
2074    err = map(exports, "version", 1, html_encode(VERSION), 0);
2075    if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2076    if (!err) err = map(exports, "my-hostname",   1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2077    if (!err) err = map(exports, "homepage",      1, html_encode(HOME_PAGE_URL), 0);
2078    if (!err) err = map(exports, "default-cgi",   1, html_encode(CGI_PREFIX), 0);
2079    if (!err) err = map(exports, "menu",          1, make_menu(caller), 0);
2080    if (!err) err = map(exports, "code-status",   1, CODE_STATUS, 1);
2081    if (!err) err = map(exports, "user-manual",   1, csp->config->usermanual ,1);
2082    if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2083 #ifdef FEATURE_TOGGLE
2084    if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2085 #else
2086    if (!err) err = map_block_killer(exports, "can-toggle");
2087 #endif
2088
2089    snprintf(buf, 20, "%d", csp->config->hport);
2090    if (!err) err = map(exports, "my-port", 1, buf, 1);
2091
2092    if(!strcmp(CODE_STATUS, "stable"))
2093    {
2094       if (!err) err = map_block_killer(exports, "unstable");
2095    }
2096
2097    if (csp->config->admin_address != NULL)
2098    {
2099       if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2100       local_help_exists = 1;
2101    }
2102    else
2103    {
2104       if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2105    }
2106
2107    if (csp->config->proxy_info_url != NULL)
2108    {
2109       if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2110       local_help_exists = 1;
2111    }
2112    else
2113    {
2114       if (!err) err = map_block_killer(exports, "have-proxy-info");
2115    }
2116
2117    if (local_help_exists == 0)
2118    {
2119       if (!err) err = map_block_killer(exports, "have-help-info");
2120    }
2121
2122    if (err)
2123    {
2124       free_map(exports);
2125       return NULL;
2126    }
2127
2128    return exports;
2129 }
2130
2131
2132 /*********************************************************************
2133  *
2134  * Function    :  map_block_killer
2135  *
2136  * Description :  Convenience function.
2137  *                Adds a "killer" for the conditional HTML-template
2138  *                block <name>, i.e. a substitution of the regex
2139  *                "if-<name>-start.*if-<name>-end" to the given
2140  *                export list.
2141  *
2142  * Parameters  :  
2143  *          1  :  exports = map to extend
2144  *          2  :  name = name of conditional block
2145  *
2146  * Returns     :  JB_ERR_OK on success
2147  *                JB_ERR_MEMORY on out-of-memory error.  
2148  *
2149  *********************************************************************/
2150 jb_err map_block_killer(struct map *exports, const char *name)
2151 {
2152    char buf[1000]; /* Will do, since the names are hardwired */
2153
2154    assert(exports);
2155    assert(name);
2156    assert(strlen(name) < 490);
2157
2158    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2159    return map(exports, buf, 1, "", 1);
2160 }
2161
2162
2163 /*********************************************************************
2164  *
2165  * Function    :  map_block_keep
2166  *
2167  * Description :  Convenience function.  Removes the markers used
2168  *                by map-block-killer, to save a few bytes.
2169  *                i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2170  *
2171  * Parameters  :  
2172  *          1  :  exports = map to extend
2173  *          2  :  name = name of conditional block
2174  *
2175  * Returns     :  JB_ERR_OK on success
2176  *                JB_ERR_MEMORY on out-of-memory error.  
2177  *
2178  *********************************************************************/
2179 jb_err map_block_keep(struct map *exports, const char *name)
2180 {
2181    jb_err err;
2182    char buf[500]; /* Will do, since the names are hardwired */
2183
2184    assert(exports);
2185    assert(name);
2186    assert(strlen(name) < 490);
2187
2188    snprintf(buf, 500, "if-%s-start", name);
2189    err = map(exports, buf, 1, "", 1);
2190
2191    if (err)
2192    {
2193       return err;
2194    }
2195
2196    snprintf(buf, 500, "if-%s-end", name);
2197    return map(exports, buf, 1, "", 1);
2198 }
2199
2200
2201 /*********************************************************************
2202  *
2203  * Function    :  map_conditional
2204  *
2205  * Description :  Convenience function.
2206  *                Adds an "if-then-else" for the conditional HTML-template
2207  *                block <name>, i.e. a substitution of the form:
2208  *                @if-<name>-then@
2209  *                   True text
2210  *                @else-not-<name>@
2211  *                   False text
2212  *                @endif-<name>@
2213  *
2214  *                The control structure and one of the alternatives
2215  *                will be hidden.
2216  *
2217  * Parameters  :  
2218  *          1  :  exports = map to extend
2219  *          2  :  name = name of conditional block
2220  *          3  :  choose_first = nonzero for first, zero for second.
2221  *
2222  * Returns     :  JB_ERR_OK on success
2223  *                JB_ERR_MEMORY on out-of-memory error.  
2224  *
2225  *********************************************************************/
2226 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2227 {
2228    char buf[1000]; /* Will do, since the names are hardwired */
2229    jb_err err;
2230
2231    assert(exports);
2232    assert(name);
2233    assert(strlen(name) < 480);
2234
2235    snprintf(buf, 1000, (choose_first
2236       ? "else-not-%s@.*@endif-%s"
2237       : "if-%s-then@.*@else-not-%s"),
2238       name, name);
2239
2240    err = map(exports, buf, 1, "", 1);
2241    if (err)
2242    {
2243       return err;
2244    }
2245
2246    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2247    return map(exports, buf, 1, "", 1);
2248 }
2249
2250
2251 /*********************************************************************
2252  *
2253  * Function    :  make_menu
2254  *
2255  * Description :  Returns an HTML-formatted menu of the available 
2256  *                unhidden CGIs, excluding the one given in <self>
2257  *
2258  * Parameters  :  self = name of CGI to leave out, can be NULL for
2259  *                complete listing.
2260  *
2261  * Returns     :  menu string, or NULL on out-of-memory error.
2262  *
2263  *********************************************************************/
2264 char *make_menu(const char *self)
2265 {
2266    const struct cgi_dispatcher *d;
2267    char *result = strdup("");
2268
2269    if (self == NULL)
2270    {
2271       self = "NO-SUCH-CGI!";
2272    }
2273
2274    /* List available unhidden CGI's and export as "other-cgis" */
2275    for (d = cgi_dispatchers; d->name; d++)
2276    {
2277       if (d->description && strcmp(d->name, self))
2278       {
2279          string_append(&result, "<li><a href=\"" CGI_PREFIX);
2280          string_append(&result, d->name);
2281          string_append(&result, "\">");
2282          string_append(&result, d->description);
2283          string_append(&result, "</a></li>");
2284       }
2285    }
2286
2287    return result;
2288 }
2289
2290
2291 /*********************************************************************
2292  *
2293  * Function    :  dump_map
2294  *
2295  * Description :  HTML-dump a map for debugging (as table)
2296  *
2297  * Parameters  :
2298  *          1  :  the_map = map to dump
2299  *
2300  * Returns     :  string with HTML
2301  *
2302  *********************************************************************/
2303 char *dump_map(const struct map *the_map)
2304 {
2305    struct map_entry *cur_entry;
2306    char *ret = strdup("");
2307
2308    string_append(&ret, "<table>\n");
2309
2310    for (cur_entry = the_map->first;
2311         (cur_entry != NULL) && (ret != NULL);
2312         cur_entry = cur_entry->next)
2313    {
2314       string_append(&ret, "<tr><td><b>");
2315       string_join  (&ret, html_encode(cur_entry->name));
2316       string_append(&ret, "</b></td><td>");
2317       string_join  (&ret, html_encode(cur_entry->value));
2318       string_append(&ret, "</td></tr>\n");
2319    }
2320
2321    string_append(&ret, "</table>\n");
2322    return ret;
2323 }
2324
2325
2326 /*
2327   Local Variables:
2328   tab-width: 3
2329   end:
2330 */