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