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