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