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