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