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