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