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