1 const char cgi_rcs[] = "$Id: cgi.c,v 1.152 2012/06/08 15:08:33 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)
599 struct map *cgi_params;
602 * XXX: This estimate is guaranteed to be high enough as we
603 * let ssplit() ignore empty fields, but also a bit wasteful.
604 * The same hack is used in get_last_url() so it looks like
605 * a real solution is needed.
607 size_t max_segments = strlen(argstring) / 2;
608 if (max_segments == 0)
611 * XXX: If the argstring is empty, there's really
612 * no point in creating a param list, but currently
613 * other parts of Privoxy depend on the list's existence.
617 vector = malloc(max_segments * sizeof(char *));
624 if (NULL == (cgi_params = new_map()))
631 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
632 * the fragment identifier along with the request, so we must
633 * cut it off here, so it won't pollute the CGI params:
635 if (NULL != (p = strchr(argstring, '#')))
640 pairs = ssplit(argstring, "&", vector, max_segments);
645 free_map(cgi_params);
649 for (i = 0; i < pairs; i++)
651 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
654 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
657 free_map(cgi_params);
670 /*********************************************************************
672 * Function : get_char_param
674 * Description : Get a single-character parameter passed to a CGI
678 * 1 : parameters = map of cgi parameters
679 * 2 : param_name = The name of the parameter to read
681 * Returns : Uppercase character on success, '\0' on error.
683 *********************************************************************/
684 char get_char_param(const struct map *parameters,
685 const char *param_name)
692 ch = *(lookup(parameters, param_name));
693 if ((ch >= 'a') && (ch <= 'z'))
695 ch = (char)(ch - 'a' + 'A');
702 /*********************************************************************
704 * Function : get_string_param
706 * Description : Get a string paramater, to be used as an
707 * ACTION_STRING or ACTION_MULTI paramater.
708 * Validates the input to prevent stupid/malicious
709 * users from corrupting their action file.
712 * 1 : parameters = map of cgi parameters
713 * 2 : param_name = The name of the parameter to read
714 * 3 : pparam = destination for paramater. Allocated as
715 * part of the map "parameters", so don't free it.
716 * Set to NULL if not specified.
718 * Returns : JB_ERR_OK on success, or if the paramater
720 * JB_ERR_MEMORY on out-of-memory.
721 * JB_ERR_CGI_PARAMS if the paramater is not valid.
723 *********************************************************************/
724 jb_err get_string_param(const struct map *parameters,
725 const char *param_name,
738 param = lookup(parameters, param_name);
744 if (strlen(param) >= CGI_PARAM_LEN_MAX)
749 * Note that the length limit is arbitrary, it just seems
750 * sensible to limit it to *something*. There's no
751 * technical reason for any limit at all.
753 return JB_ERR_CGI_PARAMS;
756 /* Check every character to see if it's legal */
758 while ((ch = *s++) != '\0')
760 if (((unsigned char)ch < (unsigned char)' ')
763 /* Probable hack attempt, or user accidentally used '}'. */
764 return JB_ERR_CGI_PARAMS;
775 /*********************************************************************
777 * Function : get_number_param
779 * Description : Get a non-negative integer from the parameters
780 * passed to a CGI function.
783 * 1 : csp = Current client state (buffers, headers, etc...)
784 * 2 : parameters = map of cgi parameters
785 * 3 : name = Name of CGI parameter to read
786 * 4 : pvalue = destination for value.
787 * Set to -1 on error.
789 * Returns : JB_ERR_OK on success
790 * JB_ERR_MEMORY on out-of-memory
791 * JB_ERR_CGI_PARAMS if the parameter was not specified
794 *********************************************************************/
795 jb_err get_number_param(struct client_state *csp,
796 const struct map *parameters,
811 param = lookup(parameters, name);
814 return JB_ERR_CGI_PARAMS;
817 /* We don't use atoi because I want to check this carefully... */
820 while ((ch = *param++) != '\0')
822 if ((ch < '0') || (ch > '9'))
824 return JB_ERR_CGI_PARAMS;
827 ch = (char)(ch - '0');
831 * <limits.h> defines UINT_MAX
833 * (UINT_MAX - ch) / 10 is the largest number that
834 * can be safely multiplied by 10 then have ch added.
836 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
838 return JB_ERR_CGI_PARAMS;
841 value = value * 10 + (unsigned)ch;
852 /*********************************************************************
854 * Function : error_response
856 * Description : returns an http_response that explains the reason
857 * why a request failed.
860 * 1 : csp = Current client state (buffers, headers, etc...)
861 * 2 : templatename = Which template should be used for the answer
863 * Returns : A http_response. If we run out of memory, this
864 * will be cgi_error_memory().
866 *********************************************************************/
867 struct http_response *error_response(struct client_state *csp,
868 const char *templatename)
871 struct http_response *rsp;
872 struct map *exports = default_exports(csp, NULL);
877 return cgi_error_memory();
880 if (NULL == (rsp = alloc_http_response()))
883 return cgi_error_memory();
886 #ifdef FEATURE_FORCE_LOAD
887 if (csp->flags & CSP_FLAG_FORCED)
889 path = strdup(FORCE_PREFIX);
892 #endif /* def FEATURE_FORCE_LOAD */
896 err = string_append(&path, csp->http->path);
898 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
899 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
900 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
901 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
904 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
907 /* Some failures, like "404 no such domain", don't have an IP address. */
908 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
916 free_http_response(rsp);
917 return cgi_error_memory();
920 if (!strcmp(templatename, "no-such-domain"))
922 rsp->status = strdup("404 No such domain");
923 rsp->crunch_reason = NO_SUCH_DOMAIN;
925 else if (!strcmp(templatename, "forwarding-failed"))
927 const struct forward_spec *fwd = forward_url(csp, csp->http);
928 char *socks_type = NULL;
931 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
932 /* Never get here - LOG_LEVEL_FATAL causes program exit */
936 * XXX: While the template is called forwarding-failed,
937 * it currently only handles socks forwarding failures.
940 assert(fwd->type != SOCKS_NONE);
943 * Map failure reason, forwarding type and forwarder.
945 if (NULL == csp->error_message)
948 * Either we forgot to record the failure reason,
949 * or the memory allocation failed.
951 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
952 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
954 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
957 * XXX: this is almost the same code as in cgi_show_url_info()
958 * and thus should be factored out and shared.
963 socks_type = "socks4-";
966 socks_type = "socks4a-";
969 socks_type = "socks5-";
972 log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
975 if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
976 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
977 if ((NULL == csp->error_message) || err)
980 free_http_response(rsp);
981 return cgi_error_memory();
984 rsp->status = strdup("503 Forwarding failure");
985 rsp->crunch_reason = FORWARDING_FAILED;
987 else if (!strcmp(templatename, "connect-failed"))
989 rsp->status = strdup("503 Connect failed");
990 rsp->crunch_reason = CONNECT_FAILED;
992 else if (!strcmp(templatename, "connection-timeout"))
994 rsp->status = strdup("504 Connection timeout");
995 rsp->crunch_reason = CONNECTION_TIMEOUT;
997 else if (!strcmp(templatename, "no-server-data"))
999 rsp->status = strdup("502 No data received from server or forwarder");
1000 rsp->crunch_reason = NO_SERVER_DATA;
1003 if (rsp->status == NULL)
1006 free_http_response(rsp);
1007 return cgi_error_memory();
1010 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1013 free_http_response(rsp);
1014 return cgi_error_memory();
1017 return finish_http_response(csp, rsp);
1021 /*********************************************************************
1023 * Function : cgi_error_disabled
1025 * Description : CGI function that is called to generate an error
1026 * response if the actions editor or toggle CGI are
1027 * accessed despite having being disabled at compile-
1028 * or run-time, or if the user followed an untrusted link
1029 * to access a unsafe CGI feature that is only reachable
1030 * through Privoxy directly.
1033 * 1 : csp = Current client state (buffers, headers, etc...)
1034 * 2 : rsp = http_response data structure for output
1036 * CGI Parameters : none
1038 * Returns : JB_ERR_OK on success
1039 * JB_ERR_MEMORY on out-of-memory error.
1041 *********************************************************************/
1042 jb_err cgi_error_disabled(const struct client_state *csp,
1043 struct http_response *rsp)
1045 struct map *exports;
1050 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1052 return JB_ERR_MEMORY;
1054 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1056 /* Not important enough to do anything */
1057 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1060 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1064 /*********************************************************************
1066 * Function : cgi_init_error_messages
1068 * Description : Call at the start of the program to initialize
1069 * the error message used by cgi_error_memory().
1075 *********************************************************************/
1076 void cgi_init_error_messages(void)
1078 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1079 cgi_error_memory_response->head =
1080 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1081 "Content-Type: text/html\r\n"
1083 cgi_error_memory_response->body =
1086 " <title>500 Internal Privoxy Error</title>\n"
1087 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1090 "<h1>500 Internal Privoxy Error</h1>\n"
1091 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\n"
1092 "<p>Please contact your proxy administrator, or try again later</p>\n"
1096 cgi_error_memory_response->head_length =
1097 strlen(cgi_error_memory_response->head);
1098 cgi_error_memory_response->content_length =
1099 strlen(cgi_error_memory_response->body);
1100 cgi_error_memory_response->crunch_reason = OUT_OF_MEMORY;
1104 /*********************************************************************
1106 * Function : cgi_error_memory
1108 * Description : Called if a CGI function runs out of memory.
1109 * Returns a statically-allocated error response.
1113 * Returns : http_response data structure for output. This is
1114 * statically allocated, for obvious reasons.
1116 *********************************************************************/
1117 struct http_response *cgi_error_memory(void)
1119 /* assert that it's been initialized. */
1120 assert(cgi_error_memory_response->head);
1122 return cgi_error_memory_response;
1126 /*********************************************************************
1128 * Function : cgi_error_no_template
1130 * Description : Almost-CGI function that is called if a template
1131 * cannot be loaded. Note this is not a true CGI,
1132 * it takes a template name rather than a map of
1136 * 1 : csp = Current client state (buffers, headers, etc...)
1137 * 2 : rsp = http_response data structure for output
1138 * 3 : template_name = Name of template that could not
1141 * Returns : JB_ERR_OK on success
1142 * JB_ERR_MEMORY on out-of-memory error.
1144 *********************************************************************/
1145 jb_err cgi_error_no_template(const struct client_state *csp,
1146 struct http_response *rsp,
1147 const char *template_name)
1149 static const char status[] =
1150 "500 Internal Privoxy Error";
1151 static const char body_prefix[] =
1154 " <title>500 Internal Privoxy Error</title>\n"
1155 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1158 "<h1>500 Internal Privoxy Error</h1>\n"
1159 "<p>Privoxy encountered an error while processing your request:</p>\n"
1160 "<p><b>Could not load template file <code>";
1161 static const char body_suffix[] =
1162 "</code> or one of its included components.</b></p>\n"
1163 "<p>Please contact your proxy administrator.</p>\n"
1164 "<p>If you are the proxy administrator, please put the required file(s)"
1165 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1166 "location of the <code><i>(confdir)</i></code> directory "
1167 "is specified in the main Privoxy <code>config</code> "
1168 "file. (It's typically the Privoxy install directory"
1170 ", or <code>/etc/privoxy/</code>"
1171 #endif /* ndef _WIN32 */
1175 const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1179 assert(template_name);
1181 /* Reset rsp, if needed */
1185 rsp->content_length = 0;
1186 rsp->head_length = 0;
1189 rsp->body = malloc(body_size);
1190 if (rsp->body == NULL)
1192 return JB_ERR_MEMORY;
1194 strlcpy(rsp->body, body_prefix, body_size);
1195 strlcat(rsp->body, template_name, body_size);
1196 strlcat(rsp->body, body_suffix, body_size);
1198 rsp->status = strdup(status);
1199 if (rsp->status == NULL)
1201 return JB_ERR_MEMORY;
1208 /*********************************************************************
1210 * Function : cgi_error_unknown
1212 * Description : Almost-CGI function that is called if an unexpected
1213 * error occurs in the top-level CGI dispatcher.
1214 * In this context, "unexpected" means "anything other
1215 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1216 * expected to handle all other errors internally,
1217 * since they can give more relavent error messages
1220 * Note this is not a true CGI, it takes an error
1221 * code rather than a map of parameters.
1224 * 1 : csp = Current client state (buffers, headers, etc...)
1225 * 2 : rsp = http_response data structure for output
1226 * 3 : error_to_report = Error code to report.
1228 * Returns : JB_ERR_OK on success
1229 * JB_ERR_MEMORY on out-of-memory error.
1231 *********************************************************************/
1232 jb_err cgi_error_unknown(const struct client_state *csp,
1233 struct http_response *rsp,
1234 jb_err error_to_report)
1236 static const char status[] =
1237 "500 Internal Privoxy Error";
1238 static const char body_prefix[] =
1241 " <title>500 Internal Privoxy Error</title>\n"
1242 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1245 "<h1>500 Internal Privoxy Error</h1>\n"
1246 "<p>Privoxy encountered an error while processing your request:</p>\n"
1247 "<p><b>Unexpected internal error: ";
1248 static const char body_suffix[] =
1251 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1252 "file a bug report</a>.</p>\n"
1255 /* Includes room for larger error numbers in the future. */
1256 const size_t body_size = sizeof(body_prefix) + sizeof(body_suffix) + 5;
1260 /* Reset rsp, if needed */
1264 rsp->content_length = 0;
1265 rsp->head_length = 0;
1267 rsp->crunch_reason = INTERNAL_ERROR;
1269 rsp->body = malloc(body_size);
1270 if (rsp->body == NULL)
1272 return JB_ERR_MEMORY;
1275 snprintf(rsp->body, body_size, "%s%d%s", body_prefix, error_to_report, body_suffix);
1277 rsp->status = strdup(status);
1278 if (rsp->status == NULL)
1280 return JB_ERR_MEMORY;
1287 /*********************************************************************
1289 * Function : cgi_error_bad_param
1291 * Description : CGI function that is called if the parameters
1292 * (query string) for a CGI were wrong.
1295 * 1 : csp = Current client state (buffers, headers, etc...)
1296 * 2 : rsp = http_response data structure for output
1298 * CGI Parameters : none
1300 * Returns : JB_ERR_OK on success
1301 * JB_ERR_MEMORY on out-of-memory error.
1303 *********************************************************************/
1304 jb_err cgi_error_bad_param(const struct client_state *csp,
1305 struct http_response *rsp)
1307 struct map *exports;
1312 if (NULL == (exports = default_exports(csp, NULL)))
1314 return JB_ERR_MEMORY;
1317 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1321 /*********************************************************************
1323 * Function : cgi_redirect
1325 * Description : CGI support function to generate a HTTP redirect
1329 * 1 : rsp = http_response data structure for output
1330 * 2 : target = string with the target URL
1332 * CGI Parameters : None
1334 * Returns : JB_ERR_OK on success
1335 * JB_ERR_MEMORY on out-of-memory error.
1337 *********************************************************************/
1338 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1345 err = enlist_unique_header(rsp->headers, "Location", target);
1347 rsp->status = strdup("302 Local Redirect from Privoxy");
1348 if (rsp->status == NULL)
1350 return JB_ERR_MEMORY;
1357 /*********************************************************************
1359 * Function : add_help_link
1361 * Description : Produce a copy of the string given as item,
1362 * embedded in an HTML link to its corresponding
1363 * section (item name in uppercase) in the actions
1364 * chapter of the user manual, (whose URL is given in
1365 * the config and defaults to our web site).
1367 * FIXME: I currently only work for actions, and would
1368 * like to be generalized for other topics.
1371 * 1 : item = item (will NOT be free()d.)
1372 * It is assumed to be HTML-safe.
1373 * 2 : config = The current configuration.
1375 * Returns : String with item embedded in link, or NULL on
1378 *********************************************************************/
1379 char *add_help_link(const char *item,
1380 struct configuration_spec *config)
1384 if (!item) return NULL;
1386 result = strdup("<a href=\"");
1387 if (!strncmpic(config->usermanual, "file://", 7) ||
1388 !strncmpic(config->usermanual, "http", 4))
1390 string_append(&result, config->usermanual);
1394 string_append(&result, "http://");
1395 string_append(&result, CGI_SITE_2_HOST);
1396 string_append(&result, "/user-manual/");
1398 string_append(&result, ACTIONS_HELP_PREFIX);
1399 string_join (&result, string_toupper(item));
1400 string_append(&result, "\">");
1401 string_append(&result, item);
1402 string_append(&result, "</a>");
1408 /*********************************************************************
1410 * Function : get_http_time
1412 * Description : Get the time in a format suitable for use in a
1413 * HTTP header - e.g.:
1414 * "Sun, 06 Nov 1994 08:49:37 GMT"
1417 * 1 : time_offset = Time returned will be current time
1418 * plus this number of seconds.
1419 * 2 : buf = Destination for result.
1420 * 3 : buffer_size = Size of the buffer above. Must be big
1421 * enough to hold 29 characters plus a
1426 *********************************************************************/
1427 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1430 time_t current_time;
1431 #if defined(HAVE_GMTIME_R)
1436 assert(buffer_size > (size_t)29);
1438 time(¤t_time);
1440 current_time += time_offset;
1442 /* get and save the gmt */
1444 t = gmtime_r(¤t_time, &dummy);
1445 #elif defined(MUTEX_LOCKS_AVAILABLE)
1446 privoxy_mutex_lock(&gmtime_mutex);
1447 t = gmtime(¤t_time);
1448 privoxy_mutex_unlock(&gmtime_mutex);
1450 t = gmtime(¤t_time);
1453 strftime(buf, buffer_size, "%a, %d %b %Y %H:%M:%S GMT", t);
1457 /*********************************************************************
1459 * Function : get_locale_time
1461 * Description : Get the time in a date(1)-like format
1462 * according to the current locale - e.g.:
1463 * "Fri Aug 29 19:37:12 CEST 2008"
1465 * XXX: Should we allow the user to change the format?
1468 * 1 : buf = Destination for result.
1469 * 2 : buffer_size = Size of the buffer above. Must be big
1470 * enough to hold 29 characters plus a
1475 *********************************************************************/
1476 static void get_locale_time(char *buf, size_t buffer_size)
1479 time_t current_time;
1480 #if defined(HAVE_LOCALTIME_R)
1485 assert(buffer_size > (size_t)29);
1487 time(¤t_time);
1489 #if HAVE_LOCALTIME_R
1490 timeptr = localtime_r(¤t_time, &dummy);
1491 #elif defined(MUTEX_LOCKS_AVAILABLE)
1492 privoxy_mutex_lock(&localtime_mutex);
1493 timeptr = localtime(¤t_time);
1494 privoxy_mutex_unlock(&localtime_mutex);
1496 timeptr = localtime(¤t_time);
1499 strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1504 #ifdef FEATURE_COMPRESSION
1505 /*********************************************************************
1507 * Function : compress_buffer
1509 * Description : Compresses the content of a buffer with zlib's deflate
1510 * Allocates a new buffer for the result, free'ing it is
1514 * 1 : buffer = buffer whose content should be compressed
1515 * 2 : buffer_length = length of the buffer
1516 * 3 : compression_level = compression level for compress2()
1518 * Returns : NULL on error, otherwise a pointer to the compressed
1519 * content of the input buffer.
1521 *********************************************************************/
1522 char *compress_buffer(char *buffer, size_t *buffer_length, int compression_level)
1524 char *compressed_buffer;
1526 assert(-1 <= compression_level && compression_level <= 9);
1528 /* Let zlib figure out the maximum length of the compressed data */
1529 new_length = compressBound((uLongf)*buffer_length);
1531 compressed_buffer = malloc(new_length);
1532 if (NULL == compressed_buffer)
1534 log_error(LOG_LEVEL_FATAL,
1535 "Out of memory allocation compression buffer.");
1538 if (Z_OK != compress2((Bytef *)compressed_buffer, &new_length,
1539 (Bytef *)buffer, *buffer_length, compression_level))
1541 log_error(LOG_LEVEL_ERROR,
1542 "compress2() failed. Buffer size: %d, compression level: %d.",
1543 new_length, compression_level);
1544 freez(compressed_buffer);
1548 log_error(LOG_LEVEL_RE_FILTER,
1549 "Compressed content from %d to %d bytes. Compression level: %d",
1550 *buffer_length, new_length, compression_level);
1552 *buffer_length = (size_t)new_length;
1554 return compressed_buffer;
1560 /*********************************************************************
1562 * Function : finish_http_response
1564 * Description : Fill in the missing headers in an http response,
1565 * and flatten the headers to an http head.
1566 * For HEAD requests the body is freed once
1567 * the Content-Length header is set.
1570 * 1 : rsp = pointer to http_response to be processed
1572 * Returns : A http_response, usually the rsp parameter.
1573 * On error, free()s rsp and returns cgi_error_memory()
1575 *********************************************************************/
1576 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1578 char buf[BUFFER_SIZE];
1581 /* Special case - do NOT change this statically allocated response,
1582 * which is ready for output anyway.
1584 if (rsp == cgi_error_memory_response)
1590 * Fill in the HTTP Status, using HTTP/1.1
1591 * unless the client asked for HTTP/1.0.
1593 snprintf(buf, sizeof(buf), "%s %s",
1594 strcmpic(csp->http->ver, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1595 rsp->status ? rsp->status : "200 OK");
1596 err = enlist_first(rsp->headers, buf);
1599 * Set the Content-Length
1601 if (rsp->content_length == 0)
1603 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1606 #ifdef FEATURE_COMPRESSION
1607 if (!err && (csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
1608 && (rsp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
1610 char *compressed_content;
1612 compressed_content = compress_buffer(rsp->body, &rsp->content_length,
1613 csp->config->compression_level);
1614 if (NULL != compressed_content)
1617 rsp->body = compressed_content;
1618 err = enlist_unique_header(rsp->headers, "Content-Encoding", "deflate");
1625 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1626 err = enlist(rsp->headers, buf);
1629 if (0 == strcmpic(csp->http->gpc, "head"))
1632 * The client only asked for the head. Dispose
1633 * the body and log an offensive message.
1635 * While it may seem to be a bit inefficient to
1636 * prepare the body if it isn't needed, it's the
1637 * only way to get the Content-Length right for
1638 * dynamic pages. We could have disposed the body
1639 * earlier, but not without duplicating the
1640 * Content-Length setting code above.
1642 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1644 rsp->content_length = 0;
1647 if (strncmpic(rsp->status, "302", 3))
1650 * If it's not a redirect without any content,
1651 * set the Content-Type to text/html if it's
1652 * not already specified.
1654 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1658 * Fill in the rest of the default headers:
1660 * Date: set to current date/time.
1661 * Last-Modified: set to date/time the page was last changed.
1662 * Expires: set to date/time page next needs reloading.
1663 * Cache-Control: set to "no-cache" if applicable.
1665 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1670 * Set Expires to about 10 min into the future so it'll get reloaded
1671 * occasionally, e.g. if Privoxy gets upgraded.
1676 get_http_time(0, buf, sizeof(buf));
1677 err = enlist_unique_header(rsp->headers, "Date", buf);
1680 /* Some date in the past. */
1681 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1685 get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1686 err = enlist_unique_header(rsp->headers, "Expires", buf);
1689 else if (!strncmpic(rsp->status, "302", 3))
1691 get_http_time(0, buf, sizeof(buf));
1692 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1697 * Setting "Cache-Control" to "no-cache" and "Expires" to
1698 * the current time doesn't exactly forbid caching, it just
1699 * requires the client to revalidate the cached copy.
1701 * If a temporary problem occurs and the user tries again after
1702 * getting Privoxy's error message, a compliant browser may set the
1703 * If-Modified-Since header with the content of the error page's
1704 * Last-Modified header. More often than not, the document on the server
1705 * is older than Privoxy's error message, the server would send status code
1706 * 304 and the browser would display the outdated error message again and again.
1708 * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1709 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1710 * and can be safely used to "revalidate" without getting a status code 304.
1712 * There is no need to let the useless If-Modified-Since header reach the
1713 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1715 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1717 get_http_time(0, buf, sizeof(buf));
1718 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1719 if (!strncmpic(rsp->status, "403", 3)
1720 || !strncmpic(rsp->status, "404", 3)
1721 || !strncmpic(rsp->status, "502", 3)
1722 || !strncmpic(rsp->status, "503", 3)
1723 || !strncmpic(rsp->status, "504", 3))
1725 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1729 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1731 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1732 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1735 if (!err && !(csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1737 err = enlist_unique_header(rsp->headers, "Connection", "close");
1743 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1745 free_http_response(rsp);
1746 return cgi_error_memory();
1748 rsp->head_length = strlen(rsp->head);
1755 /*********************************************************************
1757 * Function : alloc_http_response
1759 * Description : Allocates a new http_response structure.
1763 * Returns : pointer to a new http_response, or NULL.
1765 *********************************************************************/
1766 struct http_response *alloc_http_response(void)
1768 return (struct http_response *) zalloc(sizeof(struct http_response));
1773 /*********************************************************************
1775 * Function : free_http_response
1777 * Description : Free the memory occupied by an http_response
1778 * and its depandant structures.
1781 * 1 : rsp = pointer to http_response to be freed
1785 *********************************************************************/
1786 void free_http_response(struct http_response *rsp)
1789 * Must special case cgi_error_memory_response, which is never freed.
1791 if (rsp && (rsp != cgi_error_memory_response))
1796 destroy_list(rsp->headers);
1803 /*********************************************************************
1805 * Function : template_load
1807 * Description : CGI support function that loads a given HTML
1808 * template, ignoring comment lines and following
1809 * #include statements up to a depth of 1.
1812 * 1 : csp = Current client state (buffers, headers, etc...)
1813 * 2 : template_ptr = Destination for pointer to loaded
1815 * 3 : templatename = name of the HTML template to be used
1816 * 4 : recursive = Flag set if this function calls itself
1817 * following an #include statament
1819 * Returns : JB_ERR_OK on success
1820 * JB_ERR_MEMORY on out-of-memory error.
1821 * JB_ERR_FILE if the template file cannot be read
1823 *********************************************************************/
1824 jb_err template_load(const struct client_state *csp, char **template_ptr,
1825 const char *templatename, int recursive)
1828 char *templates_dir_path;
1831 char *included_module;
1834 char buf[BUFFER_SIZE];
1837 assert(template_ptr);
1838 assert(templatename);
1840 *template_ptr = NULL;
1842 /* Validate template name. Paranoia. */
1843 for (p = templatename; *p != 0; p++)
1845 if ( ((*p < 'a') || (*p > 'z'))
1846 && ((*p < 'A') || (*p > 'Z'))
1847 && ((*p < '0') || (*p > '9'))
1851 /* Illegal character */
1857 * Generate full path using either templdir
1858 * or confdir/templates as base directory.
1860 if (NULL != csp->config->templdir)
1862 templates_dir_path = strdup(csp->config->templdir);
1866 templates_dir_path = make_path(csp->config->confdir, "templates");
1869 if (templates_dir_path == NULL)
1871 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1873 return JB_ERR_MEMORY;
1876 full_path = make_path(templates_dir_path, templatename);
1877 free(templates_dir_path);
1878 if (full_path == NULL)
1880 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1882 return JB_ERR_MEMORY;
1885 /* Allocate buffer */
1887 file_buffer = strdup("");
1888 if (file_buffer == NULL)
1890 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1892 return JB_ERR_MEMORY;
1895 /* Open template file */
1897 if (NULL == (fp = fopen(full_path, "r")))
1899 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1907 * Read the file, ignoring comments, and honoring #include
1908 * statements, unless we're already called recursively.
1910 * XXX: The comment handling could break with lines lengths > sizeof(buf).
1911 * This is unlikely in practise.
1913 while (fgets(buf, sizeof(buf), fp))
1915 if (!recursive && !strncmp(buf, "#include ", 9))
1917 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1924 if (string_join(&file_buffer, included_module))
1927 return JB_ERR_MEMORY;
1933 /* skip lines starting with '#' */
1939 if (string_append(&file_buffer, buf))
1942 return JB_ERR_MEMORY;
1947 *template_ptr = file_buffer;
1953 /*********************************************************************
1955 * Function : template_fill
1957 * Description : CGI support function that fills in a pre-loaded
1958 * HTML template by replacing @name@ with value using
1959 * pcrs, for each item in the output map.
1961 * Note that a leading '$' character in the export map's
1962 * values will be stripped and toggle on backreference
1966 * 1 : template_ptr = IN: Template to be filled out.
1968 * OUT: Filled out template.
1969 * Caller must free().
1970 * 2 : exports = map with fill in symbol -> name pairs
1972 * Returns : JB_ERR_OK on success (and for uncritical errors)
1973 * JB_ERR_MEMORY on out-of-memory error
1975 *********************************************************************/
1976 jb_err template_fill(char **template_ptr, const struct map *exports)
1978 struct map_entry *m;
1980 char buf[BUFFER_SIZE];
1981 char *tmp_out_buffer;
1987 assert(template_ptr);
1988 assert(*template_ptr);
1991 file_buffer = *template_ptr;
1992 size = strlen(file_buffer) + 1;
1995 * Assemble pcrs joblist from exports map
1997 for (m = exports->first; m != NULL; m = m->next)
1999 if (*m->name == '$')
2002 * First character of name is '$', so remove this flag
2003 * character and allow backreferences ($1 etc) in the
2004 * "replace with" text.
2006 snprintf(buf, sizeof(buf), "%s", m->name + 1);
2012 * Treat the "replace with" text as a literal string -
2013 * no quoting needed, no backreferences allowed.
2014 * ("Trivial" ['T'] flag).
2018 /* Enclose name in @@ */
2019 snprintf(buf, sizeof(buf), "@%s@", m->name);
2022 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
2024 /* Make and run job. */
2025 job = pcrs_compile(buf, m->value, flags, &error);
2028 if (error == PCRS_ERR_NOMEM)
2031 *template_ptr = NULL;
2032 return JB_ERR_MEMORY;
2036 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2037 /* Hope it wasn't important and silently ignore the invalid job */
2042 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2045 if (NULL == tmp_out_buffer)
2047 *template_ptr = NULL;
2048 return JB_ERR_MEMORY;
2054 * Substitution failed, keep the original buffer,
2055 * log the problem and ignore it.
2057 * The user might see some unresolved @CGI_VARIABLES@,
2058 * but returning a special CGI error page seems unreasonable
2059 * and could mask more important error messages.
2061 free(tmp_out_buffer);
2062 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
2063 buf, m->value, flags, pcrs_strerror(error));
2067 /* Substitution succeeded, use modified buffer. */
2069 file_buffer = tmp_out_buffer;
2077 *template_ptr = file_buffer;
2082 /*********************************************************************
2084 * Function : template_fill_for_cgi
2086 * Description : CGI support function that loads a HTML template
2087 * and fills it in. Handles file-not-found errors
2088 * by sending a HTML error message. For convenience,
2089 * this function also frees the passed "exports" map.
2092 * 1 : csp = Client state
2093 * 2 : templatename = name of the HTML template to be used
2094 * 3 : exports = map with fill in symbol -> name pairs.
2095 * Will be freed by this function.
2096 * 4 : rsp = Response structure to fill in.
2098 * Returns : JB_ERR_OK on success
2099 * JB_ERR_MEMORY on out-of-memory error
2101 *********************************************************************/
2102 jb_err template_fill_for_cgi(const struct client_state *csp,
2103 const char *templatename,
2104 struct map *exports,
2105 struct http_response *rsp)
2110 assert(templatename);
2114 err = template_load(csp, &rsp->body, templatename, 0);
2115 if (err == JB_ERR_FILE)
2118 return cgi_error_no_template(csp, rsp, templatename);
2123 return err; /* JB_ERR_MEMORY */
2125 err = template_fill(&rsp->body, exports);
2131 /*********************************************************************
2133 * Function : default_exports
2135 * Description : returns a struct map list that contains exports
2136 * which are common to all CGI functions.
2139 * 1 : csp = Current client state (buffers, headers, etc...)
2140 * 2 : caller = name of CGI who calls us and which should
2141 * be excluded from the generated menu. May be
2143 * Returns : NULL if no memory, else a new map. Caller frees.
2145 *********************************************************************/
2146 struct map *default_exports(const struct client_state *csp, const char *caller)
2150 struct map * exports;
2151 int local_help_exists = 0;
2152 char *ip_address = NULL;
2154 char *hostname = NULL;
2158 exports = new_map();
2159 if (exports == NULL)
2164 if (csp->config->hostname)
2166 get_host_information(csp->cfd, &ip_address, &port, NULL);
2167 hostname = strdup(csp->config->hostname);
2171 get_host_information(csp->cfd, &ip_address, &port, &hostname);
2174 err = map(exports, "version", 1, html_encode(VERSION), 0);
2175 get_locale_time(buf, sizeof(buf));
2176 if (!err) err = map(exports, "time", 1, html_encode(buf), 0);
2177 if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2179 if (!err) err = map(exports, "my-port", 1, html_encode(port ? port : "unknown"), 0);
2181 if (!err) err = map(exports, "my-hostname", 1, html_encode(hostname ? hostname : "unknown"), 0);
2183 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2184 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2185 if (!err) err = map(exports, "menu", 1, make_menu(caller, csp->config->feature_flags), 0);
2186 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2187 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2188 !strncmpic(csp->config->usermanual, "http", 4))
2190 /* Manual is located somewhere else, just link to it. */
2191 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2195 /* Manual is delivered by Privoxy. */
2196 if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2198 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2199 #ifdef FEATURE_TOGGLE
2200 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2202 if (!err) err = map_block_killer(exports, "can-toggle");
2205 if (!strcmp(CODE_STATUS, "stable"))
2207 if (!err) err = map_block_killer(exports, "unstable");
2210 if (csp->config->admin_address != NULL)
2212 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2213 local_help_exists = 1;
2217 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2220 if (csp->config->proxy_info_url != NULL)
2222 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2223 local_help_exists = 1;
2227 if (!err) err = map_block_killer(exports, "have-proxy-info");
2230 if (local_help_exists == 0)
2232 if (!err) err = map_block_killer(exports, "have-help-info");
2245 /*********************************************************************
2247 * Function : map_block_killer
2249 * Description : Convenience function.
2250 * Adds a "killer" for the conditional HTML-template
2251 * block <name>, i.e. a substitution of the regex
2252 * "if-<name>-start.*if-<name>-end" to the given
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_killer(struct map *exports, const char *name)
2265 char buf[1000]; /* Will do, since the names are hardwired */
2269 assert(strlen(name) < (size_t)490);
2271 snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2272 return map(exports, buf, 1, "", 1);
2276 /*********************************************************************
2278 * Function : map_block_keep
2280 * Description : Convenience function. Removes the markers used
2281 * by map-block-killer, to save a few bytes.
2282 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2285 * 1 : exports = map to extend
2286 * 2 : name = name of conditional block
2288 * Returns : JB_ERR_OK on success
2289 * JB_ERR_MEMORY on out-of-memory error.
2291 *********************************************************************/
2292 jb_err map_block_keep(struct map *exports, const char *name)
2295 char buf[500]; /* Will do, since the names are hardwired */
2299 assert(strlen(name) < (size_t)490);
2301 snprintf(buf, sizeof(buf), "if-%s-start", name);
2302 err = map(exports, buf, 1, "", 1);
2309 snprintf(buf, sizeof(buf), "if-%s-end", name);
2310 return map(exports, buf, 1, "", 1);
2314 /*********************************************************************
2316 * Function : map_conditional
2318 * Description : Convenience function.
2319 * Adds an "if-then-else" for the conditional HTML-template
2320 * block <name>, i.e. a substitution of the form:
2327 * The control structure and one of the alternatives
2331 * 1 : exports = map to extend
2332 * 2 : name = name of conditional block
2333 * 3 : choose_first = nonzero for first, zero for second.
2335 * Returns : JB_ERR_OK on success
2336 * JB_ERR_MEMORY on out-of-memory error.
2338 *********************************************************************/
2339 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2341 char buf[1000]; /* Will do, since the names are hardwired */
2346 assert(strlen(name) < (size_t)480);
2348 snprintf(buf, sizeof(buf), (choose_first
2349 ? "else-not-%s@.*@endif-%s"
2350 : "if-%s-then@.*@else-not-%s"),
2353 err = map(exports, buf, 1, "", 1);
2359 snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2360 return map(exports, buf, 1, "", 1);
2364 /*********************************************************************
2366 * Function : make_menu
2368 * Description : Returns an HTML-formatted menu of the available
2369 * unhidden CGIs, excluding the one given in <self>
2370 * and the toggle CGI if toggling is disabled.
2373 * 1 : self = name of CGI to leave out, can be NULL for
2375 * 2 : feature_flags = feature bitmap from csp->config
2378 * Returns : menu string, or NULL on out-of-memory error.
2380 *********************************************************************/
2381 char *make_menu(const char *self, const unsigned feature_flags)
2383 const struct cgi_dispatcher *d;
2384 char *result = strdup("");
2388 self = "NO-SUCH-CGI!";
2391 /* List available unhidden CGI's and export as "other-cgis" */
2392 for (d = cgi_dispatchers; d->name; d++)
2395 #ifdef FEATURE_TOGGLE
2396 if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2399 * Suppress the toggle link if remote toggling is disabled.
2403 #endif /* def FEATURE_TOGGLE */
2405 if (d->description && strcmp(d->name, self))
2407 char *html_encoded_prefix;
2410 * Line breaks would be great, but break
2411 * the "blocked" template's JavaScript.
2413 string_append(&result, "<li><a href=\"");
2414 html_encoded_prefix = html_encode(CGI_PREFIX);
2415 if (html_encoded_prefix == NULL)
2421 string_append(&result, html_encoded_prefix);
2422 free(html_encoded_prefix);
2424 string_append(&result, d->name);
2425 string_append(&result, "\">");
2426 string_append(&result, d->description);
2427 string_append(&result, "</a></li>");
2435 /*********************************************************************
2437 * Function : dump_map
2439 * Description : HTML-dump a map for debugging (as table)
2442 * 1 : the_map = map to dump
2444 * Returns : string with HTML
2446 *********************************************************************/
2447 char *dump_map(const struct map *the_map)
2449 struct map_entry *cur_entry;
2450 char *ret = strdup("");
2452 string_append(&ret, "<table>\n");
2454 for (cur_entry = the_map->first;
2455 (cur_entry != NULL) && (ret != NULL);
2456 cur_entry = cur_entry->next)
2458 string_append(&ret, "<tr><td><b>");
2459 string_join (&ret, html_encode(cur_entry->name));
2460 string_append(&ret, "</b></td><td>");
2461 string_join (&ret, html_encode(cur_entry->value));
2462 string_append(&ret, "</td></tr>\n");
2465 string_append(&ret, "</table>\n");