Change a ssplit() call to use SZ(array) as the third parameter instead of the hardcoded 3
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.129 2010/05/24 11:38:22 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->crunch_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       rsp->crunch_reason = NO_SUCH_DOMAIN;
880    }
881    else if (!strcmp(templatename, "forwarding-failed"))
882    {
883       const struct forward_spec *fwd = forward_url(csp, csp->http);
884       char *socks_type = NULL;
885       if (fwd == NULL)
886       {
887          log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
888          /* Never get here - LOG_LEVEL_FATAL causes program exit */
889       }
890
891       /*
892        * XXX: While the template is called forwarding-failed,
893        * it currently only handles socks forwarding failures.
894        */
895       assert(fwd != NULL);
896       assert(fwd->type != SOCKS_NONE);
897
898       /*
899        * Map failure reason, forwarding type and forwarder.
900        */
901       if (NULL == csp->error_message)
902       {
903          /*
904           * Either we forgot to record the failure reason,
905           * or the memory allocation failed.
906           */
907          log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
908          csp->error_message = strdup("Failure reason missing. Check the log file for details.");
909       }
910       if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
911
912       /*
913        * XXX: this is almost the same code as in cgi_show_url_info()
914        * and thus should be factored out and shared.
915        */
916       switch (fwd->type)
917       {
918          case SOCKS_4:
919             socks_type = "socks4-";
920             break;
921          case SOCKS_4A:
922             socks_type = "socks4a-";
923             break;
924          case SOCKS_5:
925             socks_type = "socks5-";
926             break;
927          default:
928             log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
929       }
930
931       if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
932       if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
933       if ((NULL == csp->error_message) || err)
934       {
935          free_map(exports);
936          free_http_response(rsp);
937          return cgi_error_memory();
938       }
939
940       rsp->status = strdup("503 Forwarding failure");
941       rsp->crunch_reason = FORWARDING_FAILED;
942    }
943    else if (!strcmp(templatename, "connect-failed"))
944    {
945       rsp->status = strdup("503 Connect failed");
946       rsp->crunch_reason = CONNECT_FAILED;
947    }
948    else if (!strcmp(templatename, "connection-timeout"))
949    {
950       rsp->status = strdup("504 Connection timeout");
951       rsp->crunch_reason = CONNECTION_TIMEOUT;
952    }
953    else if (!strcmp(templatename, "no-server-data"))
954    {
955       rsp->status = strdup("502 No data received from server or forwarder");
956       rsp->crunch_reason = NO_SERVER_DATA;
957    }
958
959    if (rsp->status == NULL)
960    {
961       free_map(exports);
962       free_http_response(rsp);
963       return cgi_error_memory();
964    }
965
966    err = template_fill_for_cgi(csp, templatename, exports, rsp);
967    if (err)
968    {
969       free_http_response(rsp);
970       return cgi_error_memory();
971    }
972
973    return finish_http_response(csp, rsp);
974 }
975
976
977 /*********************************************************************
978  *
979  * Function    :  cgi_error_disabled
980  *
981  * Description :  CGI function that is called to generate an error
982  *                response if the actions editor or toggle CGI are
983  *                accessed despite having being disabled at compile-
984  *                or run-time, or if the user followed an untrusted link
985  *                to access a unsafe CGI feature that is only reachable
986  *                through Privoxy directly.
987  *
988  * Parameters  :
989  *          1  :  csp = Current client state (buffers, headers, etc...)
990  *          2  :  rsp = http_response data structure for output
991  *
992  * CGI Parameters : none
993  *
994  * Returns     :  JB_ERR_OK on success
995  *                JB_ERR_MEMORY on out-of-memory error.
996  *
997  *********************************************************************/
998 jb_err cgi_error_disabled(const struct client_state *csp,
999                           struct http_response *rsp)
1000 {
1001    struct map *exports;
1002
1003    assert(csp);
1004    assert(rsp);
1005
1006    if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1007    {
1008       return JB_ERR_MEMORY;
1009    }
1010    if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1011    {
1012       /* Not important enough to do anything */
1013       log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1014    }
1015
1016    return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1017 }
1018
1019
1020 /*********************************************************************
1021  *
1022  * Function    :  cgi_init_error_messages
1023  *
1024  * Description :  Call at the start of the program to initialize
1025  *                the error message used by cgi_error_memory().
1026  *
1027  * Parameters  :  N/A
1028  *
1029  * Returns     :  N/A
1030  *
1031  *********************************************************************/
1032 void cgi_init_error_messages(void)
1033 {
1034    memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1035    cgi_error_memory_response->head =
1036       "HTTP/1.0 500 Internal Privoxy Error\r\n"
1037       "Content-Type: text/html\r\n"
1038       "\r\n";
1039    cgi_error_memory_response->body =
1040       "<html>\r\n"
1041       "<head>\r\n"
1042       " <title>500 Internal Privoxy Error</title>\r\n"
1043       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1044       "</head>\r\n"
1045       "<body>\r\n"
1046       "<h1>500 Internal Privoxy Error</h1>\r\n"
1047       "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1048       "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1049       "</body>\r\n"
1050       "</html>\r\n";
1051
1052    cgi_error_memory_response->head_length =
1053       strlen(cgi_error_memory_response->head);
1054    cgi_error_memory_response->content_length =
1055       strlen(cgi_error_memory_response->body);
1056    cgi_error_memory_response->crunch_reason = OUT_OF_MEMORY;
1057 }
1058
1059
1060 /*********************************************************************
1061  *
1062  * Function    :  cgi_error_memory
1063  *
1064  * Description :  Called if a CGI function runs out of memory.
1065  *                Returns a statically-allocated error response.
1066  *
1067  * Parameters  :  N/A
1068  *
1069  * Returns     :  http_response data structure for output.  This is
1070  *                statically allocated, for obvious reasons.
1071  *
1072  *********************************************************************/
1073 struct http_response *cgi_error_memory(void)
1074 {
1075    /* assert that it's been initialized. */
1076    assert(cgi_error_memory_response->head);
1077
1078    return cgi_error_memory_response;
1079 }
1080
1081
1082 /*********************************************************************
1083  *
1084  * Function    :  cgi_error_no_template
1085  *
1086  * Description :  Almost-CGI function that is called if a template
1087  *                cannot be loaded.  Note this is not a true CGI,
1088  *                it takes a template name rather than a map of 
1089  *                parameters.
1090  *
1091  * Parameters  :
1092  *          1  :  csp = Current client state (buffers, headers, etc...)
1093  *          2  :  rsp = http_response data structure for output
1094  *          3  :  template_name = Name of template that could not
1095  *                                be loaded.
1096  *
1097  * Returns     :  JB_ERR_OK on success
1098  *                JB_ERR_MEMORY on out-of-memory error.  
1099  *
1100  *********************************************************************/
1101 jb_err cgi_error_no_template(const struct client_state *csp,
1102                              struct http_response *rsp,
1103                              const char *template_name)
1104 {
1105    static const char status[] =
1106       "500 Internal Privoxy Error";
1107    static const char body_prefix[] =
1108       "<html>\r\n"
1109       "<head>\r\n"
1110       " <title>500 Internal Privoxy Error</title>\r\n"
1111       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1112       "</head>\r\n"
1113       "<body>\r\n"
1114       "<h1>500 Internal Privoxy Error</h1>\r\n"
1115       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1116       "<p><b>Could not load template file <code>";
1117    static const char body_suffix[] =
1118       "</code> or one of its included components.</b></p>\r\n"
1119       "<p>Please contact your proxy administrator.</p>\r\n"
1120       "<p>If you are the proxy administrator, please put the required file(s)"
1121       "in the <code><i>(confdir)</i>/templates</code> directory.  The "
1122       "location of the <code><i>(confdir)</i></code> directory "
1123       "is specified in the main Privoxy <code>config</code> "
1124       "file.  (It's typically the Privoxy install directory"
1125 #ifndef _WIN32
1126       ", or <code>/etc/privoxy/</code>"
1127 #endif /* ndef _WIN32 */
1128       ").</p>\r\n"
1129       "</body>\r\n"
1130       "</html>\r\n";
1131    const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1132
1133    assert(csp);
1134    assert(rsp);
1135    assert(template_name);
1136
1137    /* Reset rsp, if needed */
1138    freez(rsp->status);
1139    freez(rsp->head);
1140    freez(rsp->body);
1141    rsp->content_length = 0;
1142    rsp->head_length = 0;
1143    rsp->is_static = 0;
1144
1145    rsp->body = malloc(body_size);
1146    if (rsp->body == NULL)
1147    {
1148       return JB_ERR_MEMORY;
1149    }
1150    strlcpy(rsp->body, body_prefix, body_size);
1151    strlcat(rsp->body, template_name, body_size);
1152    strlcat(rsp->body, body_suffix, body_size);
1153
1154    rsp->status = strdup(status);
1155    if (rsp->status == NULL)
1156    {
1157       return JB_ERR_MEMORY;
1158    }
1159
1160    return JB_ERR_OK;
1161 }
1162
1163
1164 /*********************************************************************
1165  *
1166  * Function    :  cgi_error_unknown
1167  *
1168  * Description :  Almost-CGI function that is called if an unexpected
1169  *                error occurs in the top-level CGI dispatcher.
1170  *                In this context, "unexpected" means "anything other
1171  *                than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1172  *                expected to handle all other errors internally,
1173  *                since they can give more relavent error messages
1174  *                that way.
1175  *
1176  *                Note this is not a true CGI, it takes an error
1177  *                code rather than a map of parameters.
1178  *
1179  * Parameters  :
1180  *          1  :  csp = Current client state (buffers, headers, etc...)
1181  *          2  :  rsp = http_response data structure for output
1182  *          3  :  error_to_report = Error code to report.
1183  *
1184  * Returns     :  JB_ERR_OK on success
1185  *                JB_ERR_MEMORY on out-of-memory error.  
1186  *
1187  *********************************************************************/
1188 jb_err cgi_error_unknown(const struct client_state *csp,
1189                          struct http_response *rsp,
1190                          jb_err error_to_report)
1191 {
1192    static const char status[] =
1193       "500 Internal Privoxy Error";
1194    static const char body_prefix[] =
1195       "<html>\r\n"
1196       "<head>\r\n"
1197       " <title>500 Internal Privoxy Error</title>\r\n"
1198       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1199       "</head>\r\n"
1200       "<body>\r\n"
1201       "<h1>500 Internal Privoxy Error</h1>\r\n"
1202       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1203       "<p><b>Unexpected internal error: ";
1204    static const char body_suffix[] =
1205       "</b></p>\r\n"
1206       "<p>Please "
1207       "<a href=\"http://sourceforge.net/tracker/?group_id=11118&amp;atid=111118\">"
1208       "file a bug report</a>.</p>\r\n"
1209       "</body>\r\n"
1210       "</html>\r\n";
1211    char errnumbuf[30];
1212    /*
1213     * Due to sizeof(errnumbuf), body_size will be slightly
1214     * bigger than necessary but it doesn't really matter.
1215     */
1216    const size_t body_size = strlen(body_prefix) + sizeof(errnumbuf) + strlen(body_suffix) + 1;
1217    assert(csp);
1218    assert(rsp);
1219
1220    /* Reset rsp, if needed */
1221    freez(rsp->status);
1222    freez(rsp->head);
1223    freez(rsp->body);
1224    rsp->content_length = 0;
1225    rsp->head_length = 0;
1226    rsp->is_static = 0;
1227    rsp->crunch_reason = INTERNAL_ERROR;
1228
1229    snprintf(errnumbuf, sizeof(errnumbuf), "%d", error_to_report);
1230
1231    rsp->body = malloc(body_size);
1232    if (rsp->body == NULL)
1233    {
1234       return JB_ERR_MEMORY;
1235    }
1236    strlcpy(rsp->body, body_prefix, body_size);
1237    strlcat(rsp->body, errnumbuf,   body_size);
1238    strlcat(rsp->body, body_suffix, body_size);
1239
1240    rsp->status = strdup(status);
1241    if (rsp->status == NULL)
1242    {
1243       return JB_ERR_MEMORY;
1244    }
1245
1246    return JB_ERR_OK;
1247 }
1248
1249
1250 /*********************************************************************
1251  *
1252  * Function    :  cgi_error_bad_param
1253  *
1254  * Description :  CGI function that is called if the parameters
1255  *                (query string) for a CGI were wrong.
1256  *               
1257  * Parameters  :
1258  *          1  :  csp = Current client state (buffers, headers, etc...)
1259  *          2  :  rsp = http_response data structure for output
1260  *
1261  * CGI Parameters : none
1262  *
1263  * Returns     :  JB_ERR_OK on success
1264  *                JB_ERR_MEMORY on out-of-memory error.  
1265  *
1266  *********************************************************************/
1267 jb_err cgi_error_bad_param(const struct client_state *csp,
1268                            struct http_response *rsp)
1269 {
1270    struct map *exports;
1271
1272    assert(csp);
1273    assert(rsp);
1274
1275    if (NULL == (exports = default_exports(csp, NULL)))
1276    {
1277       return JB_ERR_MEMORY;
1278    }
1279
1280    return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1281 }
1282
1283
1284 /*********************************************************************
1285  *
1286  * Function    :  cgi_redirect 
1287  *
1288  * Description :  CGI support function to generate a HTTP redirect
1289  *                message
1290  *
1291  * Parameters  :
1292  *          1  :  rsp = http_response data structure for output
1293  *          2  :  target = string with the target URL
1294  *
1295  * CGI Parameters : None
1296  *
1297  * Returns     :  JB_ERR_OK on success
1298  *                JB_ERR_MEMORY on out-of-memory error.  
1299  *
1300  *********************************************************************/
1301 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1302 {
1303    jb_err err;
1304
1305    assert(rsp);
1306    assert(target);
1307
1308    err = enlist_unique_header(rsp->headers, "Location", target);
1309
1310    rsp->status = strdup("302 Local Redirect from Privoxy");
1311    if (rsp->status == NULL)
1312    {
1313       return JB_ERR_MEMORY;
1314    }
1315
1316    return err;
1317 }
1318
1319
1320 /*********************************************************************
1321  *
1322  * Function    :  add_help_link
1323  *
1324  * Description :  Produce a copy of the string given as item,
1325  *                embedded in an HTML link to its corresponding
1326  *                section (item name in uppercase) in the actions
1327  *                chapter of the user manual, (whose URL is given in
1328  *                the config and defaults to our web site).
1329  *
1330  *                FIXME: I currently only work for actions, and would
1331  *                       like to be generalized for other topics.
1332  *
1333  * Parameters  :  
1334  *          1  :  item = item (will NOT be free()d.) 
1335  *                       It is assumed to be HTML-safe.
1336  *          2  :  config = The current configuration.
1337  *
1338  * Returns     :  String with item embedded in link, or NULL on
1339  *                out-of-memory
1340  *
1341  *********************************************************************/
1342 char *add_help_link(const char *item,
1343                     struct configuration_spec *config)
1344 {
1345    char *result;
1346
1347    if (!item) return NULL;
1348
1349    result = strdup("<a href=\"");
1350    if (!strncmpic(config->usermanual, "file://", 7) ||
1351        !strncmpic(config->usermanual, "http", 4))
1352    {
1353       string_append(&result, config->usermanual);
1354    }
1355    else
1356    {
1357       string_append(&result, "http://");
1358       string_append(&result, CGI_SITE_2_HOST);
1359       string_append(&result, "/user-manual/");
1360    }
1361    string_append(&result, ACTIONS_HELP_PREFIX);
1362    string_join  (&result, string_toupper(item));
1363    string_append(&result, "\">");
1364    string_append(&result, item);
1365    string_append(&result, "</a>");
1366
1367    return result;
1368 }
1369
1370
1371 /*********************************************************************
1372  *
1373  * Function    :  get_http_time
1374  *
1375  * Description :  Get the time in a format suitable for use in a
1376  *                HTTP header - e.g.:
1377  *                "Sun, 06 Nov 1994 08:49:37 GMT"
1378  *
1379  * Parameters  :  
1380  *          1  :  time_offset = Time returned will be current time
1381  *                              plus this number of seconds.
1382  *          2  :  buf = Destination for result.
1383  *          3  :  buffer_size = Size of the buffer above. Must be big
1384  *                              enough to hold 29 characters plus a
1385  *                              trailing zero.
1386  *
1387  * Returns     :  N/A
1388  *
1389  *********************************************************************/
1390 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1391 {
1392    static const char day_names[7][4] =
1393       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1394    static const char month_names[12][4] =
1395       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1396         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1397
1398    struct tm *t;
1399    time_t current_time;
1400 #if defined(HAVE_GMTIME_R)
1401    struct tm dummy;
1402 #endif
1403
1404    assert(buf);
1405    assert(buffer_size > (size_t)29);
1406
1407    time(&current_time);
1408
1409    current_time += time_offset;
1410
1411    /* get and save the gmt */
1412 #if HAVE_GMTIME_R
1413    t = gmtime_r(&current_time, &dummy);
1414 #elif defined(MUTEX_LOCKS_AVAILABLE)
1415    privoxy_mutex_lock(&gmtime_mutex);
1416    t = gmtime(&current_time);
1417    privoxy_mutex_unlock(&gmtime_mutex);
1418 #else
1419    t = gmtime(&current_time);
1420 #endif
1421
1422    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1423    snprintf(buf, buffer_size,
1424       "%s, %02d %s %4d %02d:%02d:%02d GMT",
1425       day_names[t->tm_wday],
1426       t->tm_mday,
1427       month_names[t->tm_mon],
1428       t->tm_year + 1900,
1429       t->tm_hour,
1430       t->tm_min,
1431       t->tm_sec
1432       );
1433
1434 }
1435
1436 /*********************************************************************
1437  *
1438  * Function    :  get_locale_time
1439  *
1440  * Description :  Get the time in a date(1)-like format
1441  *                according to the current locale - e.g.:
1442  *                "Fri Aug 29 19:37:12 CEST 2008"
1443  *
1444  *                XXX: Should we allow the user to change the format?
1445  *
1446  * Parameters  :
1447  *          1  :  buf         = Destination for result.
1448  *          2  :  buffer_size = Size of the buffer above. Must be big
1449  *                              enough to hold 29 characters plus a
1450  *                              trailing zero.
1451  *
1452  * Returns     :  N/A
1453  *
1454  *********************************************************************/
1455 static void get_locale_time(char *buf, size_t buffer_size)
1456 {
1457    struct tm *timeptr;
1458    time_t current_time;
1459 #if defined(HAVE_LOCALTIME_R)
1460    struct tm dummy;
1461 #endif
1462
1463    assert(buf);
1464    assert(buffer_size > (size_t)29);
1465
1466    time(&current_time);
1467
1468 #if HAVE_LOCALTIME_R
1469    timeptr = localtime_r(&current_time, &dummy);
1470 #elif defined(MUTEX_LOCKS_AVAILABLE)
1471    privoxy_mutex_lock(&localtime_mutex);
1472    timeptr = localtime(&current_time);
1473    privoxy_mutex_unlock(&localtime_mutex);
1474 #else
1475    timeptr = localtime(&current_time);
1476 #endif
1477
1478    strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1479
1480 }
1481
1482 /*********************************************************************
1483  *
1484  * Function    :  finish_http_response
1485  *
1486  * Description :  Fill in the missing headers in an http response,
1487  *                and flatten the headers to an http head.
1488  *                For HEAD requests the body is freed once
1489  *                the Content-Length header is set.
1490  *
1491  * Parameters  :
1492  *          1  :  rsp = pointer to http_response to be processed
1493  *
1494  * Returns     :  A http_response, usually the rsp parameter.
1495  *                On error, free()s rsp and returns cgi_error_memory()
1496  *
1497  *********************************************************************/
1498 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1499 {
1500    char buf[BUFFER_SIZE];
1501    jb_err err;
1502
1503    /* Special case - do NOT change this statically allocated response,
1504     * which is ready for output anyway.
1505     */
1506    if (rsp == cgi_error_memory_response)
1507    {
1508       return rsp;
1509    }
1510
1511    /* 
1512     * Fill in the HTTP Status, using HTTP/1.1
1513     * unless the client asked for HTTP/1.0.
1514     */
1515    snprintf(buf, sizeof(buf), "%s %s",
1516       strcmpic(csp->http->ver, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1517       rsp->status ? rsp->status : "200 OK");
1518    err = enlist_first(rsp->headers, buf);
1519
1520    /* 
1521     * Set the Content-Length
1522     */
1523    if (rsp->content_length == 0)
1524    {
1525       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1526    }
1527    if (!err)
1528    {
1529       snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1530       err = enlist(rsp->headers, buf);
1531    }
1532
1533    if (0 == strcmpic(csp->http->gpc, "head"))
1534    {
1535       /*
1536        * The client only asked for the head. Dispose
1537        * the body and log an offensive message.
1538        *
1539        * While it may seem to be a bit inefficient to
1540        * prepare the body if it isn't needed, it's the
1541        * only way to get the Content-Length right for
1542        * dynamic pages. We could have disposed the body
1543        * earlier, but not without duplicating the
1544        * Content-Length setting code above.
1545        */
1546       log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1547       freez(rsp->body);
1548       rsp->content_length = 0;
1549    }
1550
1551    if (strncmpic(rsp->status, "302", 3))
1552    {
1553       /*
1554        * If it's not a redirect without any content,
1555        * set the Content-Type to text/html if it's
1556        * not already specified.
1557        */
1558       if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1559    }
1560
1561    /*
1562     * Fill in the rest of the default headers:
1563     *
1564     * Date: set to current date/time.
1565     * Last-Modified: set to date/time the page was last changed.
1566     * Expires: set to date/time page next needs reloading.
1567     * Cache-Control: set to "no-cache" if applicable.
1568     * 
1569     * See http://www.w3.org/Protocols/rfc2068/rfc2068
1570     */
1571    if (rsp->is_static)
1572    {
1573       /*
1574        * Set Expires to about 10 min into the future so it'll get reloaded
1575        * occasionally, e.g. if Privoxy gets upgraded.
1576        */
1577
1578       if (!err)
1579       {
1580          get_http_time(0, buf, sizeof(buf));
1581          err = enlist_unique_header(rsp->headers, "Date", buf);
1582       }
1583
1584       /* Some date in the past. */
1585       if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1586
1587       if (!err)
1588       {
1589          get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1590          err = enlist_unique_header(rsp->headers, "Expires", buf);
1591       }
1592    }
1593    else if (!strncmpic(rsp->status, "302", 3))
1594    {
1595       get_http_time(0, buf, sizeof(buf));
1596       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1597    }
1598    else
1599    {
1600       /*
1601        * Setting "Cache-Control" to "no-cache" and  "Expires" to
1602        * the current time doesn't exactly forbid caching, it just
1603        * requires the client to revalidate the cached copy.
1604        *
1605        * If a temporary problem occurs and the user tries again after
1606        * getting Privoxy's error message, a compliant browser may set the
1607        * If-Modified-Since header with the content of the error page's
1608        * Last-Modified header. More often than not, the document on the server
1609        * is older than Privoxy's error message, the server would send status code
1610        * 304 and the browser would display the outdated error message again and again.
1611        *
1612        * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1613        * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1614        * and can be safely used to "revalidate" without getting a status code 304.
1615        *
1616        * There is no need to let the useless If-Modified-Since header reach the
1617        * server, it is therefore stripped by client_if_modified_since in parsers.c.
1618        */
1619       if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1620
1621       get_http_time(0, buf, sizeof(buf));
1622       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1623       if (!strncmpic(rsp->status, "403", 3)
1624        || !strncmpic(rsp->status, "404", 3)
1625        || !strncmpic(rsp->status, "502", 3)
1626        || !strncmpic(rsp->status, "503", 3)
1627        || !strncmpic(rsp->status, "504", 3))
1628       {
1629          if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1630       }
1631       else
1632       {
1633          if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1634       }
1635       if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1636       if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1637    }
1638
1639    if (!err && !(csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1640    {
1641       err = enlist_unique_header(rsp->headers, "Connection", "close");
1642    }
1643
1644    /* 
1645     * Write the head
1646     */
1647    if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1648    {
1649       free_http_response(rsp);
1650       return cgi_error_memory();
1651    }
1652    rsp->head_length = strlen(rsp->head);
1653
1654    return rsp;
1655
1656 }
1657
1658
1659 /*********************************************************************
1660  *
1661  * Function    :  alloc_http_response
1662  *
1663  * Description :  Allocates a new http_response structure.
1664  *
1665  * Parameters  :  N/A
1666  *
1667  * Returns     :  pointer to a new http_response, or NULL.
1668  *
1669  *********************************************************************/
1670 struct http_response *alloc_http_response(void)
1671 {
1672    return (struct http_response *) zalloc(sizeof(struct http_response));
1673
1674 }
1675
1676
1677 /*********************************************************************
1678  *
1679  * Function    :  free_http_response
1680  *
1681  * Description :  Free the memory occupied by an http_response
1682  *                and its depandant structures.
1683  *
1684  * Parameters  :
1685  *          1  :  rsp = pointer to http_response to be freed
1686  *
1687  * Returns     :  N/A
1688  *
1689  *********************************************************************/
1690 void free_http_response(struct http_response *rsp)
1691 {
1692    /*
1693     * Must special case cgi_error_memory_response, which is never freed.
1694     */
1695    if (rsp && (rsp != cgi_error_memory_response))
1696    {
1697       freez(rsp->status);
1698       freez(rsp->head);
1699       freez(rsp->body);
1700       destroy_list(rsp->headers);
1701       free(rsp);
1702    }
1703
1704 }
1705
1706
1707 /*********************************************************************
1708  *
1709  * Function    :  template_load
1710  *
1711  * Description :  CGI support function that loads a given HTML
1712  *                template, ignoring comment lines and following
1713  *                #include statements up to a depth of 1.
1714  *
1715  * Parameters  :
1716  *          1  :  csp = Current client state (buffers, headers, etc...)
1717  *          2  :  template_ptr = Destination for pointer to loaded
1718  *                               template text.
1719  *          3  :  templatename = name of the HTML template to be used
1720  *          4  :  recursive = Flag set if this function calls itself
1721  *                            following an #include statament
1722  *
1723  * Returns     :  JB_ERR_OK on success
1724  *                JB_ERR_MEMORY on out-of-memory error.  
1725  *                JB_ERR_FILE if the template file cannot be read
1726  *
1727  *********************************************************************/
1728 jb_err template_load(const struct client_state *csp, char **template_ptr, 
1729                      const char *templatename, int recursive)
1730 {
1731    jb_err err;
1732    char *templates_dir_path;
1733    char *full_path;
1734    char *file_buffer;
1735    char *included_module;
1736    const char *p;
1737    FILE *fp;
1738    char buf[BUFFER_SIZE];
1739
1740    assert(csp);
1741    assert(template_ptr);
1742    assert(templatename);
1743
1744    *template_ptr = NULL;
1745
1746    /* Validate template name.  Paranoia. */
1747    for (p = templatename; *p != 0; p++)
1748    {
1749       if ( ((*p < 'a') || (*p > 'z'))
1750         && ((*p < 'A') || (*p > 'Z'))
1751         && ((*p < '0') || (*p > '9'))
1752         && (*p != '-')
1753         && (*p != '.'))
1754       {
1755          /* Illegal character */
1756          return JB_ERR_FILE;
1757       }
1758    }
1759
1760    /*
1761     * Generate full path using either templdir
1762     * or confdir/templates as base directory.
1763     */
1764    if (NULL != csp->config->templdir)
1765    {
1766       templates_dir_path = strdup(csp->config->templdir);
1767    }
1768    else
1769    {
1770       templates_dir_path = make_path(csp->config->confdir, "templates");
1771    }
1772
1773    if (templates_dir_path == NULL)
1774    {
1775       log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1776          templatename);
1777       return JB_ERR_MEMORY;
1778    }
1779
1780    full_path = make_path(templates_dir_path, templatename);
1781    free(templates_dir_path);
1782    if (full_path == NULL)
1783    {
1784       log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1785          templatename);
1786       return JB_ERR_MEMORY;
1787    }
1788
1789    /* Allocate buffer */
1790
1791    file_buffer = strdup("");
1792    if (file_buffer == NULL)
1793    {
1794       log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1795       free(full_path);
1796       return JB_ERR_MEMORY;
1797    }
1798
1799    /* Open template file */
1800
1801    if (NULL == (fp = fopen(full_path, "r")))
1802    {
1803       log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1804       free(full_path);
1805       free(file_buffer);
1806       return JB_ERR_FILE;
1807    }
1808    free(full_path);
1809
1810    /* 
1811     * Read the file, ignoring comments, and honoring #include
1812     * statements, unless we're already called recursively.
1813     *
1814     * XXX: The comment handling could break with lines lengths > sizeof(buf).
1815     *      This is unlikely in practise.
1816     */
1817    while (fgets(buf, sizeof(buf), fp))
1818    {
1819       if (!recursive && !strncmp(buf, "#include ", 9))
1820       {
1821          if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1822          {
1823             free(file_buffer);
1824             fclose(fp);
1825             return err;
1826          }
1827
1828          if (string_join(&file_buffer, included_module))
1829          {
1830             fclose(fp);
1831             return JB_ERR_MEMORY;
1832          }
1833
1834          continue;
1835       }
1836
1837       /* skip lines starting with '#' */
1838       if (*buf == '#')
1839       {
1840          continue;
1841       }
1842
1843       if (string_append(&file_buffer, buf))
1844       {
1845          fclose(fp);
1846          return JB_ERR_MEMORY;
1847       }
1848    }
1849    fclose(fp);
1850
1851    *template_ptr = file_buffer;
1852
1853    return JB_ERR_OK;
1854 }
1855
1856
1857 /*********************************************************************
1858  *
1859  * Function    :  template_fill
1860  *
1861  * Description :  CGI support function that fills in a pre-loaded
1862  *                HTML template by replacing @name@ with value using
1863  *                pcrs, for each item in the output map.
1864  *
1865  *                Note that a leading '$' character in the export map's
1866  *                values will be stripped and toggle on backreference
1867  *                interpretation.
1868  *
1869  * Parameters  :
1870  *          1  :  template_ptr = IN: Template to be filled out.
1871  *                                   Will be free()d.
1872  *                               OUT: Filled out template.
1873  *                                    Caller must free().
1874  *          2  :  exports = map with fill in symbol -> name pairs
1875  *
1876  * Returns     :  JB_ERR_OK on success (and for uncritical errors)
1877  *                JB_ERR_MEMORY on out-of-memory error
1878  *
1879  *********************************************************************/
1880 jb_err template_fill(char **template_ptr, const struct map *exports)
1881 {
1882    struct map_entry *m;
1883    pcrs_job *job;
1884    char buf[BUFFER_SIZE];
1885    char *tmp_out_buffer;
1886    char *file_buffer;
1887    size_t size;
1888    int error;
1889    const char *flags;
1890
1891    assert(template_ptr);
1892    assert(*template_ptr);
1893    assert(exports);
1894
1895    file_buffer = *template_ptr;
1896    size = strlen(file_buffer) + 1;
1897
1898    /* 
1899     * Assemble pcrs joblist from exports map
1900     */
1901    for (m = exports->first; m != NULL; m = m->next)
1902    {
1903       if (*m->name == '$')
1904       {
1905          /*
1906           * First character of name is '$', so remove this flag
1907           * character and allow backreferences ($1 etc) in the
1908           * "replace with" text.
1909           */
1910          snprintf(buf, sizeof(buf), "%s", m->name + 1);
1911          flags = "sigU";
1912       }
1913       else
1914       {
1915          /*
1916           * Treat the "replace with" text as a literal string - 
1917           * no quoting needed, no backreferences allowed.
1918           * ("Trivial" ['T'] flag).
1919           */
1920          flags = "sigTU";
1921
1922          /* Enclose name in @@ */
1923          snprintf(buf, sizeof(buf), "@%s@", m->name);
1924       }
1925
1926       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1927
1928       /* Make and run job. */
1929       job = pcrs_compile(buf, m->value, flags,  &error);
1930       if (job == NULL) 
1931       {
1932          if (error == PCRS_ERR_NOMEM)
1933          {
1934             free(file_buffer);
1935             *template_ptr = NULL;
1936             return JB_ERR_MEMORY;
1937          }
1938          else
1939          {
1940             log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1941             /* Hope it wasn't important and silently ignore the invalid job */
1942          }
1943       }
1944       else
1945       {
1946          error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1947
1948          pcrs_free_job(job);
1949          if (NULL == tmp_out_buffer)
1950          {
1951             *template_ptr = NULL;
1952             return JB_ERR_MEMORY;
1953          }
1954
1955          if (error < 0)
1956          {
1957             /* 
1958              * Substitution failed, keep the original buffer,
1959              * log the problem and ignore it.
1960              * 
1961              * The user might see some unresolved @CGI_VARIABLES@,
1962              * but returning a special CGI error page seems unreasonable
1963              * and could mask more important error messages.
1964              */
1965             free(tmp_out_buffer);
1966             log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
1967                buf, m->value, flags, pcrs_strerror(error));
1968          }
1969          else
1970          {
1971             /* Substitution succeeded, use modified buffer. */
1972             free(file_buffer);
1973             file_buffer = tmp_out_buffer;
1974          }
1975       }
1976    }
1977
1978    /*
1979     * Return
1980     */
1981    *template_ptr = file_buffer;
1982    return JB_ERR_OK;
1983 }
1984
1985
1986 /*********************************************************************
1987  *
1988  * Function    :  template_fill_for_cgi
1989  *
1990  * Description :  CGI support function that loads a HTML template
1991  *                and fills it in.  Handles file-not-found errors
1992  *                by sending a HTML error message.  For convenience,
1993  *                this function also frees the passed "exports" map.
1994  *
1995  * Parameters  :
1996  *          1  :  csp = Client state
1997  *          2  :  templatename = name of the HTML template to be used
1998  *          3  :  exports = map with fill in symbol -> name pairs.
1999  *                          Will be freed by this function.
2000  *          4  :  rsp = Response structure to fill in.
2001  *
2002  * Returns     :  JB_ERR_OK on success
2003  *                JB_ERR_MEMORY on out-of-memory error
2004  *
2005  *********************************************************************/
2006 jb_err template_fill_for_cgi(const struct client_state *csp,
2007                              const char *templatename,
2008                              struct map *exports,
2009                              struct http_response *rsp)
2010 {
2011    jb_err err;
2012    
2013    assert(csp);
2014    assert(templatename);
2015    assert(exports);
2016    assert(rsp);
2017
2018    err = template_load(csp, &rsp->body, templatename, 0);
2019    if (err == JB_ERR_FILE)
2020    {
2021       free_map(exports);
2022       return cgi_error_no_template(csp, rsp, templatename);
2023    }
2024    else if (err)
2025    {
2026       free_map(exports);
2027       return err; /* JB_ERR_MEMORY */
2028    }
2029    err = template_fill(&rsp->body, exports);
2030    free_map(exports);
2031    return err;
2032 }
2033
2034
2035 /*********************************************************************
2036  *
2037  * Function    :  default_exports
2038  *
2039  * Description :  returns a struct map list that contains exports
2040  *                which are common to all CGI functions.
2041  *
2042  * Parameters  :
2043  *          1  :  csp = Current client state (buffers, headers, etc...)
2044  *          2  :  caller = name of CGI who calls us and which should
2045  *                         be excluded from the generated menu. May be
2046  *                         NULL.
2047  * Returns     :  NULL if no memory, else a new map.  Caller frees.
2048  *
2049  *********************************************************************/
2050 struct map *default_exports(const struct client_state *csp, const char *caller)
2051 {
2052    char buf[30];
2053    jb_err err;
2054    struct map * exports;
2055    int local_help_exists = 0;
2056    char *ip_address = NULL;
2057    char *hostname = NULL;
2058
2059    assert(csp);
2060
2061    exports = new_map();
2062    if (exports == NULL)
2063    {
2064       return NULL;
2065    }
2066
2067    if (csp->config->hostname)
2068    {
2069       get_host_information(csp->cfd, &ip_address, NULL);
2070       hostname = strdup(csp->config->hostname);
2071    }
2072    else
2073    {
2074       get_host_information(csp->cfd, &ip_address, &hostname);
2075    }
2076
2077    err = map(exports, "version", 1, html_encode(VERSION), 0);
2078    get_locale_time(buf, sizeof(buf));
2079    if (!err) err = map(exports, "time",          1, html_encode(buf), 0);
2080    if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2081    freez(ip_address);
2082    if (!err) err = map(exports, "my-hostname",   1, html_encode(hostname ? hostname : "unknown"), 0);
2083    freez(hostname);
2084    if (!err) err = map(exports, "homepage",      1, html_encode(HOME_PAGE_URL), 0);
2085    if (!err) err = map(exports, "default-cgi",   1, html_encode(CGI_PREFIX), 0);
2086    if (!err) err = map(exports, "menu",          1, make_menu(caller, csp->config->feature_flags), 0);
2087    if (!err) err = map(exports, "code-status",   1, CODE_STATUS, 1);
2088    if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2089        !strncmpic(csp->config->usermanual, "http", 4))
2090    {
2091       /* Manual is located somewhere else, just link to it. */
2092       if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2093    }
2094    else
2095    {
2096       /* Manual is delivered by Privoxy. */
2097       if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2098    }
2099    if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2100 #ifdef FEATURE_TOGGLE
2101    if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2102 #else
2103    if (!err) err = map_block_killer(exports, "can-toggle");
2104 #endif
2105
2106    snprintf(buf, sizeof(buf), "%d", csp->config->hport);
2107    if (!err) err = map(exports, "my-port", 1, buf, 1);
2108
2109    if(!strcmp(CODE_STATUS, "stable"))
2110    {
2111       if (!err) err = map_block_killer(exports, "unstable");
2112    }
2113
2114    if (csp->config->admin_address != NULL)
2115    {
2116       if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2117       local_help_exists = 1;
2118    }
2119    else
2120    {
2121       if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2122    }
2123
2124    if (csp->config->proxy_info_url != NULL)
2125    {
2126       if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2127       local_help_exists = 1;
2128    }
2129    else
2130    {
2131       if (!err) err = map_block_killer(exports, "have-proxy-info");
2132    }
2133
2134    if (local_help_exists == 0)
2135    {
2136       if (!err) err = map_block_killer(exports, "have-help-info");
2137    }
2138
2139    if (err)
2140    {
2141       free_map(exports);
2142       return NULL;
2143    }
2144
2145    return exports;
2146 }
2147
2148
2149 /*********************************************************************
2150  *
2151  * Function    :  map_block_killer
2152  *
2153  * Description :  Convenience function.
2154  *                Adds a "killer" for the conditional HTML-template
2155  *                block <name>, i.e. a substitution of the regex
2156  *                "if-<name>-start.*if-<name>-end" to the given
2157  *                export list.
2158  *
2159  * Parameters  :  
2160  *          1  :  exports = map to extend
2161  *          2  :  name = name of conditional block
2162  *
2163  * Returns     :  JB_ERR_OK on success
2164  *                JB_ERR_MEMORY on out-of-memory error.  
2165  *
2166  *********************************************************************/
2167 jb_err map_block_killer(struct map *exports, const char *name)
2168 {
2169    char buf[1000]; /* Will do, since the names are hardwired */
2170
2171    assert(exports);
2172    assert(name);
2173    assert(strlen(name) < (size_t)490);
2174
2175    snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2176    return map(exports, buf, 1, "", 1);
2177 }
2178
2179
2180 /*********************************************************************
2181  *
2182  * Function    :  map_block_keep
2183  *
2184  * Description :  Convenience function.  Removes the markers used
2185  *                by map-block-killer, to save a few bytes.
2186  *                i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2187  *
2188  * Parameters  :  
2189  *          1  :  exports = map to extend
2190  *          2  :  name = name of conditional block
2191  *
2192  * Returns     :  JB_ERR_OK on success
2193  *                JB_ERR_MEMORY on out-of-memory error.  
2194  *
2195  *********************************************************************/
2196 jb_err map_block_keep(struct map *exports, const char *name)
2197 {
2198    jb_err err;
2199    char buf[500]; /* Will do, since the names are hardwired */
2200
2201    assert(exports);
2202    assert(name);
2203    assert(strlen(name) < (size_t)490);
2204
2205    snprintf(buf, sizeof(buf), "if-%s-start", name);
2206    err = map(exports, buf, 1, "", 1);
2207
2208    if (err)
2209    {
2210       return err;
2211    }
2212
2213    snprintf(buf, sizeof(buf), "if-%s-end", name);
2214    return map(exports, buf, 1, "", 1);
2215 }
2216
2217
2218 /*********************************************************************
2219  *
2220  * Function    :  map_conditional
2221  *
2222  * Description :  Convenience function.
2223  *                Adds an "if-then-else" for the conditional HTML-template
2224  *                block <name>, i.e. a substitution of the form:
2225  *                @if-<name>-then@
2226  *                   True text
2227  *                @else-not-<name>@
2228  *                   False text
2229  *                @endif-<name>@
2230  *
2231  *                The control structure and one of the alternatives
2232  *                will be hidden.
2233  *
2234  * Parameters  :  
2235  *          1  :  exports = map to extend
2236  *          2  :  name = name of conditional block
2237  *          3  :  choose_first = nonzero for first, zero for second.
2238  *
2239  * Returns     :  JB_ERR_OK on success
2240  *                JB_ERR_MEMORY on out-of-memory error.  
2241  *
2242  *********************************************************************/
2243 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2244 {
2245    char buf[1000]; /* Will do, since the names are hardwired */
2246    jb_err err;
2247
2248    assert(exports);
2249    assert(name);
2250    assert(strlen(name) < (size_t)480);
2251
2252    snprintf(buf, sizeof(buf), (choose_first
2253       ? "else-not-%s@.*@endif-%s"
2254       : "if-%s-then@.*@else-not-%s"),
2255       name, name);
2256
2257    err = map(exports, buf, 1, "", 1);
2258    if (err)
2259    {
2260       return err;
2261    }
2262
2263    snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2264    return map(exports, buf, 1, "", 1);
2265 }
2266
2267
2268 /*********************************************************************
2269  *
2270  * Function    :  make_menu
2271  *
2272  * Description :  Returns an HTML-formatted menu of the available 
2273  *                unhidden CGIs, excluding the one given in <self>
2274  *                and the toggle CGI if toggling is disabled.
2275  *
2276  * Parameters  :
2277  *          1  :  self = name of CGI to leave out, can be NULL for
2278  *                complete listing.
2279  *          2  :  feature_flags = feature bitmap from csp->config
2280  *                
2281  *
2282  * Returns     :  menu string, or NULL on out-of-memory error.
2283  *
2284  *********************************************************************/
2285 char *make_menu(const char *self, const unsigned feature_flags)
2286 {
2287    const struct cgi_dispatcher *d;
2288    char *result = strdup("");
2289
2290    if (self == NULL)
2291    {
2292       self = "NO-SUCH-CGI!";
2293    }
2294
2295    /* List available unhidden CGI's and export as "other-cgis" */
2296    for (d = cgi_dispatchers; d->name; d++)
2297    {
2298
2299 #ifdef FEATURE_TOGGLE
2300       if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2301       {
2302          /*
2303           * Suppress the toggle link if remote toggling is disabled.
2304           */
2305          continue;
2306       }
2307 #endif /* def FEATURE_TOGGLE */
2308
2309       if (d->description && strcmp(d->name, self))
2310       {
2311          char *html_encoded_prefix;
2312
2313          /*
2314           * Line breaks would be great, but break
2315           * the "blocked" template's JavaScript.
2316           */
2317          string_append(&result, "<li><a href=\"");
2318          html_encoded_prefix = html_encode(CGI_PREFIX);
2319          if (html_encoded_prefix == NULL)
2320          {
2321             return NULL;  
2322          }
2323          else
2324          {
2325             string_append(&result, html_encoded_prefix);
2326             free(html_encoded_prefix);
2327          }
2328          string_append(&result, d->name);
2329          string_append(&result, "\">");
2330          string_append(&result, d->description);
2331          string_append(&result, "</a></li>");
2332       }
2333    }
2334
2335    return result;
2336 }
2337
2338
2339 /*********************************************************************
2340  *
2341  * Function    :  dump_map
2342  *
2343  * Description :  HTML-dump a map for debugging (as table)
2344  *
2345  * Parameters  :
2346  *          1  :  the_map = map to dump
2347  *
2348  * Returns     :  string with HTML
2349  *
2350  *********************************************************************/
2351 char *dump_map(const struct map *the_map)
2352 {
2353    struct map_entry *cur_entry;
2354    char *ret = strdup("");
2355
2356    string_append(&ret, "<table>\n");
2357
2358    for (cur_entry = the_map->first;
2359         (cur_entry != NULL) && (ret != NULL);
2360         cur_entry = cur_entry->next)
2361    {
2362       string_append(&ret, "<tr><td><b>");
2363       string_join  (&ret, html_encode(cur_entry->name));
2364       string_append(&ret, "</b></td><td>");
2365       string_join  (&ret, html_encode(cur_entry->value));
2366       string_append(&ret, "</td></tr>\n");
2367    }
2368
2369    string_append(&ret, "</table>\n");
2370    return ret;
2371 }
2372
2373
2374 /*
2375   Local Variables:
2376   tab-width: 3
2377   end:
2378 */