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