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