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