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