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