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