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