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