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