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