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