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