1 const char cgi_rcs[] = "$Id: cgi.c,v 1.150 2012/03/09 17:55:49 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 * Copyright : Written by and Copyright (C) 2001-2004, 2006-2008
12 * the SourceForge Privoxy team. http://www.privoxy.org/
14 * Based on the Internet Junkbuster originally written
15 * by and Copyright (C) 1997 Anonymous Coders and
16 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
36 **********************************************************************/
42 #include <sys/types.h>
49 #ifdef FEATURE_COMPRESSION
61 #include "cgisimple.h"
62 #include "jbsockets.h"
63 #if defined(FEATURE_CGI_EDIT_ACTIONS) || defined(FEATURE_TOGGLE)
65 #endif /* defined(FEATURE_CGI_EDIT_ACTIONS) || defined (FEATURE_TOGGLE) */
67 /* loadcfg.h is for global_toggle_state only */
69 /* jcc.h is for mutex semaphore globals only */
72 const char cgi_h_rcs[] = CGI_H_VERSION;
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!
79 static const struct cgi_dispatcher cgi_dispatchers[] = {
84 #ifdef FEATURE_GRACEFUL_TERMINATION
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>",
93 #ifdef FEATURE_CGI_EDIT_ACTIONS
94 "View & change the current configuration",
96 "View the current configuration",
101 "View the source code version numbers",
105 "View the request headers",
109 "Look up which actions apply to a URL and why",
111 #ifdef FEATURE_TOGGLE
114 "Toggle Privoxy on or off",
116 #endif /* def FEATURE_TOGGLE */
117 #ifdef FEATURE_CGI_EDIT_ACTIONS
118 { "edit-actions", /* Edit the actions list */
121 { "eaa", /* Shortcut for edit-actions-add-url-form */
122 cgi_edit_actions_add_url_form,
124 { "eau", /* Shortcut for edit-actions-url-form */
125 cgi_edit_actions_url_form,
127 { "ear", /* Shortcut for edit-actions-remove-url-form */
128 cgi_edit_actions_remove_url_form,
130 { "eal", /* Shortcut for edit-actions-list */
131 cgi_edit_actions_list,
133 { "eafu", /* Shortcut for edit-actions-for-url */
134 cgi_edit_actions_for_url,
136 { "eas", /* Shortcut for edit-actions-submit */
137 cgi_edit_actions_submit,
139 { "easa", /* Shortcut for edit-actions-section-add */
140 cgi_edit_actions_section_add,
142 { "easr", /* Shortcut for edit-actions-section-remove */
143 cgi_edit_actions_section_remove,
145 { "eass", /* Shortcut for edit-actions-section-swap */
146 cgi_edit_actions_section_swap,
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. */ },
189 cgi_send_default_favicon,
190 NULL, TRUE /* Sends the default favicon image. */ },
193 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
196 NULL, TRUE /* Send a built-in image */ },
199 NULL, FALSE /* Send templates/cgi-style.css */ },
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 */ },
207 cgi_send_user_manual,
208 NULL, TRUE /* Send user-manual */ },
209 { NULL, /* NULL Indicates end of list and default page */
211 NULL, TRUE /* Unknown CGI page */ }
216 * Built-in images for ad replacement
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)); }'
222 #ifdef FEATURE_NO_GIFS
225 * Checkerboard pattern, as a PNG.
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";
237 * 1x1 transparant PNG.
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";
250 * Checkerboard pattern, as a GIF.
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"
260 * 1x1 transparant GIF.
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;";
268 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
269 const size_t image_blank_length = sizeof(image_blank_data) - 1;
271 #ifdef FEATURE_COMPRESSION
273 * Minimum length which a buffer has to reach before
274 * we bother to (re-)compress it. Completely arbitrary.
276 const size_t LOWER_LENGTH_LIMIT_FOR_COMPRESSION = 1024U;
279 static struct http_response cgi_error_memory_response[1];
281 static struct http_response *dispatch_known_cgi(struct client_state * csp,
283 static struct map *parse_cgi_parameters(char *argstring);
286 /*********************************************************************
288 * Function : dispatch_cgi
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.
298 * 1 : csp = Current client state (buffers, headers, etc...)
300 * Returns : http_response if match, NULL if nonmatch or handler fail
302 *********************************************************************/
303 struct http_response *dispatch_cgi(struct client_state *csp)
305 const char *host = csp->http->host;
306 const char *path = csp->http->path;
309 * Should we intercept ?
312 /* Note: "example.com" and "example.com." are equivalent hostnames. */
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 ".")))
319 /* ..then the path will all be for us. Remove leading '/' */
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))))
327 /* take everything following CGI_SITE_2_PATH */
328 path += strlen(CGI_SITE_2_PATH);
331 /* skip the forward slash after CGI_SITE_2_PATH */
334 else if (*path != '\0')
337 * weirdness: URL is /configXXX, where XXX is some string
338 * Do *NOT* intercept.
350 * This is a CGI call.
353 return dispatch_known_cgi(csp, path);
357 /*********************************************************************
359 * Function : grep_cgi_referrer
361 * Description : Ugly provisorical fix that greps the value of the
362 * referer HTTP header field out of a linked list of
363 * strings like found at csp->headers. Will disappear
366 * FIXME: csp->headers ought to be csp->http->headers
367 * FIXME: Parsing all client header lines should
368 * happen right after the request is received!
371 * 1 : csp = Current client state (buffers, headers, etc...)
373 * Returns : pointer to value (no copy!), or NULL if none found.
375 *********************************************************************/
376 static char *grep_cgi_referrer(const struct client_state *csp)
378 struct list_entry *p;
380 for (p = csp->headers->first; p != NULL; p = p->next)
382 if (p->str == NULL) continue;
383 if (strncmpic(p->str, "Referer: ", 9) == 0)
385 return ((p->str) + 9);
393 /*********************************************************************
395 * Function : referrer_is_safe
397 * Description : Decides whether we trust the Referer for
398 * CGI pages which are only meant to be reachable
399 * through Privoxy's web interface directly.
402 * 1 : csp = Current client state (buffers, headers, etc...)
404 * Returns : TRUE if the referrer is safe, or
405 * FALSE if the referrer is unsafe or not set.
407 *********************************************************************/
408 static int referrer_is_safe(const struct client_state *csp)
411 static const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
413 referrer = grep_cgi_referrer(csp);
415 if (NULL == referrer)
417 /* No referrer, no access */
418 log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
421 else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)
422 || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix)))))
424 /* Trustworthy referrer */
425 log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
426 csp->http->url, referrer);
432 /* Untrustworthy referrer */
433 log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
434 csp->http->url, referrer);
441 /*********************************************************************
443 * Function : dispatch_known_cgi
445 * Description : Processes a CGI once dispatch_cgi has determined that
446 * it matches one of the magic prefixes. Parses the path
447 * as a cgi name plus query string, prepares a map that
448 * maps CGI parameter names to their values, initializes
449 * the http_response struct, and calls the relevant CGI
453 * 1 : csp = Current client state (buffers, headers, etc...)
454 * 2 : path = Path of CGI, with the CGI prefix removed.
455 * Should not have a leading "/".
457 * Returns : http_response, or NULL on handler failure or out of
460 *********************************************************************/
461 static struct http_response *dispatch_known_cgi(struct client_state * csp,
464 const struct cgi_dispatcher *d;
465 struct map *param_list;
466 struct http_response *rsp;
467 char *query_args_start;
471 if (NULL == (path_copy = strdup(path)))
473 return cgi_error_memory();
475 query_args_start = path_copy;
476 while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
480 if (*query_args_start == '/')
482 *query_args_start++ = '\0';
483 if ((param_list = new_map()))
485 map(param_list, "file", 1, url_decode(query_args_start), 0);
490 if (*query_args_start == '?')
492 *query_args_start++ = '\0';
494 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
497 return cgi_error_memory();
503 * path_copy = CGI call name
504 * param_list = CGI params, as map
507 /* Get mem for response or fail*/
508 if (NULL == (rsp = alloc_http_response()))
511 free_map(param_list);
512 return cgi_error_memory();
516 * Find and start the right CGI function
521 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
524 * If the called CGI is either harmless, or referred
525 * from a trusted source, start it.
527 if (d->harmless || referrer_is_safe(csp))
529 err = (d->handler)(csp, rsp, param_list);
534 * Else, modify toggle calls so that they only display
535 * the status, and deny all other calls.
537 if (0 == strcmp(path_copy, "toggle"))
539 unmap(param_list, "set");
540 err = (d->handler)(csp, rsp, param_list);
544 err = cgi_error_disabled(csp, rsp);
549 free_map(param_list);
551 if (err == JB_ERR_CGI_PARAMS)
553 err = cgi_error_bad_param(csp, rsp);
555 if (err && (err != JB_ERR_MEMORY))
557 /* Unexpected error! Shouldn't get here */
558 log_error(LOG_LEVEL_ERROR,
559 "Unexpected CGI error %d in top-level handler. "
560 "Please file a bug report!", err);
561 err = cgi_error_unknown(csp, rsp, err);
566 rsp->crunch_reason = CGI_CALL;
567 return finish_http_response(csp, rsp);
571 /* Error in handler, probably out-of-memory */
572 free_http_response(rsp);
573 return cgi_error_memory();
581 /*********************************************************************
583 * Function : parse_cgi_parameters
585 * Description : Parse a URL-encoded argument string into name/value
586 * pairs and store them in a struct map list.
589 * 1 : argstring = string to be parsed. Will be trashed.
591 * Returns : pointer to param list, or NULL if out of memory.
593 *********************************************************************/
594 static struct map *parse_cgi_parameters(char *argstring)
597 char *vector[BUFFER_SIZE];
599 struct map *cgi_params;
601 if (NULL == (cgi_params = new_map()))
607 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
608 * the fragment identifier along with the request, so we must
609 * cut it off here, so it won't pollute the CGI params:
611 if (NULL != (p = strchr(argstring, '#')))
616 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
619 free_map(cgi_params);
623 for (i = 0; i < pairs; i++)
625 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
628 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
630 free_map(cgi_params);
641 /*********************************************************************
643 * Function : get_char_param
645 * Description : Get a single-character parameter passed to a CGI
649 * 1 : parameters = map of cgi parameters
650 * 2 : param_name = The name of the parameter to read
652 * Returns : Uppercase character on success, '\0' on error.
654 *********************************************************************/
655 char get_char_param(const struct map *parameters,
656 const char *param_name)
663 ch = *(lookup(parameters, param_name));
664 if ((ch >= 'a') && (ch <= 'z'))
666 ch = (char)(ch - 'a' + 'A');
673 /*********************************************************************
675 * Function : get_string_param
677 * Description : Get a string paramater, to be used as an
678 * ACTION_STRING or ACTION_MULTI paramater.
679 * Validates the input to prevent stupid/malicious
680 * users from corrupting their action file.
683 * 1 : parameters = map of cgi parameters
684 * 2 : param_name = The name of the parameter to read
685 * 3 : pparam = destination for paramater. Allocated as
686 * part of the map "parameters", so don't free it.
687 * Set to NULL if not specified.
689 * Returns : JB_ERR_OK on success, or if the paramater
691 * JB_ERR_MEMORY on out-of-memory.
692 * JB_ERR_CGI_PARAMS if the paramater is not valid.
694 *********************************************************************/
695 jb_err get_string_param(const struct map *parameters,
696 const char *param_name,
709 param = lookup(parameters, param_name);
715 if (strlen(param) >= CGI_PARAM_LEN_MAX)
720 * Note that the length limit is arbitrary, it just seems
721 * sensible to limit it to *something*. There's no
722 * technical reason for any limit at all.
724 return JB_ERR_CGI_PARAMS;
727 /* Check every character to see if it's legal */
729 while ((ch = *s++) != '\0')
731 if (((unsigned char)ch < (unsigned char)' ')
734 /* Probable hack attempt, or user accidentally used '}'. */
735 return JB_ERR_CGI_PARAMS;
746 /*********************************************************************
748 * Function : get_number_param
750 * Description : Get a non-negative integer from the parameters
751 * passed to a CGI function.
754 * 1 : csp = Current client state (buffers, headers, etc...)
755 * 2 : parameters = map of cgi parameters
756 * 3 : name = Name of CGI parameter to read
757 * 4 : pvalue = destination for value.
758 * Set to -1 on error.
760 * Returns : JB_ERR_OK on success
761 * JB_ERR_MEMORY on out-of-memory
762 * JB_ERR_CGI_PARAMS if the parameter was not specified
765 *********************************************************************/
766 jb_err get_number_param(struct client_state *csp,
767 const struct map *parameters,
782 param = lookup(parameters, name);
785 return JB_ERR_CGI_PARAMS;
788 /* We don't use atoi because I want to check this carefully... */
791 while ((ch = *param++) != '\0')
793 if ((ch < '0') || (ch > '9'))
795 return JB_ERR_CGI_PARAMS;
798 ch = (char)(ch - '0');
802 * <limits.h> defines UINT_MAX
804 * (UINT_MAX - ch) / 10 is the largest number that
805 * can be safely multiplied by 10 then have ch added.
807 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
809 return JB_ERR_CGI_PARAMS;
812 value = value * 10 + (unsigned)ch;
823 /*********************************************************************
825 * Function : error_response
827 * Description : returns an http_response that explains the reason
828 * why a request failed.
831 * 1 : csp = Current client state (buffers, headers, etc...)
832 * 2 : templatename = Which template should be used for the answer
834 * Returns : A http_response. If we run out of memory, this
835 * will be cgi_error_memory().
837 *********************************************************************/
838 struct http_response *error_response(struct client_state *csp,
839 const char *templatename)
842 struct http_response *rsp;
843 struct map *exports = default_exports(csp, NULL);
848 return cgi_error_memory();
851 if (NULL == (rsp = alloc_http_response()))
854 return cgi_error_memory();
857 #ifdef FEATURE_FORCE_LOAD
858 if (csp->flags & CSP_FLAG_FORCED)
860 path = strdup(FORCE_PREFIX);
863 #endif /* def FEATURE_FORCE_LOAD */
867 err = string_append(&path, csp->http->path);
869 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
870 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
871 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
872 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
875 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
878 /* Some failures, like "404 no such domain", don't have an IP address. */
879 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
887 free_http_response(rsp);
888 return cgi_error_memory();
891 if (!strcmp(templatename, "no-such-domain"))
893 rsp->status = strdup("404 No such domain");
894 rsp->crunch_reason = NO_SUCH_DOMAIN;
896 else if (!strcmp(templatename, "forwarding-failed"))
898 const struct forward_spec *fwd = forward_url(csp, csp->http);
899 char *socks_type = NULL;
902 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
903 /* Never get here - LOG_LEVEL_FATAL causes program exit */
907 * XXX: While the template is called forwarding-failed,
908 * it currently only handles socks forwarding failures.
911 assert(fwd->type != SOCKS_NONE);
914 * Map failure reason, forwarding type and forwarder.
916 if (NULL == csp->error_message)
919 * Either we forgot to record the failure reason,
920 * or the memory allocation failed.
922 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
923 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
925 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
928 * XXX: this is almost the same code as in cgi_show_url_info()
929 * and thus should be factored out and shared.
934 socks_type = "socks4-";
937 socks_type = "socks4a-";
940 socks_type = "socks5-";
943 log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
946 if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
947 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
948 if ((NULL == csp->error_message) || err)
951 free_http_response(rsp);
952 return cgi_error_memory();
955 rsp->status = strdup("503 Forwarding failure");
956 rsp->crunch_reason = FORWARDING_FAILED;
958 else if (!strcmp(templatename, "connect-failed"))
960 rsp->status = strdup("503 Connect failed");
961 rsp->crunch_reason = CONNECT_FAILED;
963 else if (!strcmp(templatename, "connection-timeout"))
965 rsp->status = strdup("504 Connection timeout");
966 rsp->crunch_reason = CONNECTION_TIMEOUT;
968 else if (!strcmp(templatename, "no-server-data"))
970 rsp->status = strdup("502 No data received from server or forwarder");
971 rsp->crunch_reason = NO_SERVER_DATA;
974 if (rsp->status == NULL)
977 free_http_response(rsp);
978 return cgi_error_memory();
981 err = template_fill_for_cgi(csp, templatename, exports, rsp);
984 free_http_response(rsp);
985 return cgi_error_memory();
988 return finish_http_response(csp, rsp);
992 /*********************************************************************
994 * Function : cgi_error_disabled
996 * Description : CGI function that is called to generate an error
997 * response if the actions editor or toggle CGI are
998 * accessed despite having being disabled at compile-
999 * or run-time, or if the user followed an untrusted link
1000 * to access a unsafe CGI feature that is only reachable
1001 * through Privoxy directly.
1004 * 1 : csp = Current client state (buffers, headers, etc...)
1005 * 2 : rsp = http_response data structure for output
1007 * CGI Parameters : none
1009 * Returns : JB_ERR_OK on success
1010 * JB_ERR_MEMORY on out-of-memory error.
1012 *********************************************************************/
1013 jb_err cgi_error_disabled(const struct client_state *csp,
1014 struct http_response *rsp)
1016 struct map *exports;
1021 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1023 return JB_ERR_MEMORY;
1025 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1027 /* Not important enough to do anything */
1028 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1031 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1035 /*********************************************************************
1037 * Function : cgi_init_error_messages
1039 * Description : Call at the start of the program to initialize
1040 * the error message used by cgi_error_memory().
1046 *********************************************************************/
1047 void cgi_init_error_messages(void)
1049 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1050 cgi_error_memory_response->head =
1051 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1052 "Content-Type: text/html\r\n"
1054 cgi_error_memory_response->body =
1057 " <title>500 Internal Privoxy Error</title>\n"
1058 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1061 "<h1>500 Internal Privoxy Error</h1>\n"
1062 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\n"
1063 "<p>Please contact your proxy administrator, or try again later</p>\n"
1067 cgi_error_memory_response->head_length =
1068 strlen(cgi_error_memory_response->head);
1069 cgi_error_memory_response->content_length =
1070 strlen(cgi_error_memory_response->body);
1071 cgi_error_memory_response->crunch_reason = OUT_OF_MEMORY;
1075 /*********************************************************************
1077 * Function : cgi_error_memory
1079 * Description : Called if a CGI function runs out of memory.
1080 * Returns a statically-allocated error response.
1084 * Returns : http_response data structure for output. This is
1085 * statically allocated, for obvious reasons.
1087 *********************************************************************/
1088 struct http_response *cgi_error_memory(void)
1090 /* assert that it's been initialized. */
1091 assert(cgi_error_memory_response->head);
1093 return cgi_error_memory_response;
1097 /*********************************************************************
1099 * Function : cgi_error_no_template
1101 * Description : Almost-CGI function that is called if a template
1102 * cannot be loaded. Note this is not a true CGI,
1103 * it takes a template name rather than a map of
1107 * 1 : csp = Current client state (buffers, headers, etc...)
1108 * 2 : rsp = http_response data structure for output
1109 * 3 : template_name = Name of template that could not
1112 * Returns : JB_ERR_OK on success
1113 * JB_ERR_MEMORY on out-of-memory error.
1115 *********************************************************************/
1116 jb_err cgi_error_no_template(const struct client_state *csp,
1117 struct http_response *rsp,
1118 const char *template_name)
1120 static const char status[] =
1121 "500 Internal Privoxy Error";
1122 static const char body_prefix[] =
1125 " <title>500 Internal Privoxy Error</title>\n"
1126 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1129 "<h1>500 Internal Privoxy Error</h1>\n"
1130 "<p>Privoxy encountered an error while processing your request:</p>\n"
1131 "<p><b>Could not load template file <code>";
1132 static const char body_suffix[] =
1133 "</code> or one of its included components.</b></p>\n"
1134 "<p>Please contact your proxy administrator.</p>\n"
1135 "<p>If you are the proxy administrator, please put the required file(s)"
1136 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1137 "location of the <code><i>(confdir)</i></code> directory "
1138 "is specified in the main Privoxy <code>config</code> "
1139 "file. (It's typically the Privoxy install directory"
1141 ", or <code>/etc/privoxy/</code>"
1142 #endif /* ndef _WIN32 */
1146 const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1150 assert(template_name);
1152 /* Reset rsp, if needed */
1156 rsp->content_length = 0;
1157 rsp->head_length = 0;
1160 rsp->body = malloc(body_size);
1161 if (rsp->body == NULL)
1163 return JB_ERR_MEMORY;
1165 strlcpy(rsp->body, body_prefix, body_size);
1166 strlcat(rsp->body, template_name, body_size);
1167 strlcat(rsp->body, body_suffix, body_size);
1169 rsp->status = strdup(status);
1170 if (rsp->status == NULL)
1172 return JB_ERR_MEMORY;
1179 /*********************************************************************
1181 * Function : cgi_error_unknown
1183 * Description : Almost-CGI function that is called if an unexpected
1184 * error occurs in the top-level CGI dispatcher.
1185 * In this context, "unexpected" means "anything other
1186 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1187 * expected to handle all other errors internally,
1188 * since they can give more relavent error messages
1191 * Note this is not a true CGI, it takes an error
1192 * code rather than a map of parameters.
1195 * 1 : csp = Current client state (buffers, headers, etc...)
1196 * 2 : rsp = http_response data structure for output
1197 * 3 : error_to_report = Error code to report.
1199 * Returns : JB_ERR_OK on success
1200 * JB_ERR_MEMORY on out-of-memory error.
1202 *********************************************************************/
1203 jb_err cgi_error_unknown(const struct client_state *csp,
1204 struct http_response *rsp,
1205 jb_err error_to_report)
1207 static const char status[] =
1208 "500 Internal Privoxy Error";
1209 static const char body_prefix[] =
1212 " <title>500 Internal Privoxy Error</title>\n"
1213 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1216 "<h1>500 Internal Privoxy Error</h1>\n"
1217 "<p>Privoxy encountered an error while processing your request:</p>\n"
1218 "<p><b>Unexpected internal error: ";
1219 static const char body_suffix[] =
1222 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1223 "file a bug report</a>.</p>\n"
1226 /* Includes room for larger error numbers in the future. */
1227 const size_t body_size = sizeof(body_prefix) + sizeof(body_suffix) + 5;
1231 /* Reset rsp, if needed */
1235 rsp->content_length = 0;
1236 rsp->head_length = 0;
1238 rsp->crunch_reason = INTERNAL_ERROR;
1240 rsp->body = malloc(body_size);
1241 if (rsp->body == NULL)
1243 return JB_ERR_MEMORY;
1246 snprintf(rsp->body, body_size, "%s%d%s", body_prefix, error_to_report, body_suffix);
1248 rsp->status = strdup(status);
1249 if (rsp->status == NULL)
1251 return JB_ERR_MEMORY;
1258 /*********************************************************************
1260 * Function : cgi_error_bad_param
1262 * Description : CGI function that is called if the parameters
1263 * (query string) for a CGI were wrong.
1266 * 1 : csp = Current client state (buffers, headers, etc...)
1267 * 2 : rsp = http_response data structure for output
1269 * CGI Parameters : none
1271 * Returns : JB_ERR_OK on success
1272 * JB_ERR_MEMORY on out-of-memory error.
1274 *********************************************************************/
1275 jb_err cgi_error_bad_param(const struct client_state *csp,
1276 struct http_response *rsp)
1278 struct map *exports;
1283 if (NULL == (exports = default_exports(csp, NULL)))
1285 return JB_ERR_MEMORY;
1288 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1292 /*********************************************************************
1294 * Function : cgi_redirect
1296 * Description : CGI support function to generate a HTTP redirect
1300 * 1 : rsp = http_response data structure for output
1301 * 2 : target = string with the target URL
1303 * CGI Parameters : None
1305 * Returns : JB_ERR_OK on success
1306 * JB_ERR_MEMORY on out-of-memory error.
1308 *********************************************************************/
1309 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1316 err = enlist_unique_header(rsp->headers, "Location", target);
1318 rsp->status = strdup("302 Local Redirect from Privoxy");
1319 if (rsp->status == NULL)
1321 return JB_ERR_MEMORY;
1328 /*********************************************************************
1330 * Function : add_help_link
1332 * Description : Produce a copy of the string given as item,
1333 * embedded in an HTML link to its corresponding
1334 * section (item name in uppercase) in the actions
1335 * chapter of the user manual, (whose URL is given in
1336 * the config and defaults to our web site).
1338 * FIXME: I currently only work for actions, and would
1339 * like to be generalized for other topics.
1342 * 1 : item = item (will NOT be free()d.)
1343 * It is assumed to be HTML-safe.
1344 * 2 : config = The current configuration.
1346 * Returns : String with item embedded in link, or NULL on
1349 *********************************************************************/
1350 char *add_help_link(const char *item,
1351 struct configuration_spec *config)
1355 if (!item) return NULL;
1357 result = strdup("<a href=\"");
1358 if (!strncmpic(config->usermanual, "file://", 7) ||
1359 !strncmpic(config->usermanual, "http", 4))
1361 string_append(&result, config->usermanual);
1365 string_append(&result, "http://");
1366 string_append(&result, CGI_SITE_2_HOST);
1367 string_append(&result, "/user-manual/");
1369 string_append(&result, ACTIONS_HELP_PREFIX);
1370 string_join (&result, string_toupper(item));
1371 string_append(&result, "\">");
1372 string_append(&result, item);
1373 string_append(&result, "</a>");
1379 /*********************************************************************
1381 * Function : get_http_time
1383 * Description : Get the time in a format suitable for use in a
1384 * HTTP header - e.g.:
1385 * "Sun, 06 Nov 1994 08:49:37 GMT"
1388 * 1 : time_offset = Time returned will be current time
1389 * plus this number of seconds.
1390 * 2 : buf = Destination for result.
1391 * 3 : buffer_size = Size of the buffer above. Must be big
1392 * enough to hold 29 characters plus a
1397 *********************************************************************/
1398 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1401 time_t current_time;
1402 #if defined(HAVE_GMTIME_R)
1407 assert(buffer_size > (size_t)29);
1409 time(¤t_time);
1411 current_time += time_offset;
1413 /* get and save the gmt */
1415 t = gmtime_r(¤t_time, &dummy);
1416 #elif defined(MUTEX_LOCKS_AVAILABLE)
1417 privoxy_mutex_lock(&gmtime_mutex);
1418 t = gmtime(¤t_time);
1419 privoxy_mutex_unlock(&gmtime_mutex);
1421 t = gmtime(¤t_time);
1424 strftime(buf, buffer_size, "%a, %d %b %Y %H:%M:%S GMT", t);
1428 /*********************************************************************
1430 * Function : get_locale_time
1432 * Description : Get the time in a date(1)-like format
1433 * according to the current locale - e.g.:
1434 * "Fri Aug 29 19:37:12 CEST 2008"
1436 * XXX: Should we allow the user to change the format?
1439 * 1 : buf = Destination for result.
1440 * 2 : buffer_size = Size of the buffer above. Must be big
1441 * enough to hold 29 characters plus a
1446 *********************************************************************/
1447 static void get_locale_time(char *buf, size_t buffer_size)
1450 time_t current_time;
1451 #if defined(HAVE_LOCALTIME_R)
1456 assert(buffer_size > (size_t)29);
1458 time(¤t_time);
1460 #if HAVE_LOCALTIME_R
1461 timeptr = localtime_r(¤t_time, &dummy);
1462 #elif defined(MUTEX_LOCKS_AVAILABLE)
1463 privoxy_mutex_lock(&localtime_mutex);
1464 timeptr = localtime(¤t_time);
1465 privoxy_mutex_unlock(&localtime_mutex);
1467 timeptr = localtime(¤t_time);
1470 strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1475 #ifdef FEATURE_COMPRESSION
1476 /*********************************************************************
1478 * Function : compress_buffer
1480 * Description : Compresses the content of a buffer with zlib's deflate
1481 * Allocates a new buffer for the result, free'ing it is
1485 * 1 : buffer = buffer whose content should be compressed
1486 * 2 : buffer_length = length of the buffer
1487 * 3 : compression_level = compression level for compress2()
1489 * Returns : NULL on error, otherwise a pointer to the compressed
1490 * content of the input buffer.
1492 *********************************************************************/
1493 char *compress_buffer(char *buffer, size_t *buffer_length, int compression_level)
1495 char *compressed_buffer;
1497 assert(-1 <= compression_level && compression_level <= 9);
1499 /* Let zlib figure out the maximum length of the compressed data */
1500 new_length = compressBound((uLongf)*buffer_length);
1502 compressed_buffer = malloc(new_length);
1503 if (NULL == compressed_buffer)
1505 log_error(LOG_LEVEL_FATAL,
1506 "Out of memory allocation compression buffer.");
1509 if (Z_OK != compress2((Bytef *)compressed_buffer, &new_length,
1510 (Bytef *)buffer, *buffer_length, compression_level))
1512 log_error(LOG_LEVEL_ERROR,
1513 "compress2() failed. Buffer size: %d, compression level: %d.",
1514 new_length, compression_level);
1515 freez(compressed_buffer);
1519 log_error(LOG_LEVEL_RE_FILTER,
1520 "Compressed content from %d to %d bytes. Compression level: %d",
1521 *buffer_length, new_length, compression_level);
1523 *buffer_length = (size_t)new_length;
1525 return compressed_buffer;
1531 /*********************************************************************
1533 * Function : finish_http_response
1535 * Description : Fill in the missing headers in an http response,
1536 * and flatten the headers to an http head.
1537 * For HEAD requests the body is freed once
1538 * the Content-Length header is set.
1541 * 1 : rsp = pointer to http_response to be processed
1543 * Returns : A http_response, usually the rsp parameter.
1544 * On error, free()s rsp and returns cgi_error_memory()
1546 *********************************************************************/
1547 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1549 char buf[BUFFER_SIZE];
1552 /* Special case - do NOT change this statically allocated response,
1553 * which is ready for output anyway.
1555 if (rsp == cgi_error_memory_response)
1561 * Fill in the HTTP Status, using HTTP/1.1
1562 * unless the client asked for HTTP/1.0.
1564 snprintf(buf, sizeof(buf), "%s %s",
1565 strcmpic(csp->http->ver, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1566 rsp->status ? rsp->status : "200 OK");
1567 err = enlist_first(rsp->headers, buf);
1570 * Set the Content-Length
1572 if (rsp->content_length == 0)
1574 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1577 #ifdef FEATURE_COMPRESSION
1578 if (!err && (csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
1579 && (rsp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
1581 char *compressed_content;
1583 compressed_content = compress_buffer(rsp->body, &rsp->content_length,
1584 csp->config->compression_level);
1585 if (NULL != compressed_content)
1588 rsp->body = compressed_content;
1589 err = enlist_unique_header(rsp->headers, "Content-Encoding", "deflate");
1596 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1597 err = enlist(rsp->headers, buf);
1600 if (0 == strcmpic(csp->http->gpc, "head"))
1603 * The client only asked for the head. Dispose
1604 * the body and log an offensive message.
1606 * While it may seem to be a bit inefficient to
1607 * prepare the body if it isn't needed, it's the
1608 * only way to get the Content-Length right for
1609 * dynamic pages. We could have disposed the body
1610 * earlier, but not without duplicating the
1611 * Content-Length setting code above.
1613 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1615 rsp->content_length = 0;
1618 if (strncmpic(rsp->status, "302", 3))
1621 * If it's not a redirect without any content,
1622 * set the Content-Type to text/html if it's
1623 * not already specified.
1625 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1629 * Fill in the rest of the default headers:
1631 * Date: set to current date/time.
1632 * Last-Modified: set to date/time the page was last changed.
1633 * Expires: set to date/time page next needs reloading.
1634 * Cache-Control: set to "no-cache" if applicable.
1636 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1641 * Set Expires to about 10 min into the future so it'll get reloaded
1642 * occasionally, e.g. if Privoxy gets upgraded.
1647 get_http_time(0, buf, sizeof(buf));
1648 err = enlist_unique_header(rsp->headers, "Date", buf);
1651 /* Some date in the past. */
1652 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1656 get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1657 err = enlist_unique_header(rsp->headers, "Expires", buf);
1660 else if (!strncmpic(rsp->status, "302", 3))
1662 get_http_time(0, buf, sizeof(buf));
1663 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1668 * Setting "Cache-Control" to "no-cache" and "Expires" to
1669 * the current time doesn't exactly forbid caching, it just
1670 * requires the client to revalidate the cached copy.
1672 * If a temporary problem occurs and the user tries again after
1673 * getting Privoxy's error message, a compliant browser may set the
1674 * If-Modified-Since header with the content of the error page's
1675 * Last-Modified header. More often than not, the document on the server
1676 * is older than Privoxy's error message, the server would send status code
1677 * 304 and the browser would display the outdated error message again and again.
1679 * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1680 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1681 * and can be safely used to "revalidate" without getting a status code 304.
1683 * There is no need to let the useless If-Modified-Since header reach the
1684 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1686 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1688 get_http_time(0, buf, sizeof(buf));
1689 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1690 if (!strncmpic(rsp->status, "403", 3)
1691 || !strncmpic(rsp->status, "404", 3)
1692 || !strncmpic(rsp->status, "502", 3)
1693 || !strncmpic(rsp->status, "503", 3)
1694 || !strncmpic(rsp->status, "504", 3))
1696 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1700 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1702 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1703 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1706 if (!err && !(csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1708 err = enlist_unique_header(rsp->headers, "Connection", "close");
1714 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1716 free_http_response(rsp);
1717 return cgi_error_memory();
1719 rsp->head_length = strlen(rsp->head);
1726 /*********************************************************************
1728 * Function : alloc_http_response
1730 * Description : Allocates a new http_response structure.
1734 * Returns : pointer to a new http_response, or NULL.
1736 *********************************************************************/
1737 struct http_response *alloc_http_response(void)
1739 return (struct http_response *) zalloc(sizeof(struct http_response));
1744 /*********************************************************************
1746 * Function : free_http_response
1748 * Description : Free the memory occupied by an http_response
1749 * and its depandant structures.
1752 * 1 : rsp = pointer to http_response to be freed
1756 *********************************************************************/
1757 void free_http_response(struct http_response *rsp)
1760 * Must special case cgi_error_memory_response, which is never freed.
1762 if (rsp && (rsp != cgi_error_memory_response))
1767 destroy_list(rsp->headers);
1774 /*********************************************************************
1776 * Function : template_load
1778 * Description : CGI support function that loads a given HTML
1779 * template, ignoring comment lines and following
1780 * #include statements up to a depth of 1.
1783 * 1 : csp = Current client state (buffers, headers, etc...)
1784 * 2 : template_ptr = Destination for pointer to loaded
1786 * 3 : templatename = name of the HTML template to be used
1787 * 4 : recursive = Flag set if this function calls itself
1788 * following an #include statament
1790 * Returns : JB_ERR_OK on success
1791 * JB_ERR_MEMORY on out-of-memory error.
1792 * JB_ERR_FILE if the template file cannot be read
1794 *********************************************************************/
1795 jb_err template_load(const struct client_state *csp, char **template_ptr,
1796 const char *templatename, int recursive)
1799 char *templates_dir_path;
1802 char *included_module;
1805 char buf[BUFFER_SIZE];
1808 assert(template_ptr);
1809 assert(templatename);
1811 *template_ptr = NULL;
1813 /* Validate template name. Paranoia. */
1814 for (p = templatename; *p != 0; p++)
1816 if ( ((*p < 'a') || (*p > 'z'))
1817 && ((*p < 'A') || (*p > 'Z'))
1818 && ((*p < '0') || (*p > '9'))
1822 /* Illegal character */
1828 * Generate full path using either templdir
1829 * or confdir/templates as base directory.
1831 if (NULL != csp->config->templdir)
1833 templates_dir_path = strdup(csp->config->templdir);
1837 templates_dir_path = make_path(csp->config->confdir, "templates");
1840 if (templates_dir_path == NULL)
1842 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1844 return JB_ERR_MEMORY;
1847 full_path = make_path(templates_dir_path, templatename);
1848 free(templates_dir_path);
1849 if (full_path == NULL)
1851 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1853 return JB_ERR_MEMORY;
1856 /* Allocate buffer */
1858 file_buffer = strdup("");
1859 if (file_buffer == NULL)
1861 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1863 return JB_ERR_MEMORY;
1866 /* Open template file */
1868 if (NULL == (fp = fopen(full_path, "r")))
1870 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1878 * Read the file, ignoring comments, and honoring #include
1879 * statements, unless we're already called recursively.
1881 * XXX: The comment handling could break with lines lengths > sizeof(buf).
1882 * This is unlikely in practise.
1884 while (fgets(buf, sizeof(buf), fp))
1886 if (!recursive && !strncmp(buf, "#include ", 9))
1888 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1895 if (string_join(&file_buffer, included_module))
1898 return JB_ERR_MEMORY;
1904 /* skip lines starting with '#' */
1910 if (string_append(&file_buffer, buf))
1913 return JB_ERR_MEMORY;
1918 *template_ptr = file_buffer;
1924 /*********************************************************************
1926 * Function : template_fill
1928 * Description : CGI support function that fills in a pre-loaded
1929 * HTML template by replacing @name@ with value using
1930 * pcrs, for each item in the output map.
1932 * Note that a leading '$' character in the export map's
1933 * values will be stripped and toggle on backreference
1937 * 1 : template_ptr = IN: Template to be filled out.
1939 * OUT: Filled out template.
1940 * Caller must free().
1941 * 2 : exports = map with fill in symbol -> name pairs
1943 * Returns : JB_ERR_OK on success (and for uncritical errors)
1944 * JB_ERR_MEMORY on out-of-memory error
1946 *********************************************************************/
1947 jb_err template_fill(char **template_ptr, const struct map *exports)
1949 struct map_entry *m;
1951 char buf[BUFFER_SIZE];
1952 char *tmp_out_buffer;
1958 assert(template_ptr);
1959 assert(*template_ptr);
1962 file_buffer = *template_ptr;
1963 size = strlen(file_buffer) + 1;
1966 * Assemble pcrs joblist from exports map
1968 for (m = exports->first; m != NULL; m = m->next)
1970 if (*m->name == '$')
1973 * First character of name is '$', so remove this flag
1974 * character and allow backreferences ($1 etc) in the
1975 * "replace with" text.
1977 snprintf(buf, sizeof(buf), "%s", m->name + 1);
1983 * Treat the "replace with" text as a literal string -
1984 * no quoting needed, no backreferences allowed.
1985 * ("Trivial" ['T'] flag).
1989 /* Enclose name in @@ */
1990 snprintf(buf, sizeof(buf), "@%s@", m->name);
1993 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1995 /* Make and run job. */
1996 job = pcrs_compile(buf, m->value, flags, &error);
1999 if (error == PCRS_ERR_NOMEM)
2002 *template_ptr = NULL;
2003 return JB_ERR_MEMORY;
2007 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2008 /* Hope it wasn't important and silently ignore the invalid job */
2013 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2016 if (NULL == tmp_out_buffer)
2018 *template_ptr = NULL;
2019 return JB_ERR_MEMORY;
2025 * Substitution failed, keep the original buffer,
2026 * log the problem and ignore it.
2028 * The user might see some unresolved @CGI_VARIABLES@,
2029 * but returning a special CGI error page seems unreasonable
2030 * and could mask more important error messages.
2032 free(tmp_out_buffer);
2033 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
2034 buf, m->value, flags, pcrs_strerror(error));
2038 /* Substitution succeeded, use modified buffer. */
2040 file_buffer = tmp_out_buffer;
2048 *template_ptr = file_buffer;
2053 /*********************************************************************
2055 * Function : template_fill_for_cgi
2057 * Description : CGI support function that loads a HTML template
2058 * and fills it in. Handles file-not-found errors
2059 * by sending a HTML error message. For convenience,
2060 * this function also frees the passed "exports" map.
2063 * 1 : csp = Client state
2064 * 2 : templatename = name of the HTML template to be used
2065 * 3 : exports = map with fill in symbol -> name pairs.
2066 * Will be freed by this function.
2067 * 4 : rsp = Response structure to fill in.
2069 * Returns : JB_ERR_OK on success
2070 * JB_ERR_MEMORY on out-of-memory error
2072 *********************************************************************/
2073 jb_err template_fill_for_cgi(const struct client_state *csp,
2074 const char *templatename,
2075 struct map *exports,
2076 struct http_response *rsp)
2081 assert(templatename);
2085 err = template_load(csp, &rsp->body, templatename, 0);
2086 if (err == JB_ERR_FILE)
2089 return cgi_error_no_template(csp, rsp, templatename);
2094 return err; /* JB_ERR_MEMORY */
2096 err = template_fill(&rsp->body, exports);
2102 /*********************************************************************
2104 * Function : default_exports
2106 * Description : returns a struct map list that contains exports
2107 * which are common to all CGI functions.
2110 * 1 : csp = Current client state (buffers, headers, etc...)
2111 * 2 : caller = name of CGI who calls us and which should
2112 * be excluded from the generated menu. May be
2114 * Returns : NULL if no memory, else a new map. Caller frees.
2116 *********************************************************************/
2117 struct map *default_exports(const struct client_state *csp, const char *caller)
2121 struct map * exports;
2122 int local_help_exists = 0;
2123 char *ip_address = NULL;
2125 char *hostname = NULL;
2129 exports = new_map();
2130 if (exports == NULL)
2135 if (csp->config->hostname)
2137 get_host_information(csp->cfd, &ip_address, &port, NULL);
2138 hostname = strdup(csp->config->hostname);
2142 get_host_information(csp->cfd, &ip_address, &port, &hostname);
2145 err = map(exports, "version", 1, html_encode(VERSION), 0);
2146 get_locale_time(buf, sizeof(buf));
2147 if (!err) err = map(exports, "time", 1, html_encode(buf), 0);
2148 if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2150 if (!err) err = map(exports, "my-port", 1, html_encode(port ? port : "unknown"), 0);
2152 if (!err) err = map(exports, "my-hostname", 1, html_encode(hostname ? hostname : "unknown"), 0);
2154 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2155 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2156 if (!err) err = map(exports, "menu", 1, make_menu(caller, csp->config->feature_flags), 0);
2157 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2158 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2159 !strncmpic(csp->config->usermanual, "http", 4))
2161 /* Manual is located somewhere else, just link to it. */
2162 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2166 /* Manual is delivered by Privoxy. */
2167 if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2169 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2170 #ifdef FEATURE_TOGGLE
2171 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2173 if (!err) err = map_block_killer(exports, "can-toggle");
2176 if (!strcmp(CODE_STATUS, "stable"))
2178 if (!err) err = map_block_killer(exports, "unstable");
2181 if (csp->config->admin_address != NULL)
2183 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2184 local_help_exists = 1;
2188 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2191 if (csp->config->proxy_info_url != NULL)
2193 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2194 local_help_exists = 1;
2198 if (!err) err = map_block_killer(exports, "have-proxy-info");
2201 if (local_help_exists == 0)
2203 if (!err) err = map_block_killer(exports, "have-help-info");
2216 /*********************************************************************
2218 * Function : map_block_killer
2220 * Description : Convenience function.
2221 * Adds a "killer" for the conditional HTML-template
2222 * block <name>, i.e. a substitution of the regex
2223 * "if-<name>-start.*if-<name>-end" to the given
2227 * 1 : exports = map to extend
2228 * 2 : name = name of conditional block
2230 * Returns : JB_ERR_OK on success
2231 * JB_ERR_MEMORY on out-of-memory error.
2233 *********************************************************************/
2234 jb_err map_block_killer(struct map *exports, const char *name)
2236 char buf[1000]; /* Will do, since the names are hardwired */
2240 assert(strlen(name) < (size_t)490);
2242 snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2243 return map(exports, buf, 1, "", 1);
2247 /*********************************************************************
2249 * Function : map_block_keep
2251 * Description : Convenience function. Removes the markers used
2252 * by map-block-killer, to save a few bytes.
2253 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2256 * 1 : exports = map to extend
2257 * 2 : name = name of conditional block
2259 * Returns : JB_ERR_OK on success
2260 * JB_ERR_MEMORY on out-of-memory error.
2262 *********************************************************************/
2263 jb_err map_block_keep(struct map *exports, const char *name)
2266 char buf[500]; /* Will do, since the names are hardwired */
2270 assert(strlen(name) < (size_t)490);
2272 snprintf(buf, sizeof(buf), "if-%s-start", name);
2273 err = map(exports, buf, 1, "", 1);
2280 snprintf(buf, sizeof(buf), "if-%s-end", name);
2281 return map(exports, buf, 1, "", 1);
2285 /*********************************************************************
2287 * Function : map_conditional
2289 * Description : Convenience function.
2290 * Adds an "if-then-else" for the conditional HTML-template
2291 * block <name>, i.e. a substitution of the form:
2298 * The control structure and one of the alternatives
2302 * 1 : exports = map to extend
2303 * 2 : name = name of conditional block
2304 * 3 : choose_first = nonzero for first, zero for second.
2306 * Returns : JB_ERR_OK on success
2307 * JB_ERR_MEMORY on out-of-memory error.
2309 *********************************************************************/
2310 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2312 char buf[1000]; /* Will do, since the names are hardwired */
2317 assert(strlen(name) < (size_t)480);
2319 snprintf(buf, sizeof(buf), (choose_first
2320 ? "else-not-%s@.*@endif-%s"
2321 : "if-%s-then@.*@else-not-%s"),
2324 err = map(exports, buf, 1, "", 1);
2330 snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2331 return map(exports, buf, 1, "", 1);
2335 /*********************************************************************
2337 * Function : make_menu
2339 * Description : Returns an HTML-formatted menu of the available
2340 * unhidden CGIs, excluding the one given in <self>
2341 * and the toggle CGI if toggling is disabled.
2344 * 1 : self = name of CGI to leave out, can be NULL for
2346 * 2 : feature_flags = feature bitmap from csp->config
2349 * Returns : menu string, or NULL on out-of-memory error.
2351 *********************************************************************/
2352 char *make_menu(const char *self, const unsigned feature_flags)
2354 const struct cgi_dispatcher *d;
2355 char *result = strdup("");
2359 self = "NO-SUCH-CGI!";
2362 /* List available unhidden CGI's and export as "other-cgis" */
2363 for (d = cgi_dispatchers; d->name; d++)
2366 #ifdef FEATURE_TOGGLE
2367 if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2370 * Suppress the toggle link if remote toggling is disabled.
2374 #endif /* def FEATURE_TOGGLE */
2376 if (d->description && strcmp(d->name, self))
2378 char *html_encoded_prefix;
2381 * Line breaks would be great, but break
2382 * the "blocked" template's JavaScript.
2384 string_append(&result, "<li><a href=\"");
2385 html_encoded_prefix = html_encode(CGI_PREFIX);
2386 if (html_encoded_prefix == NULL)
2392 string_append(&result, html_encoded_prefix);
2393 free(html_encoded_prefix);
2395 string_append(&result, d->name);
2396 string_append(&result, "\">");
2397 string_append(&result, d->description);
2398 string_append(&result, "</a></li>");
2406 /*********************************************************************
2408 * Function : dump_map
2410 * Description : HTML-dump a map for debugging (as table)
2413 * 1 : the_map = map to dump
2415 * Returns : string with HTML
2417 *********************************************************************/
2418 char *dump_map(const struct map *the_map)
2420 struct map_entry *cur_entry;
2421 char *ret = strdup("");
2423 string_append(&ret, "<table>\n");
2425 for (cur_entry = the_map->first;
2426 (cur_entry != NULL) && (ret != NULL);
2427 cur_entry = cur_entry->next)
2429 string_append(&ret, "<tr><td><b>");
2430 string_join (&ret, html_encode(cur_entry->name));
2431 string_append(&ret, "</b></td><td>");
2432 string_join (&ret, html_encode(cur_entry->value));
2433 string_append(&ret, "</td></tr>\n");
2436 string_append(&ret, "</table>\n");