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