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