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