Synced with the stable branch:
[privoxy.git] / src / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 2.1 2002/06/04 17:55:24 jongfoster 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.1  2002/06/04 17:55:24  jongfoster
42  *    Adding comments
43  *
44  *    Revision 2.0  2002/06/04 14:34:21  jongfoster
45  *    Moving source files to src/
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 #ifdef FEATURE_GRACEFUL_TERMINATION
437    { "die", 
438          cgi_die,  
439          "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
440          "this is a one click Denial Of Service attack!!!</em>" }, 
441 #endif
442    { "show-status", 
443          cgi_show_status,  
444          "View & change the current configuration" }, 
445    { "show-version", 
446          cgi_show_version,  
447          "View the source code version numbers" }, 
448    { "show-request", 
449          cgi_show_request,  
450          "View the request headers." }, 
451    { "show-url-info",
452          cgi_show_url_info, 
453          "Look up which actions apply to a URL and why"  },
454 #ifdef FEATURE_CGI_EDIT_ACTIONS
455    { "toggle",
456          cgi_toggle, 
457          "Toggle Privoxy on or off" },
458
459    { "edit-actions", /* Edit the actions list */
460          cgi_edit_actions, 
461          NULL },
462    { "eaa", /* Shortcut for edit-actions-add-url-form */
463          cgi_edit_actions_add_url_form, 
464          NULL },
465    { "eau", /* Shortcut for edit-actions-url-form */
466          cgi_edit_actions_url_form, 
467          NULL },
468    { "ear", /* Shortcut for edit-actions-remove-url-form */
469          cgi_edit_actions_remove_url_form, 
470          NULL },
471    { "eafu", /* Shortcut for edit-actions-for-url */
472          cgi_edit_actions_for_url, 
473          NULL },
474    { "eas", /* Shortcut for edit-actions-submit */
475          cgi_edit_actions_submit, 
476          NULL },
477    { "easa", /* Shortcut for edit-actions-section-add */
478          cgi_edit_actions_section_add, 
479          NULL },
480    { "easr", /* Shortcut for edit-actions-section-remove */
481          cgi_edit_actions_section_remove, 
482          NULL },
483    { "eass", /* Shortcut for edit-actions-section-swap */
484          cgi_edit_actions_section_swap, 
485          NULL },
486    { "edit-actions-for-url",
487          cgi_edit_actions_for_url, 
488          NULL /* Edit the actions for (a) specified URL(s) */ },
489    { "edit-actions-list",
490          cgi_edit_actions_list, 
491          NULL /* Edit the actions list */ },
492    { "edit-actions-submit",
493          cgi_edit_actions_submit, 
494          NULL /* Change the actions for (a) specified URL(s) */ },
495    { "edit-actions-url",
496          cgi_edit_actions_url, 
497          NULL /* Change a URL pattern in the actionsfile */ },
498    { "edit-actions-url-form",
499          cgi_edit_actions_url_form, 
500          NULL /* Form to change a URL pattern in the actionsfile */ },
501    { "edit-actions-add-url",
502          cgi_edit_actions_add_url, 
503          NULL /* Add a URL pattern to the actionsfile */ },
504    { "edit-actions-add-url-form",
505          cgi_edit_actions_add_url_form, 
506          NULL /* Form to add a URL pattern to the actionsfile */ },
507    { "edit-actions-remove-url",
508          cgi_edit_actions_remove_url, 
509          NULL /* Remove a URL pattern from the actionsfile */ },
510    { "edit-actions-remove-url-form",
511          cgi_edit_actions_remove_url_form, 
512          NULL /* Form to remove a URL pattern from the actionsfile */ },
513    { "edit-actions-section-add",
514          cgi_edit_actions_section_add, 
515          NULL /* Remove a section from the actionsfile */ },
516    { "edit-actions-section-remove",
517          cgi_edit_actions_section_remove, 
518          NULL /* Remove a section from the actionsfile */ },
519    { "edit-actions-section-swap",
520          cgi_edit_actions_section_swap, 
521          NULL /* Swap two sections in the actionsfile */ },
522 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
523    { "robots.txt", 
524          cgi_robots_txt,  
525          NULL /* Sends a robots.txt file to tell robots to go away. */ }, 
526    { "send-banner",
527          cgi_send_banner, 
528          NULL /* Send a built-in image */ },
529    { "send-stylesheet",
530          cgi_send_stylesheet, 
531          NULL /* Send templates/cgi-style.css */ },
532    { "t",
533          cgi_transparent_image, 
534          NULL /* Send a transparent image (short name) */ },
535    { NULL, /* NULL Indicates end of list and default page */
536          cgi_error_404,
537          NULL /* Unknown CGI page */ }
538 };
539
540
541 /*
542  * Built-in images for ad replacement
543  *
544  * Hint: You can encode your own images like this:
545  * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
546  */
547
548 #ifdef FEATURE_NO_GIFS
549
550 /*
551  * Checkerboard pattern, as a PNG.
552  */
553 const char image_pattern_data[] =
554    "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
555    "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
556    "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
557    "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
558    "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
559    "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
560    "\000\000\000\111\105\116\104\256\102\140\202";
561
562 /*
563  * 1x1 transparant PNG.
564  */
565 const char image_blank_data[] =
566  "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
567  "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
568  "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
569  "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
570  "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
571  "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
572  "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
573  "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
574  "\000\000\000\000\111\105\116\104\256\102\140\202";
575 #else
576
577 /**
578  * Checkerboard pattern, as a GIF.
579  */
580 const char image_pattern_data[] =
581    "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
582    "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
583    "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
584    "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
585    "\270\005\000\073";
586
587 /**
588  * 1x1 transparant GIF.
589  */
590 const char image_blank_data[] =
591    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
592    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
593    "\000\001\000\000\002\002D\001\000;";
594 #endif
595
596 /**
597  * The size of the image_pattern, in bytes.
598  */
599 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
600
601 /**
602  * The size of the image_blank, in bytes.
603  */
604 const size_t image_blank_length   = sizeof(image_blank_data) - 1;
605
606
607 /**
608  * The "Out of memory" CGI response.  This is statically allocated
609  * and is initialized at startup, for obvious reasons.  It's
610  * read-only.  finish_http_response() and free_http_response()
611  * have been special-cased to do nothing if they are passed
612  * this structure.
613  */
614 static struct http_response cgi_error_memory_response[1];
615
616
617 static struct http_response *dispatch_known_cgi(struct client_state * csp,
618                                                 const char * path);
619 static struct map *parse_cgi_parameters(char *argstring);
620
621
622 /*********************************************************************
623  * 
624  * Function    :  dispatch_cgi
625  *
626  * Description :  Checks if a request URL has either the magical
627  *                hostname CGI_SITE_1_HOST (usually http://p.p/) or
628  *                matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
629  *                http://config.privoxy.org/). If so, it passes
630  *                the (rest of the) path onto dispatch_known_cgi, which
631  *                calls the relevant CGI handler function.
632  *
633  * Parameters  :
634  *          1  :  csp = Current client state (buffers, headers, etc...)
635  *
636  * Returns     :  http_response if match, NULL if nonmatch or handler fail
637  *
638  *********************************************************************/
639 struct http_response *dispatch_cgi(struct client_state *csp)
640 {
641    const char *host = csp->http->host;
642    const char *path = csp->http->path;
643
644    /*
645     * Should we intercept ?
646     */
647
648    /* Note: "example.com" and "example.com." are equivalent hostnames. */
649
650    /* Either the host matches CGI_SITE_1_HOST ..*/
651    if (   ( (0 == strcmpic(host, CGI_SITE_1_HOST))
652          || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
653        && (path[0] == '/') )
654    {
655       /* ..then the path will all be for us.  Remove leading '/' */
656       path++;
657    }
658    /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
659    else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
660             || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
661           && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
662    {
663       /* take everything following CGI_SITE_2_PATH */
664       path += strlen(CGI_SITE_2_PATH);
665       if (*path == '/')
666       {
667          /* skip the forward slash after CGI_SITE_2_PATH */
668          path++;
669       }
670       else if (*path != '\0')
671       {
672          /*
673           * wierdness: URL is /configXXX, where XXX is some string
674           * Do *NOT* intercept.
675           */
676          return NULL;
677       }
678    }
679    else
680    {
681       /* Not a CGI */
682       return NULL;
683    }
684
685    /* 
686     * This is a CGI call.
687     */
688
689    return dispatch_known_cgi(csp, path);
690 }
691
692
693 /*********************************************************************
694  * 
695  * Function    :  dispatch_known_cgi
696  *
697  * Description :  Processes a CGI once dispatch_cgi has determined that
698  *                it matches one of the magic prefixes. Parses the path
699  *                as a cgi name plus query string, prepares a map that
700  *                maps CGI parameter names to their values, initializes
701  *                the http_response struct, and calls the relevant CGI
702  *                handler function.
703  *
704  * Parameters  :
705  *          1  :  csp = Current client state (buffers, headers, etc...)
706  *          2  :  path = Path of CGI, with the CGI prefix removed.
707  *                       Should not have a leading "/".
708  *
709  * Returns     :  http_response, or NULL on handler failure or out of
710  *                memory.
711  *
712  *********************************************************************/
713 static struct http_response *dispatch_known_cgi(struct client_state * csp,
714                                                 const char * path)
715 {
716    const struct cgi_dispatcher *d;
717    struct map *param_list;
718    struct http_response *rsp;
719    char *query_args_start;
720    char *path_copy;
721    jb_err err;
722
723    if (NULL == (path_copy = strdup(path)))
724    {
725       return cgi_error_memory();
726    }
727
728    query_args_start = path_copy;
729    while (*query_args_start && *query_args_start != '?')
730    {
731       query_args_start++;
732    }
733    if (*query_args_start == '?')
734    {
735       *query_args_start++ = '\0';
736    }
737
738    if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
739    {
740       free(path_copy);
741       return cgi_error_memory();
742    }
743
744
745    /*
746     * At this point:
747     * path_copy        = CGI call name
748     * param_list       = CGI params, as map
749     */
750
751    /* Get mem for response or fail*/
752    if (NULL == (rsp = alloc_http_response()))
753    {
754       free(path_copy);
755       free_map(param_list);
756       return cgi_error_memory();
757    }
758
759    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
760    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
761                             csp->ip_addr_str, csp->http->cmd); 
762
763    /* Find and start the right CGI function*/
764    d = cgi_dispatchers;
765    for (;;)
766    {
767       if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
768       {
769          err = (d->handler)(csp, rsp, param_list);
770          free(path_copy);
771          free_map(param_list);
772          if (err == JB_ERR_CGI_PARAMS)
773          {
774             err = cgi_error_bad_param(csp, rsp);
775          }
776          if (err && (err != JB_ERR_MEMORY))
777          {
778             /* Unexpected error! Shouldn't get here */
779             log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler.  Please file a bug report!", err);
780             err = cgi_error_unknown(csp, rsp, err);
781          }
782          if (!err)
783          {
784             /* It worked */
785             return finish_http_response(rsp);
786          }
787          else
788          {
789             /* Error in handler, probably out-of-memory */
790             free_http_response(rsp);
791             return cgi_error_memory();
792          }
793       }
794       d++;
795    }
796 }
797
798
799 /*********************************************************************
800  *
801  * Function    :  parse_cgi_parameters
802  *
803  * Description :  Parse a URL-encoded argument string into name/value
804  *                pairs and store them in a struct map list.
805  *
806  * Parameters  :
807  *          1  :  argstring = string to be parsed.  Will be trashed.
808  *
809  * Returns     :  pointer to param list, or NULL if out of memory.
810  *
811  *********************************************************************/
812 static struct map *parse_cgi_parameters(char *argstring)
813 {
814    char *p;
815    char *vector[BUFFER_SIZE];
816    int pairs, i;
817    struct map *cgi_params;
818
819    if (NULL == (cgi_params = new_map()))
820    {
821       return NULL;
822    }
823
824    /* 
825     * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
826     * the fragment identifier along with the request, so we must
827     * cut it off here, so it won't pollute the CGI params:
828     */
829    if (NULL != (p = strchr(argstring, '#')))
830    {
831       *p = '\0';
832    }
833
834    pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
835
836    for (i = 0; i < pairs; i++)
837    {
838       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
839       {
840          *p = '\0';
841          if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
842          {
843             free_map(cgi_params);
844             return NULL;
845          }
846       }
847    }
848
849    return cgi_params;
850
851 }
852
853
854 /*********************************************************************
855  *
856  * Function    :  get_char_param
857  *
858  * Description :  Get a single-character parameter passed to a CGI
859  *                function.
860  *
861  * Parameters  :
862  *          1  :  parameters = map of cgi parameters
863  *          2  :  param_name = The name of the parameter to read
864  *
865  * Returns     :  Uppercase character on success, '\0' on error.
866  *
867  *********************************************************************/
868 char get_char_param(const struct map *parameters,
869                     const char *param_name)
870 {
871    char ch;
872
873    assert(parameters);
874    assert(param_name);
875
876    ch = *(lookup(parameters, param_name));
877    if ((ch >= 'a') && (ch <= 'z'))
878    {
879       ch = ch - 'a' + 'A';
880    }
881
882    return ch;
883 }
884
885
886 /*********************************************************************
887  *
888  * Function    :  get_string_param
889  *
890  * Description :  Get a string paramater, to be used as an
891  *                ACTION_STRING or ACTION_MULTI paramater.
892  *                Validates the input to prevent stupid/malicious
893  *                users from corrupting their action file.
894  *
895  * Parameters  :
896  *          1  :  parameters = map of cgi parameters
897  *          2  :  param_name = The name of the parameter to read
898  *          3  :  pparam = destination for paramater.  Allocated as
899  *                part of the map "parameters", so don't free it.
900  *                Set to NULL if not specified.
901  *
902  * Returns     :  JB_ERR_OK         on success, or if the paramater
903  *                                  was not specified.
904  *                JB_ERR_MEMORY     on out-of-memory.
905  *                JB_ERR_CGI_PARAMS if the paramater is not valid.
906  *
907  *********************************************************************/
908 jb_err get_string_param(const struct map *parameters,
909                         const char *param_name,
910                         const char **pparam)
911 {
912    const char *param;
913    const char *s;
914    char ch;
915
916    assert(parameters);
917    assert(param_name);
918    assert(pparam);
919
920    *pparam = NULL;
921
922    param = lookup(parameters, param_name);
923    if (!*param)
924    {
925       return JB_ERR_OK;
926    }
927
928    if (strlen(param) >= CGI_PARAM_LEN_MAX)
929    {
930       /*
931        * Too long.
932        *
933        * Note that the length limit is arbitrary, it just seems
934        * sensible to limit it to *something*.  There's no
935        * technical reason for any limit at all.
936        */
937       return JB_ERR_CGI_PARAMS;
938    }
939
940    /* Check every character to see if it's legal */
941    s = param;
942    while ((ch = *s++) != '\0')
943    {
944       if ( ((unsigned char)ch < (unsigned char)' ')
945         || (ch == '}') )
946       {
947          /* Probable hack attempt, or user accidentally used '}'. */
948          return JB_ERR_CGI_PARAMS;
949       }
950    }
951
952    /* Success */
953    *pparam = param;
954
955    return JB_ERR_OK;
956 }
957
958
959 /*********************************************************************
960  *
961  * Function    :  get_number_param
962  *
963  * Description :  Get a non-negative integer from the parameters
964  *                passed to a CGI function.
965  *
966  * Parameters  :
967  *          1  :  csp = Current client state (buffers, headers, etc...)
968  *          2  :  parameters = map of cgi parameters
969  *          3  :  name = Name of CGI parameter to read
970  *          4  :  pvalue = destination for value.
971  *                         Set to -1 on error.
972  *
973  * Returns     :  JB_ERR_OK         on success
974  *                JB_ERR_MEMORY     on out-of-memory
975  *                JB_ERR_CGI_PARAMS if the parameter was not specified
976  *                                  or is not valid.
977  *
978  *********************************************************************/
979 jb_err get_number_param(struct client_state *csp,
980                         const struct map *parameters,
981                         char *name,
982                         unsigned *pvalue)
983 {
984    const char *param;
985    char ch;
986    unsigned value;
987
988    assert(csp);
989    assert(parameters);
990    assert(name);
991    assert(pvalue);
992
993    *pvalue = 0; 
994
995    param = lookup(parameters, name);
996    if (!*param)
997    {
998       return JB_ERR_CGI_PARAMS;
999    }
1000
1001    /* We don't use atoi because I want to check this carefully... */
1002
1003    value = 0;
1004    while ((ch = *param++) != '\0')
1005    {
1006       if ((ch < '0') || (ch > '9'))
1007       {
1008          return JB_ERR_CGI_PARAMS;
1009       }
1010
1011       ch -= '0';
1012
1013       /* Note:
1014        *
1015        * <limits.h> defines UINT_MAX
1016        *
1017        * (UINT_MAX - ch) / 10 is the largest number that
1018        *     can be safely multiplied by 10 then have ch added.
1019        */
1020       if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1021       {
1022          return JB_ERR_CGI_PARAMS;
1023       }
1024
1025       value = value * 10 + ch;
1026    }
1027
1028    /* Success */
1029    *pvalue = value;
1030
1031    return JB_ERR_OK;
1032
1033 }
1034
1035
1036 /*********************************************************************
1037  *
1038  * Function    :  error_response
1039  *
1040  * Description :  returns an http_response that explains the reason
1041  *                why a request failed.
1042  *
1043  * Parameters  :
1044  *          1  :  csp = Current client state (buffers, headers, etc...)
1045  *          2  :  templatename = Which template should be used for the answer
1046  *          3  :  sys_err = system error number
1047  *
1048  * Returns     :  A http_response.  If we run out of memory, this
1049  *                will be cgi_error_memory().
1050  *
1051  *********************************************************************/
1052 struct http_response *error_response(struct client_state *csp,
1053                                      const char *templatename,
1054                                      int sys_err)
1055 {
1056    jb_err err;
1057    struct http_response *rsp;
1058    struct map * exports = default_exports(csp, NULL);
1059    if (exports == NULL)
1060    {
1061       return cgi_error_memory();
1062    }
1063
1064    if (NULL == (rsp = alloc_http_response()))
1065    {
1066       free_map(exports);
1067       return cgi_error_memory();
1068    }
1069
1070    err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1071    if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1072    if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1073    if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1074    if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1); 
1075    if (!err)
1076    {
1077      err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1078      if (err)
1079      {
1080        /* Some failures, like "404 no such domain", don't have an IP address. */
1081        err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1082      }
1083    }
1084
1085
1086    if (err)
1087    {
1088       free_map(exports);
1089       free_http_response(rsp);
1090       return cgi_error_memory();
1091    }
1092
1093    if (!strcmp(templatename, "no-such-domain"))
1094    {
1095       rsp->status = strdup("404 No such domain");
1096       if (rsp->status == NULL)
1097       {
1098          free_map(exports);
1099          free_http_response(rsp);
1100          return cgi_error_memory();
1101       }
1102    }
1103    else if (!strcmp(templatename, "connect-failed"))
1104    {
1105       rsp->status = strdup("503 Connect failed");
1106       if (rsp->status == NULL)
1107       {
1108          free_map(exports);
1109          free_http_response(rsp);
1110          return cgi_error_memory();
1111       }
1112    }
1113
1114    err = template_fill_for_cgi(csp, templatename, exports, rsp);
1115    if (err)
1116    {
1117       free_http_response(rsp);
1118       return cgi_error_memory();
1119    }
1120
1121    return finish_http_response(rsp);
1122 }
1123
1124
1125 /*********************************************************************
1126  *
1127  * Function    :  cgi_init_error_messages
1128  *
1129  * Description :  Call at the start of the program to initialize
1130  *                the error message used by cgi_error_memory().
1131  *
1132  * Parameters  :  N/A
1133  *
1134  * Returns     :  N/A
1135  *
1136  *********************************************************************/
1137 void cgi_init_error_messages(void)
1138 {
1139    memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1140    cgi_error_memory_response->head =
1141       "HTTP/1.0 500 Internal Privoxy Error\r\n"
1142       "Content-Type: text/html\r\n"
1143       "\r\n";
1144    cgi_error_memory_response->body =
1145       "<html>\r\n"
1146       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1147       "<body>\r\n"
1148       "<h1>500 Internal Privoxy Error</h1>\r\n"
1149       "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1150       "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1151       "</body>\r\n"
1152       "</html>\r\n";
1153
1154    cgi_error_memory_response->head_length =
1155       strlen(cgi_error_memory_response->head);
1156    cgi_error_memory_response->content_length =
1157       strlen(cgi_error_memory_response->body);
1158 }
1159
1160
1161 /*********************************************************************
1162  *
1163  * Function    :  cgi_error_memory
1164  *
1165  * Description :  Called if a CGI function runs out of memory.
1166  *                Returns a statically-allocated error response.
1167  *
1168  * Parameters  :  N/A
1169  *
1170  * Returns     :  http_response data structure for output.  This is
1171  *                statically allocated, for obvious reasons.
1172  *
1173  *********************************************************************/
1174 struct http_response *cgi_error_memory(void)
1175 {
1176    /* assert that it's been initialized. */
1177    assert(cgi_error_memory_response->head);
1178
1179    return cgi_error_memory_response;
1180 }
1181
1182
1183 /*********************************************************************
1184  *
1185  * Function    :  cgi_error_no_template
1186  *
1187  * Description :  Almost-CGI function that is called if a template
1188  *                cannot be loaded.  Note this is not a true CGI,
1189  *                it takes a template name rather than a map of 
1190  *                parameters.
1191  *
1192  * Parameters  :
1193  *          1  :  csp = Current client state (buffers, headers, etc...)
1194  *          2  :  rsp = http_response data structure for output
1195  *          3  :  template_name = Name of template that could not
1196  *                                be loaded.
1197  *
1198  * Returns     :  JB_ERR_OK on success
1199  *                JB_ERR_MEMORY on out-of-memory error.  
1200  *
1201  *********************************************************************/
1202 jb_err cgi_error_no_template(struct client_state *csp,
1203                              struct http_response *rsp,
1204                              const char *template_name)
1205 {
1206    static const char status[] =
1207       "500 Internal Privoxy Error";
1208    static const char body_prefix[] =
1209       "<html>\r\n"
1210       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1211       "<body>\r\n"
1212       "<h1>500 Internal Privoxy Error</h1>\r\n"
1213       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1214       "<p><b>Could not load template file <code>";
1215    static const char body_suffix[] =
1216       "</code> or one of it's included components.</b></p>\r\n"
1217       "<p>Please contact your proxy administrator.</p>\r\n"
1218       "<p>If you are the proxy administrator, please put the required file(s)"
1219       "in the <code><i>(confdir)</i>/templates</code> directory.  The "
1220       "location of the <code><i>(confdir)</i></code> directory "
1221       "is specified in the main Privoxy <code>config</code> "
1222       "file.  (It's typically the Privoxy install directory"
1223 #ifndef _WIN32
1224       ", or <code>/etc/privoxy/</code>"
1225 #endif /* ndef _WIN32 */
1226       ").</p>\r\n"
1227       "</body>\r\n"
1228       "</html>\r\n";
1229
1230    assert(csp);
1231    assert(rsp);
1232    assert(template_name);
1233
1234    /* Reset rsp, if needed */
1235    freez(rsp->status);
1236    freez(rsp->head);
1237    freez(rsp->body);
1238    rsp->content_length = 0;
1239    rsp->head_length = 0;
1240    rsp->is_static = 0;
1241
1242    rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1243    if (rsp->body == NULL)
1244    {
1245       return JB_ERR_MEMORY;
1246    }
1247    strcpy(rsp->body, body_prefix);
1248    strcat(rsp->body, template_name);
1249    strcat(rsp->body, body_suffix);
1250
1251    rsp->status = strdup(status);
1252    if (rsp->body == NULL)
1253    {
1254       return JB_ERR_MEMORY;
1255    }
1256
1257    return JB_ERR_OK;
1258 }
1259
1260
1261 /*********************************************************************
1262  *
1263  * Function    :  cgi_error_unknown
1264  *
1265  * Description :  Almost-CGI function that is called if an unexpected
1266  *                error occurs in the top-level CGI dispatcher.
1267  *                In this context, "unexpected" means "anything other
1268  *                than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1269  *                expected to handle all other errors internally,
1270  *                since they can give more relavent error messages
1271  *                that way.
1272  *
1273  *                Note this is not a true CGI, it takes an error
1274  *                code rather than a map of parameters.
1275  *
1276  * Parameters  :
1277  *          1  :  csp = Current client state (buffers, headers, etc...)
1278  *          2  :  rsp = http_response data structure for output
1279  *          3  :  error_to_report = Error code to report.
1280  *
1281  * Returns     :  JB_ERR_OK on success
1282  *                JB_ERR_MEMORY on out-of-memory error.  
1283  *
1284  *********************************************************************/
1285 jb_err cgi_error_unknown(struct client_state *csp,
1286                          struct http_response *rsp,
1287                          jb_err error_to_report)
1288 {
1289    static const char status[] =
1290       "500 Internal Privoxy Error";
1291    static const char body_prefix[] =
1292       "<html>\r\n"
1293       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1294       "<body>\r\n"
1295       "<h1>500 Internal Privoxy Error</h1>\r\n"
1296       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1297       "<p><b>Unexpected internal error: ";
1298    static const char body_suffix[] =
1299       "</b></p>\r\n"
1300       "<p>Please "
1301       "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1302       "file a bug report</a>.</p>\r\n"
1303       "</body>\r\n"
1304       "</html>\r\n";
1305    char errnumbuf[30];
1306    assert(csp);
1307    assert(rsp);
1308
1309    /* Reset rsp, if needed */
1310    freez(rsp->status);
1311    freez(rsp->head);
1312    freez(rsp->body);
1313    rsp->content_length = 0;
1314    rsp->head_length = 0;
1315    rsp->is_static = 0;
1316
1317    sprintf(errnumbuf, "%d", error_to_report);
1318
1319    rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1320    if (rsp->body == NULL)
1321    {
1322       return JB_ERR_MEMORY;
1323    }
1324    strcpy(rsp->body, body_prefix);
1325    strcat(rsp->body, errnumbuf);
1326    strcat(rsp->body, body_suffix);
1327
1328    rsp->status = strdup(status);
1329    if (rsp->body == NULL)
1330    {
1331       return JB_ERR_MEMORY;
1332    }
1333
1334    return JB_ERR_OK;
1335 }
1336
1337
1338 /*********************************************************************
1339  *
1340  * Function    :  cgi_error_bad_param
1341  *
1342  * Description :  CGI function that is called if the parameters
1343  *                (query string) for a CGI were wrong.
1344  *               
1345  * Parameters  :
1346  *          1  :  csp = Current client state (buffers, headers, etc...)
1347  *          2  :  rsp = http_response data structure for output
1348  *
1349  * CGI Parameters : none
1350  *
1351  * Returns     :  JB_ERR_OK on success
1352  *                JB_ERR_MEMORY on out-of-memory error.  
1353  *
1354  *********************************************************************/
1355 jb_err cgi_error_bad_param(struct client_state *csp,
1356                            struct http_response *rsp)
1357 {
1358    struct map *exports;
1359
1360    assert(csp);
1361    assert(rsp);
1362
1363    if (NULL == (exports = default_exports(csp, NULL)))
1364    {
1365       return JB_ERR_MEMORY;
1366    }
1367
1368    return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1369 }
1370
1371
1372 /*********************************************************************
1373  *
1374  * Function    :  add_help_link
1375  *
1376  * Description :  Produce a copy of the string given as item,
1377  *                embedded in an HTML link to its corresponding
1378  *                section (item name in uppercase) in the actions
1379  *                chapter of the user manual, (whose URL is given in
1380  *                the config and defaults to our web site).
1381  *
1382  *                FIXME: I currently only work for actions, and would
1383  *                       like to be generalized for other topics.
1384  *
1385  * Parameters  :  
1386  *          1  :  item = item (will NOT be free()d.) 
1387  *                       It is assumed to be HTML-safe.
1388  *          2  :  config = The current configuration.
1389  *
1390  * Returns     :  String with item embedded in link, or NULL on
1391  *                out-of-memory
1392  *
1393  *********************************************************************/
1394 char *add_help_link(const char *item,
1395                     struct configuration_spec *config)
1396 {
1397    char *result;
1398
1399    if (!item) return NULL;
1400
1401    result = strdup("<a href=\"");
1402    string_append(&result, config->usermanual);
1403    string_append(&result, ACTIONS_HELP_PREFIX);
1404    string_join  (&result, string_toupper(item));
1405    string_append(&result, "\">");
1406    string_append(&result, item);
1407    string_append(&result, "</a> ");
1408
1409    return result;
1410 }
1411
1412
1413 /*********************************************************************
1414  *
1415  * Function    :  get_http_time
1416  *
1417  * Description :  Get the time in a format suitable for use in a
1418  *                HTTP header - e.g.:
1419  *                "Sun, 06 Nov 1994 08:49:37 GMT"
1420  *
1421  * Parameters  :  
1422  *          1  :  time_offset = Time returned will be current time
1423  *                              plus this number of seconds.
1424  *          2  :  buf = Destination for result.  Must be long enough
1425  *                      to hold 29 characters plus a trailing zero.
1426  *
1427  * Returns     :  N/A
1428  *
1429  *********************************************************************/
1430 void get_http_time(int time_offset, char *buf)
1431 {
1432    static const char day_names[7][4] =
1433       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1434    static const char month_names[12][4] =
1435       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1436         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1437
1438    struct tm *t;
1439    time_t current_time;
1440
1441    assert(buf);
1442
1443    time(&current_time); /* get current time */
1444
1445    current_time += time_offset;
1446
1447    /* get and save the gmt */
1448    {
1449 #ifdef HAVE_GMTIME_R
1450       struct tm dummy;
1451       t = gmtime_r(&current_time, &dummy);
1452 #else
1453       t = gmtime(&current_time);
1454 #endif
1455    }
1456
1457    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1458    snprintf(buf, 30,
1459       "%s, %02d %s %4d %02d:%02d:%02d GMT",
1460       day_names[t->tm_wday],
1461       t->tm_mday,
1462       month_names[t->tm_mon],
1463       t->tm_year + 1900,
1464       t->tm_hour,
1465       t->tm_min,
1466       t->tm_sec
1467       );
1468
1469 }
1470
1471
1472 /*********************************************************************
1473  *
1474  * Function    :  finish_http_response
1475  *
1476  * Description :  Fill in the missing headers in an http response,
1477  *                and flatten the headers to an http head.
1478  *
1479  * Parameters  :
1480  *          1  :  rsp = pointer to http_response to be processed
1481  *
1482  * Returns     :  A http_response, usually the rsp parameter.
1483  *                On error, free()s rsp and returns cgi_error_memory()
1484  *
1485  *********************************************************************/
1486 struct http_response *finish_http_response(struct http_response *rsp)
1487 {
1488    char buf[BUFFER_SIZE];
1489    jb_err err;
1490
1491    /* Special case - do NOT change this statically allocated response,
1492     * which is ready for output anyway.
1493     */
1494    if (rsp == cgi_error_memory_response)
1495    {
1496       return rsp;
1497    }
1498
1499    /* 
1500     * Fill in the HTTP Status
1501     */
1502    sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1503    err = enlist_first(rsp->headers, buf);
1504
1505    /* 
1506     * Set the Content-Length
1507     */
1508    if (rsp->content_length == 0)
1509    {
1510       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1511    }
1512    if (!err)
1513    {
1514       sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1515       err = enlist(rsp->headers, buf);
1516    }
1517
1518    /* 
1519     * Fill in the default headers:
1520     *
1521     * Content-Type: default to text/html if not already specified.
1522     * Date: set to current date/time.
1523     * Last-Modified: set to date/time the page was last changed.
1524     * Expires: set to date/time page next needs reloading.
1525     * Cache-Control: set to "no-cache" if applicable.
1526     * 
1527     * See http://www.w3.org/Protocols/rfc2068/rfc2068
1528     */
1529    if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1530
1531    if (rsp->is_static)
1532    {
1533       /*
1534        * Set Expires to about 10 min into the future so it'll get reloaded
1535        * occasionally, e.g. if Privoxy gets upgraded.
1536        */
1537
1538       if (!err)
1539       {
1540          get_http_time(0, buf);
1541          err = enlist_unique_header(rsp->headers, "Date", buf);
1542       }
1543
1544       /* Some date in the past. */
1545       if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1546
1547       if (!err)
1548       {
1549          get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1550          err = enlist_unique_header(rsp->headers, "Expires", buf);
1551       }
1552    }
1553    else
1554    {
1555       /*
1556        * Compliant browsers should not cache this due to the "Cache-Control"
1557        * setting.  However, to be certain, we also set both "Last-Modified"
1558        * and "Expires" to the current time.
1559        */
1560       if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1561
1562       get_http_time(0, buf);
1563       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1564       if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1565       if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1566    }
1567
1568
1569    /* 
1570     * Write the head
1571     */
1572    if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1573    {
1574       free_http_response(rsp);
1575       return cgi_error_memory();
1576    }
1577    rsp->head_length = strlen(rsp->head);
1578
1579    return rsp;
1580
1581 }
1582
1583
1584 /*********************************************************************
1585  *
1586  * Function    :  alloc_http_response
1587  *
1588  * Description :  Allocates a new http_response structure.
1589  *
1590  * Parameters  :  N/A
1591  *
1592  * Returns     :  pointer to a new http_response, or NULL.
1593  *
1594  *********************************************************************/
1595 struct http_response *alloc_http_response(void)
1596 {
1597    return (struct http_response *) zalloc(sizeof(struct http_response));
1598
1599 }
1600
1601
1602 /*********************************************************************
1603  *
1604  * Function    :  free_http_response
1605  *
1606  * Description :  Free the memory occupied by an http_response
1607  *                and its depandant structures.
1608  *
1609  * Parameters  :
1610  *          1  :  rsp = pointer to http_response to be freed
1611  *
1612  * Returns     :  N/A
1613  *
1614  *********************************************************************/
1615 void free_http_response(struct http_response *rsp)
1616 {
1617    /*
1618     * Must special case cgi_error_memory_response, which is never freed.
1619     */
1620    if (rsp && (rsp != cgi_error_memory_response))
1621    {
1622       freez(rsp->status);
1623       freez(rsp->head);
1624       freez(rsp->body);
1625       destroy_list(rsp->headers);
1626       free(rsp);
1627    }
1628
1629 }
1630
1631
1632 /*********************************************************************
1633  *
1634  * Function    :  template_load
1635  *
1636  * Description :  CGI support function that loads a given HTML
1637  *                template from the confdir, ignoring comment
1638  *                lines and following #include statements up to
1639  *                a depth of 1.
1640  *
1641  * Parameters  :
1642  *          1  :  csp = Current client state (buffers, headers, etc...)
1643  *          2  :  template_ptr = Destination for pointer to loaded
1644  *                               template text.
1645  *          3  :  templatename = name of the HTML template to be used
1646  *          4  :  recursive = Flag set if this function calls itself
1647  *                            following an #include statament
1648  *
1649  * Returns     :  JB_ERR_OK on success
1650  *                JB_ERR_MEMORY on out-of-memory error.  
1651  *                JB_ERR_FILE if the template file cannot be read
1652  *
1653  *********************************************************************/
1654 jb_err template_load(struct client_state *csp, char **template_ptr, 
1655                      const char *templatename, int recursive)
1656 {
1657    jb_err err;
1658    char *templates_dir_path;
1659    char *full_path;
1660    char *file_buffer;
1661    char *included_module;
1662    const char *p;
1663    FILE *fp;
1664    char buf[BUFFER_SIZE];
1665
1666    assert(csp);
1667    assert(template_ptr);
1668    assert(templatename);
1669
1670    *template_ptr = NULL;
1671
1672    /* Validate template name.  Paranoia. */
1673    for (p = templatename; *p != 0; p++)
1674    {
1675       if ( ((*p < 'a') || (*p > 'z'))
1676         && ((*p < 'A') || (*p > 'Z'))
1677         && ((*p < '0') || (*p > '9'))
1678         && (*p != '-')
1679         && (*p != '.'))
1680       {
1681          /* Illegal character */
1682          return JB_ERR_FILE;
1683       }
1684    }
1685
1686    /* Generate full path */
1687
1688    templates_dir_path = make_path(csp->config->confdir, "templates");
1689    if (templates_dir_path == NULL)
1690    {
1691       return JB_ERR_MEMORY;
1692    }
1693
1694    full_path = make_path(templates_dir_path, templatename);
1695    free(templates_dir_path);
1696    if (full_path == NULL)
1697    {
1698       return JB_ERR_MEMORY;
1699    }
1700
1701    /* Allocate buffer */
1702
1703    file_buffer = strdup("");
1704    if (file_buffer == NULL)
1705    {
1706       free(full_path);
1707       return JB_ERR_MEMORY;
1708    }
1709
1710    /* Open template file */
1711
1712    if (NULL == (fp = fopen(full_path, "r")))
1713    {
1714       log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1715       free(full_path);
1716       free(file_buffer);
1717       return JB_ERR_FILE;
1718    }
1719    free(full_path);
1720
1721    /* 
1722     * Read the file, ignoring comments, and honoring #include
1723     * statements, unless we're already called recursively.
1724     *
1725     * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1726     *        This is unlikely in practise.
1727     */
1728    while (fgets(buf, BUFFER_SIZE, fp))
1729    {
1730       if (!recursive && !strncmp(buf, "#include ", 9))
1731       {
1732          if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1733          {
1734             free(file_buffer);
1735             fclose(fp);
1736             return err;
1737          }
1738
1739          if (string_join(&file_buffer, included_module))
1740          {
1741             fclose(fp);
1742             return JB_ERR_MEMORY;
1743          }
1744
1745          continue;
1746       }
1747
1748       /* skip lines starting with '#' */
1749       if (*buf == '#')
1750       {
1751          continue;
1752       }
1753
1754       if (string_append(&file_buffer, buf))
1755       {
1756          fclose(fp);
1757          return JB_ERR_MEMORY;
1758       }
1759    }
1760    fclose(fp);
1761
1762    *template_ptr = file_buffer;
1763
1764    return JB_ERR_OK;
1765 }
1766
1767
1768 /*********************************************************************
1769  *
1770  * Function    :  template_fill
1771  *
1772  * Description :  CGI support function that fills in a pre-loaded
1773  *                HTML template by replacing @name@ with value using
1774  *                pcrs, for each item in the output map.
1775  *
1776  *                Note that a leading '$' charachter in the export map's
1777  *                values will be stripped and toggle on backreference
1778  *                interpretation.
1779  *
1780  * Parameters  :
1781  *          1  :  template_ptr = IN: Template to be filled out.
1782  *                                   Will be free()d.
1783  *                               OUT: Filled out template.
1784  *                                    Caller must free().
1785  *          2  :  exports = map with fill in symbol -> name pairs
1786  *
1787  * Returns     :  JB_ERR_OK on success
1788  *                JB_ERR_MEMORY on out-of-memory error
1789  *
1790  *********************************************************************/
1791 jb_err template_fill(char **template_ptr, const struct map *exports)
1792 {
1793    struct map_entry *m;
1794    pcrs_job *job;
1795    char buf[BUFFER_SIZE];
1796    char *tmp_out_buffer;
1797    char *file_buffer;
1798    size_t  size;
1799    int error;
1800    const char *flags;
1801
1802    assert(template_ptr);
1803    assert(*template_ptr);
1804    assert(exports);
1805
1806    file_buffer = *template_ptr;
1807    size = strlen(file_buffer) + 1;
1808
1809    /* 
1810     * Assemble pcrs joblist from exports map
1811     */
1812    for (m = exports->first; m != NULL; m = m->next)
1813    {
1814       if (*m->name == '$')
1815       {
1816          /*
1817           * First character of name is '$', so remove this flag
1818           * character and allow backreferences ($1 etc) in the
1819           * "replace with" text.
1820           */
1821          snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1822          flags = "sigU";
1823       }
1824       else
1825       {
1826          /*
1827           * Treat the "replace with" text as a literal string - 
1828           * no quoting needed, no backreferences allowed.
1829           * ("Trivial" ['T'] flag).
1830           */
1831          flags = "sigTU";
1832
1833          /* Enclose name in @@ */
1834          snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1835       }
1836
1837
1838       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1839
1840       /* Make and run job. */
1841       job = pcrs_compile(buf, m->value, flags,  &error);
1842       if (job == NULL) 
1843       {
1844          if (error == PCRS_ERR_NOMEM)
1845          {
1846             free(file_buffer);
1847             *template_ptr = NULL;
1848             return JB_ERR_MEMORY;
1849          }
1850          else
1851          {
1852             log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1853             /* Hope it wasn't important and silently ignore the invalid job */
1854          }
1855       }
1856       else
1857       {
1858          pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1859          free(file_buffer);
1860          pcrs_free_job(job);
1861          if (NULL == tmp_out_buffer)
1862          {
1863             *template_ptr = NULL;
1864             return JB_ERR_MEMORY;
1865          }
1866          file_buffer = tmp_out_buffer;
1867       }
1868    }
1869
1870    /*
1871     * Return
1872     */
1873    *template_ptr = file_buffer;
1874    return JB_ERR_OK;
1875 }
1876
1877
1878 /*********************************************************************
1879  *
1880  * Function    :  template_fill_for_cgi
1881  *
1882  * Description :  CGI support function that loads a HTML template
1883  *                and fills it in.  Handles file-not-found errors
1884  *                by sending a HTML error message.  For convenience,
1885  *                this function also frees the passed "exports" map.
1886  *
1887  * Parameters  :
1888  *          1  :  csp = Client state
1889  *          2  :  templatename = name of the HTML template to be used
1890  *          3  :  exports = map with fill in symbol -> name pairs.
1891  *                          Will be freed by this function.
1892  *          4  :  rsp = Response structure to fill in.
1893  *
1894  * Returns     :  JB_ERR_OK on success
1895  *                JB_ERR_MEMORY on out-of-memory error
1896  *
1897  *********************************************************************/
1898 jb_err template_fill_for_cgi(struct client_state *csp,
1899                              const char *templatename,
1900                              struct map *exports,
1901                              struct http_response *rsp)
1902 {
1903    jb_err err;
1904    
1905    assert(csp);
1906    assert(templatename);
1907    assert(exports);
1908    assert(rsp);
1909
1910    err = template_load(csp, &rsp->body, templatename, 0);
1911    if (err == JB_ERR_FILE)
1912    {
1913       free_map(exports);
1914       return cgi_error_no_template(csp, rsp, templatename);
1915    }
1916    else if (err)
1917    {
1918       free_map(exports);
1919       return err; /* JB_ERR_MEMORY */
1920    }
1921    err = template_fill(&rsp->body, exports);
1922    free_map(exports);
1923    return err;
1924 }
1925
1926
1927 /*********************************************************************
1928  *
1929  * Function    :  default_exports
1930  *
1931  * Description :  returns a struct map list that contains exports
1932  *                which are common to all CGI functions.
1933  *
1934  * Parameters  :
1935  *          1  :  csp = Current client state (buffers, headers, etc...)
1936  *          2  :  caller = name of CGI who calls us and which should
1937  *                         be excluded from the generated menu. May be
1938  *                         NULL.
1939  * Returns     :  NULL if no memory, else a new map.  Caller frees.
1940  *
1941  *********************************************************************/
1942 struct map *default_exports(const struct client_state *csp, const char *caller)
1943 {
1944    char buf[20];
1945    jb_err err;
1946    struct map * exports;
1947    int local_help_exists = 0;
1948
1949    assert(csp);
1950
1951    exports = new_map();
1952    if (exports == NULL)
1953    {
1954       return NULL;
1955    }
1956
1957    err = map(exports, "version", 1, html_encode(VERSION), 0);
1958    if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1959    if (!err) err = map(exports, "my-hostname",   1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1960    if (!err) err = map(exports, "homepage",      1, html_encode(HOME_PAGE_URL), 0);
1961    if (!err) err = map(exports, "default-cgi",   1, html_encode(CGI_PREFIX), 0);
1962    if (!err) err = map(exports, "menu",          1, make_menu(caller), 0);
1963    if (!err) err = map(exports, "code-status",   1, CODE_STATUS, 1);
1964    if (!err) err = map(exports, "user-manual",   1, csp->config->usermanual ,1);
1965    if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
1966    if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1967
1968    snprintf(buf, 20, "%d", csp->config->hport);
1969    if (!err) err = map(exports, "my-port", 1, buf, 1);
1970
1971    if(!strcmp(CODE_STATUS, "stable"))
1972    {
1973       if (!err) err = map_block_killer(exports, "unstable");
1974    }
1975
1976    if (csp->config->admin_address != NULL)
1977    {
1978       if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1979       local_help_exists = 1;
1980    }
1981    else
1982    {
1983       if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1984    }
1985
1986    if (csp->config->proxy_info_url != NULL)
1987    {
1988       if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1989       local_help_exists = 1;
1990    }
1991    else
1992    {
1993       if (!err) err = map_block_killer(exports, "have-proxy-info");
1994    }
1995
1996    if (local_help_exists == 0)
1997    {
1998       if (!err) err = map_block_killer(exports, "have-help-info");
1999    }
2000
2001    if (err)
2002    {
2003       free_map(exports);
2004       return NULL;
2005    }
2006
2007    return exports;
2008 }
2009
2010
2011 /*********************************************************************
2012  *
2013  * Function    :  map_block_killer
2014  *
2015  * Description :  Convenience function.
2016  *                Adds a "killer" for the conditional HTML-template
2017  *                block <name>, i.e. a substitution of the regex
2018  *                "if-<name>-start.*if-<name>-end" to the given
2019  *                export list.
2020  *
2021  * Parameters  :  
2022  *          1  :  exports = map to extend
2023  *          2  :  name = name of conditional block
2024  *
2025  * Returns     :  JB_ERR_OK on success
2026  *                JB_ERR_MEMORY on out-of-memory error.  
2027  *
2028  *********************************************************************/
2029 jb_err map_block_killer(struct map *exports, const char *name)
2030 {
2031    char buf[1000]; /* Will do, since the names are hardwired */
2032
2033    assert(exports);
2034    assert(name);
2035    assert(strlen(name) < 490);
2036
2037    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2038    return map(exports, buf, 1, "", 1);
2039 }
2040
2041
2042 /*********************************************************************
2043  *
2044  * Function    :  map_block_keep
2045  *
2046  * Description :  Convenience function.  Removes the markers used
2047  *                by map-block-killer, to save a few bytes.
2048  *                i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2049  *
2050  * Parameters  :  
2051  *          1  :  exports = map to extend
2052  *          2  :  name = name of conditional block
2053  *
2054  * Returns     :  JB_ERR_OK on success
2055  *                JB_ERR_MEMORY on out-of-memory error.  
2056  *
2057  *********************************************************************/
2058 jb_err map_block_keep(struct map *exports, const char *name)
2059 {
2060    jb_err err;
2061    char buf[500]; /* Will do, since the names are hardwired */
2062
2063    assert(exports);
2064    assert(name);
2065    assert(strlen(name) < 490);
2066
2067    snprintf(buf, 500, "if-%s-start", name);
2068    err = map(exports, buf, 1, "", 1);
2069
2070    if (err)
2071    {
2072       return err;
2073    }
2074
2075    snprintf(buf, 500, "if-%s-end", name);
2076    return map(exports, buf, 1, "", 1);
2077 }
2078
2079
2080 /*********************************************************************
2081  *
2082  * Function    :  map_conditional
2083  *
2084  * Description :  Convenience function.
2085  *                Adds an "if-then-else" for the conditional HTML-template
2086  *                block <name>, i.e. a substitution of the form:
2087  *                @if-<name>-then@
2088  *                   True text
2089  *                @else-not-<name>@
2090  *                   False text
2091  *                @endif-<name>@
2092  *
2093  *                The control structure and one of the alternatives
2094  *                will be hidden.
2095  *
2096  * Parameters  :  
2097  *          1  :  exports = map to extend
2098  *          2  :  name = name of conditional block
2099  *          3  :  choose_first = nonzero for first, zero for second.
2100  *
2101  * Returns     :  JB_ERR_OK on success
2102  *                JB_ERR_MEMORY on out-of-memory error.  
2103  *
2104  *********************************************************************/
2105 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2106 {
2107    char buf[1000]; /* Will do, since the names are hardwired */
2108    jb_err err;
2109
2110    assert(exports);
2111    assert(name);
2112    assert(strlen(name) < 480);
2113
2114    snprintf(buf, 1000, (choose_first
2115       ? "else-not-%s@.*@endif-%s"
2116       : "if-%s-then@.*@else-not-%s"),
2117       name, name);
2118
2119    err = map(exports, buf, 1, "", 1);
2120    if (err)
2121    {
2122       return err;
2123    }
2124
2125    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2126    return map(exports, buf, 1, "", 1);
2127 }
2128
2129
2130 /*********************************************************************
2131  *
2132  * Function    :  make_menu
2133  *
2134  * Description :  Returns an HTML-formatted menu of the available 
2135  *                unhidden CGIs, excluding the one given in <self>
2136  *
2137  * Parameters  :  self = name of CGI to leave out, can be NULL for
2138  *                complete listing.
2139  *
2140  * Returns     :  menu string, or NULL on out-of-memory error.
2141  *
2142  *********************************************************************/
2143 char *make_menu(const char *self)
2144 {
2145    const struct cgi_dispatcher *d;
2146    char *result = strdup("");
2147
2148    if (self == NULL)
2149    {
2150       self = "NO-SUCH-CGI!";
2151    }
2152
2153    /* List available unhidden CGI's and export as "other-cgis" */
2154    for (d = cgi_dispatchers; d->name; d++)
2155    {
2156       if (d->description && strcmp(d->name, self))
2157       {
2158          string_append(&result, "<li><a href=\"" CGI_PREFIX);
2159          string_append(&result, d->name);
2160          string_append(&result, "\">");
2161          string_append(&result, d->description);
2162          string_append(&result, "</a></li>");
2163       }
2164    }
2165
2166    return result;
2167 }
2168
2169
2170 /*********************************************************************
2171  *
2172  * Function    :  dump_map
2173  *
2174  * Description :  HTML-dump a map for debugging (as table)
2175  *
2176  * Parameters  :
2177  *          1  :  the_map = map to dump
2178  *
2179  * Returns     :  string with HTML
2180  *
2181  *********************************************************************/
2182 char *dump_map(const struct map *the_map)
2183 {
2184    struct map_entry *cur_entry;
2185    char *ret = strdup("");
2186
2187    string_append(&ret, "<table>\n");
2188
2189    for (cur_entry = the_map->first;
2190         (cur_entry != NULL) && (ret != NULL);
2191         cur_entry = cur_entry->next)
2192    {
2193       string_append(&ret, "<tr><td><b>");
2194       string_join  (&ret, html_encode(cur_entry->name));
2195       string_append(&ret, "</b></td><td>");
2196       string_join  (&ret, html_encode(cur_entry->value));
2197       string_append(&ret, "</td></tr>\n");
2198    }
2199
2200    string_append(&ret, "</table>\n");
2201    return ret;
2202 }
2203
2204
2205 /*
2206   Local Variables:
2207   tab-width: 3
2208   end:
2209 */