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