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