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