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