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