Remove error_response()'s third parameter. None of the templates use it.
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.119 2009/05/28 21:13:34 fabiankeil 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-2004, 2006-2008
15  *                the SourceForge Privoxy team. http://www.privoxy.org/
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  **********************************************************************/
40
41
42 #include "config.h"
43
44 #include <stdio.h>
45 #include <sys/types.h>
46 #include <stdlib.h>
47 #include <ctype.h>
48 #include <string.h>
49 #include <limits.h>
50 #include <assert.h>
51
52 #include "project.h"
53 #include "cgi.h"
54 #include "list.h"
55 #include "encode.h"
56 #include "ssplit.h"
57 #include "errlog.h"
58 #include "filters.h"
59 #include "miscutil.h"
60 #include "cgisimple.h"
61 #include "jbsockets.h"
62 #if defined(FEATURE_CGI_EDIT_ACTIONS) || defined(FEATURE_TOGGLE)
63 #include "cgiedit.h"
64 #endif /* defined(FEATURE_CGI_EDIT_ACTIONS) || defined (FEATURE_TOGGLE) */
65
66 /* loadcfg.h is for global_toggle_state only */
67 #include "loadcfg.h"
68 /* jcc.h is for mutex semaphore globals only */
69 #include "jcc.h"
70
71 const char cgi_h_rcs[] = CGI_H_VERSION;
72
73 /*
74  * List of CGI functions: name, handler, description
75  * Note: Do NOT use single quotes in the description;
76  *       this will break the dynamic "blocked" template!
77  */
78 static const struct cgi_dispatcher cgi_dispatchers[] = {
79    { "",
80          cgi_default,
81          "Privoxy main page",
82          TRUE },
83 #ifdef FEATURE_GRACEFUL_TERMINATION
84    { "die", 
85          cgi_die,  
86          "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
87         "this is a one click Denial Of Service attack!!!</em>",
88          FALSE }, 
89 #endif
90    { "show-status", 
91          cgi_show_status,  
92 #ifdef FEATURE_CGI_EDIT_ACTIONS
93         "View &amp; change the current configuration",
94 #else
95         "View the current configuration",
96 #endif
97          TRUE }, 
98    { "show-version", 
99          cgi_show_version,  
100          "View the source code version numbers",
101           TRUE }, 
102    { "show-request", 
103          cgi_show_request,  
104          "View the request headers",
105          TRUE }, 
106    { "show-url-info",
107          cgi_show_url_info, 
108          "Look up which actions apply to a URL and why",
109          TRUE },
110 #ifdef FEATURE_TOGGLE
111    { "toggle",
112          cgi_toggle, 
113          "Toggle Privoxy on or off",
114          FALSE },
115 #endif /* def FEATURE_TOGGLE */
116 #ifdef FEATURE_CGI_EDIT_ACTIONS
117    { "edit-actions", /* Edit the actions list */
118          cgi_edit_actions, 
119          NULL, FALSE },
120    { "eaa", /* Shortcut for edit-actions-add-url-form */
121          cgi_edit_actions_add_url_form, 
122          NULL, FALSE },
123    { "eau", /* Shortcut for edit-actions-url-form */
124          cgi_edit_actions_url_form, 
125          NULL, FALSE },
126    { "ear", /* Shortcut for edit-actions-remove-url-form */
127          cgi_edit_actions_remove_url_form, 
128          NULL, FALSE },
129    { "eal", /* Shortcut for edit-actions-list */
130          cgi_edit_actions_list, 
131          NULL, FALSE },
132    { "eafu", /* Shortcut for edit-actions-for-url */
133          cgi_edit_actions_for_url, 
134          NULL, FALSE },
135    { "eas", /* Shortcut for edit-actions-submit */
136          cgi_edit_actions_submit, 
137          NULL, FALSE },
138    { "easa", /* Shortcut for edit-actions-section-add */
139          cgi_edit_actions_section_add, 
140          NULL, FALSE  },
141    { "easr", /* Shortcut for edit-actions-section-remove */
142          cgi_edit_actions_section_remove, 
143          NULL, FALSE  },
144    { "eass", /* Shortcut for edit-actions-section-swap */
145          cgi_edit_actions_section_swap, 
146          NULL, FALSE  },
147    { "edit-actions-for-url",
148          cgi_edit_actions_for_url, 
149          NULL, FALSE  /* Edit the actions for (a) specified URL(s) */ },
150    { "edit-actions-list",
151          cgi_edit_actions_list, 
152          NULL, TRUE /* Edit the actions list */ },
153    { "edit-actions-submit",
154          cgi_edit_actions_submit, 
155          NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
156    { "edit-actions-url",
157          cgi_edit_actions_url, 
158          NULL, FALSE /* Change a URL pattern in the actionsfile */ },
159    { "edit-actions-url-form",
160          cgi_edit_actions_url_form, 
161          NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
162    { "edit-actions-add-url",
163          cgi_edit_actions_add_url, 
164          NULL, FALSE /* Add a URL pattern to the actionsfile */ },
165    { "edit-actions-add-url-form",
166          cgi_edit_actions_add_url_form, 
167          NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
168    { "edit-actions-remove-url",
169          cgi_edit_actions_remove_url, 
170          NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
171    { "edit-actions-remove-url-form",
172          cgi_edit_actions_remove_url_form, 
173          NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
174    { "edit-actions-section-add",
175          cgi_edit_actions_section_add, 
176          NULL, FALSE /* Remove a section from the actionsfile */ },
177    { "edit-actions-section-remove",
178          cgi_edit_actions_section_remove, 
179          NULL, FALSE /* Remove a section from the actionsfile */ },
180    { "edit-actions-section-swap",
181          cgi_edit_actions_section_swap, 
182          NULL, FALSE /* Swap two sections in the actionsfile */ },
183 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
184    { "error-favicon.ico", 
185          cgi_send_error_favicon,  
186          NULL, TRUE /* Sends the favicon image for error pages. */ },
187    { "favicon.ico", 
188          cgi_send_default_favicon,  
189          NULL, TRUE /* Sends the default favicon image. */ },
190    { "robots.txt", 
191          cgi_robots_txt,  
192          NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ }, 
193    { "send-banner",
194          cgi_send_banner, 
195          NULL, TRUE /* Send a built-in image */ },
196    { "send-stylesheet",
197          cgi_send_stylesheet, 
198          NULL, FALSE /* Send templates/cgi-style.css */ },
199    { "t",
200          cgi_transparent_image, 
201          NULL, TRUE /* Send a transparent image (short name) */ },
202    { "url-info-osd.xml",
203          cgi_send_url_info_osd, 
204          NULL, TRUE /* Send templates/url-info-osd.xml */ },
205    { "user-manual",
206           cgi_send_user_manual,
207           NULL, TRUE /* Send user-manual */ },
208    { NULL, /* NULL Indicates end of list and default page */
209          cgi_error_404,
210          NULL, TRUE /* Unknown CGI page */ }
211 };
212
213
214 /*
215  * Built-in images for ad replacement
216  *
217  * Hint: You can encode your own images like this:
218  * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
219  */
220
221 #ifdef FEATURE_NO_GIFS
222
223 /*
224  * Checkerboard pattern, as a PNG.
225  */
226 const char image_pattern_data[] =
227    "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
228    "\122\000\000\000\004\000\000\000\004\010\006\000\000\000\251"
229    "\361\236\176\000\000\000\006\142\113\107\104\000\000\000\000"
230    "\000\000\371\103\273\177\000\000\000\033\111\104\101\124\010"
231    "\327\143\140\140\140\060\377\377\377\077\003\234\106\341\060"
232    "\060\230\063\020\124\001\000\161\021\031\241\034\364\030\143"
233    "\000\000\000\000\111\105\116\104\256\102\140\202";
234
235 /*
236  * 1x1 transparant PNG.
237  */
238 const char image_blank_data[] =
239  "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
240  "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
241  "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
242  "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
243  "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
244  "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
245  "\000\000\000\000\111\105\116\104\256\102\140\202";
246 #else
247
248 /*
249  * Checkerboard pattern, as a GIF.
250  */
251 const char image_pattern_data[] =
252    "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
253    "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
254    "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
255    "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
256    "\270\005\000\073";
257
258 /*
259  * 1x1 transparant GIF.
260  */
261 const char image_blank_data[] =
262    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
263    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
264    "\000\001\000\000\002\002D\001\000;";
265 #endif
266
267 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
268 const size_t image_blank_length   = sizeof(image_blank_data) - 1;
269
270
271 static struct http_response cgi_error_memory_response[1];
272
273 static struct http_response *dispatch_known_cgi(struct client_state * csp,
274                                                 const char * path);
275 static struct map *parse_cgi_parameters(char *argstring);
276
277
278 /*********************************************************************
279  * 
280  * Function    :  dispatch_cgi
281  *
282  * Description :  Checks if a request URL has either the magical
283  *                hostname CGI_SITE_1_HOST (usually http://p.p/) or
284  *                matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
285  *                http://config.privoxy.org/). If so, it passes
286  *                the (rest of the) path onto dispatch_known_cgi, which
287  *                calls the relevant CGI handler function.
288  *
289  * Parameters  :
290  *          1  :  csp = Current client state (buffers, headers, etc...)
291  *
292  * Returns     :  http_response if match, NULL if nonmatch or handler fail
293  *
294  *********************************************************************/
295 struct http_response *dispatch_cgi(struct client_state *csp)
296 {
297    const char *host = csp->http->host;
298    const char *path = csp->http->path;
299
300    /*
301     * Should we intercept ?
302     */
303
304    /* Note: "example.com" and "example.com." are equivalent hostnames. */
305
306    /* Either the host matches CGI_SITE_1_HOST ..*/
307    if (   ( (0 == strcmpic(host, CGI_SITE_1_HOST))
308          || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
309        && (path[0] == '/') )
310    {
311       /* ..then the path will all be for us.  Remove leading '/' */
312       path++;
313    }
314    /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
315    else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
316             || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
317           && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
318    {
319       /* take everything following CGI_SITE_2_PATH */
320       path += strlen(CGI_SITE_2_PATH);
321       if (*path == '/')
322       {
323          /* skip the forward slash after CGI_SITE_2_PATH */
324          path++;
325       }
326       else if (*path != '\0')
327       {
328          /*
329           * weirdness: URL is /configXXX, where XXX is some string
330           * Do *NOT* intercept.
331           */
332          return NULL;
333       }
334    }
335    else
336    {
337       /* Not a CGI */
338       return NULL;
339    }
340
341    /* 
342     * This is a CGI call.
343     */
344
345    return dispatch_known_cgi(csp, path);
346 }
347
348
349 /*********************************************************************
350  *
351  * Function    :  grep_cgi_referrer
352  *
353  * Description :  Ugly provisorical fix that greps the value of the
354  *                referer HTTP header field out of a linked list of
355  *                strings like found at csp->headers. Will disappear
356  *                in Privoxy 3.1.
357  *
358  *                FIXME: csp->headers ought to be csp->http->headers
359  *                FIXME: Parsing all client header lines should
360  *                       happen right after the request is received!
361  *
362  * Parameters  :
363  *          1  :  csp = Current client state (buffers, headers, etc...)
364  *
365  * Returns     :  pointer to value (no copy!), or NULL if none found.
366  *
367  *********************************************************************/
368 static char *grep_cgi_referrer(const struct client_state *csp)
369 {
370    struct list_entry *p;
371
372    for (p = csp->headers->first; p != NULL; p = p->next)
373    {
374       if (p->str == NULL) continue;
375       if (strncmpic(p->str, "Referer: ", 9) == 0)
376       {
377          return ((p->str) + 9);
378       }
379    }
380    return NULL;
381
382 }
383
384
385 /*********************************************************************
386  * 
387  * Function    :  referrer_is_safe
388  *
389  * Description :  Decides whether we trust the Referer for
390  *                CGI pages which are only meant to be reachable
391  *                through Privoxy's web interface directly.
392  *
393  * Parameters  :
394  *          1  :  csp = Current client state (buffers, headers, etc...)
395  *
396  * Returns     :  TRUE  if the referrer is safe, or
397  *                FALSE if the referrer is unsafe or not set.
398  *
399  *********************************************************************/
400 static int referrer_is_safe(const struct client_state *csp)
401 {
402    char *referrer;
403    static const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
404
405    referrer = grep_cgi_referrer(csp);
406
407    if (NULL == referrer)
408    {
409       /* No referrer, no access  */
410       log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
411          csp->http->url);
412    }
413    else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)
414          || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix)))))
415    {
416       /* Trustworthy referrer */
417       log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
418          csp->http->url, referrer);
419
420       return TRUE;
421    }
422    else
423    {
424       /* Untrustworthy referrer */
425       log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
426          csp->http->url, referrer);
427    }
428
429    return FALSE;
430
431 }
432
433 /*********************************************************************
434  * 
435  * Function    :  dispatch_known_cgi
436  *
437  * Description :  Processes a CGI once dispatch_cgi has determined that
438  *                it matches one of the magic prefixes. Parses the path
439  *                as a cgi name plus query string, prepares a map that
440  *                maps CGI parameter names to their values, initializes
441  *                the http_response struct, and calls the relevant CGI
442  *                handler function.
443  *
444  * Parameters  :
445  *          1  :  csp = Current client state (buffers, headers, etc...)
446  *          2  :  path = Path of CGI, with the CGI prefix removed.
447  *                       Should not have a leading "/".
448  *
449  * Returns     :  http_response, or NULL on handler failure or out of
450  *                memory.
451  *
452  *********************************************************************/
453 static struct http_response *dispatch_known_cgi(struct client_state * csp,
454                                                 const char * path)
455 {
456    const struct cgi_dispatcher *d;
457    struct map *param_list;
458    struct http_response *rsp;
459    char *query_args_start;
460    char *path_copy;
461    jb_err err;
462
463    if (NULL == (path_copy = strdup(path)))
464    {
465       return cgi_error_memory();
466    }
467    query_args_start = path_copy;
468    while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
469    {
470       query_args_start++;
471    }
472    if (*query_args_start == '/') 
473    {
474       *query_args_start++ = '\0';
475       if ((param_list = new_map()))
476       {
477          map(param_list, "file", 1, url_decode(query_args_start), 0);
478       }
479    }
480    else
481    {
482       if (*query_args_start == '?')
483       {
484          *query_args_start++ = '\0';
485       }
486       if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
487       {
488          free(path_copy);
489          return cgi_error_memory();
490       }
491    }
492
493    /*
494     * At this point:
495     * path_copy        = CGI call name
496     * param_list       = CGI params, as map
497     */
498
499    /* Get mem for response or fail*/
500    if (NULL == (rsp = alloc_http_response()))
501    {
502       free(path_copy);
503       free_map(param_list);
504       return cgi_error_memory();
505    }
506
507    /* 
508     * Find and start the right CGI function
509     */
510    d = cgi_dispatchers;
511    for (;;)
512    {
513       if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
514       {
515          /*
516           * If the called CGI is either harmless, or referred
517           * from a trusted source, start it.
518           */
519          if (d->harmless || referrer_is_safe(csp))
520          {
521             err = (d->handler)(csp, rsp, param_list);
522          }
523          else
524          {
525             /*
526              * Else, modify toggle calls so that they only display
527              * the status, and deny all other calls.
528              */
529             if (0 == strcmp(path_copy, "toggle"))
530             {
531                unmap(param_list, "set");
532                err = (d->handler)(csp, rsp, param_list);
533             }
534             else
535             {
536                err = cgi_error_disabled(csp, rsp);
537             }
538          }
539
540          free(path_copy);
541          free_map(param_list);
542
543          if (err == JB_ERR_CGI_PARAMS)
544          {
545             err = cgi_error_bad_param(csp, rsp);
546          }
547          if (err && (err != JB_ERR_MEMORY))
548          {
549             /* Unexpected error! Shouldn't get here */
550             log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler.  Please file a bug report!", err);
551             err = cgi_error_unknown(csp, rsp, err);
552          }
553          if (!err)
554          {
555             /* It worked */
556             rsp->reason = RSP_REASON_CGI_CALL;
557             return finish_http_response(csp, rsp);
558          }
559          else
560          {
561             /* Error in handler, probably out-of-memory */
562             free_http_response(rsp);
563             return cgi_error_memory();
564          }
565       }
566       d++;
567    }
568 }
569    
570         
571 /*********************************************************************
572  *
573  * Function    :  parse_cgi_parameters
574  *
575  * Description :  Parse a URL-encoded argument string into name/value
576  *                pairs and store them in a struct map list.
577  *
578  * Parameters  :
579  *          1  :  argstring = string to be parsed.  Will be trashed.
580  *
581  * Returns     :  pointer to param list, or NULL if out of memory.
582  *
583  *********************************************************************/
584 static struct map *parse_cgi_parameters(char *argstring)
585 {
586    char *p;
587    char *vector[BUFFER_SIZE];
588    int pairs, i;
589    struct map *cgi_params;
590
591    if (NULL == (cgi_params = new_map()))
592    {
593       return NULL;
594    }
595
596    /* 
597     * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
598     * the fragment identifier along with the request, so we must
599     * cut it off here, so it won't pollute the CGI params:
600     */
601    if (NULL != (p = strchr(argstring, '#')))
602    {
603       *p = '\0';
604    }
605
606    pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
607
608    for (i = 0; i < pairs; i++)
609    {
610       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
611       {
612          *p = '\0';
613          if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
614          {
615             free_map(cgi_params);
616             return NULL;
617          }
618       }
619    }
620
621    return cgi_params;
622
623 }
624
625
626 /*********************************************************************
627  *
628  * Function    :  get_char_param
629  *
630  * Description :  Get a single-character parameter passed to a CGI
631  *                function.
632  *
633  * Parameters  :
634  *          1  :  parameters = map of cgi parameters
635  *          2  :  param_name = The name of the parameter to read
636  *
637  * Returns     :  Uppercase character on success, '\0' on error.
638  *
639  *********************************************************************/
640 char get_char_param(const struct map *parameters,
641                     const char *param_name)
642 {
643    char ch;
644
645    assert(parameters);
646    assert(param_name);
647
648    ch = *(lookup(parameters, param_name));
649    if ((ch >= 'a') && (ch <= 'z'))
650    {
651       ch = (char)(ch - 'a' + 'A');
652    }
653
654    return ch;
655 }
656
657
658 /*********************************************************************
659  *
660  * Function    :  get_string_param
661  *
662  * Description :  Get a string paramater, to be used as an
663  *                ACTION_STRING or ACTION_MULTI paramater.
664  *                Validates the input to prevent stupid/malicious
665  *                users from corrupting their action file.
666  *
667  * Parameters  :
668  *          1  :  parameters = map of cgi parameters
669  *          2  :  param_name = The name of the parameter to read
670  *          3  :  pparam = destination for paramater.  Allocated as
671  *                part of the map "parameters", so don't free it.
672  *                Set to NULL if not specified.
673  *
674  * Returns     :  JB_ERR_OK         on success, or if the paramater
675  *                                  was not specified.
676  *                JB_ERR_MEMORY     on out-of-memory.
677  *                JB_ERR_CGI_PARAMS if the paramater is not valid.
678  *
679  *********************************************************************/
680 jb_err get_string_param(const struct map *parameters,
681                         const char *param_name,
682                         const char **pparam)
683 {
684    const char *param;
685    const char *s;
686    char ch;
687
688    assert(parameters);
689    assert(param_name);
690    assert(pparam);
691
692    *pparam = NULL;
693
694    param = lookup(parameters, param_name);
695    if (!*param)
696    {
697       return JB_ERR_OK;
698    }
699
700    if (strlen(param) >= CGI_PARAM_LEN_MAX)
701    {
702       /*
703        * Too long.
704        *
705        * Note that the length limit is arbitrary, it just seems
706        * sensible to limit it to *something*.  There's no
707        * technical reason for any limit at all.
708        */
709       return JB_ERR_CGI_PARAMS;
710    }
711
712    /* Check every character to see if it's legal */
713    s = param;
714    while ((ch = *s++) != '\0')
715    {
716       if ( ((unsigned char)ch < (unsigned char)' ')
717         || (ch == '}') )
718       {
719          /* Probable hack attempt, or user accidentally used '}'. */
720          return JB_ERR_CGI_PARAMS;
721       }
722    }
723
724    /* Success */
725    *pparam = param;
726
727    return JB_ERR_OK;
728 }
729
730
731 /*********************************************************************
732  *
733  * Function    :  get_number_param
734  *
735  * Description :  Get a non-negative integer from the parameters
736  *                passed to a CGI function.
737  *
738  * Parameters  :
739  *          1  :  csp = Current client state (buffers, headers, etc...)
740  *          2  :  parameters = map of cgi parameters
741  *          3  :  name = Name of CGI parameter to read
742  *          4  :  pvalue = destination for value.
743  *                         Set to -1 on error.
744  *
745  * Returns     :  JB_ERR_OK         on success
746  *                JB_ERR_MEMORY     on out-of-memory
747  *                JB_ERR_CGI_PARAMS if the parameter was not specified
748  *                                  or is not valid.
749  *
750  *********************************************************************/
751 jb_err get_number_param(struct client_state *csp,
752                         const struct map *parameters,
753                         char *name,
754                         unsigned *pvalue)
755 {
756    const char *param;
757    char ch;
758    unsigned value;
759
760    assert(csp);
761    assert(parameters);
762    assert(name);
763    assert(pvalue);
764
765    *pvalue = 0; 
766
767    param = lookup(parameters, name);
768    if (!*param)
769    {
770       return JB_ERR_CGI_PARAMS;
771    }
772
773    /* We don't use atoi because I want to check this carefully... */
774
775    value = 0;
776    while ((ch = *param++) != '\0')
777    {
778       if ((ch < '0') || (ch > '9'))
779       {
780          return JB_ERR_CGI_PARAMS;
781       }
782
783       ch = (char)(ch - '0');
784
785       /* Note:
786        *
787        * <limits.h> defines UINT_MAX
788        *
789        * (UINT_MAX - ch) / 10 is the largest number that
790        *     can be safely multiplied by 10 then have ch added.
791        */
792       if (value > ((UINT_MAX - (unsigned)ch) / 10U))
793       {
794          return JB_ERR_CGI_PARAMS;
795       }
796
797       value = value * 10 + (unsigned)ch;
798    }
799
800    /* Success */
801    *pvalue = value;
802
803    return JB_ERR_OK;
804
805 }
806
807
808 /*********************************************************************
809  *
810  * Function    :  error_response
811  *
812  * Description :  returns an http_response that explains the reason
813  *                why a request failed.
814  *
815  * Parameters  :
816  *          1  :  csp = Current client state (buffers, headers, etc...)
817  *          2  :  templatename = Which template should be used for the answer
818  *
819  * Returns     :  A http_response.  If we run out of memory, this
820  *                will be cgi_error_memory().
821  *
822  *********************************************************************/
823 struct http_response *error_response(struct client_state *csp,
824                                      const char *templatename)
825 {
826    jb_err err;
827    struct http_response *rsp;
828    struct map *exports = default_exports(csp, NULL);
829    char *path = NULL;
830
831    if (exports == NULL)
832    {
833       return cgi_error_memory();
834    }
835
836    if (NULL == (rsp = alloc_http_response()))
837    {
838       free_map(exports);
839       return cgi_error_memory();
840    }
841
842 #ifdef FEATURE_FORCE_LOAD
843    if (csp->flags & CSP_FLAG_FORCED)
844    {
845       path = strdup(FORCE_PREFIX);
846    }
847    else
848 #endif /* def FEATURE_FORCE_LOAD */
849    {
850       path = strdup("");
851    }
852    err = string_append(&path, csp->http->path);
853
854    if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
855    if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
856    if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
857    if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1); 
858    if (!err)
859    {
860      err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
861      if (err)
862      {
863        /* Some failures, like "404 no such domain", don't have an IP address. */
864        err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
865      }
866    }
867
868
869    if (err)
870    {
871       free_map(exports);
872       free_http_response(rsp);
873       return cgi_error_memory();
874    }
875
876    if (!strcmp(templatename, "no-such-domain"))
877    {
878       rsp->status = strdup("404 No such domain");
879       if (rsp->status == NULL)
880       {
881          free_map(exports);
882          free_http_response(rsp);
883          return cgi_error_memory();
884       }
885       rsp->reason = RSP_REASON_NO_SUCH_DOMAIN;
886    }
887    else if (!strcmp(templatename, "forwarding-failed"))
888    {
889       const struct forward_spec *fwd = forward_url(csp, csp->http);
890       char *socks_type = NULL;
891       if (fwd == NULL)
892       {
893          log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
894          /* Never get here - LOG_LEVEL_FATAL causes program exit */
895       }
896
897       /*
898        * XXX: While the template is called forwarding-failed,
899        * it currently only handles socks forwarding failures.
900        */
901       assert(fwd != NULL);
902       assert(fwd->type != SOCKS_NONE);
903
904       /*
905        * Map failure reason, forwarding type and forwarder.
906        */
907       if (NULL == csp->error_message)
908       {
909          /*
910           * Either we forgot to record the failure reason,
911           * or the memory allocation failed.
912           */
913          log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
914          csp->error_message = strdup("Failure reason missing. Check the log file for details.");
915       }
916       if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
917
918       /*
919        * XXX: this is almost the same code as in cgi_show_url_info()
920        * and thus should be factored out and shared.
921        */
922       switch (fwd->type)
923       {
924          case SOCKS_4:
925             socks_type = "socks4-";
926             break;
927          case SOCKS_4A:
928             socks_type = "socks4a-";
929             break;
930          case SOCKS_5:
931             socks_type = "socks5-";
932             break;
933          default:
934             log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
935       }
936
937       if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
938       if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
939
940       if (!err) rsp->status = strdup("503 Forwarding failure");
941       if ((rsp->status == NULL) || (NULL == csp->error_message) || err)
942       {
943          free_map(exports);
944          free_http_response(rsp);
945          return cgi_error_memory();
946       }
947       rsp->reason = RSP_REASON_FORWARDING_FAILED;
948    }
949    else if (!strcmp(templatename, "connect-failed"))
950    {
951       rsp->status = strdup("503 Connect failed");
952       if (rsp->status == NULL)
953       {
954          free_map(exports);
955          free_http_response(rsp);
956          return cgi_error_memory();
957       }
958       rsp->reason = RSP_REASON_CONNECT_FAILED;
959    }
960
961    err = template_fill_for_cgi(csp, templatename, exports, rsp);
962    if (err)
963    {
964       free_http_response(rsp);
965       return cgi_error_memory();
966    }
967
968    return finish_http_response(csp, rsp);
969 }
970
971
972 /*********************************************************************
973  *
974  * Function    :  cgi_error_disabled
975  *
976  * Description :  CGI function that is called to generate an error
977  *                response if the actions editor or toggle CGI are
978  *                accessed despite having being disabled at compile-
979  *                or run-time, or if the user followed an untrusted link
980  *                to access a unsafe CGI feature that is only reachable
981  *                through Privoxy directly.
982  *
983  * Parameters  :
984  *          1  :  csp = Current client state (buffers, headers, etc...)
985  *          2  :  rsp = http_response data structure for output
986  *
987  * CGI Parameters : none
988  *
989  * Returns     :  JB_ERR_OK on success
990  *                JB_ERR_MEMORY on out-of-memory error.
991  *
992  *********************************************************************/
993 jb_err cgi_error_disabled(const struct client_state *csp,
994                           struct http_response *rsp)
995 {
996    struct map *exports;
997
998    assert(csp);
999    assert(rsp);
1000
1001    if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1002    {
1003       return JB_ERR_MEMORY;
1004    }
1005    if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1006    {
1007       /* Not important enough to do anything */
1008       log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1009    }
1010
1011    return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1012 }
1013
1014
1015 /*********************************************************************
1016  *
1017  * Function    :  cgi_init_error_messages
1018  *
1019  * Description :  Call at the start of the program to initialize
1020  *                the error message used by cgi_error_memory().
1021  *
1022  * Parameters  :  N/A
1023  *
1024  * Returns     :  N/A
1025  *
1026  *********************************************************************/
1027 void cgi_init_error_messages(void)
1028 {
1029    memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1030    cgi_error_memory_response->head =
1031       "HTTP/1.0 500 Internal Privoxy Error\r\n"
1032       "Content-Type: text/html\r\n"
1033       "\r\n";
1034    cgi_error_memory_response->body =
1035       "<html>\r\n"
1036       "<head>\r\n"
1037       " <title>500 Internal Privoxy Error</title>\r\n"
1038       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1039       "</head>\r\n"
1040       "<body>\r\n"
1041       "<h1>500 Internal Privoxy Error</h1>\r\n"
1042       "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1043       "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1044       "</body>\r\n"
1045       "</html>\r\n";
1046
1047    cgi_error_memory_response->head_length =
1048       strlen(cgi_error_memory_response->head);
1049    cgi_error_memory_response->content_length =
1050       strlen(cgi_error_memory_response->body);
1051    cgi_error_memory_response->reason = RSP_REASON_OUT_OF_MEMORY;
1052 }
1053
1054
1055 /*********************************************************************
1056  *
1057  * Function    :  cgi_error_memory
1058  *
1059  * Description :  Called if a CGI function runs out of memory.
1060  *                Returns a statically-allocated error response.
1061  *
1062  * Parameters  :  N/A
1063  *
1064  * Returns     :  http_response data structure for output.  This is
1065  *                statically allocated, for obvious reasons.
1066  *
1067  *********************************************************************/
1068 struct http_response *cgi_error_memory(void)
1069 {
1070    /* assert that it's been initialized. */
1071    assert(cgi_error_memory_response->head);
1072
1073    return cgi_error_memory_response;
1074 }
1075
1076
1077 /*********************************************************************
1078  *
1079  * Function    :  cgi_error_no_template
1080  *
1081  * Description :  Almost-CGI function that is called if a template
1082  *                cannot be loaded.  Note this is not a true CGI,
1083  *                it takes a template name rather than a map of 
1084  *                parameters.
1085  *
1086  * Parameters  :
1087  *          1  :  csp = Current client state (buffers, headers, etc...)
1088  *          2  :  rsp = http_response data structure for output
1089  *          3  :  template_name = Name of template that could not
1090  *                                be loaded.
1091  *
1092  * Returns     :  JB_ERR_OK on success
1093  *                JB_ERR_MEMORY on out-of-memory error.  
1094  *
1095  *********************************************************************/
1096 jb_err cgi_error_no_template(const struct client_state *csp,
1097                              struct http_response *rsp,
1098                              const char *template_name)
1099 {
1100    static const char status[] =
1101       "500 Internal Privoxy Error";
1102    static const char body_prefix[] =
1103       "<html>\r\n"
1104       "<head>\r\n"
1105       " <title>500 Internal Privoxy Error</title>\r\n"
1106       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1107       "</head>\r\n"
1108       "<body>\r\n"
1109       "<h1>500 Internal Privoxy Error</h1>\r\n"
1110       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1111       "<p><b>Could not load template file <code>";
1112    static const char body_suffix[] =
1113       "</code> or one of its included components.</b></p>\r\n"
1114       "<p>Please contact your proxy administrator.</p>\r\n"
1115       "<p>If you are the proxy administrator, please put the required file(s)"
1116       "in the <code><i>(confdir)</i>/templates</code> directory.  The "
1117       "location of the <code><i>(confdir)</i></code> directory "
1118       "is specified in the main Privoxy <code>config</code> "
1119       "file.  (It's typically the Privoxy install directory"
1120 #ifndef _WIN32
1121       ", or <code>/etc/privoxy/</code>"
1122 #endif /* ndef _WIN32 */
1123       ").</p>\r\n"
1124       "</body>\r\n"
1125       "</html>\r\n";
1126    const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1127
1128    assert(csp);
1129    assert(rsp);
1130    assert(template_name);
1131
1132    /* Reset rsp, if needed */
1133    freez(rsp->status);
1134    freez(rsp->head);
1135    freez(rsp->body);
1136    rsp->content_length = 0;
1137    rsp->head_length = 0;
1138    rsp->is_static = 0;
1139
1140    rsp->body = malloc(body_size);
1141    if (rsp->body == NULL)
1142    {
1143       return JB_ERR_MEMORY;
1144    }
1145    strlcpy(rsp->body, body_prefix, body_size);
1146    strlcat(rsp->body, template_name, body_size);
1147    strlcat(rsp->body, body_suffix, body_size);
1148
1149    rsp->status = strdup(status);
1150    if (rsp->status == NULL)
1151    {
1152       return JB_ERR_MEMORY;
1153    }
1154
1155    return JB_ERR_OK;
1156 }
1157
1158
1159 /*********************************************************************
1160  *
1161  * Function    :  cgi_error_unknown
1162  *
1163  * Description :  Almost-CGI function that is called if an unexpected
1164  *                error occurs in the top-level CGI dispatcher.
1165  *                In this context, "unexpected" means "anything other
1166  *                than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1167  *                expected to handle all other errors internally,
1168  *                since they can give more relavent error messages
1169  *                that way.
1170  *
1171  *                Note this is not a true CGI, it takes an error
1172  *                code rather than a map of parameters.
1173  *
1174  * Parameters  :
1175  *          1  :  csp = Current client state (buffers, headers, etc...)
1176  *          2  :  rsp = http_response data structure for output
1177  *          3  :  error_to_report = Error code to report.
1178  *
1179  * Returns     :  JB_ERR_OK on success
1180  *                JB_ERR_MEMORY on out-of-memory error.  
1181  *
1182  *********************************************************************/
1183 jb_err cgi_error_unknown(const struct client_state *csp,
1184                          struct http_response *rsp,
1185                          jb_err error_to_report)
1186 {
1187    static const char status[] =
1188       "500 Internal Privoxy Error";
1189    static const char body_prefix[] =
1190       "<html>\r\n"
1191       "<head>\r\n"
1192       " <title>500 Internal Privoxy Error</title>\r\n"
1193       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1194       "</head>\r\n"
1195       "<body>\r\n"
1196       "<h1>500 Internal Privoxy Error</h1>\r\n"
1197       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1198       "<p><b>Unexpected internal error: ";
1199    static const char body_suffix[] =
1200       "</b></p>\r\n"
1201       "<p>Please "
1202       "<a href=\"http://sourceforge.net/tracker/?group_id=11118&amp;atid=111118\">"
1203       "file a bug report</a>.</p>\r\n"
1204       "</body>\r\n"
1205       "</html>\r\n";
1206    char errnumbuf[30];
1207    /*
1208     * Due to sizeof(errnumbuf), body_size will be slightly
1209     * bigger than necessary but it doesn't really matter.
1210     */
1211    const size_t body_size = strlen(body_prefix) + sizeof(errnumbuf) + strlen(body_suffix) + 1;
1212    assert(csp);
1213    assert(rsp);
1214
1215    /* Reset rsp, if needed */
1216    freez(rsp->status);
1217    freez(rsp->head);
1218    freez(rsp->body);
1219    rsp->content_length = 0;
1220    rsp->head_length = 0;
1221    rsp->is_static = 0;
1222    rsp->reason = RSP_REASON_INTERNAL_ERROR;
1223
1224    snprintf(errnumbuf, sizeof(errnumbuf), "%d", error_to_report);
1225
1226    rsp->body = malloc(body_size);
1227    if (rsp->body == NULL)
1228    {
1229       return JB_ERR_MEMORY;
1230    }
1231    strlcpy(rsp->body, body_prefix, body_size);
1232    strlcat(rsp->body, errnumbuf,   body_size);
1233    strlcat(rsp->body, body_suffix, body_size);
1234
1235    rsp->status = strdup(status);
1236    if (rsp->status == NULL)
1237    {
1238       return JB_ERR_MEMORY;
1239    }
1240
1241    return JB_ERR_OK;
1242 }
1243
1244
1245 /*********************************************************************
1246  *
1247  * Function    :  cgi_error_bad_param
1248  *
1249  * Description :  CGI function that is called if the parameters
1250  *                (query string) for a CGI were wrong.
1251  *               
1252  * Parameters  :
1253  *          1  :  csp = Current client state (buffers, headers, etc...)
1254  *          2  :  rsp = http_response data structure for output
1255  *
1256  * CGI Parameters : none
1257  *
1258  * Returns     :  JB_ERR_OK on success
1259  *                JB_ERR_MEMORY on out-of-memory error.  
1260  *
1261  *********************************************************************/
1262 jb_err cgi_error_bad_param(const struct client_state *csp,
1263                            struct http_response *rsp)
1264 {
1265    struct map *exports;
1266
1267    assert(csp);
1268    assert(rsp);
1269
1270    if (NULL == (exports = default_exports(csp, NULL)))
1271    {
1272       return JB_ERR_MEMORY;
1273    }
1274
1275    return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1276 }
1277
1278
1279 /*********************************************************************
1280  *
1281  * Function    :  cgi_redirect 
1282  *
1283  * Description :  CGI support function to generate a HTTP redirect
1284  *                message
1285  *
1286  * Parameters  :
1287  *          1  :  rsp = http_response data structure for output
1288  *          2  :  target = string with the target URL
1289  *
1290  * CGI Parameters : None
1291  *
1292  * Returns     :  JB_ERR_OK on success
1293  *                JB_ERR_MEMORY on out-of-memory error.  
1294  *
1295  *********************************************************************/
1296 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1297 {
1298    jb_err err;
1299
1300    assert(rsp);
1301    assert(target);
1302
1303    err = enlist_unique_header(rsp->headers, "Location", target);
1304
1305    rsp->status = strdup("302 Local Redirect from Privoxy");
1306    if (rsp->status == NULL)
1307    {
1308       return JB_ERR_MEMORY;
1309    }
1310
1311    return err;
1312 }
1313
1314
1315 /*********************************************************************
1316  *
1317  * Function    :  add_help_link
1318  *
1319  * Description :  Produce a copy of the string given as item,
1320  *                embedded in an HTML link to its corresponding
1321  *                section (item name in uppercase) in the actions
1322  *                chapter of the user manual, (whose URL is given in
1323  *                the config and defaults to our web site).
1324  *
1325  *                FIXME: I currently only work for actions, and would
1326  *                       like to be generalized for other topics.
1327  *
1328  * Parameters  :  
1329  *          1  :  item = item (will NOT be free()d.) 
1330  *                       It is assumed to be HTML-safe.
1331  *          2  :  config = The current configuration.
1332  *
1333  * Returns     :  String with item embedded in link, or NULL on
1334  *                out-of-memory
1335  *
1336  *********************************************************************/
1337 char *add_help_link(const char *item,
1338                     struct configuration_spec *config)
1339 {
1340    char *result;
1341
1342    if (!item) return NULL;
1343
1344    result = strdup("<a href=\"");
1345    if (!strncmpic(config->usermanual, "file://", 7) ||
1346        !strncmpic(config->usermanual, "http", 4))
1347    {
1348       string_append(&result, config->usermanual);
1349    }
1350    else
1351    {
1352       string_append(&result, "http://");
1353       string_append(&result, CGI_SITE_2_HOST);
1354       string_append(&result, "/user-manual/");
1355    }
1356    string_append(&result, ACTIONS_HELP_PREFIX);
1357    string_join  (&result, string_toupper(item));
1358    string_append(&result, "\">");
1359    string_append(&result, item);
1360    string_append(&result, "</a> ");
1361
1362    return result;
1363 }
1364
1365
1366 /*********************************************************************
1367  *
1368  * Function    :  get_http_time
1369  *
1370  * Description :  Get the time in a format suitable for use in a
1371  *                HTTP header - e.g.:
1372  *                "Sun, 06 Nov 1994 08:49:37 GMT"
1373  *
1374  * Parameters  :  
1375  *          1  :  time_offset = Time returned will be current time
1376  *                              plus this number of seconds.
1377  *          2  :  buf = Destination for result.
1378  *          3  :  buffer_size = Size of the buffer above. Must be big
1379  *                              enough to hold 29 characters plus a
1380  *                              trailing zero.
1381  *
1382  * Returns     :  N/A
1383  *
1384  *********************************************************************/
1385 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1386 {
1387    static const char day_names[7][4] =
1388       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1389    static const char month_names[12][4] =
1390       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1391         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1392
1393    struct tm *t;
1394    time_t current_time;
1395 #if defined(HAVE_GMTIME_R)
1396    struct tm dummy;
1397 #endif
1398
1399    assert(buf);
1400    assert(buffer_size > (size_t)29);
1401
1402    time(&current_time);
1403
1404    current_time += time_offset;
1405
1406    /* get and save the gmt */
1407 #if HAVE_GMTIME_R
1408    t = gmtime_r(&current_time, &dummy);
1409 #elif defined(MUTEX_LOCKS_AVAILABLE)
1410    privoxy_mutex_lock(&gmtime_mutex);
1411    t = gmtime(&current_time);
1412    privoxy_mutex_unlock(&gmtime_mutex);
1413 #else
1414    t = gmtime(&current_time);
1415 #endif
1416
1417    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1418    snprintf(buf, buffer_size,
1419       "%s, %02d %s %4d %02d:%02d:%02d GMT",
1420       day_names[t->tm_wday],
1421       t->tm_mday,
1422       month_names[t->tm_mon],
1423       t->tm_year + 1900,
1424       t->tm_hour,
1425       t->tm_min,
1426       t->tm_sec
1427       );
1428
1429 }
1430
1431 /*********************************************************************
1432  *
1433  * Function    :  get_locale_time
1434  *
1435  * Description :  Get the time in a date(1)-like format
1436  *                according to the current locale - e.g.:
1437  *                "Fri Aug 29 19:37:12 CEST 2008"
1438  *
1439  *                XXX: Should we allow the user to change the format?
1440  *
1441  * Parameters  :
1442  *          1  :  buf         = Destination for result.
1443  *          2  :  buffer_size = Size of the buffer above. Must be big
1444  *                              enough to hold 29 characters plus a
1445  *                              trailing zero.
1446  *
1447  * Returns     :  N/A
1448  *
1449  *********************************************************************/
1450 static void get_locale_time(char *buf, size_t buffer_size)
1451 {
1452    struct tm *timeptr;
1453    time_t current_time;
1454 #if defined(HAVE_LOCALTIME_R)
1455    struct tm dummy;
1456 #endif
1457
1458    assert(buf);
1459    assert(buffer_size > (size_t)29);
1460
1461    time(&current_time);
1462
1463 #if HAVE_LOCALTIME_R
1464    timeptr = localtime_r(&current_time, &dummy);
1465 #elif defined(MUTEX_LOCKS_AVAILABLE)
1466    privoxy_mutex_lock(&localtime_mutex);
1467    timeptr = localtime(&current_time);
1468    privoxy_mutex_unlock(&localtime_mutex);
1469 #else
1470    timeptr = localtime(&current_time);
1471 #endif
1472
1473    strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1474
1475 }
1476
1477 /*********************************************************************
1478  *
1479  * Function    :  finish_http_response
1480  *
1481  * Description :  Fill in the missing headers in an http response,
1482  *                and flatten the headers to an http head.
1483  *                For HEAD requests the body is freed once
1484  *                the Content-Length header is set.
1485  *
1486  * Parameters  :
1487  *          1  :  rsp = pointer to http_response to be processed
1488  *
1489  * Returns     :  A http_response, usually the rsp parameter.
1490  *                On error, free()s rsp and returns cgi_error_memory()
1491  *
1492  *********************************************************************/
1493 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1494 {
1495    char buf[BUFFER_SIZE];
1496    jb_err err;
1497
1498    /* Special case - do NOT change this statically allocated response,
1499     * which is ready for output anyway.
1500     */
1501    if (rsp == cgi_error_memory_response)
1502    {
1503       return rsp;
1504    }
1505
1506    /* 
1507     * Fill in the HTTP Status, using HTTP/1.1
1508     * unless the client asked for HTTP/1.0.
1509     */
1510    snprintf(buf, sizeof(buf), "%s %s",
1511       strcmpic(csp->http->ver, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1512       rsp->status ? rsp->status : "200 OK");
1513    err = enlist_first(rsp->headers, buf);
1514
1515    /* 
1516     * Set the Content-Length
1517     */
1518    if (rsp->content_length == 0)
1519    {
1520       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1521    }
1522    if (!err)
1523    {
1524       snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1525       err = enlist(rsp->headers, buf);
1526    }
1527
1528    if (0 == strcmpic(csp->http->gpc, "head"))
1529    {
1530       /*
1531        * The client only asked for the head. Dispose
1532        * the body and log an offensive message.
1533        *
1534        * While it may seem to be a bit inefficient to
1535        * prepare the body if it isn't needed, it's the
1536        * only way to get the Content-Length right for
1537        * dynamic pages. We could have disposed the body
1538        * earlier, but not without duplicating the
1539        * Content-Length setting code above.
1540        */
1541       log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1542       freez(rsp->body);
1543       rsp->content_length = 0;
1544    }
1545
1546    if (strncmpic(rsp->status, "302", 3))
1547    {
1548       /*
1549        * If it's not a redirect without any content,
1550        * set the Content-Type to text/html if it's
1551        * not already specified.
1552        */
1553       if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1554    }
1555
1556    /*
1557     * Fill in the rest of the default headers:
1558     *
1559     * Date: set to current date/time.
1560     * Last-Modified: set to date/time the page was last changed.
1561     * Expires: set to date/time page next needs reloading.
1562     * Cache-Control: set to "no-cache" if applicable.
1563     * 
1564     * See http://www.w3.org/Protocols/rfc2068/rfc2068
1565     */
1566    if (rsp->is_static)
1567    {
1568       /*
1569        * Set Expires to about 10 min into the future so it'll get reloaded
1570        * occasionally, e.g. if Privoxy gets upgraded.
1571        */
1572
1573       if (!err)
1574       {
1575          get_http_time(0, buf, sizeof(buf));
1576          err = enlist_unique_header(rsp->headers, "Date", buf);
1577       }
1578
1579       /* Some date in the past. */
1580       if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1581
1582       if (!err)
1583       {
1584          get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1585          err = enlist_unique_header(rsp->headers, "Expires", buf);
1586       }
1587    }
1588    else if (!strncmpic(rsp->status, "302", 3))
1589    {
1590       get_http_time(0, buf, sizeof(buf));
1591       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1592    }
1593    else
1594    {
1595       /*
1596        * Setting "Cache-Control" to "no-cache" and  "Expires" to
1597        * the current time doesn't exactly forbid caching, it just
1598        * requires the client to revalidate the cached copy.
1599        *
1600        * If a temporary problem occurs and the user tries again after
1601        * getting Privoxy's error message, a compliant browser may set the
1602        * If-Modified-Since header with the content of the error page's
1603        * Last-Modified header. More often than not, the document on the server
1604        * is older than Privoxy's error message, the server would send status code
1605        * 304 and the browser would display the outdated error message again and again.
1606        *
1607        * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1608        * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1609        * and can be safely used to "revalidate" without getting a status code 304.
1610        *
1611        * There is no need to let the useless If-Modified-Since header reach the
1612        * server, it is therefore stripped by client_if_modified_since in parsers.c.
1613        */
1614       if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1615
1616       get_http_time(0, buf, sizeof(buf));
1617       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1618       if (!strncmpic(rsp->status, "403", 3)
1619        || !strncmpic(rsp->status, "404", 3)
1620        || !strncmpic(rsp->status, "503", 3))
1621       {
1622          if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1623       }
1624       else
1625       {
1626          if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1627       }
1628       if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1629       if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1630    }
1631
1632    /*
1633     * Quoting RFC 2616:
1634     *
1635     * HTTP/1.1 applications that do not support persistent connections MUST
1636     * include the "close" connection option in every message.
1637     */
1638    if (!err) err = enlist_unique_header(rsp->headers, "Connection", "close");
1639
1640    /* 
1641     * Write the head
1642     */
1643    if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1644    {
1645       free_http_response(rsp);
1646       return cgi_error_memory();
1647    }
1648    rsp->head_length = strlen(rsp->head);
1649
1650    return rsp;
1651
1652 }
1653
1654
1655 /*********************************************************************
1656  *
1657  * Function    :  alloc_http_response
1658  *
1659  * Description :  Allocates a new http_response structure.
1660  *
1661  * Parameters  :  N/A
1662  *
1663  * Returns     :  pointer to a new http_response, or NULL.
1664  *
1665  *********************************************************************/
1666 struct http_response *alloc_http_response(void)
1667 {
1668    return (struct http_response *) zalloc(sizeof(struct http_response));
1669
1670 }
1671
1672
1673 /*********************************************************************
1674  *
1675  * Function    :  free_http_response
1676  *
1677  * Description :  Free the memory occupied by an http_response
1678  *                and its depandant structures.
1679  *
1680  * Parameters  :
1681  *          1  :  rsp = pointer to http_response to be freed
1682  *
1683  * Returns     :  N/A
1684  *
1685  *********************************************************************/
1686 void free_http_response(struct http_response *rsp)
1687 {
1688    /*
1689     * Must special case cgi_error_memory_response, which is never freed.
1690     */
1691    if (rsp && (rsp != cgi_error_memory_response))
1692    {
1693       freez(rsp->status);
1694       freez(rsp->head);
1695       freez(rsp->body);
1696       destroy_list(rsp->headers);
1697       free(rsp);
1698    }
1699
1700 }
1701
1702
1703 /*********************************************************************
1704  *
1705  * Function    :  template_load
1706  *
1707  * Description :  CGI support function that loads a given HTML
1708  *                template, ignoring comment lines and following
1709  *                #include statements up to a depth of 1.
1710  *
1711  * Parameters  :
1712  *          1  :  csp = Current client state (buffers, headers, etc...)
1713  *          2  :  template_ptr = Destination for pointer to loaded
1714  *                               template text.
1715  *          3  :  templatename = name of the HTML template to be used
1716  *          4  :  recursive = Flag set if this function calls itself
1717  *                            following an #include statament
1718  *
1719  * Returns     :  JB_ERR_OK on success
1720  *                JB_ERR_MEMORY on out-of-memory error.  
1721  *                JB_ERR_FILE if the template file cannot be read
1722  *
1723  *********************************************************************/
1724 jb_err template_load(const struct client_state *csp, char **template_ptr, 
1725                      const char *templatename, int recursive)
1726 {
1727    jb_err err;
1728    char *templates_dir_path;
1729    char *full_path;
1730    char *file_buffer;
1731    char *included_module;
1732    const char *p;
1733    FILE *fp;
1734    char buf[BUFFER_SIZE];
1735
1736    assert(csp);
1737    assert(template_ptr);
1738    assert(templatename);
1739
1740    *template_ptr = NULL;
1741
1742    /* Validate template name.  Paranoia. */
1743    for (p = templatename; *p != 0; p++)
1744    {
1745       if ( ((*p < 'a') || (*p > 'z'))
1746         && ((*p < 'A') || (*p > 'Z'))
1747         && ((*p < '0') || (*p > '9'))
1748         && (*p != '-')
1749         && (*p != '.'))
1750       {
1751          /* Illegal character */
1752          return JB_ERR_FILE;
1753       }
1754    }
1755
1756    /*
1757     * Generate full path using either templdir
1758     * or confdir/templates as base directory.
1759     */
1760    if (NULL != csp->config->templdir)
1761    {
1762       templates_dir_path = strdup(csp->config->templdir);
1763    }
1764    else
1765    {
1766       templates_dir_path = make_path(csp->config->confdir, "templates");
1767    }
1768
1769    if (templates_dir_path == NULL)
1770    {
1771       log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1772          templatename);
1773       return JB_ERR_MEMORY;
1774    }
1775
1776    full_path = make_path(templates_dir_path, templatename);
1777    free(templates_dir_path);
1778    if (full_path == NULL)
1779    {
1780       log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1781          templatename);
1782       return JB_ERR_MEMORY;
1783    }
1784
1785    /* Allocate buffer */
1786
1787    file_buffer = strdup("");
1788    if (file_buffer == NULL)
1789    {
1790       log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1791       free(full_path);
1792       return JB_ERR_MEMORY;
1793    }
1794
1795    /* Open template file */
1796
1797    if (NULL == (fp = fopen(full_path, "r")))
1798    {
1799       log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1800       free(full_path);
1801       free(file_buffer);
1802       return JB_ERR_FILE;
1803    }
1804    free(full_path);
1805
1806    /* 
1807     * Read the file, ignoring comments, and honoring #include
1808     * statements, unless we're already called recursively.
1809     *
1810     * XXX: The comment handling could break with lines lengths > sizeof(buf).
1811     *      This is unlikely in practise.
1812     */
1813    while (fgets(buf, sizeof(buf), fp))
1814    {
1815       if (!recursive && !strncmp(buf, "#include ", 9))
1816       {
1817          if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1818          {
1819             free(file_buffer);
1820             fclose(fp);
1821             return err;
1822          }
1823
1824          if (string_join(&file_buffer, included_module))
1825          {
1826             fclose(fp);
1827             return JB_ERR_MEMORY;
1828          }
1829
1830          continue;
1831       }
1832
1833       /* skip lines starting with '#' */
1834       if (*buf == '#')
1835       {
1836          continue;
1837       }
1838
1839       if (string_append(&file_buffer, buf))
1840       {
1841          fclose(fp);
1842          return JB_ERR_MEMORY;
1843       }
1844    }
1845    fclose(fp);
1846
1847    *template_ptr = file_buffer;
1848
1849    return JB_ERR_OK;
1850 }
1851
1852
1853 /*********************************************************************
1854  *
1855  * Function    :  template_fill
1856  *
1857  * Description :  CGI support function that fills in a pre-loaded
1858  *                HTML template by replacing @name@ with value using
1859  *                pcrs, for each item in the output map.
1860  *
1861  *                Note that a leading '$' charachter in the export map's
1862  *                values will be stripped and toggle on backreference
1863  *                interpretation.
1864  *
1865  * Parameters  :
1866  *          1  :  template_ptr = IN: Template to be filled out.
1867  *                                   Will be free()d.
1868  *                               OUT: Filled out template.
1869  *                                    Caller must free().
1870  *          2  :  exports = map with fill in symbol -> name pairs
1871  *
1872  * Returns     :  JB_ERR_OK on success (and for uncritical errors)
1873  *                JB_ERR_MEMORY on out-of-memory error
1874  *
1875  *********************************************************************/
1876 jb_err template_fill(char **template_ptr, const struct map *exports)
1877 {
1878    struct map_entry *m;
1879    pcrs_job *job;
1880    char buf[BUFFER_SIZE];
1881    char *tmp_out_buffer;
1882    char *file_buffer;
1883    size_t size;
1884    int error;
1885    const char *flags;
1886
1887    assert(template_ptr);
1888    assert(*template_ptr);
1889    assert(exports);
1890
1891    file_buffer = *template_ptr;
1892    size = strlen(file_buffer) + 1;
1893
1894    /* 
1895     * Assemble pcrs joblist from exports map
1896     */
1897    for (m = exports->first; m != NULL; m = m->next)
1898    {
1899       if (*m->name == '$')
1900       {
1901          /*
1902           * First character of name is '$', so remove this flag
1903           * character and allow backreferences ($1 etc) in the
1904           * "replace with" text.
1905           */
1906          snprintf(buf, sizeof(buf), "%s", m->name + 1);
1907          flags = "sigU";
1908       }
1909       else
1910       {
1911          /*
1912           * Treat the "replace with" text as a literal string - 
1913           * no quoting needed, no backreferences allowed.
1914           * ("Trivial" ['T'] flag).
1915           */
1916          flags = "sigTU";
1917
1918          /* Enclose name in @@ */
1919          snprintf(buf, sizeof(buf), "@%s@", m->name);
1920       }
1921
1922       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1923
1924       /* Make and run job. */
1925       job = pcrs_compile(buf, m->value, flags,  &error);
1926       if (job == NULL) 
1927       {
1928          if (error == PCRS_ERR_NOMEM)
1929          {
1930             free(file_buffer);
1931             *template_ptr = NULL;
1932             return JB_ERR_MEMORY;
1933          }
1934          else
1935          {
1936             log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1937             /* Hope it wasn't important and silently ignore the invalid job */
1938          }
1939       }
1940       else
1941       {
1942          error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1943
1944          pcrs_free_job(job);
1945          if (NULL == tmp_out_buffer)
1946          {
1947             *template_ptr = NULL;
1948             return JB_ERR_MEMORY;
1949          }
1950
1951          if (error < 0)
1952          {
1953             /* 
1954              * Substitution failed, keep the original buffer,
1955              * log the problem and ignore it.
1956              * 
1957              * The user might see some unresolved @CGI_VARIABLES@,
1958              * but returning a special CGI error page seems unreasonable
1959              * and could mask more important error messages.
1960              */
1961             free(tmp_out_buffer);
1962             log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
1963                buf, m->value, flags, pcrs_strerror(error));
1964          }
1965          else
1966          {
1967             /* Substitution succeeded, use modified buffer. */
1968             free(file_buffer);
1969             file_buffer = tmp_out_buffer;
1970          }
1971       }
1972    }
1973
1974    /*
1975     * Return
1976     */
1977    *template_ptr = file_buffer;
1978    return JB_ERR_OK;
1979 }
1980
1981
1982 /*********************************************************************
1983  *
1984  * Function    :  template_fill_for_cgi
1985  *
1986  * Description :  CGI support function that loads a HTML template
1987  *                and fills it in.  Handles file-not-found errors
1988  *                by sending a HTML error message.  For convenience,
1989  *                this function also frees the passed "exports" map.
1990  *
1991  * Parameters  :
1992  *          1  :  csp = Client state
1993  *          2  :  templatename = name of the HTML template to be used
1994  *          3  :  exports = map with fill in symbol -> name pairs.
1995  *                          Will be freed by this function.
1996  *          4  :  rsp = Response structure to fill in.
1997  *
1998  * Returns     :  JB_ERR_OK on success
1999  *                JB_ERR_MEMORY on out-of-memory error
2000  *
2001  *********************************************************************/
2002 jb_err template_fill_for_cgi(const struct client_state *csp,
2003                              const char *templatename,
2004                              struct map *exports,
2005                              struct http_response *rsp)
2006 {
2007    jb_err err;
2008    
2009    assert(csp);
2010    assert(templatename);
2011    assert(exports);
2012    assert(rsp);
2013
2014    err = template_load(csp, &rsp->body, templatename, 0);
2015    if (err == JB_ERR_FILE)
2016    {
2017       free_map(exports);
2018       return cgi_error_no_template(csp, rsp, templatename);
2019    }
2020    else if (err)
2021    {
2022       free_map(exports);
2023       return err; /* JB_ERR_MEMORY */
2024    }
2025    err = template_fill(&rsp->body, exports);
2026    free_map(exports);
2027    return err;
2028 }
2029
2030
2031 /*********************************************************************
2032  *
2033  * Function    :  default_exports
2034  *
2035  * Description :  returns a struct map list that contains exports
2036  *                which are common to all CGI functions.
2037  *
2038  * Parameters  :
2039  *          1  :  csp = Current client state (buffers, headers, etc...)
2040  *          2  :  caller = name of CGI who calls us and which should
2041  *                         be excluded from the generated menu. May be
2042  *                         NULL.
2043  * Returns     :  NULL if no memory, else a new map.  Caller frees.
2044  *
2045  *********************************************************************/
2046 struct map *default_exports(const struct client_state *csp, const char *caller)
2047 {
2048    char buf[30];
2049    jb_err err;
2050    struct map * exports;
2051    int local_help_exists = 0;
2052    char *ip_address = NULL;
2053    char *hostname = NULL;
2054
2055    assert(csp);
2056
2057    exports = new_map();
2058    if (exports == NULL)
2059    {
2060       return NULL;
2061    }
2062
2063    if (csp->config->hostname)
2064    {
2065       get_host_information(csp->cfd, &ip_address, NULL);
2066       hostname = strdup(csp->config->hostname);
2067    }
2068    else
2069    {
2070       get_host_information(csp->cfd, &ip_address, &hostname);
2071    }
2072
2073    err = map(exports, "version", 1, html_encode(VERSION), 0);
2074    get_locale_time(buf, sizeof(buf));
2075    if (!err) err = map(exports, "time",          1, html_encode(buf), 0);
2076    if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2077    freez(ip_address);
2078    if (!err) err = map(exports, "my-hostname",   1, html_encode(hostname ? hostname : "unknown"), 0);
2079    freez(hostname);
2080    if (!err) err = map(exports, "homepage",      1, html_encode(HOME_PAGE_URL), 0);
2081    if (!err) err = map(exports, "default-cgi",   1, html_encode(CGI_PREFIX), 0);
2082    if (!err) err = map(exports, "menu",          1, make_menu(caller, csp->config->feature_flags), 0);
2083    if (!err) err = map(exports, "code-status",   1, CODE_STATUS, 1);
2084    if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2085        !strncmpic(csp->config->usermanual, "http", 4))
2086    {
2087       /* Manual is located somewhere else, just link to it. */
2088       if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2089    }
2090    else
2091    {
2092       /* Manual is delivered by Privoxy. */
2093       if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2094    }
2095    if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2096 #ifdef FEATURE_TOGGLE
2097    if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2098 #else
2099    if (!err) err = map_block_killer(exports, "can-toggle");
2100 #endif
2101
2102    snprintf(buf, sizeof(buf), "%d", csp->config->hport);
2103    if (!err) err = map(exports, "my-port", 1, buf, 1);
2104
2105    if(!strcmp(CODE_STATUS, "stable"))
2106    {
2107       if (!err) err = map_block_killer(exports, "unstable");
2108    }
2109
2110    if (csp->config->admin_address != NULL)
2111    {
2112       if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2113       local_help_exists = 1;
2114    }
2115    else
2116    {
2117       if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2118    }
2119
2120    if (csp->config->proxy_info_url != NULL)
2121    {
2122       if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2123       local_help_exists = 1;
2124    }
2125    else
2126    {
2127       if (!err) err = map_block_killer(exports, "have-proxy-info");
2128    }
2129
2130    if (local_help_exists == 0)
2131    {
2132       if (!err) err = map_block_killer(exports, "have-help-info");
2133    }
2134
2135    if (err)
2136    {
2137       free_map(exports);
2138       return NULL;
2139    }
2140
2141    return exports;
2142 }
2143
2144
2145 /*********************************************************************
2146  *
2147  * Function    :  map_block_killer
2148  *
2149  * Description :  Convenience function.
2150  *                Adds a "killer" for the conditional HTML-template
2151  *                block <name>, i.e. a substitution of the regex
2152  *                "if-<name>-start.*if-<name>-end" to the given
2153  *                export list.
2154  *
2155  * Parameters  :  
2156  *          1  :  exports = map to extend
2157  *          2  :  name = name of conditional block
2158  *
2159  * Returns     :  JB_ERR_OK on success
2160  *                JB_ERR_MEMORY on out-of-memory error.  
2161  *
2162  *********************************************************************/
2163 jb_err map_block_killer(struct map *exports, const char *name)
2164 {
2165    char buf[1000]; /* Will do, since the names are hardwired */
2166
2167    assert(exports);
2168    assert(name);
2169    assert(strlen(name) < (size_t)490);
2170
2171    snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2172    return map(exports, buf, 1, "", 1);
2173 }
2174
2175
2176 /*********************************************************************
2177  *
2178  * Function    :  map_block_keep
2179  *
2180  * Description :  Convenience function.  Removes the markers used
2181  *                by map-block-killer, to save a few bytes.
2182  *                i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2183  *
2184  * Parameters  :  
2185  *          1  :  exports = map to extend
2186  *          2  :  name = name of conditional block
2187  *
2188  * Returns     :  JB_ERR_OK on success
2189  *                JB_ERR_MEMORY on out-of-memory error.  
2190  *
2191  *********************************************************************/
2192 jb_err map_block_keep(struct map *exports, const char *name)
2193 {
2194    jb_err err;
2195    char buf[500]; /* Will do, since the names are hardwired */
2196
2197    assert(exports);
2198    assert(name);
2199    assert(strlen(name) < (size_t)490);
2200
2201    snprintf(buf, sizeof(buf), "if-%s-start", name);
2202    err = map(exports, buf, 1, "", 1);
2203
2204    if (err)
2205    {
2206       return err;
2207    }
2208
2209    snprintf(buf, sizeof(buf), "if-%s-end", name);
2210    return map(exports, buf, 1, "", 1);
2211 }
2212
2213
2214 /*********************************************************************
2215  *
2216  * Function    :  map_conditional
2217  *
2218  * Description :  Convenience function.
2219  *                Adds an "if-then-else" for the conditional HTML-template
2220  *                block <name>, i.e. a substitution of the form:
2221  *                @if-<name>-then@
2222  *                   True text
2223  *                @else-not-<name>@
2224  *                   False text
2225  *                @endif-<name>@
2226  *
2227  *                The control structure and one of the alternatives
2228  *                will be hidden.
2229  *
2230  * Parameters  :  
2231  *          1  :  exports = map to extend
2232  *          2  :  name = name of conditional block
2233  *          3  :  choose_first = nonzero for first, zero for second.
2234  *
2235  * Returns     :  JB_ERR_OK on success
2236  *                JB_ERR_MEMORY on out-of-memory error.  
2237  *
2238  *********************************************************************/
2239 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2240 {
2241    char buf[1000]; /* Will do, since the names are hardwired */
2242    jb_err err;
2243
2244    assert(exports);
2245    assert(name);
2246    assert(strlen(name) < (size_t)480);
2247
2248    snprintf(buf, sizeof(buf), (choose_first
2249       ? "else-not-%s@.*@endif-%s"
2250       : "if-%s-then@.*@else-not-%s"),
2251       name, name);
2252
2253    err = map(exports, buf, 1, "", 1);
2254    if (err)
2255    {
2256       return err;
2257    }
2258
2259    snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2260    return map(exports, buf, 1, "", 1);
2261 }
2262
2263
2264 /*********************************************************************
2265  *
2266  * Function    :  make_menu
2267  *
2268  * Description :  Returns an HTML-formatted menu of the available 
2269  *                unhidden CGIs, excluding the one given in <self>
2270  *                and the toggle CGI if toggling is disabled.
2271  *
2272  * Parameters  :
2273  *          1  :  self = name of CGI to leave out, can be NULL for
2274  *                complete listing.
2275  *          2  :  feature_flags = feature bitmap from csp->config
2276  *                
2277  *
2278  * Returns     :  menu string, or NULL on out-of-memory error.
2279  *
2280  *********************************************************************/
2281 char *make_menu(const char *self, const unsigned feature_flags)
2282 {
2283    const struct cgi_dispatcher *d;
2284    char *result = strdup("");
2285
2286    if (self == NULL)
2287    {
2288       self = "NO-SUCH-CGI!";
2289    }
2290
2291    /* List available unhidden CGI's and export as "other-cgis" */
2292    for (d = cgi_dispatchers; d->name; d++)
2293    {
2294
2295 #ifdef FEATURE_TOGGLE
2296       if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2297       {
2298          /*
2299           * Suppress the toggle link if remote toggling is disabled.
2300           */
2301          continue;
2302       }
2303 #endif /* def FEATURE_TOGGLE */
2304
2305       if (d->description && strcmp(d->name, self))
2306       {
2307          char *html_encoded_prefix;
2308
2309          /*
2310           * Line breaks would be great, but break
2311           * the "blocked" template's JavaScript.
2312           */
2313          string_append(&result, "<li><a href=\"");
2314          html_encoded_prefix = html_encode(CGI_PREFIX);
2315          if (html_encoded_prefix == NULL)
2316          {
2317             return NULL;  
2318          }
2319          else
2320          {
2321             string_append(&result, html_encoded_prefix);
2322             free(html_encoded_prefix);
2323          }
2324          string_append(&result, d->name);
2325          string_append(&result, "\">");
2326          string_append(&result, d->description);
2327          string_append(&result, "</a></li>");
2328       }
2329    }
2330
2331    return result;
2332 }
2333
2334
2335 /*********************************************************************
2336  *
2337  * Function    :  dump_map
2338  *
2339  * Description :  HTML-dump a map for debugging (as table)
2340  *
2341  * Parameters  :
2342  *          1  :  the_map = map to dump
2343  *
2344  * Returns     :  string with HTML
2345  *
2346  *********************************************************************/
2347 char *dump_map(const struct map *the_map)
2348 {
2349    struct map_entry *cur_entry;
2350    char *ret = strdup("");
2351
2352    string_append(&ret, "<table>\n");
2353
2354    for (cur_entry = the_map->first;
2355         (cur_entry != NULL) && (ret != NULL);
2356         cur_entry = cur_entry->next)
2357    {
2358       string_append(&ret, "<tr><td><b>");
2359       string_join  (&ret, html_encode(cur_entry->name));
2360       string_append(&ret, "</b></td><td>");
2361       string_join  (&ret, html_encode(cur_entry->value));
2362       string_append(&ret, "</td></tr>\n");
2363    }
2364
2365    string_append(&ret, "</table>\n");
2366    return ret;
2367 }
2368
2369
2370 /*
2371   Local Variables:
2372   tab-width: 3
2373   end:
2374 */