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