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