1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/cgi.c,v $
5 * Purpose : Declares functions to intercept request, generate
6 * html or gif answers, and to compose HTTP responses.
7 * This only contains the framework functions, the
8 * actual handler functions are declared elsewhere.
10 * Copyright : Written by and Copyright (C) 2001-2020
11 * members of the Privoxy team. https://www.privoxy.org/
13 * Based on the Internet Junkbuster originally written
14 * by and Copyright (C) 1997 Anonymous Coders and
15 * Junkbusters Corporation. http://www.junkbusters.com
17 * This program is free software; you can redistribute it
18 * and/or modify it under the terms of the GNU General
19 * Public License as published by the Free Software
20 * Foundation; either version 2 of the License, or (at
21 * your option) any later version.
23 * This program is distributed in the hope that it will
24 * be useful, but WITHOUT ANY WARRANTY; without even the
25 * implied warranty of MERCHANTABILITY or FITNESS FOR A
26 * PARTICULAR PURPOSE. See the GNU General Public
27 * License for more details.
29 * The GNU General Public License should be included with
30 * this file. If not, you can view it at
31 * http://www.gnu.org/copyleft/gpl.html
32 * or write to the Free Software Foundation, Inc., 59
33 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35 **********************************************************************/
41 #include <sys/types.h>
48 #ifdef FEATURE_COMPRESSION
60 #include "cgisimple.h"
61 #include "jbsockets.h"
62 #if defined(FEATURE_CGI_EDIT_ACTIONS) || defined(FEATURE_TOGGLE)
64 #endif /* defined(FEATURE_CGI_EDIT_ACTIONS) || defined (FEATURE_TOGGLE) */
65 #ifdef FEATURE_HTTPS_INSPECTION
69 /* loadcfg.h is for global_toggle_state only */
71 /* jcc.h is for mutex semaphore globals only */
74 static char *make_menu(const struct client_state *csp, const char *self);
77 * List of CGI functions: name, handler, description
78 * Note: Do NOT use single quotes in the description;
79 * this will break the dynamic "blocked" template!
81 static const struct cgi_dispatcher cgi_dispatchers[] = {
86 #ifdef FEATURE_GRACEFUL_TERMINATION
89 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
90 "this is a one click Denial Of Service attack!!!</em>",
95 #ifdef FEATURE_CGI_EDIT_ACTIONS
96 "View & change the current configuration",
98 "View the current configuration",
101 #ifdef FEATURE_CLIENT_TAGS
103 * This is marked as harmless because despite the description
104 * used in the menu the actual toggling is done through another
105 * path ("/toggle-client-tag").
108 cgi_show_client_tags,
109 "View or toggle the tags that can be set based on the clients address",
114 "View the request headers",
118 "Look up which actions apply to a URL and why",
120 #ifdef FEATURE_TOGGLE
123 "Toggle Privoxy on or off",
125 #endif /* def FEATURE_TOGGLE */
126 #ifdef FEATURE_CLIENT_TAGS
127 { "toggle-client-tag",
128 cgi_toggle_client_tag,
132 #ifdef FEATURE_CGI_EDIT_ACTIONS
133 { "edit-actions", /* Edit the actions list */
136 { "eaa", /* Shortcut for edit-actions-add-url-form */
137 cgi_edit_actions_add_url_form,
139 { "eau", /* Shortcut for edit-actions-url-form */
140 cgi_edit_actions_url_form,
142 { "ear", /* Shortcut for edit-actions-remove-url-form */
143 cgi_edit_actions_remove_url_form,
145 { "eal", /* Shortcut for edit-actions-list */
146 cgi_edit_actions_list,
148 { "eafu", /* Shortcut for edit-actions-for-url */
149 cgi_edit_actions_for_url,
151 { "eas", /* Shortcut for edit-actions-submit */
152 cgi_edit_actions_submit,
154 { "easa", /* Shortcut for edit-actions-section-add */
155 cgi_edit_actions_section_add,
157 { "easr", /* Shortcut for edit-actions-section-remove */
158 cgi_edit_actions_section_remove,
160 { "eass", /* Shortcut for edit-actions-section-swap */
161 cgi_edit_actions_section_swap,
163 { "edit-actions-for-url",
164 cgi_edit_actions_for_url,
165 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
166 { "edit-actions-list",
167 cgi_edit_actions_list,
168 NULL, TRUE /* Edit the actions list */ },
169 { "edit-actions-submit",
170 cgi_edit_actions_submit,
171 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
172 { "edit-actions-url",
173 cgi_edit_actions_url,
174 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
175 { "edit-actions-url-form",
176 cgi_edit_actions_url_form,
177 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
178 { "edit-actions-add-url",
179 cgi_edit_actions_add_url,
180 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
181 { "edit-actions-add-url-form",
182 cgi_edit_actions_add_url_form,
183 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
184 { "edit-actions-remove-url",
185 cgi_edit_actions_remove_url,
186 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
187 { "edit-actions-remove-url-form",
188 cgi_edit_actions_remove_url_form,
189 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
190 { "edit-actions-section-add",
191 cgi_edit_actions_section_add,
192 NULL, FALSE /* Remove a section from the actionsfile */ },
193 { "edit-actions-section-remove",
194 cgi_edit_actions_section_remove,
195 NULL, FALSE /* Remove a section from the actionsfile */ },
196 { "edit-actions-section-swap",
197 cgi_edit_actions_section_swap,
198 NULL, FALSE /* Swap two sections in the actionsfile */ },
199 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
200 { "error-favicon.ico",
201 cgi_send_error_favicon,
202 NULL, TRUE /* Sends the favicon image for error pages. */ },
204 cgi_send_default_favicon,
205 NULL, TRUE /* Sends the default favicon image. */ },
208 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
211 NULL, TRUE /* Send a built-in image */ },
214 NULL, FALSE /* Send templates/cgi-style.css */ },
216 cgi_transparent_image,
217 NULL, TRUE /* Send a transparent image (short name) */ },
218 { "url-info-osd.xml",
219 cgi_send_url_info_osd,
220 NULL, TRUE /* Send templates/url-info-osd.xml */ },
222 cgi_send_user_manual,
223 NULL, TRUE /* Send user-manual */ },
224 { NULL, /* NULL Indicates end of list and default page */
226 NULL, TRUE /* Unknown CGI page */ }
231 * Built-in images for ad replacement
233 * Hint: You can encode your own images like this:
234 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
237 #ifdef FEATURE_NO_GIFS
240 * Checkerboard pattern, as a PNG.
242 const char image_pattern_data[] =
243 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
244 "\122\000\000\000\004\000\000\000\004\010\006\000\000\000\251"
245 "\361\236\176\000\000\000\006\142\113\107\104\000\000\000\000"
246 "\000\000\371\103\273\177\000\000\000\033\111\104\101\124\010"
247 "\327\143\140\140\140\060\377\377\377\077\003\234\106\341\060"
248 "\060\230\063\020\124\001\000\161\021\031\241\034\364\030\143"
249 "\000\000\000\000\111\105\116\104\256\102\140\202";
252 * 1x1 transparent PNG.
254 const char image_blank_data[] =
255 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
256 "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
257 "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
258 "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
259 "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
260 "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
261 "\000\000\000\000\111\105\116\104\256\102\140\202";
265 * Checkerboard pattern, as a GIF.
267 const char image_pattern_data[] =
268 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
269 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
270 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
271 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
275 * 1x1 transparent GIF.
277 const char image_blank_data[] =
278 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
279 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
280 "\000\001\000\000\002\002D\001\000;";
283 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
284 const size_t image_blank_length = sizeof(image_blank_data) - 1;
286 #ifdef FEATURE_COMPRESSION
288 * Minimum length which a buffer has to reach before
289 * we bother to (re-)compress it. Completely arbitrary.
291 const size_t LOWER_LENGTH_LIMIT_FOR_COMPRESSION = 1024U;
294 static struct http_response cgi_error_memory_response[1];
296 static struct http_response *dispatch_known_cgi(struct client_state * csp,
298 static struct map *parse_cgi_parameters(char *argstring);
301 /*********************************************************************
303 * Function : dispatch_cgi
305 * Description : Checks if a request URL has either the magical
306 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
307 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
308 * http://config.privoxy.org/). If so, it passes
309 * the (rest of the) path onto dispatch_known_cgi, which
310 * calls the relevant CGI handler function.
313 * 1 : csp = Current client state (buffers, headers, etc...)
315 * Returns : http_response if match, NULL if nonmatch or handler fail
317 *********************************************************************/
318 struct http_response *dispatch_cgi(struct client_state *csp)
320 const char *host = csp->http->host;
321 const char *path = csp->http->path;
324 * Should we intercept ?
327 /* Note: "example.com" and "example.com." are equivalent hostnames. */
329 /* Either the host matches CGI_SITE_1_HOST ..*/
330 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
331 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
334 /* ..then the path will all be for us. Remove leading '/' */
337 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
338 else if (( (0 == strcmpic(host, CGI_SITE_2_HOST))
339 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
340 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))))
342 /* take everything following CGI_SITE_2_PATH */
343 path += strlen(CGI_SITE_2_PATH);
346 /* skip the forward slash after CGI_SITE_2_PATH */
349 else if (*path != '\0')
352 * weirdness: URL is /configXXX, where XXX is some string
353 * Do *NOT* intercept.
364 if (strcmpic(csp->http->gpc, "GET")
365 && strcmpic(csp->http->gpc, "HEAD"))
367 log_error(LOG_LEVEL_ERROR,
368 "CGI request with unsupported method received: %s", csp->http->gpc);
370 * The CGI pages currently only support GET and HEAD requests.
372 * If the client used a different method, ditch any data following
373 * the current headers to reduce the likelihood of parse errors
374 * with the following request.
376 csp->client_iob->eod = csp->client_iob->cur;
380 * This is a CGI call.
383 return dispatch_known_cgi(csp, path);
387 /*********************************************************************
389 * Function : grep_cgi_referrer
391 * Description : Ugly provisorical fix that greps the value of the
392 * referer HTTP header field out of a linked list of
393 * strings like found at csp->headers. Will disappear
396 * FIXME: csp->headers ought to be csp->http->headers
397 * FIXME: Parsing all client header lines should
398 * happen right after the request is received!
401 * 1 : csp = Current client state (buffers, headers, etc...)
403 * Returns : pointer to value (no copy!), or NULL if none found.
405 *********************************************************************/
406 static char *grep_cgi_referrer(const struct client_state *csp)
408 struct list_entry *p;
409 struct list_entry *first_header =
410 #ifdef FEATURE_HTTPS_INSPECTION
411 client_use_ssl(csp) ? csp->https_headers->first :
415 for (p = first_header; p != NULL; p = p->next)
417 if (p->str == NULL) continue;
418 if (strncmpic(p->str, "Referer: ", 9) == 0)
420 return ((p->str) + 9);
428 /*********************************************************************
430 * Function : referrer_is_safe
432 * Description : Decides whether we trust the Referer for
433 * CGI pages which are only meant to be reachable
434 * through Privoxy's web interface directly.
437 * 1 : csp = Current client state (buffers, headers, etc...)
439 * Returns : TRUE if the referrer is safe, or
440 * FALSE if the referrer is unsafe or not set.
442 *********************************************************************/
443 static int referrer_is_safe(const struct client_state *csp)
446 static const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
447 static const char alt_prefix_https[] = "https://" CGI_SITE_1_HOST "/";
448 const char *trusted_cgi_referrer = csp->config->trusted_cgi_referrer;
450 referrer = grep_cgi_referrer(csp);
452 if (NULL == referrer)
454 /* No referrer, no access */
455 log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
458 else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1))
459 #ifdef FEATURE_HTTPS_INSPECTION
460 || (0 == strncmp(referrer, CGI_PREFIX_HTTPS, sizeof(CGI_PREFIX_HTTPS)-1))
461 || (0 == strncmp(referrer, alt_prefix_https, strlen(alt_prefix_https)))
463 || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix))))
465 /* Trustworthy referrer */
466 log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
467 csp->http->url, referrer);
471 else if ((trusted_cgi_referrer != NULL) && (0 == strncmp(referrer,
472 trusted_cgi_referrer, strlen(trusted_cgi_referrer))))
475 * After some more testing this block should be merged with
476 * the previous one or the log level should bedowngraded.
478 log_error(LOG_LEVEL_INFO, "Granting access to %s based on trusted referrer %s",
479 csp->http->url, referrer);
485 /* Untrustworthy referrer */
486 log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
487 csp->http->url, referrer);
494 /*********************************************************************
496 * Function : dispatch_known_cgi
498 * Description : Processes a CGI once dispatch_cgi has determined that
499 * it matches one of the magic prefixes. Parses the path
500 * as a cgi name plus query string, prepares a map that
501 * maps CGI parameter names to their values, initializes
502 * the http_response struct, and calls the relevant CGI
506 * 1 : csp = Current client state (buffers, headers, etc...)
507 * 2 : path = Path of CGI, with the CGI prefix removed.
508 * Should not have a leading "/".
510 * Returns : http_response, or NULL on handler failure or out of
513 *********************************************************************/
514 static struct http_response *dispatch_known_cgi(struct client_state * csp,
517 const struct cgi_dispatcher *d;
518 struct map *param_list;
519 struct http_response *rsp;
520 char *query_args_start;
524 if (NULL == (path_copy = strdup(path)))
526 return cgi_error_memory();
528 query_args_start = path_copy;
529 while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
533 if (*query_args_start == '/')
535 *query_args_start++ = '\0';
536 param_list = new_map();
537 err = map(param_list, "file", 1, url_decode(query_args_start), 0);
538 if (JB_ERR_OK != err) {
541 return cgi_error_memory();
546 if (*query_args_start == '?')
548 *query_args_start++ = '\0';
550 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
553 return cgi_error_memory();
559 * path_copy = CGI call name
560 * param_list = CGI params, as map
563 /* Get mem for response or fail*/
564 if (NULL == (rsp = alloc_http_response()))
567 free_map(param_list);
568 return cgi_error_memory();
572 * Find and start the right CGI function
577 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
580 * If the called CGI is either harmless, or referred
581 * from a trusted source, start it.
583 if (d->harmless || referrer_is_safe(csp))
585 err = (d->handler)(csp, rsp, param_list);
590 * Else, modify toggle calls so that they only display
591 * the status, and deny all other calls.
593 if (0 == strcmp(path_copy, "toggle"))
595 unmap(param_list, "set");
596 err = (d->handler)(csp, rsp, param_list);
600 err = cgi_error_disabled(csp, rsp);
605 free_map(param_list);
607 if (err == JB_ERR_CGI_PARAMS)
609 err = cgi_error_bad_param(csp, rsp);
611 if (err && (err != JB_ERR_MEMORY))
613 /* Unexpected error! Shouldn't get here */
614 log_error(LOG_LEVEL_ERROR,
615 "Unexpected CGI error %d in top-level handler. "
616 "Please file a bug report!", err);
617 err = cgi_error_unknown(csp, rsp, err);
622 rsp->crunch_reason = CGI_CALL;
623 return finish_http_response(csp, rsp);
627 /* Error in handler, probably out-of-memory */
628 free_http_response(rsp);
629 return cgi_error_memory();
637 /*********************************************************************
639 * Function : parse_cgi_parameters
641 * Description : Parse a URL-encoded argument string into name/value
642 * pairs and store them in a struct map list.
645 * 1 : argstring = string to be parsed. Will be trashed.
647 * Returns : pointer to param list, or NULL if out of memory.
649 *********************************************************************/
650 static struct map *parse_cgi_parameters(char *argstring)
655 struct map *cgi_params;
658 * XXX: This estimate is guaranteed to be high enough as we
659 * let ssplit() ignore empty fields, but also a bit wasteful.
660 * The same hack is used in get_last_url() so it looks like
661 * a real solution is needed.
663 size_t max_segments = strlen(argstring) / 2;
664 if (max_segments == 0)
667 * XXX: If the argstring is empty, there's really
668 * no point in creating a param list, but currently
669 * other parts of Privoxy depend on the list's existence.
673 vector = malloc_or_die(max_segments * sizeof(char *));
675 cgi_params = new_map();
678 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
679 * the fragment identifier along with the request, so we must
680 * cut it off here, so it won't pollute the CGI params:
682 if (NULL != (p = strchr(argstring, '#')))
687 pairs = ssplit(argstring, "&", vector, max_segments);
692 free_map(cgi_params);
696 for (i = 0; i < pairs; i++)
698 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
701 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
704 free_map(cgi_params);
717 /*********************************************************************
719 * Function : get_char_param
721 * Description : Get a single-character parameter passed to a CGI
725 * 1 : parameters = map of cgi parameters
726 * 2 : param_name = The name of the parameter to read
728 * Returns : Uppercase character on success, '\0' on error.
730 *********************************************************************/
731 char get_char_param(const struct map *parameters,
732 const char *param_name)
739 ch = *(lookup(parameters, param_name));
740 if ((ch >= 'a') && (ch <= 'z'))
742 ch = (char)(ch - 'a' + 'A');
749 /*********************************************************************
751 * Function : get_string_param
753 * Description : Get a string parameter, to be used as an
754 * ACTION_STRING or ACTION_MULTI parameter.
755 * Validates the input to prevent stupid/malicious
756 * users from corrupting their action file.
759 * 1 : parameters = map of cgi parameters
760 * 2 : param_name = The name of the parameter to read
761 * 3 : pparam = destination for parameter. Allocated as
762 * part of the map "parameters", so don't free it.
763 * Set to NULL if not specified.
765 * Returns : JB_ERR_OK on success, or if the parameter
767 * JB_ERR_MEMORY on out-of-memory.
768 * JB_ERR_CGI_PARAMS if the parameter is not valid.
770 *********************************************************************/
771 jb_err get_string_param(const struct map *parameters,
772 const char *param_name,
785 param = lookup(parameters, param_name);
791 if (strlen(param) >= CGI_PARAM_LEN_MAX)
796 * Note that the length limit is arbitrary, it just seems
797 * sensible to limit it to *something*. There's no
798 * technical reason for any limit at all.
800 return JB_ERR_CGI_PARAMS;
803 /* Check every character to see if it's legal */
805 while ((ch = *s++) != '\0')
807 if (((unsigned char)ch < (unsigned char)' ')
810 /* Probable hack attempt, or user accidentally used '}'. */
811 return JB_ERR_CGI_PARAMS;
822 /*********************************************************************
824 * Function : get_number_param
826 * Description : Get a non-negative integer from the parameters
827 * passed to a CGI function.
830 * 1 : csp = Current client state (buffers, headers, etc...)
831 * 2 : parameters = map of cgi parameters
832 * 3 : name = Name of CGI parameter to read
833 * 4 : pvalue = destination for value.
834 * Set to -1 on error.
836 * Returns : JB_ERR_OK on success
837 * JB_ERR_MEMORY on out-of-memory
838 * JB_ERR_CGI_PARAMS if the parameter was not specified
841 *********************************************************************/
842 jb_err get_number_param(struct client_state *csp,
843 const struct map *parameters,
857 param = lookup(parameters, name);
860 return JB_ERR_CGI_PARAMS;
863 *pvalue = (unsigned int)strtol(param, &endptr, 0);
866 return JB_ERR_CGI_PARAMS;
874 /*********************************************************************
876 * Function : error_response
878 * Description : returns an http_response that explains the reason
879 * why a request failed.
882 * 1 : csp = Current client state (buffers, headers, etc...)
883 * 2 : templatename = Which template should be used for the answer
885 * Returns : A http_response. If we run out of memory, this
886 * will be cgi_error_memory().
888 *********************************************************************/
889 struct http_response *error_response(struct client_state *csp,
890 const char *templatename)
893 struct http_response *rsp;
894 struct map *exports = default_exports(csp, NULL);
899 return cgi_error_memory();
902 if (NULL == (rsp = alloc_http_response()))
905 return cgi_error_memory();
908 #ifdef FEATURE_FORCE_LOAD
909 if (csp->flags & CSP_FLAG_FORCED)
911 path = strdup(FORCE_PREFIX);
914 #endif /* def FEATURE_FORCE_LOAD */
918 err = string_append(&path, csp->http->path);
920 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
921 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
922 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
923 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
926 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
929 /* Some failures, like "404 no such domain", don't have an IP address. */
930 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
938 free_http_response(rsp);
939 return cgi_error_memory();
942 if (!strcmp(templatename, "no-such-domain"))
944 rsp->status = strdup("404 No such domain");
945 rsp->crunch_reason = NO_SUCH_DOMAIN;
947 else if (!strcmp(templatename, "forwarding-failed"))
949 const struct forward_spec *fwd = forward_url(csp, csp->http);
950 char *socks_type = NULL;
953 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
954 /* Never get here - LOG_LEVEL_FATAL causes program exit */
958 * XXX: While the template is called forwarding-failed,
959 * it currently only handles socks forwarding failures.
962 assert(fwd->type != SOCKS_NONE);
965 * Map failure reason, forwarding type and forwarder.
967 if (NULL == csp->error_message)
970 * Either we forgot to record the failure reason,
971 * or the memory allocation failed.
973 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
974 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
976 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
979 * XXX: this is almost the same code as in cgi_show_url_info()
980 * and thus should be factored out and shared.
985 socks_type = "socks4-";
988 socks_type = "socks4a-";
991 socks_type = "socks5-";
994 socks_type = "socks5t-";
996 case FORWARD_WEBSERVER:
997 socks_type = "webserver-";
1000 log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
1003 if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
1004 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
1005 if ((NULL == csp->error_message) || err)
1008 free_http_response(rsp);
1009 return cgi_error_memory();
1012 rsp->status = strdup("503 Forwarding failure");
1013 rsp->crunch_reason = FORWARDING_FAILED;
1015 else if (!strcmp(templatename, "connect-failed"))
1017 rsp->status = strdup("503 Connect failed");
1018 rsp->crunch_reason = CONNECT_FAILED;
1020 else if (!strcmp(templatename, "connection-timeout"))
1022 rsp->status = strdup("504 Connection timeout");
1023 rsp->crunch_reason = CONNECTION_TIMEOUT;
1025 else if (!strcmp(templatename, "no-server-data"))
1027 rsp->status = strdup("502 No data received from server or forwarder");
1028 rsp->crunch_reason = NO_SERVER_DATA;
1031 if (rsp->status == NULL)
1034 free_http_response(rsp);
1035 return cgi_error_memory();
1038 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1041 free_http_response(rsp);
1042 return cgi_error_memory();
1045 return finish_http_response(csp, rsp);
1049 /*********************************************************************
1051 * Function : cgi_error_disabled
1053 * Description : CGI function that is called to generate an error
1054 * response if the actions editor or toggle CGI are
1055 * accessed despite having being disabled at compile-
1056 * or run-time, or if the user followed an untrusted link
1057 * to access a unsafe CGI feature that is only reachable
1058 * through Privoxy directly.
1061 * 1 : csp = Current client state (buffers, headers, etc...)
1062 * 2 : rsp = http_response data structure for output
1064 * CGI Parameters : none
1066 * Returns : JB_ERR_OK on success
1067 * JB_ERR_MEMORY on out-of-memory error.
1069 *********************************************************************/
1070 jb_err cgi_error_disabled(const struct client_state *csp,
1071 struct http_response *rsp)
1073 struct map *exports;
1078 rsp->status = strdup_or_die("403 Request not trusted or feature disabled");
1080 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1082 return JB_ERR_MEMORY;
1084 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1086 /* Not important enough to do anything */
1087 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1090 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1094 /*********************************************************************
1096 * Function : cgi_init_error_messages
1098 * Description : Call at the start of the program to initialize
1099 * the error message used by cgi_error_memory().
1105 *********************************************************************/
1106 void cgi_init_error_messages(void)
1108 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1109 cgi_error_memory_response->head =
1110 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1111 "Content-Type: text/html\r\n"
1113 cgi_error_memory_response->body =
1116 " <title>500 Internal Privoxy Error</title>\n"
1117 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1120 "<h1>500 Internal Privoxy Error</h1>\n"
1121 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\n"
1122 "<p>Please contact your proxy administrator, or try again later</p>\n"
1126 cgi_error_memory_response->head_length =
1127 strlen(cgi_error_memory_response->head);
1128 cgi_error_memory_response->content_length =
1129 strlen(cgi_error_memory_response->body);
1130 cgi_error_memory_response->crunch_reason = OUT_OF_MEMORY;
1134 /*********************************************************************
1136 * Function : cgi_error_memory
1138 * Description : Called if a CGI function runs out of memory.
1139 * Returns a statically-allocated error response.
1143 * Returns : http_response data structure for output. This is
1144 * statically allocated, for obvious reasons.
1146 *********************************************************************/
1147 struct http_response *cgi_error_memory(void)
1149 /* assert that it's been initialized. */
1150 assert(cgi_error_memory_response->head);
1152 return cgi_error_memory_response;
1156 /*********************************************************************
1158 * Function : cgi_error_no_template
1160 * Description : Almost-CGI function that is called if a template
1161 * cannot be loaded. Note this is not a true CGI,
1162 * it takes a template name rather than a map of
1166 * 1 : csp = Current client state (buffers, headers, etc...)
1167 * 2 : rsp = http_response data structure for output
1168 * 3 : template_name = Name of template that could not
1171 * Returns : JB_ERR_OK on success
1172 * JB_ERR_MEMORY on out-of-memory error.
1174 *********************************************************************/
1175 jb_err cgi_error_no_template(const struct client_state *csp,
1176 struct http_response *rsp,
1177 const char *template_name)
1179 static const char status[] =
1180 "500 Internal Privoxy Error";
1181 static const char body_prefix[] =
1184 " <title>500 Internal Privoxy Error</title>\n"
1185 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1188 "<h1>500 Internal Privoxy Error</h1>\n"
1189 "<p>Privoxy encountered an error while processing your request:</p>\n"
1190 "<p><b>Could not load template file <code>";
1191 static const char body_suffix[] =
1192 "</code> or one of its included components.</b></p>\n"
1193 "<p>Please contact your proxy administrator.</p>\n"
1194 "<p>If you are the proxy administrator, please put the required file(s)"
1195 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1196 "location of the <code><i>(confdir)</i></code> directory "
1197 "is specified in the main Privoxy <code>config</code> "
1198 "file. (It's typically the Privoxy install directory"
1200 ", or <code>/etc/privoxy/</code>"
1201 #endif /* ndef _WIN32 */
1205 const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1209 assert(template_name);
1211 /* Reset rsp, if needed */
1215 rsp->content_length = 0;
1216 rsp->head_length = 0;
1219 rsp->body = malloc_or_die(body_size);
1220 strlcpy(rsp->body, body_prefix, body_size);
1221 strlcat(rsp->body, template_name, body_size);
1222 strlcat(rsp->body, body_suffix, body_size);
1224 rsp->status = strdup(status);
1225 if (rsp->status == NULL)
1227 return JB_ERR_MEMORY;
1234 /*********************************************************************
1236 * Function : cgi_error_unknown
1238 * Description : Almost-CGI function that is called if an unexpected
1239 * error occurs in the top-level CGI dispatcher.
1240 * In this context, "unexpected" means "anything other
1241 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1242 * expected to handle all other errors internally,
1243 * since they can give more relevant error messages
1246 * Note this is not a true CGI, it takes an error
1247 * code rather than a map of parameters.
1250 * 1 : csp = Current client state (buffers, headers, etc...)
1251 * 2 : rsp = http_response data structure for output
1252 * 3 : error_to_report = Error code to report.
1254 * Returns : JB_ERR_OK on success
1255 * JB_ERR_MEMORY on out-of-memory error.
1257 *********************************************************************/
1258 jb_err cgi_error_unknown(const struct client_state *csp,
1259 struct http_response *rsp,
1260 jb_err error_to_report)
1262 static const char status[] =
1263 "500 Internal Privoxy Error";
1264 static const char body_prefix[] =
1267 " <title>500 Internal Privoxy Error</title>\n"
1268 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1271 "<h1>500 Internal Privoxy Error</h1>\n"
1272 "<p>Privoxy encountered an error while processing your request:</p>\n"
1273 "<p><b>Unexpected internal error: ";
1274 static const char body_suffix[] =
1277 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1278 "file a bug report</a>.</p>\n"
1281 /* Includes room for larger error numbers in the future. */
1282 const size_t body_size = sizeof(body_prefix) + sizeof(body_suffix) + 5;
1286 /* Reset rsp, if needed */
1290 rsp->content_length = 0;
1291 rsp->head_length = 0;
1293 rsp->crunch_reason = INTERNAL_ERROR;
1295 rsp->body = malloc_or_die(body_size);
1297 snprintf(rsp->body, body_size, "%s%d%s", body_prefix, error_to_report, body_suffix);
1299 rsp->status = strdup(status);
1300 if (rsp->status == NULL)
1302 return JB_ERR_MEMORY;
1309 /*********************************************************************
1311 * Function : cgi_error_bad_param
1313 * Description : CGI function that is called if the parameters
1314 * (query string) for a CGI were wrong.
1317 * 1 : csp = Current client state (buffers, headers, etc...)
1318 * 2 : rsp = http_response data structure for output
1320 * CGI Parameters : none
1322 * Returns : JB_ERR_OK on success
1323 * JB_ERR_MEMORY on out-of-memory error.
1325 *********************************************************************/
1326 jb_err cgi_error_bad_param(const struct client_state *csp,
1327 struct http_response *rsp)
1329 struct map *exports;
1334 if (NULL == (exports = default_exports(csp, NULL)))
1336 return JB_ERR_MEMORY;
1339 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1343 /*********************************************************************
1345 * Function : cgi_redirect
1347 * Description : CGI support function to generate a HTTP redirect
1351 * 1 : rsp = http_response data structure for output
1352 * 2 : target = string with the target URL
1354 * CGI Parameters : None
1356 * Returns : JB_ERR_OK on success
1357 * JB_ERR_MEMORY on out-of-memory error.
1359 *********************************************************************/
1360 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1367 err = enlist_unique_header(rsp->headers, "Location", target);
1369 rsp->status = strdup("302 Local Redirect from Privoxy");
1370 if (rsp->status == NULL)
1372 return JB_ERR_MEMORY;
1379 /*********************************************************************
1381 * Function : add_help_link
1383 * Description : Produce a copy of the string given as item,
1384 * embedded in an HTML link to its corresponding
1385 * section (item name in uppercase) in the actions
1386 * chapter of the user manual, (whose URL is given in
1387 * the config and defaults to our web site).
1389 * FIXME: I currently only work for actions, and would
1390 * like to be generalized for other topics.
1393 * 1 : item = item (will NOT be free()d.)
1394 * It is assumed to be HTML-safe.
1395 * 2 : config = The current configuration.
1397 * Returns : String with item embedded in link, or NULL on
1400 *********************************************************************/
1401 char *add_help_link(const char *item,
1402 struct configuration_spec *config)
1406 if (!item) return NULL;
1408 result = strdup("<a href=\"");
1409 if (!strncmpic(config->usermanual, "file://", 7) ||
1410 !strncmpic(config->usermanual, "http", 4))
1412 string_append(&result, config->usermanual);
1416 string_append(&result, "http://");
1417 string_append(&result, CGI_SITE_2_HOST);
1418 string_append(&result, "/user-manual/");
1420 string_append(&result, ACTIONS_HELP_PREFIX);
1421 string_join (&result, string_toupper(item));
1422 string_append(&result, "\">");
1423 string_append(&result, item);
1424 string_append(&result, "</a>");
1430 /*********************************************************************
1432 * Function : get_http_time
1434 * Description : Get the time in a format suitable for use in a
1435 * HTTP header - e.g.:
1436 * "Sun, 06 Nov 1994 08:49:37 GMT"
1439 * 1 : time_offset = Time returned will be current time
1440 * plus this number of seconds.
1441 * 2 : buf = Destination for result.
1442 * 3 : buffer_size = Size of the buffer above. Must be big
1443 * enough to hold 29 characters plus a
1448 *********************************************************************/
1449 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1452 time_t current_time;
1453 #if defined(HAVE_GMTIME_R)
1458 assert(buffer_size > (size_t)29);
1460 time(¤t_time);
1462 current_time += time_offset;
1464 /* get and save the gmt */
1466 t = gmtime_r(¤t_time, &dummy);
1467 #elif defined(MUTEX_LOCKS_AVAILABLE)
1468 privoxy_mutex_lock(&gmtime_mutex);
1469 t = gmtime(¤t_time);
1470 privoxy_mutex_unlock(&gmtime_mutex);
1472 t = gmtime(¤t_time);
1475 strftime(buf, buffer_size, "%a, %d %b %Y %H:%M:%S GMT", t);
1479 /*********************************************************************
1481 * Function : get_locale_time
1483 * Description : Get the time in a date(1)-like format
1484 * according to the current locale - e.g.:
1485 * "Fri Aug 29 19:37:12 CEST 2008"
1487 * XXX: Should we allow the user to change the format?
1490 * 1 : buf = Destination for result.
1491 * 2 : buffer_size = Size of the buffer above. Must be big
1492 * enough to hold 29 characters plus a
1497 *********************************************************************/
1498 static void get_locale_time(char *buf, size_t buffer_size)
1501 time_t current_time;
1502 #if defined(HAVE_LOCALTIME_R)
1507 assert(buffer_size > (size_t)29);
1509 time(¤t_time);
1511 #if HAVE_LOCALTIME_R
1512 timeptr = localtime_r(¤t_time, &dummy);
1513 #elif defined(MUTEX_LOCKS_AVAILABLE)
1514 privoxy_mutex_lock(&localtime_mutex);
1515 timeptr = localtime(¤t_time);
1516 privoxy_mutex_unlock(&localtime_mutex);
1518 timeptr = localtime(¤t_time);
1521 strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1526 #ifdef FEATURE_COMPRESSION
1527 /*********************************************************************
1529 * Function : compress_buffer
1531 * Description : Compresses the content of a buffer with zlib's deflate
1532 * Allocates a new buffer for the result, free'ing it is
1536 * 1 : buffer = buffer whose content should be compressed
1537 * 2 : buffer_length = length of the buffer
1538 * 3 : compression_level = compression level for compress2()
1540 * Returns : NULL on error, otherwise a pointer to the compressed
1541 * content of the input buffer.
1543 *********************************************************************/
1544 char *compress_buffer(char *buffer, size_t *buffer_length, int compression_level)
1546 char *compressed_buffer;
1548 assert(-1 <= compression_level && compression_level <= 9);
1550 /* Let zlib figure out the maximum length of the compressed data */
1551 new_length = compressBound((uLongf)*buffer_length);
1553 compressed_buffer = malloc_or_die(new_length);
1555 if (Z_OK != compress2((Bytef *)compressed_buffer, &new_length,
1556 (Bytef *)buffer, *buffer_length, compression_level))
1558 log_error(LOG_LEVEL_ERROR,
1559 "compress2() failed. Buffer size: %d, compression level: %d.",
1560 new_length, compression_level);
1561 freez(compressed_buffer);
1565 log_error(LOG_LEVEL_RE_FILTER,
1566 "Compressed content from %d to %d bytes. Compression level: %d",
1567 *buffer_length, new_length, compression_level);
1569 *buffer_length = (size_t)new_length;
1571 return compressed_buffer;
1577 /*********************************************************************
1579 * Function : finish_http_response
1581 * Description : Fill in the missing headers in an http response,
1582 * and flatten the headers to an http head.
1583 * For HEAD requests the body is freed once
1584 * the Content-Length header is set.
1587 * 1 : rsp = pointer to http_response to be processed
1589 * Returns : A http_response, usually the rsp parameter.
1590 * On error, free()s rsp and returns cgi_error_memory()
1592 *********************************************************************/
1593 struct http_response *finish_http_response(struct client_state *csp, struct http_response *rsp)
1595 char buf[BUFFER_SIZE];
1598 /* Special case - do NOT change this statically allocated response,
1599 * which is ready for output anyway.
1601 if (rsp == cgi_error_memory_response)
1607 * Add "Cross-origin resource sharing" (CORS) headers if enabled
1609 if (NULL != csp->config->cors_allowed_origin)
1611 enlist_unique_header(rsp->headers, "Access-Control-Allow-Origin",
1612 csp->config->cors_allowed_origin);
1613 enlist_unique_header(rsp->headers, "Access-Control-Allow-Methods", "GET,POST");
1614 enlist_unique_header(rsp->headers, "Access-Control-Allow-Headers", "X-Requested-With");
1615 enlist_unique_header(rsp->headers, "Access-Control-Max-Age", "86400");
1619 * Fill in the HTTP Status, using HTTP/1.1
1620 * unless the client asked for HTTP/1.0.
1622 snprintf(buf, sizeof(buf), "%s %s",
1623 strcmpic(csp->http->version, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1624 rsp->status ? rsp->status : "200 OK");
1625 err = enlist_first(rsp->headers, buf);
1628 * Set the Content-Length
1630 if (rsp->content_length == 0)
1632 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1635 #ifdef FEATURE_COMPRESSION
1636 if (!err && (csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
1637 && (rsp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
1639 char *compressed_content;
1641 compressed_content = compress_buffer(rsp->body, &rsp->content_length,
1642 csp->config->compression_level);
1643 if (NULL != compressed_content)
1646 rsp->body = compressed_content;
1647 err = enlist_unique_header(rsp->headers, "Content-Encoding", "deflate");
1654 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1656 * Signal serve() that the client will be able to figure out
1657 * the end of the response without having to close the connection.
1659 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1660 err = enlist(rsp->headers, buf);
1663 if (0 == strcmpic(csp->http->gpc, "head"))
1666 * The client only asked for the head. Dispose
1667 * the body and log an offensive message.
1669 * While it may seem to be a bit inefficient to
1670 * prepare the body if it isn't needed, it's the
1671 * only way to get the Content-Length right for
1672 * dynamic pages. We could have disposed the body
1673 * earlier, but not without duplicating the
1674 * Content-Length setting code above.
1676 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1678 rsp->content_length = 0;
1681 if (strncmpic(rsp->status, "302", 3))
1684 * If it's not a redirect without any content,
1685 * set the Content-Type to text/html if it's
1686 * not already specified.
1688 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1692 * Fill in the rest of the default headers:
1694 * Date: set to current date/time.
1695 * Last-Modified: set to date/time the page was last changed.
1696 * Expires: set to date/time page next needs reloading.
1697 * Cache-Control: set to "no-cache" if applicable.
1699 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1704 * Set Expires to about 10 min into the future so it'll get reloaded
1705 * occasionally, e.g. if Privoxy gets upgraded.
1710 get_http_time(0, buf, sizeof(buf));
1711 err = enlist_unique_header(rsp->headers, "Date", buf);
1714 /* Some date in the past. */
1715 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1719 get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1720 err = enlist_unique_header(rsp->headers, "Expires", buf);
1723 else if (!strncmpic(rsp->status, "302", 3))
1725 get_http_time(0, buf, sizeof(buf));
1726 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1731 * Setting "Cache-Control" to "no-cache" and "Expires" to
1732 * the current time doesn't exactly forbid caching, it just
1733 * requires the client to revalidate the cached copy.
1735 * If a temporary problem occurs and the user tries again after
1736 * getting Privoxy's error message, a compliant browser may set the
1737 * If-Modified-Since header with the content of the error page's
1738 * Last-Modified header. More often than not, the document on the server
1739 * is older than Privoxy's error message, the server would send status code
1740 * 304 and the browser would display the outdated error message again and again.
1742 * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1743 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1744 * and can be safely used to "revalidate" without getting a status code 304.
1746 * There is no need to let the useless If-Modified-Since header reach the
1747 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1749 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1751 get_http_time(0, buf, sizeof(buf));
1752 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1753 if (!strncmpic(rsp->status, "403", 3)
1754 || !strncmpic(rsp->status, "404", 3)
1755 || !strncmpic(rsp->status, "502", 3)
1756 || !strncmpic(rsp->status, "503", 3)
1757 || !strncmpic(rsp->status, "504", 3))
1759 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1763 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1765 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1766 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1769 if (!err && (!(csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1770 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)))
1772 err = enlist_unique_header(rsp->headers, "Connection", "close");
1778 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1780 free_http_response(rsp);
1781 return cgi_error_memory();
1783 rsp->head_length = strlen(rsp->head);
1790 /*********************************************************************
1792 * Function : alloc_http_response
1794 * Description : Allocates a new http_response structure.
1798 * Returns : pointer to a new http_response, or NULL.
1800 *********************************************************************/
1801 struct http_response *alloc_http_response(void)
1803 return (struct http_response *) zalloc(sizeof(struct http_response));
1808 /*********************************************************************
1810 * Function : free_http_response
1812 * Description : Free the memory occupied by an http_response
1813 * and its depandant structures.
1816 * 1 : rsp = pointer to http_response to be freed
1820 *********************************************************************/
1821 void free_http_response(struct http_response *rsp)
1824 * Must special case cgi_error_memory_response, which is never freed.
1826 if (rsp && (rsp != cgi_error_memory_response))
1831 destroy_list(rsp->headers);
1838 /*********************************************************************
1840 * Function : template_load
1842 * Description : CGI support function that loads a given HTML
1843 * template, ignoring comment lines and following
1844 * #include statements up to a depth of 1.
1847 * 1 : csp = Current client state (buffers, headers, etc...)
1848 * 2 : template_ptr = Destination for pointer to loaded
1850 * 3 : templatename = name of the HTML template to be used
1851 * 4 : recursive = Flag set if this function calls itself
1852 * following an #include statament
1854 * Returns : JB_ERR_OK on success
1855 * JB_ERR_MEMORY on out-of-memory error.
1856 * JB_ERR_FILE if the template file cannot be read
1858 *********************************************************************/
1859 jb_err template_load(const struct client_state *csp, char **template_ptr,
1860 const char *templatename, int recursive)
1863 char *templates_dir_path;
1866 char *included_module;
1869 char buf[BUFFER_SIZE];
1872 assert(template_ptr);
1873 assert(templatename);
1875 *template_ptr = NULL;
1877 /* Validate template name. Paranoia. */
1878 for (p = templatename; *p != 0; p++)
1880 if ( ((*p < 'a') || (*p > 'z'))
1881 && ((*p < 'A') || (*p > 'Z'))
1882 && ((*p < '0') || (*p > '9'))
1886 /* Illegal character */
1892 * Generate full path using either templdir
1893 * or confdir/templates as base directory.
1895 if (NULL != csp->config->templdir)
1897 templates_dir_path = strdup(csp->config->templdir);
1901 templates_dir_path = make_path(csp->config->confdir, "templates");
1904 if (templates_dir_path == NULL)
1906 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1908 return JB_ERR_MEMORY;
1911 full_path = make_path(templates_dir_path, templatename);
1912 free(templates_dir_path);
1913 if (full_path == NULL)
1915 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1917 return JB_ERR_MEMORY;
1920 /* Allocate buffer */
1922 file_buffer = strdup("");
1923 if (file_buffer == NULL)
1925 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1927 return JB_ERR_MEMORY;
1930 /* Open template file */
1932 if (NULL == (fp = fopen(full_path, "r")))
1934 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1942 * Read the file, ignoring comments, and honoring #include
1943 * statements, unless we're already called recursively.
1945 * XXX: The comment handling could break with lines lengths > sizeof(buf).
1946 * This is unlikely in practise.
1948 while (fgets(buf, sizeof(buf), fp))
1950 if (!recursive && !strncmp(buf, "#include ", 9))
1952 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1959 if (string_join(&file_buffer, included_module))
1962 return JB_ERR_MEMORY;
1968 /* skip lines starting with '#' */
1974 if (string_append(&file_buffer, buf))
1977 return JB_ERR_MEMORY;
1982 *template_ptr = file_buffer;
1988 /*********************************************************************
1990 * Function : template_fill
1992 * Description : CGI support function that fills in a pre-loaded
1993 * HTML template by replacing @name@ with value using
1994 * pcrs, for each item in the output map.
1996 * Note that a leading '$' character in the export map's
1997 * values will be stripped and toggle on backreference
2001 * 1 : template_ptr = IN: Template to be filled out.
2003 * OUT: Filled out template.
2004 * Caller must free().
2005 * 2 : exports = map with fill in symbol -> name pairs
2007 * Returns : JB_ERR_OK on success (and for uncritical errors)
2008 * JB_ERR_MEMORY on out-of-memory error
2010 *********************************************************************/
2011 jb_err template_fill(char **template_ptr, const struct map *exports)
2013 struct map_entry *m;
2015 char buf[BUFFER_SIZE];
2016 char *tmp_out_buffer;
2022 assert(template_ptr);
2023 assert(*template_ptr);
2026 file_buffer = *template_ptr;
2027 size = strlen(file_buffer) + 1;
2030 * Assemble pcrs joblist from exports map
2032 for (m = exports->first; m != NULL; m = m->next)
2034 if (*m->name == '$')
2037 * First character of name is '$', so remove this flag
2038 * character and allow backreferences ($1 etc) in the
2039 * "replace with" text.
2041 snprintf(buf, sizeof(buf), "%s", m->name + 1);
2047 * Treat the "replace with" text as a literal string -
2048 * no quoting needed, no backreferences allowed.
2049 * ("Trivial" ['T'] flag).
2053 /* Enclose name in @@ */
2054 snprintf(buf, sizeof(buf), "@%s@", m->name);
2057 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
2059 /* Make and run job. */
2060 job = pcrs_compile(buf, m->value, flags, &error);
2063 if (error == PCRS_ERR_NOMEM)
2066 *template_ptr = NULL;
2067 return JB_ERR_MEMORY;
2071 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2072 /* Hope it wasn't important and silently ignore the invalid job */
2077 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2080 if (NULL == tmp_out_buffer)
2082 *template_ptr = NULL;
2083 return JB_ERR_MEMORY;
2089 * Substitution failed, keep the original buffer,
2090 * log the problem and ignore it.
2092 * The user might see some unresolved @CGI_VARIABLES@,
2093 * but returning a special CGI error page seems unreasonable
2094 * and could mask more important error messages.
2096 free(tmp_out_buffer);
2097 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
2098 buf, m->value, flags, pcrs_strerror(error));
2102 /* Substitution succeeded, use modified buffer. */
2104 file_buffer = tmp_out_buffer;
2112 *template_ptr = file_buffer;
2117 /*********************************************************************
2119 * Function : template_fill_for_cgi
2121 * Description : CGI support function that loads a HTML template
2122 * and fills it in. Handles file-not-found errors
2123 * by sending a HTML error message. For convenience,
2124 * this function also frees the passed "exports" map.
2127 * 1 : csp = Client state
2128 * 2 : templatename = name of the HTML template to be used
2129 * 3 : exports = map with fill in symbol -> name pairs.
2130 * Will be freed by this function.
2131 * 4 : rsp = Response structure to fill in.
2133 * Returns : JB_ERR_OK on success
2134 * JB_ERR_MEMORY on out-of-memory error
2136 *********************************************************************/
2137 jb_err template_fill_for_cgi(const struct client_state *csp,
2138 const char *templatename,
2139 struct map *exports,
2140 struct http_response *rsp)
2145 assert(templatename);
2149 err = template_load(csp, &rsp->body, templatename, 0);
2150 if (err == JB_ERR_FILE)
2152 err = cgi_error_no_template(csp, rsp, templatename);
2154 else if (err == JB_ERR_OK)
2156 err = template_fill(&rsp->body, exports);
2163 /*********************************************************************
2165 * Function : default_exports
2167 * Description : returns a struct map list that contains exports
2168 * which are common to all CGI functions.
2171 * 1 : csp = Current client state (buffers, headers, etc...)
2172 * 2 : caller = name of CGI who calls us and which should
2173 * be excluded from the generated menu. May be
2175 * Returns : NULL if no memory, else a new map. Caller frees.
2177 *********************************************************************/
2178 struct map *default_exports(const struct client_state *csp, const char *caller)
2182 struct map * exports;
2183 int local_help_exists = 0;
2184 char *ip_address = NULL;
2186 char *hostname = NULL;
2190 exports = new_map();
2192 if (csp->config->hostname)
2194 get_host_information(csp->cfd, &ip_address, &port, NULL);
2195 hostname = strdup(csp->config->hostname);
2199 get_host_information(csp->cfd, &ip_address, &port, &hostname);
2202 err = map(exports, "version", 1, html_encode(VERSION), 0);
2203 get_locale_time(buf, sizeof(buf));
2204 if (!err) err = map(exports, "time", 1, html_encode(buf), 0);
2205 if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2207 if (!err) err = map(exports, "my-port", 1, html_encode(port ? port : "unknown"), 0);
2209 if (!err) err = map(exports, "my-hostname", 1, html_encode(hostname ? hostname : "unknown"), 0);
2211 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2214 err = map(exports, "default-cgi", 1, html_encode(
2215 #ifdef FEATURE_HTTPS_INSPECTION
2216 client_use_ssl(csp) ? CGI_PREFIX_HTTPS :
2220 if (!err) err = map(exports, "menu", 1, make_menu(csp, caller), 0);
2221 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2222 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2223 !strncmpic(csp->config->usermanual, "http", 4))
2225 /* Manual is located somewhere else, just link to it. */
2226 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2230 /* Manual is delivered by Privoxy. */
2233 err = map(exports, "user-manual", 1, html_encode(
2234 #ifdef FEATURE_HTTPS_INSPECTION
2235 client_use_ssl(csp) ? CGI_PREFIX_HTTPS"user-manual/" :
2237 CGI_PREFIX"user-manual/"), 0);
2240 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2241 #ifdef FEATURE_TOGGLE
2242 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2244 if (!err) err = map_block_killer(exports, "can-toggle");
2247 if (!strcmp(CODE_STATUS, "stable"))
2249 if (!err) err = map_block_killer(exports, "unstable");
2252 if (csp->config->admin_address != NULL)
2254 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2255 local_help_exists = 1;
2259 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2262 if (csp->config->proxy_info_url != NULL)
2264 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2265 local_help_exists = 1;
2269 if (!err) err = map_block_killer(exports, "have-proxy-info");
2272 if (local_help_exists == 0)
2274 if (!err) err = map_block_killer(exports, "have-help-info");
2287 /*********************************************************************
2289 * Function : map_block_killer
2291 * Description : Convenience function.
2292 * Adds a "killer" for the conditional HTML-template
2293 * block <name>, i.e. a substitution of the regex
2294 * "if-<name>-start.*if-<name>-end" to the given
2298 * 1 : exports = map to extend
2299 * 2 : name = name of conditional block
2301 * Returns : JB_ERR_OK on success
2302 * JB_ERR_MEMORY on out-of-memory error.
2304 *********************************************************************/
2305 jb_err map_block_killer(struct map *exports, const char *name)
2307 char buf[1000]; /* Will do, since the names are hardwired */
2311 assert(strlen(name) < (size_t)490);
2313 snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2314 return map(exports, buf, 1, "", 1);
2318 /*********************************************************************
2320 * Function : map_block_keep
2322 * Description : Convenience function. Removes the markers used
2323 * by map-block-killer, to save a few bytes.
2324 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2327 * 1 : exports = map to extend
2328 * 2 : name = name of conditional block
2330 * Returns : JB_ERR_OK on success
2331 * JB_ERR_MEMORY on out-of-memory error.
2333 *********************************************************************/
2334 jb_err map_block_keep(struct map *exports, const char *name)
2337 char buf[500]; /* Will do, since the names are hardwired */
2341 assert(strlen(name) < (size_t)490);
2343 snprintf(buf, sizeof(buf), "if-%s-start", name);
2344 err = map(exports, buf, 1, "", 1);
2351 snprintf(buf, sizeof(buf), "if-%s-end", name);
2352 return map(exports, buf, 1, "", 1);
2356 /*********************************************************************
2358 * Function : map_conditional
2360 * Description : Convenience function.
2361 * Adds an "if-then-else" for the conditional HTML-template
2362 * block <name>, i.e. a substitution of the form:
2369 * The control structure and one of the alternatives
2373 * 1 : exports = map to extend
2374 * 2 : name = name of conditional block
2375 * 3 : choose_first = nonzero for first, zero for second.
2377 * Returns : JB_ERR_OK on success
2378 * JB_ERR_MEMORY on out-of-memory error.
2380 *********************************************************************/
2381 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2383 char buf[1000]; /* Will do, since the names are hardwired */
2388 assert(strlen(name) < (size_t)480);
2390 snprintf(buf, sizeof(buf), (choose_first
2391 ? "else-not-%s@.*@endif-%s"
2392 : "if-%s-then@.*@else-not-%s"),
2395 err = map(exports, buf, 1, "", 1);
2401 snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2402 return map(exports, buf, 1, "", 1);
2406 /*********************************************************************
2408 * Function : make_menu
2410 * Description : Returns an HTML-formatted menu of the available
2411 * unhidden CGIs, excluding the one given in <self>
2412 * and the toggle CGI if toggling is disabled.
2415 * 1 : csp = Current client state (buffers, headers, etc...)
2416 * 2 : self = name of CGI to leave out, can be NULL for
2419 * Returns : menu string, or NULL on out-of-memory error.
2421 *********************************************************************/
2422 char *make_menu(const struct client_state *csp, const char *self)
2424 const struct cgi_dispatcher *d;
2425 char *result = strdup("");
2429 self = "NO-SUCH-CGI!";
2432 /* List available unhidden CGI's and export as "other-cgis" */
2433 for (d = cgi_dispatchers; d->name; d++)
2436 #ifdef FEATURE_TOGGLE
2437 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2440 * Suppress the toggle link if remote toggling is disabled.
2444 #endif /* def FEATURE_TOGGLE */
2446 if (d->description && strcmp(d->name, self))
2448 char *html_encoded_prefix;
2451 * Line breaks would be great, but break
2452 * the "blocked" template's JavaScript.
2454 string_append(&result, "<li><a href=\"");
2455 html_encoded_prefix = html_encode(
2456 #ifdef FEATURE_HTTPS_INSPECTION
2457 client_use_ssl(csp) ? CGI_PREFIX_HTTPS :
2460 if (html_encoded_prefix == NULL)
2466 string_append(&result, html_encoded_prefix);
2467 free(html_encoded_prefix);
2469 string_append(&result, d->name);
2470 string_append(&result, "\">");
2471 string_append(&result, d->description);
2472 string_append(&result, "</a></li>");
2480 /*********************************************************************
2482 * Function : dump_map
2484 * Description : HTML-dump a map for debugging (as table)
2487 * 1 : the_map = map to dump
2489 * Returns : string with HTML
2491 *********************************************************************/
2492 char *dump_map(const struct map *the_map)
2494 struct map_entry *cur_entry;
2495 char *ret = strdup("");
2497 string_append(&ret, "<table>\n");
2499 for (cur_entry = the_map->first;
2500 (cur_entry != NULL) && (ret != NULL);
2501 cur_entry = cur_entry->next)
2503 string_append(&ret, "<tr><td><b>");
2504 string_join (&ret, html_encode(cur_entry->name));
2505 string_append(&ret, "</b></td><td>");
2506 string_join (&ret, html_encode(cur_entry->value));
2507 string_append(&ret, "</td></tr>\n");
2510 string_append(&ret, "</table>\n");