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