1 const char cgi_rcs[] = "$Id: cgi.c,v 1.134 2011/06/25 12:40:55 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/cgi.c,v $
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.
11 * Functions declared include:
14 * Copyright : Written by and Copyright (C) 2001-2004, 2006-2008
15 * the SourceForge Privoxy team. http://www.privoxy.org/
17 * Based on the Internet Junkbuster originally written
18 * by and Copyright (C) 1997 Anonymous Coders and
19 * Junkbusters Corporation. http://www.junkbusters.com
21 * This program is free software; you can redistribute it
22 * and/or modify it under the terms of the GNU General
23 * Public License as published by the Free Software
24 * Foundation; either version 2 of the License, or (at
25 * your option) any later version.
27 * This program is distributed in the hope that it will
28 * be useful, but WITHOUT ANY WARRANTY; without even the
29 * implied warranty of MERCHANTABILITY or FITNESS FOR A
30 * PARTICULAR PURPOSE. See the GNU General Public
31 * License for more details.
33 * The GNU General Public License should be included with
34 * this file. If not, you can view it at
35 * http://www.gnu.org/copyleft/gpl.html
36 * or write to the Free Software Foundation, Inc., 59
37 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39 **********************************************************************/
45 #include <sys/types.h>
52 #ifdef FEATURE_COMPRESSION
64 #include "cgisimple.h"
65 #include "jbsockets.h"
66 #if defined(FEATURE_CGI_EDIT_ACTIONS) || defined(FEATURE_TOGGLE)
68 #endif /* defined(FEATURE_CGI_EDIT_ACTIONS) || defined (FEATURE_TOGGLE) */
70 /* loadcfg.h is for global_toggle_state only */
72 /* jcc.h is for mutex semaphore globals only */
75 const char cgi_h_rcs[] = CGI_H_VERSION;
78 * List of CGI functions: name, handler, description
79 * Note: Do NOT use single quotes in the description;
80 * this will break the dynamic "blocked" template!
82 static const struct cgi_dispatcher cgi_dispatchers[] = {
87 #ifdef FEATURE_GRACEFUL_TERMINATION
90 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
91 "this is a one click Denial Of Service attack!!!</em>",
96 #ifdef FEATURE_CGI_EDIT_ACTIONS
97 "View & change the current configuration",
99 "View the current configuration",
104 "View the source code version numbers",
108 "View the request headers",
112 "Look up which actions apply to a URL and why",
114 #ifdef FEATURE_TOGGLE
117 "Toggle Privoxy on or off",
119 #endif /* def FEATURE_TOGGLE */
120 #ifdef FEATURE_CGI_EDIT_ACTIONS
121 { "edit-actions", /* Edit the actions list */
124 { "eaa", /* Shortcut for edit-actions-add-url-form */
125 cgi_edit_actions_add_url_form,
127 { "eau", /* Shortcut for edit-actions-url-form */
128 cgi_edit_actions_url_form,
130 { "ear", /* Shortcut for edit-actions-remove-url-form */
131 cgi_edit_actions_remove_url_form,
133 { "eal", /* Shortcut for edit-actions-list */
134 cgi_edit_actions_list,
136 { "eafu", /* Shortcut for edit-actions-for-url */
137 cgi_edit_actions_for_url,
139 { "eas", /* Shortcut for edit-actions-submit */
140 cgi_edit_actions_submit,
142 { "easa", /* Shortcut for edit-actions-section-add */
143 cgi_edit_actions_section_add,
145 { "easr", /* Shortcut for edit-actions-section-remove */
146 cgi_edit_actions_section_remove,
148 { "eass", /* Shortcut for edit-actions-section-swap */
149 cgi_edit_actions_section_swap,
151 { "edit-actions-for-url",
152 cgi_edit_actions_for_url,
153 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
154 { "edit-actions-list",
155 cgi_edit_actions_list,
156 NULL, TRUE /* Edit the actions list */ },
157 { "edit-actions-submit",
158 cgi_edit_actions_submit,
159 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
160 { "edit-actions-url",
161 cgi_edit_actions_url,
162 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
163 { "edit-actions-url-form",
164 cgi_edit_actions_url_form,
165 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
166 { "edit-actions-add-url",
167 cgi_edit_actions_add_url,
168 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
169 { "edit-actions-add-url-form",
170 cgi_edit_actions_add_url_form,
171 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
172 { "edit-actions-remove-url",
173 cgi_edit_actions_remove_url,
174 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
175 { "edit-actions-remove-url-form",
176 cgi_edit_actions_remove_url_form,
177 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
178 { "edit-actions-section-add",
179 cgi_edit_actions_section_add,
180 NULL, FALSE /* Remove a section from the actionsfile */ },
181 { "edit-actions-section-remove",
182 cgi_edit_actions_section_remove,
183 NULL, FALSE /* Remove a section from the actionsfile */ },
184 { "edit-actions-section-swap",
185 cgi_edit_actions_section_swap,
186 NULL, FALSE /* Swap two sections in the actionsfile */ },
187 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
188 { "error-favicon.ico",
189 cgi_send_error_favicon,
190 NULL, TRUE /* Sends the favicon image for error pages. */ },
192 cgi_send_default_favicon,
193 NULL, TRUE /* Sends the default favicon image. */ },
196 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
199 NULL, TRUE /* Send a built-in image */ },
202 NULL, FALSE /* Send templates/cgi-style.css */ },
204 cgi_transparent_image,
205 NULL, TRUE /* Send a transparent image (short name) */ },
206 { "url-info-osd.xml",
207 cgi_send_url_info_osd,
208 NULL, TRUE /* Send templates/url-info-osd.xml */ },
210 cgi_send_user_manual,
211 NULL, TRUE /* Send user-manual */ },
212 { NULL, /* NULL Indicates end of list and default page */
214 NULL, TRUE /* Unknown CGI page */ }
219 * Built-in images for ad replacement
221 * Hint: You can encode your own images like this:
222 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
225 #ifdef FEATURE_NO_GIFS
228 * Checkerboard pattern, as a PNG.
230 const char image_pattern_data[] =
231 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
232 "\122\000\000\000\004\000\000\000\004\010\006\000\000\000\251"
233 "\361\236\176\000\000\000\006\142\113\107\104\000\000\000\000"
234 "\000\000\371\103\273\177\000\000\000\033\111\104\101\124\010"
235 "\327\143\140\140\140\060\377\377\377\077\003\234\106\341\060"
236 "\060\230\063\020\124\001\000\161\021\031\241\034\364\030\143"
237 "\000\000\000\000\111\105\116\104\256\102\140\202";
240 * 1x1 transparant PNG.
242 const char image_blank_data[] =
243 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
244 "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
245 "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
246 "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
247 "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
248 "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
249 "\000\000\000\000\111\105\116\104\256\102\140\202";
253 * Checkerboard pattern, as a GIF.
255 const char image_pattern_data[] =
256 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
257 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
258 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
259 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
263 * 1x1 transparant GIF.
265 const char image_blank_data[] =
266 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
267 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
268 "\000\001\000\000\002\002D\001\000;";
271 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
272 const size_t image_blank_length = sizeof(image_blank_data) - 1;
275 static struct http_response cgi_error_memory_response[1];
277 static struct http_response *dispatch_known_cgi(struct client_state * csp,
279 static struct map *parse_cgi_parameters(char *argstring);
282 /*********************************************************************
284 * Function : dispatch_cgi
286 * Description : Checks if a request URL has either the magical
287 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
288 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
289 * http://config.privoxy.org/). If so, it passes
290 * the (rest of the) path onto dispatch_known_cgi, which
291 * calls the relevant CGI handler function.
294 * 1 : csp = Current client state (buffers, headers, etc...)
296 * Returns : http_response if match, NULL if nonmatch or handler fail
298 *********************************************************************/
299 struct http_response *dispatch_cgi(struct client_state *csp)
301 const char *host = csp->http->host;
302 const char *path = csp->http->path;
305 * Should we intercept ?
308 /* Note: "example.com" and "example.com." are equivalent hostnames. */
310 /* Either the host matches CGI_SITE_1_HOST ..*/
311 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
312 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
313 && (path[0] == '/') )
315 /* ..then the path will all be for us. Remove leading '/' */
318 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
319 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
320 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
321 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
323 /* take everything following CGI_SITE_2_PATH */
324 path += strlen(CGI_SITE_2_PATH);
327 /* skip the forward slash after CGI_SITE_2_PATH */
330 else if (*path != '\0')
333 * weirdness: URL is /configXXX, where XXX is some string
334 * Do *NOT* intercept.
346 * This is a CGI call.
349 return dispatch_known_cgi(csp, path);
353 /*********************************************************************
355 * Function : grep_cgi_referrer
357 * Description : Ugly provisorical fix that greps the value of the
358 * referer HTTP header field out of a linked list of
359 * strings like found at csp->headers. Will disappear
362 * FIXME: csp->headers ought to be csp->http->headers
363 * FIXME: Parsing all client header lines should
364 * happen right after the request is received!
367 * 1 : csp = Current client state (buffers, headers, etc...)
369 * Returns : pointer to value (no copy!), or NULL if none found.
371 *********************************************************************/
372 static char *grep_cgi_referrer(const struct client_state *csp)
374 struct list_entry *p;
376 for (p = csp->headers->first; p != NULL; p = p->next)
378 if (p->str == NULL) continue;
379 if (strncmpic(p->str, "Referer: ", 9) == 0)
381 return ((p->str) + 9);
389 /*********************************************************************
391 * Function : referrer_is_safe
393 * Description : Decides whether we trust the Referer for
394 * CGI pages which are only meant to be reachable
395 * through Privoxy's web interface directly.
398 * 1 : csp = Current client state (buffers, headers, etc...)
400 * Returns : TRUE if the referrer is safe, or
401 * FALSE if the referrer is unsafe or not set.
403 *********************************************************************/
404 static int referrer_is_safe(const struct client_state *csp)
407 static const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
409 referrer = grep_cgi_referrer(csp);
411 if (NULL == referrer)
413 /* No referrer, no access */
414 log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
417 else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)
418 || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix)))))
420 /* Trustworthy referrer */
421 log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
422 csp->http->url, referrer);
428 /* Untrustworthy referrer */
429 log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
430 csp->http->url, referrer);
437 /*********************************************************************
439 * Function : dispatch_known_cgi
441 * Description : Processes a CGI once dispatch_cgi has determined that
442 * it matches one of the magic prefixes. Parses the path
443 * as a cgi name plus query string, prepares a map that
444 * maps CGI parameter names to their values, initializes
445 * the http_response struct, and calls the relevant CGI
449 * 1 : csp = Current client state (buffers, headers, etc...)
450 * 2 : path = Path of CGI, with the CGI prefix removed.
451 * Should not have a leading "/".
453 * Returns : http_response, or NULL on handler failure or out of
456 *********************************************************************/
457 static struct http_response *dispatch_known_cgi(struct client_state * csp,
460 const struct cgi_dispatcher *d;
461 struct map *param_list;
462 struct http_response *rsp;
463 char *query_args_start;
467 if (NULL == (path_copy = strdup(path)))
469 return cgi_error_memory();
471 query_args_start = path_copy;
472 while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
476 if (*query_args_start == '/')
478 *query_args_start++ = '\0';
479 if ((param_list = new_map()))
481 map(param_list, "file", 1, url_decode(query_args_start), 0);
486 if (*query_args_start == '?')
488 *query_args_start++ = '\0';
490 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
493 return cgi_error_memory();
499 * path_copy = CGI call name
500 * param_list = CGI params, as map
503 /* Get mem for response or fail*/
504 if (NULL == (rsp = alloc_http_response()))
507 free_map(param_list);
508 return cgi_error_memory();
512 * Find and start the right CGI function
517 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
520 * If the called CGI is either harmless, or referred
521 * from a trusted source, start it.
523 if (d->harmless || referrer_is_safe(csp))
525 err = (d->handler)(csp, rsp, param_list);
530 * Else, modify toggle calls so that they only display
531 * the status, and deny all other calls.
533 if (0 == strcmp(path_copy, "toggle"))
535 unmap(param_list, "set");
536 err = (d->handler)(csp, rsp, param_list);
540 err = cgi_error_disabled(csp, rsp);
545 free_map(param_list);
547 if (err == JB_ERR_CGI_PARAMS)
549 err = cgi_error_bad_param(csp, rsp);
551 if (err && (err != JB_ERR_MEMORY))
553 /* Unexpected error! Shouldn't get here */
554 log_error(LOG_LEVEL_ERROR,
555 "Unexpected CGI error %d in top-level handler. "
556 "Please file a bug report!", err);
557 err = cgi_error_unknown(csp, rsp, err);
562 rsp->crunch_reason = CGI_CALL;
563 return finish_http_response(csp, rsp);
567 /* Error in handler, probably out-of-memory */
568 free_http_response(rsp);
569 return cgi_error_memory();
577 /*********************************************************************
579 * Function : parse_cgi_parameters
581 * Description : Parse a URL-encoded argument string into name/value
582 * pairs and store them in a struct map list.
585 * 1 : argstring = string to be parsed. Will be trashed.
587 * Returns : pointer to param list, or NULL if out of memory.
589 *********************************************************************/
590 static struct map *parse_cgi_parameters(char *argstring)
593 char *vector[BUFFER_SIZE];
595 struct map *cgi_params;
597 if (NULL == (cgi_params = new_map()))
603 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
604 * the fragment identifier along with the request, so we must
605 * cut it off here, so it won't pollute the CGI params:
607 if (NULL != (p = strchr(argstring, '#')))
612 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
614 for (i = 0; i < pairs; i++)
616 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
619 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
621 free_map(cgi_params);
632 /*********************************************************************
634 * Function : get_char_param
636 * Description : Get a single-character parameter passed to a CGI
640 * 1 : parameters = map of cgi parameters
641 * 2 : param_name = The name of the parameter to read
643 * Returns : Uppercase character on success, '\0' on error.
645 *********************************************************************/
646 char get_char_param(const struct map *parameters,
647 const char *param_name)
654 ch = *(lookup(parameters, param_name));
655 if ((ch >= 'a') && (ch <= 'z'))
657 ch = (char)(ch - 'a' + 'A');
664 /*********************************************************************
666 * Function : get_string_param
668 * Description : Get a string paramater, to be used as an
669 * ACTION_STRING or ACTION_MULTI paramater.
670 * Validates the input to prevent stupid/malicious
671 * users from corrupting their action file.
674 * 1 : parameters = map of cgi parameters
675 * 2 : param_name = The name of the parameter to read
676 * 3 : pparam = destination for paramater. Allocated as
677 * part of the map "parameters", so don't free it.
678 * Set to NULL if not specified.
680 * Returns : JB_ERR_OK on success, or if the paramater
682 * JB_ERR_MEMORY on out-of-memory.
683 * JB_ERR_CGI_PARAMS if the paramater is not valid.
685 *********************************************************************/
686 jb_err get_string_param(const struct map *parameters,
687 const char *param_name,
700 param = lookup(parameters, param_name);
706 if (strlen(param) >= CGI_PARAM_LEN_MAX)
711 * Note that the length limit is arbitrary, it just seems
712 * sensible to limit it to *something*. There's no
713 * technical reason for any limit at all.
715 return JB_ERR_CGI_PARAMS;
718 /* Check every character to see if it's legal */
720 while ((ch = *s++) != '\0')
722 if ( ((unsigned char)ch < (unsigned char)' ')
725 /* Probable hack attempt, or user accidentally used '}'. */
726 return JB_ERR_CGI_PARAMS;
737 /*********************************************************************
739 * Function : get_number_param
741 * Description : Get a non-negative integer from the parameters
742 * passed to a CGI function.
745 * 1 : csp = Current client state (buffers, headers, etc...)
746 * 2 : parameters = map of cgi parameters
747 * 3 : name = Name of CGI parameter to read
748 * 4 : pvalue = destination for value.
749 * Set to -1 on error.
751 * Returns : JB_ERR_OK on success
752 * JB_ERR_MEMORY on out-of-memory
753 * JB_ERR_CGI_PARAMS if the parameter was not specified
756 *********************************************************************/
757 jb_err get_number_param(struct client_state *csp,
758 const struct map *parameters,
773 param = lookup(parameters, name);
776 return JB_ERR_CGI_PARAMS;
779 /* We don't use atoi because I want to check this carefully... */
782 while ((ch = *param++) != '\0')
784 if ((ch < '0') || (ch > '9'))
786 return JB_ERR_CGI_PARAMS;
789 ch = (char)(ch - '0');
793 * <limits.h> defines UINT_MAX
795 * (UINT_MAX - ch) / 10 is the largest number that
796 * can be safely multiplied by 10 then have ch added.
798 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
800 return JB_ERR_CGI_PARAMS;
803 value = value * 10 + (unsigned)ch;
814 /*********************************************************************
816 * Function : error_response
818 * Description : returns an http_response that explains the reason
819 * why a request failed.
822 * 1 : csp = Current client state (buffers, headers, etc...)
823 * 2 : templatename = Which template should be used for the answer
825 * Returns : A http_response. If we run out of memory, this
826 * will be cgi_error_memory().
828 *********************************************************************/
829 struct http_response *error_response(struct client_state *csp,
830 const char *templatename)
833 struct http_response *rsp;
834 struct map *exports = default_exports(csp, NULL);
839 return cgi_error_memory();
842 if (NULL == (rsp = alloc_http_response()))
845 return cgi_error_memory();
848 #ifdef FEATURE_FORCE_LOAD
849 if (csp->flags & CSP_FLAG_FORCED)
851 path = strdup(FORCE_PREFIX);
854 #endif /* def FEATURE_FORCE_LOAD */
858 err = string_append(&path, csp->http->path);
860 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
861 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
862 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
863 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
866 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
869 /* Some failures, like "404 no such domain", don't have an IP address. */
870 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
878 free_http_response(rsp);
879 return cgi_error_memory();
882 if (!strcmp(templatename, "no-such-domain"))
884 rsp->status = strdup("404 No such domain");
885 rsp->crunch_reason = NO_SUCH_DOMAIN;
887 else if (!strcmp(templatename, "forwarding-failed"))
889 const struct forward_spec *fwd = forward_url(csp, csp->http);
890 char *socks_type = NULL;
893 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
894 /* Never get here - LOG_LEVEL_FATAL causes program exit */
898 * XXX: While the template is called forwarding-failed,
899 * it currently only handles socks forwarding failures.
902 assert(fwd->type != SOCKS_NONE);
905 * Map failure reason, forwarding type and forwarder.
907 if (NULL == csp->error_message)
910 * Either we forgot to record the failure reason,
911 * or the memory allocation failed.
913 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
914 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
916 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
919 * XXX: this is almost the same code as in cgi_show_url_info()
920 * and thus should be factored out and shared.
925 socks_type = "socks4-";
928 socks_type = "socks4a-";
931 socks_type = "socks5-";
934 log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
937 if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
938 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
939 if ((NULL == csp->error_message) || err)
942 free_http_response(rsp);
943 return cgi_error_memory();
946 rsp->status = strdup("503 Forwarding failure");
947 rsp->crunch_reason = FORWARDING_FAILED;
949 else if (!strcmp(templatename, "connect-failed"))
951 rsp->status = strdup("503 Connect failed");
952 rsp->crunch_reason = CONNECT_FAILED;
954 else if (!strcmp(templatename, "connection-timeout"))
956 rsp->status = strdup("504 Connection timeout");
957 rsp->crunch_reason = CONNECTION_TIMEOUT;
959 else if (!strcmp(templatename, "no-server-data"))
961 rsp->status = strdup("502 No data received from server or forwarder");
962 rsp->crunch_reason = NO_SERVER_DATA;
965 if (rsp->status == NULL)
968 free_http_response(rsp);
969 return cgi_error_memory();
972 err = template_fill_for_cgi(csp, templatename, exports, rsp);
975 free_http_response(rsp);
976 return cgi_error_memory();
979 return finish_http_response(csp, rsp);
983 /*********************************************************************
985 * Function : cgi_error_disabled
987 * Description : CGI function that is called to generate an error
988 * response if the actions editor or toggle CGI are
989 * accessed despite having being disabled at compile-
990 * or run-time, or if the user followed an untrusted link
991 * to access a unsafe CGI feature that is only reachable
992 * through Privoxy directly.
995 * 1 : csp = Current client state (buffers, headers, etc...)
996 * 2 : rsp = http_response data structure for output
998 * CGI Parameters : none
1000 * Returns : JB_ERR_OK on success
1001 * JB_ERR_MEMORY on out-of-memory error.
1003 *********************************************************************/
1004 jb_err cgi_error_disabled(const struct client_state *csp,
1005 struct http_response *rsp)
1007 struct map *exports;
1012 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1014 return JB_ERR_MEMORY;
1016 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1018 /* Not important enough to do anything */
1019 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1022 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1026 /*********************************************************************
1028 * Function : cgi_init_error_messages
1030 * Description : Call at the start of the program to initialize
1031 * the error message used by cgi_error_memory().
1037 *********************************************************************/
1038 void cgi_init_error_messages(void)
1040 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1041 cgi_error_memory_response->head =
1042 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1043 "Content-Type: text/html\r\n"
1045 cgi_error_memory_response->body =
1048 " <title>500 Internal Privoxy Error</title>\n"
1049 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1052 "<h1>500 Internal Privoxy Error</h1>\n"
1053 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\n"
1054 "<p>Please contact your proxy administrator, or try again later</p>\n"
1058 cgi_error_memory_response->head_length =
1059 strlen(cgi_error_memory_response->head);
1060 cgi_error_memory_response->content_length =
1061 strlen(cgi_error_memory_response->body);
1062 cgi_error_memory_response->crunch_reason = OUT_OF_MEMORY;
1066 /*********************************************************************
1068 * Function : cgi_error_memory
1070 * Description : Called if a CGI function runs out of memory.
1071 * Returns a statically-allocated error response.
1075 * Returns : http_response data structure for output. This is
1076 * statically allocated, for obvious reasons.
1078 *********************************************************************/
1079 struct http_response *cgi_error_memory(void)
1081 /* assert that it's been initialized. */
1082 assert(cgi_error_memory_response->head);
1084 return cgi_error_memory_response;
1088 /*********************************************************************
1090 * Function : cgi_error_no_template
1092 * Description : Almost-CGI function that is called if a template
1093 * cannot be loaded. Note this is not a true CGI,
1094 * it takes a template name rather than a map of
1098 * 1 : csp = Current client state (buffers, headers, etc...)
1099 * 2 : rsp = http_response data structure for output
1100 * 3 : template_name = Name of template that could not
1103 * Returns : JB_ERR_OK on success
1104 * JB_ERR_MEMORY on out-of-memory error.
1106 *********************************************************************/
1107 jb_err cgi_error_no_template(const struct client_state *csp,
1108 struct http_response *rsp,
1109 const char *template_name)
1111 static const char status[] =
1112 "500 Internal Privoxy Error";
1113 static const char body_prefix[] =
1116 " <title>500 Internal Privoxy Error</title>\n"
1117 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1120 "<h1>500 Internal Privoxy Error</h1>\n"
1121 "<p>Privoxy encountered an error while processing your request:</p>\n"
1122 "<p><b>Could not load template file <code>";
1123 static const char body_suffix[] =
1124 "</code> or one of its included components.</b></p>\n"
1125 "<p>Please contact your proxy administrator.</p>\n"
1126 "<p>If you are the proxy administrator, please put the required file(s)"
1127 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1128 "location of the <code><i>(confdir)</i></code> directory "
1129 "is specified in the main Privoxy <code>config</code> "
1130 "file. (It's typically the Privoxy install directory"
1132 ", or <code>/etc/privoxy/</code>"
1133 #endif /* ndef _WIN32 */
1137 const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1141 assert(template_name);
1143 /* Reset rsp, if needed */
1147 rsp->content_length = 0;
1148 rsp->head_length = 0;
1151 rsp->body = malloc(body_size);
1152 if (rsp->body == NULL)
1154 return JB_ERR_MEMORY;
1156 strlcpy(rsp->body, body_prefix, body_size);
1157 strlcat(rsp->body, template_name, body_size);
1158 strlcat(rsp->body, body_suffix, body_size);
1160 rsp->status = strdup(status);
1161 if (rsp->status == NULL)
1163 return JB_ERR_MEMORY;
1170 /*********************************************************************
1172 * Function : cgi_error_unknown
1174 * Description : Almost-CGI function that is called if an unexpected
1175 * error occurs in the top-level CGI dispatcher.
1176 * In this context, "unexpected" means "anything other
1177 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1178 * expected to handle all other errors internally,
1179 * since they can give more relavent error messages
1182 * Note this is not a true CGI, it takes an error
1183 * code rather than a map of parameters.
1186 * 1 : csp = Current client state (buffers, headers, etc...)
1187 * 2 : rsp = http_response data structure for output
1188 * 3 : error_to_report = Error code to report.
1190 * Returns : JB_ERR_OK on success
1191 * JB_ERR_MEMORY on out-of-memory error.
1193 *********************************************************************/
1194 jb_err cgi_error_unknown(const struct client_state *csp,
1195 struct http_response *rsp,
1196 jb_err error_to_report)
1198 static const char status[] =
1199 "500 Internal Privoxy Error";
1200 static const char body_prefix[] =
1203 " <title>500 Internal Privoxy Error</title>\n"
1204 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1207 "<h1>500 Internal Privoxy Error</h1>\n"
1208 "<p>Privoxy encountered an error while processing your request:</p>\n"
1209 "<p><b>Unexpected internal error: ";
1210 static const char body_suffix[] =
1213 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1214 "file a bug report</a>.</p>\n"
1217 /* Includes room for larger error numbers in the future. */
1218 const size_t body_size = sizeof(body_prefix) + sizeof(body_suffix) + 5;
1222 /* Reset rsp, if needed */
1226 rsp->content_length = 0;
1227 rsp->head_length = 0;
1229 rsp->crunch_reason = INTERNAL_ERROR;
1231 rsp->body = malloc(body_size);
1232 if (rsp->body == NULL)
1234 return JB_ERR_MEMORY;
1237 snprintf(rsp->body, body_size, "%s%d%s", body_prefix, error_to_report, body_suffix);
1239 rsp->status = strdup(status);
1240 if (rsp->status == NULL)
1242 return JB_ERR_MEMORY;
1249 /*********************************************************************
1251 * Function : cgi_error_bad_param
1253 * Description : CGI function that is called if the parameters
1254 * (query string) for a CGI were wrong.
1257 * 1 : csp = Current client state (buffers, headers, etc...)
1258 * 2 : rsp = http_response data structure for output
1260 * CGI Parameters : none
1262 * Returns : JB_ERR_OK on success
1263 * JB_ERR_MEMORY on out-of-memory error.
1265 *********************************************************************/
1266 jb_err cgi_error_bad_param(const struct client_state *csp,
1267 struct http_response *rsp)
1269 struct map *exports;
1274 if (NULL == (exports = default_exports(csp, NULL)))
1276 return JB_ERR_MEMORY;
1279 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1283 /*********************************************************************
1285 * Function : cgi_redirect
1287 * Description : CGI support function to generate a HTTP redirect
1291 * 1 : rsp = http_response data structure for output
1292 * 2 : target = string with the target URL
1294 * CGI Parameters : None
1296 * Returns : JB_ERR_OK on success
1297 * JB_ERR_MEMORY on out-of-memory error.
1299 *********************************************************************/
1300 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1307 err = enlist_unique_header(rsp->headers, "Location", target);
1309 rsp->status = strdup("302 Local Redirect from Privoxy");
1310 if (rsp->status == NULL)
1312 return JB_ERR_MEMORY;
1319 /*********************************************************************
1321 * Function : add_help_link
1323 * Description : Produce a copy of the string given as item,
1324 * embedded in an HTML link to its corresponding
1325 * section (item name in uppercase) in the actions
1326 * chapter of the user manual, (whose URL is given in
1327 * the config and defaults to our web site).
1329 * FIXME: I currently only work for actions, and would
1330 * like to be generalized for other topics.
1333 * 1 : item = item (will NOT be free()d.)
1334 * It is assumed to be HTML-safe.
1335 * 2 : config = The current configuration.
1337 * Returns : String with item embedded in link, or NULL on
1340 *********************************************************************/
1341 char *add_help_link(const char *item,
1342 struct configuration_spec *config)
1346 if (!item) return NULL;
1348 result = strdup("<a href=\"");
1349 if (!strncmpic(config->usermanual, "file://", 7) ||
1350 !strncmpic(config->usermanual, "http", 4))
1352 string_append(&result, config->usermanual);
1356 string_append(&result, "http://");
1357 string_append(&result, CGI_SITE_2_HOST);
1358 string_append(&result, "/user-manual/");
1360 string_append(&result, ACTIONS_HELP_PREFIX);
1361 string_join (&result, string_toupper(item));
1362 string_append(&result, "\">");
1363 string_append(&result, item);
1364 string_append(&result, "</a>");
1370 /*********************************************************************
1372 * Function : get_http_time
1374 * Description : Get the time in a format suitable for use in a
1375 * HTTP header - e.g.:
1376 * "Sun, 06 Nov 1994 08:49:37 GMT"
1379 * 1 : time_offset = Time returned will be current time
1380 * plus this number of seconds.
1381 * 2 : buf = Destination for result.
1382 * 3 : buffer_size = Size of the buffer above. Must be big
1383 * enough to hold 29 characters plus a
1388 *********************************************************************/
1389 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1391 static const char day_names[7][4] =
1392 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1393 static const char month_names[12][4] =
1394 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1395 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1398 time_t current_time;
1399 #if defined(HAVE_GMTIME_R)
1404 assert(buffer_size > (size_t)29);
1406 time(¤t_time);
1408 current_time += time_offset;
1410 /* get and save the gmt */
1412 t = gmtime_r(¤t_time, &dummy);
1413 #elif defined(MUTEX_LOCKS_AVAILABLE)
1414 privoxy_mutex_lock(&gmtime_mutex);
1415 t = gmtime(¤t_time);
1416 privoxy_mutex_unlock(&gmtime_mutex);
1418 t = gmtime(¤t_time);
1421 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1422 snprintf(buf, buffer_size,
1423 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1424 day_names[t->tm_wday],
1426 month_names[t->tm_mon],
1435 /*********************************************************************
1437 * Function : get_locale_time
1439 * Description : Get the time in a date(1)-like format
1440 * according to the current locale - e.g.:
1441 * "Fri Aug 29 19:37:12 CEST 2008"
1443 * XXX: Should we allow the user to change the format?
1446 * 1 : buf = Destination for result.
1447 * 2 : buffer_size = Size of the buffer above. Must be big
1448 * enough to hold 29 characters plus a
1453 *********************************************************************/
1454 static void get_locale_time(char *buf, size_t buffer_size)
1457 time_t current_time;
1458 #if defined(HAVE_LOCALTIME_R)
1463 assert(buffer_size > (size_t)29);
1465 time(¤t_time);
1467 #if HAVE_LOCALTIME_R
1468 timeptr = localtime_r(¤t_time, &dummy);
1469 #elif defined(MUTEX_LOCKS_AVAILABLE)
1470 privoxy_mutex_lock(&localtime_mutex);
1471 timeptr = localtime(¤t_time);
1472 privoxy_mutex_unlock(&localtime_mutex);
1474 timeptr = localtime(¤t_time);
1477 strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1482 #ifdef FEATURE_COMPRESSION
1483 /*********************************************************************
1485 * Function : compress_buffer
1487 * Description : Compresses the content of a buffer with zlib's deflate
1488 * Allocates a new buffer for the result, free'ing it is
1491 * XXX: We should add a config option for the
1492 * compression level.
1496 * 1 : buffer = buffer whose content should be compressed
1497 * 2 : buffer_length = length of the buffer
1499 * Returns : NULL on error, otherwise a pointer to the compressed
1500 * content of the input buffer.
1502 *********************************************************************/
1503 char *compress_buffer(char *buffer, size_t *buffer_length)
1505 char *compressed_buffer;
1506 size_t new_length = *buffer_length;
1508 compressed_buffer = malloc(new_length);
1509 if (NULL == compressed_buffer)
1511 log_error(LOG_LEVEL_FATAL,
1512 "Out of memory allocation compression buffer.");
1515 if (Z_OK != compress2((Bytef *)compressed_buffer, &new_length,
1516 (Bytef *)buffer, *buffer_length, Z_DEFAULT_COMPRESSION))
1518 log_error(LOG_LEVEL_ERROR, "Error in compress2()");
1519 freez(compressed_buffer);
1523 log_error(LOG_LEVEL_RE_FILTER,
1524 "Compressed content from %d to %d bytes.", *buffer_length, new_length);
1526 *buffer_length = new_length;
1528 return compressed_buffer;
1534 /*********************************************************************
1536 * Function : finish_http_response
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.
1544 * 1 : rsp = pointer to http_response to be processed
1546 * Returns : A http_response, usually the rsp parameter.
1547 * On error, free()s rsp and returns cgi_error_memory()
1549 *********************************************************************/
1550 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1552 char buf[BUFFER_SIZE];
1555 /* Special case - do NOT change this statically allocated response,
1556 * which is ready for output anyway.
1558 if (rsp == cgi_error_memory_response)
1564 * Fill in the HTTP Status, using HTTP/1.1
1565 * unless the client asked for HTTP/1.0.
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);
1573 * Set the Content-Length
1575 if (rsp->content_length == 0)
1577 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1580 #ifdef FEATURE_COMPRESSION
1581 if (!err && (csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
1582 && (rsp->content_length > LOWER_LENGTH_LIMIT_FOR_COMRPESSION))
1584 char *compressed_content;
1586 compressed_content = compress_buffer(rsp->body, &rsp->content_length);
1587 if (NULL != compressed_content)
1590 rsp->body = compressed_content;
1591 err = enlist_unique_header(rsp->headers, "Content-Encoding", "deflate");
1598 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1599 err = enlist(rsp->headers, buf);
1602 if (0 == strcmpic(csp->http->gpc, "head"))
1605 * The client only asked for the head. Dispose
1606 * the body and log an offensive message.
1608 * While it may seem to be a bit inefficient to
1609 * prepare the body if it isn't needed, it's the
1610 * only way to get the Content-Length right for
1611 * dynamic pages. We could have disposed the body
1612 * earlier, but not without duplicating the
1613 * Content-Length setting code above.
1615 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1617 rsp->content_length = 0;
1620 if (strncmpic(rsp->status, "302", 3))
1623 * If it's not a redirect without any content,
1624 * set the Content-Type to text/html if it's
1625 * not already specified.
1627 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1631 * Fill in the rest of the default headers:
1633 * Date: set to current date/time.
1634 * Last-Modified: set to date/time the page was last changed.
1635 * Expires: set to date/time page next needs reloading.
1636 * Cache-Control: set to "no-cache" if applicable.
1638 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1643 * Set Expires to about 10 min into the future so it'll get reloaded
1644 * occasionally, e.g. if Privoxy gets upgraded.
1649 get_http_time(0, buf, sizeof(buf));
1650 err = enlist_unique_header(rsp->headers, "Date", buf);
1653 /* Some date in the past. */
1654 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1658 get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1659 err = enlist_unique_header(rsp->headers, "Expires", buf);
1662 else if (!strncmpic(rsp->status, "302", 3))
1664 get_http_time(0, buf, sizeof(buf));
1665 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1670 * Setting "Cache-Control" to "no-cache" and "Expires" to
1671 * the current time doesn't exactly forbid caching, it just
1672 * requires the client to revalidate the cached copy.
1674 * If a temporary problem occurs and the user tries again after
1675 * getting Privoxy's error message, a compliant browser may set the
1676 * If-Modified-Since header with the content of the error page's
1677 * Last-Modified header. More often than not, the document on the server
1678 * is older than Privoxy's error message, the server would send status code
1679 * 304 and the browser would display the outdated error message again and again.
1681 * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1682 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1683 * and can be safely used to "revalidate" without getting a status code 304.
1685 * There is no need to let the useless If-Modified-Since header reach the
1686 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1688 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1690 get_http_time(0, buf, sizeof(buf));
1691 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1692 if (!strncmpic(rsp->status, "403", 3)
1693 || !strncmpic(rsp->status, "404", 3)
1694 || !strncmpic(rsp->status, "502", 3)
1695 || !strncmpic(rsp->status, "503", 3)
1696 || !strncmpic(rsp->status, "504", 3))
1698 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1702 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1704 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1705 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1708 if (!err && !(csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1710 err = enlist_unique_header(rsp->headers, "Connection", "close");
1716 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1718 free_http_response(rsp);
1719 return cgi_error_memory();
1721 rsp->head_length = strlen(rsp->head);
1728 /*********************************************************************
1730 * Function : alloc_http_response
1732 * Description : Allocates a new http_response structure.
1736 * Returns : pointer to a new http_response, or NULL.
1738 *********************************************************************/
1739 struct http_response *alloc_http_response(void)
1741 return (struct http_response *) zalloc(sizeof(struct http_response));
1746 /*********************************************************************
1748 * Function : free_http_response
1750 * Description : Free the memory occupied by an http_response
1751 * and its depandant structures.
1754 * 1 : rsp = pointer to http_response to be freed
1758 *********************************************************************/
1759 void free_http_response(struct http_response *rsp)
1762 * Must special case cgi_error_memory_response, which is never freed.
1764 if (rsp && (rsp != cgi_error_memory_response))
1769 destroy_list(rsp->headers);
1776 /*********************************************************************
1778 * Function : template_load
1780 * Description : CGI support function that loads a given HTML
1781 * template, ignoring comment lines and following
1782 * #include statements up to a depth of 1.
1785 * 1 : csp = Current client state (buffers, headers, etc...)
1786 * 2 : template_ptr = Destination for pointer to loaded
1788 * 3 : templatename = name of the HTML template to be used
1789 * 4 : recursive = Flag set if this function calls itself
1790 * following an #include statament
1792 * Returns : JB_ERR_OK on success
1793 * JB_ERR_MEMORY on out-of-memory error.
1794 * JB_ERR_FILE if the template file cannot be read
1796 *********************************************************************/
1797 jb_err template_load(const struct client_state *csp, char **template_ptr,
1798 const char *templatename, int recursive)
1801 char *templates_dir_path;
1804 char *included_module;
1807 char buf[BUFFER_SIZE];
1810 assert(template_ptr);
1811 assert(templatename);
1813 *template_ptr = NULL;
1815 /* Validate template name. Paranoia. */
1816 for (p = templatename; *p != 0; p++)
1818 if ( ((*p < 'a') || (*p > 'z'))
1819 && ((*p < 'A') || (*p > 'Z'))
1820 && ((*p < '0') || (*p > '9'))
1824 /* Illegal character */
1830 * Generate full path using either templdir
1831 * or confdir/templates as base directory.
1833 if (NULL != csp->config->templdir)
1835 templates_dir_path = strdup(csp->config->templdir);
1839 templates_dir_path = make_path(csp->config->confdir, "templates");
1842 if (templates_dir_path == NULL)
1844 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1846 return JB_ERR_MEMORY;
1849 full_path = make_path(templates_dir_path, templatename);
1850 free(templates_dir_path);
1851 if (full_path == NULL)
1853 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1855 return JB_ERR_MEMORY;
1858 /* Allocate buffer */
1860 file_buffer = strdup("");
1861 if (file_buffer == NULL)
1863 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1865 return JB_ERR_MEMORY;
1868 /* Open template file */
1870 if (NULL == (fp = fopen(full_path, "r")))
1872 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1880 * Read the file, ignoring comments, and honoring #include
1881 * statements, unless we're already called recursively.
1883 * XXX: The comment handling could break with lines lengths > sizeof(buf).
1884 * This is unlikely in practise.
1886 while (fgets(buf, sizeof(buf), fp))
1888 if (!recursive && !strncmp(buf, "#include ", 9))
1890 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1897 if (string_join(&file_buffer, included_module))
1900 return JB_ERR_MEMORY;
1906 /* skip lines starting with '#' */
1912 if (string_append(&file_buffer, buf))
1915 return JB_ERR_MEMORY;
1920 *template_ptr = file_buffer;
1926 /*********************************************************************
1928 * Function : template_fill
1930 * Description : CGI support function that fills in a pre-loaded
1931 * HTML template by replacing @name@ with value using
1932 * pcrs, for each item in the output map.
1934 * Note that a leading '$' character in the export map's
1935 * values will be stripped and toggle on backreference
1939 * 1 : template_ptr = IN: Template to be filled out.
1941 * OUT: Filled out template.
1942 * Caller must free().
1943 * 2 : exports = map with fill in symbol -> name pairs
1945 * Returns : JB_ERR_OK on success (and for uncritical errors)
1946 * JB_ERR_MEMORY on out-of-memory error
1948 *********************************************************************/
1949 jb_err template_fill(char **template_ptr, const struct map *exports)
1951 struct map_entry *m;
1953 char buf[BUFFER_SIZE];
1954 char *tmp_out_buffer;
1960 assert(template_ptr);
1961 assert(*template_ptr);
1964 file_buffer = *template_ptr;
1965 size = strlen(file_buffer) + 1;
1968 * Assemble pcrs joblist from exports map
1970 for (m = exports->first; m != NULL; m = m->next)
1972 if (*m->name == '$')
1975 * First character of name is '$', so remove this flag
1976 * character and allow backreferences ($1 etc) in the
1977 * "replace with" text.
1979 snprintf(buf, sizeof(buf), "%s", m->name + 1);
1985 * Treat the "replace with" text as a literal string -
1986 * no quoting needed, no backreferences allowed.
1987 * ("Trivial" ['T'] flag).
1991 /* Enclose name in @@ */
1992 snprintf(buf, sizeof(buf), "@%s@", m->name);
1995 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1997 /* Make and run job. */
1998 job = pcrs_compile(buf, m->value, flags, &error);
2001 if (error == PCRS_ERR_NOMEM)
2004 *template_ptr = NULL;
2005 return JB_ERR_MEMORY;
2009 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2010 /* Hope it wasn't important and silently ignore the invalid job */
2015 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2018 if (NULL == tmp_out_buffer)
2020 *template_ptr = NULL;
2021 return JB_ERR_MEMORY;
2027 * Substitution failed, keep the original buffer,
2028 * log the problem and ignore it.
2030 * The user might see some unresolved @CGI_VARIABLES@,
2031 * but returning a special CGI error page seems unreasonable
2032 * and could mask more important error messages.
2034 free(tmp_out_buffer);
2035 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
2036 buf, m->value, flags, pcrs_strerror(error));
2040 /* Substitution succeeded, use modified buffer. */
2042 file_buffer = tmp_out_buffer;
2050 *template_ptr = file_buffer;
2055 /*********************************************************************
2057 * Function : template_fill_for_cgi
2059 * Description : CGI support function that loads a HTML template
2060 * and fills it in. Handles file-not-found errors
2061 * by sending a HTML error message. For convenience,
2062 * this function also frees the passed "exports" map.
2065 * 1 : csp = Client state
2066 * 2 : templatename = name of the HTML template to be used
2067 * 3 : exports = map with fill in symbol -> name pairs.
2068 * Will be freed by this function.
2069 * 4 : rsp = Response structure to fill in.
2071 * Returns : JB_ERR_OK on success
2072 * JB_ERR_MEMORY on out-of-memory error
2074 *********************************************************************/
2075 jb_err template_fill_for_cgi(const struct client_state *csp,
2076 const char *templatename,
2077 struct map *exports,
2078 struct http_response *rsp)
2083 assert(templatename);
2087 err = template_load(csp, &rsp->body, templatename, 0);
2088 if (err == JB_ERR_FILE)
2091 return cgi_error_no_template(csp, rsp, templatename);
2096 return err; /* JB_ERR_MEMORY */
2098 err = template_fill(&rsp->body, exports);
2104 /*********************************************************************
2106 * Function : default_exports
2108 * Description : returns a struct map list that contains exports
2109 * which are common to all CGI functions.
2112 * 1 : csp = Current client state (buffers, headers, etc...)
2113 * 2 : caller = name of CGI who calls us and which should
2114 * be excluded from the generated menu. May be
2116 * Returns : NULL if no memory, else a new map. Caller frees.
2118 *********************************************************************/
2119 struct map *default_exports(const struct client_state *csp, const char *caller)
2123 struct map * exports;
2124 int local_help_exists = 0;
2125 char *ip_address = NULL;
2126 char *hostname = NULL;
2130 exports = new_map();
2131 if (exports == NULL)
2136 if (csp->config->hostname)
2138 get_host_information(csp->cfd, &ip_address, NULL);
2139 hostname = strdup(csp->config->hostname);
2143 get_host_information(csp->cfd, &ip_address, &hostname);
2146 err = map(exports, "version", 1, html_encode(VERSION), 0);
2147 get_locale_time(buf, sizeof(buf));
2148 if (!err) err = map(exports, "time", 1, html_encode(buf), 0);
2149 if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2151 if (!err) err = map(exports, "my-hostname", 1, html_encode(hostname ? hostname : "unknown"), 0);
2153 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2154 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2155 if (!err) err = map(exports, "menu", 1, make_menu(caller, csp->config->feature_flags), 0);
2156 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2157 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2158 !strncmpic(csp->config->usermanual, "http", 4))
2160 /* Manual is located somewhere else, just link to it. */
2161 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2165 /* Manual is delivered by Privoxy. */
2166 if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2168 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2169 #ifdef FEATURE_TOGGLE
2170 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2172 if (!err) err = map_block_killer(exports, "can-toggle");
2175 snprintf(buf, sizeof(buf), "%d", csp->config->hport);
2176 if (!err) err = map(exports, "my-port", 1, buf, 1);
2178 if(!strcmp(CODE_STATUS, "stable"))
2180 if (!err) err = map_block_killer(exports, "unstable");
2183 if (csp->config->admin_address != NULL)
2185 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2186 local_help_exists = 1;
2190 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2193 if (csp->config->proxy_info_url != NULL)
2195 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2196 local_help_exists = 1;
2200 if (!err) err = map_block_killer(exports, "have-proxy-info");
2203 if (local_help_exists == 0)
2205 if (!err) err = map_block_killer(exports, "have-help-info");
2218 /*********************************************************************
2220 * Function : map_block_killer
2222 * Description : Convenience function.
2223 * Adds a "killer" for the conditional HTML-template
2224 * block <name>, i.e. a substitution of the regex
2225 * "if-<name>-start.*if-<name>-end" to the given
2229 * 1 : exports = map to extend
2230 * 2 : name = name of conditional block
2232 * Returns : JB_ERR_OK on success
2233 * JB_ERR_MEMORY on out-of-memory error.
2235 *********************************************************************/
2236 jb_err map_block_killer(struct map *exports, const char *name)
2238 char buf[1000]; /* Will do, since the names are hardwired */
2242 assert(strlen(name) < (size_t)490);
2244 snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2245 return map(exports, buf, 1, "", 1);
2249 /*********************************************************************
2251 * Function : map_block_keep
2253 * Description : Convenience function. Removes the markers used
2254 * by map-block-killer, to save a few bytes.
2255 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2258 * 1 : exports = map to extend
2259 * 2 : name = name of conditional block
2261 * Returns : JB_ERR_OK on success
2262 * JB_ERR_MEMORY on out-of-memory error.
2264 *********************************************************************/
2265 jb_err map_block_keep(struct map *exports, const char *name)
2268 char buf[500]; /* Will do, since the names are hardwired */
2272 assert(strlen(name) < (size_t)490);
2274 snprintf(buf, sizeof(buf), "if-%s-start", name);
2275 err = map(exports, buf, 1, "", 1);
2282 snprintf(buf, sizeof(buf), "if-%s-end", name);
2283 return map(exports, buf, 1, "", 1);
2287 /*********************************************************************
2289 * Function : map_conditional
2291 * Description : Convenience function.
2292 * Adds an "if-then-else" for the conditional HTML-template
2293 * block <name>, i.e. a substitution of the form:
2300 * The control structure and one of the alternatives
2304 * 1 : exports = map to extend
2305 * 2 : name = name of conditional block
2306 * 3 : choose_first = nonzero for first, zero for second.
2308 * Returns : JB_ERR_OK on success
2309 * JB_ERR_MEMORY on out-of-memory error.
2311 *********************************************************************/
2312 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2314 char buf[1000]; /* Will do, since the names are hardwired */
2319 assert(strlen(name) < (size_t)480);
2321 snprintf(buf, sizeof(buf), (choose_first
2322 ? "else-not-%s@.*@endif-%s"
2323 : "if-%s-then@.*@else-not-%s"),
2326 err = map(exports, buf, 1, "", 1);
2332 snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2333 return map(exports, buf, 1, "", 1);
2337 /*********************************************************************
2339 * Function : make_menu
2341 * Description : Returns an HTML-formatted menu of the available
2342 * unhidden CGIs, excluding the one given in <self>
2343 * and the toggle CGI if toggling is disabled.
2346 * 1 : self = name of CGI to leave out, can be NULL for
2348 * 2 : feature_flags = feature bitmap from csp->config
2351 * Returns : menu string, or NULL on out-of-memory error.
2353 *********************************************************************/
2354 char *make_menu(const char *self, const unsigned feature_flags)
2356 const struct cgi_dispatcher *d;
2357 char *result = strdup("");
2361 self = "NO-SUCH-CGI!";
2364 /* List available unhidden CGI's and export as "other-cgis" */
2365 for (d = cgi_dispatchers; d->name; d++)
2368 #ifdef FEATURE_TOGGLE
2369 if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2372 * Suppress the toggle link if remote toggling is disabled.
2376 #endif /* def FEATURE_TOGGLE */
2378 if (d->description && strcmp(d->name, self))
2380 char *html_encoded_prefix;
2383 * Line breaks would be great, but break
2384 * the "blocked" template's JavaScript.
2386 string_append(&result, "<li><a href=\"");
2387 html_encoded_prefix = html_encode(CGI_PREFIX);
2388 if (html_encoded_prefix == NULL)
2394 string_append(&result, html_encoded_prefix);
2395 free(html_encoded_prefix);
2397 string_append(&result, d->name);
2398 string_append(&result, "\">");
2399 string_append(&result, d->description);
2400 string_append(&result, "</a></li>");
2408 /*********************************************************************
2410 * Function : dump_map
2412 * Description : HTML-dump a map for debugging (as table)
2415 * 1 : the_map = map to dump
2417 * Returns : string with HTML
2419 *********************************************************************/
2420 char *dump_map(const struct map *the_map)
2422 struct map_entry *cur_entry;
2423 char *ret = strdup("");
2425 string_append(&ret, "<table>\n");
2427 for (cur_entry = the_map->first;
2428 (cur_entry != NULL) && (ret != NULL);
2429 cur_entry = cur_entry->next)
2431 string_append(&ret, "<tr><td><b>");
2432 string_join (&ret, html_encode(cur_entry->name));
2433 string_append(&ret, "</b></td><td>");
2434 string_join (&ret, html_encode(cur_entry->value));
2435 string_append(&ret, "</td></tr>\n");
2438 string_append(&ret, "</table>\n");