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