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