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