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