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