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