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