1 const char cgi_rcs[] = "$Id: cgi.c,v 1.170 2017/01/23 16:12:18 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-2017
12 * members of the 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",
103 #ifdef FEATURE_CLIENT_TAGS
105 * This is marked as harmless because despite the description
106 * used in the menu the actual toggling is done through another
107 * path ("/toggle-client-tag").
110 cgi_show_client_tags,
111 "View or toggle the tags that can be set based on the clients address",
116 "View the request headers",
120 "Look up which actions apply to a URL and why",
122 #ifdef FEATURE_TOGGLE
125 "Toggle Privoxy on or off",
127 #endif /* def FEATURE_TOGGLE */
128 #ifdef FEATURE_CLIENT_TAGS
129 { "toggle-client-tag",
130 cgi_toggle_client_tag,
134 #ifdef FEATURE_CGI_EDIT_ACTIONS
135 { "edit-actions", /* Edit the actions list */
138 { "eaa", /* Shortcut for edit-actions-add-url-form */
139 cgi_edit_actions_add_url_form,
141 { "eau", /* Shortcut for edit-actions-url-form */
142 cgi_edit_actions_url_form,
144 { "ear", /* Shortcut for edit-actions-remove-url-form */
145 cgi_edit_actions_remove_url_form,
147 { "eal", /* Shortcut for edit-actions-list */
148 cgi_edit_actions_list,
150 { "eafu", /* Shortcut for edit-actions-for-url */
151 cgi_edit_actions_for_url,
153 { "eas", /* Shortcut for edit-actions-submit */
154 cgi_edit_actions_submit,
156 { "easa", /* Shortcut for edit-actions-section-add */
157 cgi_edit_actions_section_add,
159 { "easr", /* Shortcut for edit-actions-section-remove */
160 cgi_edit_actions_section_remove,
162 { "eass", /* Shortcut for edit-actions-section-swap */
163 cgi_edit_actions_section_swap,
165 { "edit-actions-for-url",
166 cgi_edit_actions_for_url,
167 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
168 { "edit-actions-list",
169 cgi_edit_actions_list,
170 NULL, TRUE /* Edit the actions list */ },
171 { "edit-actions-submit",
172 cgi_edit_actions_submit,
173 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
174 { "edit-actions-url",
175 cgi_edit_actions_url,
176 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
177 { "edit-actions-url-form",
178 cgi_edit_actions_url_form,
179 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
180 { "edit-actions-add-url",
181 cgi_edit_actions_add_url,
182 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
183 { "edit-actions-add-url-form",
184 cgi_edit_actions_add_url_form,
185 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
186 { "edit-actions-remove-url",
187 cgi_edit_actions_remove_url,
188 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
189 { "edit-actions-remove-url-form",
190 cgi_edit_actions_remove_url_form,
191 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
192 { "edit-actions-section-add",
193 cgi_edit_actions_section_add,
194 NULL, FALSE /* Remove a section from the actionsfile */ },
195 { "edit-actions-section-remove",
196 cgi_edit_actions_section_remove,
197 NULL, FALSE /* Remove a section from the actionsfile */ },
198 { "edit-actions-section-swap",
199 cgi_edit_actions_section_swap,
200 NULL, FALSE /* Swap two sections in the actionsfile */ },
201 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
202 { "error-favicon.ico",
203 cgi_send_error_favicon,
204 NULL, TRUE /* Sends the favicon image for error pages. */ },
206 cgi_send_default_favicon,
207 NULL, TRUE /* Sends the default favicon image. */ },
210 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
213 NULL, TRUE /* Send a built-in image */ },
216 NULL, FALSE /* Send templates/cgi-style.css */ },
218 cgi_transparent_image,
219 NULL, TRUE /* Send a transparent image (short name) */ },
220 { "url-info-osd.xml",
221 cgi_send_url_info_osd,
222 NULL, TRUE /* Send templates/url-info-osd.xml */ },
224 cgi_send_user_manual,
225 NULL, TRUE /* Send user-manual */ },
226 { NULL, /* NULL Indicates end of list and default page */
228 NULL, TRUE /* Unknown CGI page */ }
233 * Built-in images for ad replacement
235 * Hint: You can encode your own images like this:
236 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
239 #ifdef FEATURE_NO_GIFS
242 * Checkerboard pattern, as a PNG.
244 const char image_pattern_data[] =
245 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
246 "\122\000\000\000\004\000\000\000\004\010\006\000\000\000\251"
247 "\361\236\176\000\000\000\006\142\113\107\104\000\000\000\000"
248 "\000\000\371\103\273\177\000\000\000\033\111\104\101\124\010"
249 "\327\143\140\140\140\060\377\377\377\077\003\234\106\341\060"
250 "\060\230\063\020\124\001\000\161\021\031\241\034\364\030\143"
251 "\000\000\000\000\111\105\116\104\256\102\140\202";
254 * 1x1 transparant PNG.
256 const char image_blank_data[] =
257 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
258 "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
259 "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
260 "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
261 "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
262 "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
263 "\000\000\000\000\111\105\116\104\256\102\140\202";
267 * Checkerboard pattern, as a GIF.
269 const char image_pattern_data[] =
270 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
271 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
272 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
273 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
277 * 1x1 transparant GIF.
279 const char image_blank_data[] =
280 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
281 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
282 "\000\001\000\000\002\002D\001\000;";
285 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
286 const size_t image_blank_length = sizeof(image_blank_data) - 1;
288 #ifdef FEATURE_COMPRESSION
290 * Minimum length which a buffer has to reach before
291 * we bother to (re-)compress it. Completely arbitrary.
293 const size_t LOWER_LENGTH_LIMIT_FOR_COMPRESSION = 1024U;
296 static struct http_response cgi_error_memory_response[1];
298 static struct http_response *dispatch_known_cgi(struct client_state * csp,
300 static struct map *parse_cgi_parameters(char *argstring);
303 /*********************************************************************
305 * Function : dispatch_cgi
307 * Description : Checks if a request URL has either the magical
308 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
309 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
310 * http://config.privoxy.org/). If so, it passes
311 * the (rest of the) path onto dispatch_known_cgi, which
312 * calls the relevant CGI handler function.
315 * 1 : csp = Current client state (buffers, headers, etc...)
317 * Returns : http_response if match, NULL if nonmatch or handler fail
319 *********************************************************************/
320 struct http_response *dispatch_cgi(struct client_state *csp)
322 const char *host = csp->http->host;
323 const char *path = csp->http->path;
326 * Should we intercept ?
329 /* Note: "example.com" and "example.com." are equivalent hostnames. */
331 /* Either the host matches CGI_SITE_1_HOST ..*/
332 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
333 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
336 /* ..then the path will all be for us. Remove leading '/' */
339 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
340 else if (( (0 == strcmpic(host, CGI_SITE_2_HOST))
341 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
342 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))))
344 /* take everything following CGI_SITE_2_PATH */
345 path += strlen(CGI_SITE_2_PATH);
348 /* skip the forward slash after CGI_SITE_2_PATH */
351 else if (*path != '\0')
354 * weirdness: URL is /configXXX, where XXX is some string
355 * Do *NOT* intercept.
366 if (strcmpic(csp->http->gpc, "GET")
367 && strcmpic(csp->http->gpc, "HEAD"))
369 log_error(LOG_LEVEL_ERROR,
370 "CGI request with unsupported method received: %s", csp->http->gpc);
372 * The CGI pages currently only support GET and HEAD requests.
374 * If the client used a different method, ditch any data following
375 * the current headers to reduce the likelihood of parse errors
376 * with the following request.
378 csp->client_iob->eod = csp->client_iob->cur;
382 * This is a CGI call.
385 return dispatch_known_cgi(csp, path);
389 /*********************************************************************
391 * Function : grep_cgi_referrer
393 * Description : Ugly provisorical fix that greps the value of the
394 * referer HTTP header field out of a linked list of
395 * strings like found at csp->headers. Will disappear
398 * FIXME: csp->headers ought to be csp->http->headers
399 * FIXME: Parsing all client header lines should
400 * happen right after the request is received!
403 * 1 : csp = Current client state (buffers, headers, etc...)
405 * Returns : pointer to value (no copy!), or NULL if none found.
407 *********************************************************************/
408 static char *grep_cgi_referrer(const struct client_state *csp)
410 struct list_entry *p;
412 for (p = csp->headers->first; p != NULL; p = p->next)
414 if (p->str == NULL) continue;
415 if (strncmpic(p->str, "Referer: ", 9) == 0)
417 return ((p->str) + 9);
425 /*********************************************************************
427 * Function : referrer_is_safe
429 * Description : Decides whether we trust the Referer for
430 * CGI pages which are only meant to be reachable
431 * through Privoxy's web interface directly.
434 * 1 : csp = Current client state (buffers, headers, etc...)
436 * Returns : TRUE if the referrer is safe, or
437 * FALSE if the referrer is unsafe or not set.
439 *********************************************************************/
440 static int referrer_is_safe(const struct client_state *csp)
443 static const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
444 const char *trusted_cgi_referrer = csp->config->trusted_cgi_referrer;
446 referrer = grep_cgi_referrer(csp);
448 if (NULL == referrer)
450 /* No referrer, no access */
451 log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
454 else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)
455 || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix)))))
457 /* Trustworthy referrer */
458 log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
459 csp->http->url, referrer);
463 else if ((trusted_cgi_referrer != NULL) && (0 == strncmp(referrer,
464 trusted_cgi_referrer, strlen(trusted_cgi_referrer))))
467 * After some more testing this block should be merged with
468 * the previous one or the log level should bedowngraded.
470 log_error(LOG_LEVEL_INFO, "Granting access to %s based on trusted referrer %s",
471 csp->http->url, referrer);
477 /* Untrustworthy referrer */
478 log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
479 csp->http->url, referrer);
486 /*********************************************************************
488 * Function : dispatch_known_cgi
490 * Description : Processes a CGI once dispatch_cgi has determined that
491 * it matches one of the magic prefixes. Parses the path
492 * as a cgi name plus query string, prepares a map that
493 * maps CGI parameter names to their values, initializes
494 * the http_response struct, and calls the relevant CGI
498 * 1 : csp = Current client state (buffers, headers, etc...)
499 * 2 : path = Path of CGI, with the CGI prefix removed.
500 * Should not have a leading "/".
502 * Returns : http_response, or NULL on handler failure or out of
505 *********************************************************************/
506 static struct http_response *dispatch_known_cgi(struct client_state * csp,
509 const struct cgi_dispatcher *d;
510 struct map *param_list;
511 struct http_response *rsp;
512 char *query_args_start;
516 if (NULL == (path_copy = strdup(path)))
518 return cgi_error_memory();
520 query_args_start = path_copy;
521 while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
525 if (*query_args_start == '/')
527 *query_args_start++ = '\0';
528 param_list = new_map();
529 err = map(param_list, "file", 1, url_decode(query_args_start), 0);
530 if (JB_ERR_OK != err) {
533 return cgi_error_memory();
538 if (*query_args_start == '?')
540 *query_args_start++ = '\0';
542 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
545 return cgi_error_memory();
551 * path_copy = CGI call name
552 * param_list = CGI params, as map
555 /* Get mem for response or fail*/
556 if (NULL == (rsp = alloc_http_response()))
559 free_map(param_list);
560 return cgi_error_memory();
564 * Find and start the right CGI function
569 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
572 * If the called CGI is either harmless, or referred
573 * from a trusted source, start it.
575 if (d->harmless || referrer_is_safe(csp))
577 err = (d->handler)(csp, rsp, param_list);
582 * Else, modify toggle calls so that they only display
583 * the status, and deny all other calls.
585 if (0 == strcmp(path_copy, "toggle"))
587 unmap(param_list, "set");
588 err = (d->handler)(csp, rsp, param_list);
592 err = cgi_error_disabled(csp, rsp);
597 free_map(param_list);
599 if (err == JB_ERR_CGI_PARAMS)
601 err = cgi_error_bad_param(csp, rsp);
603 if (err && (err != JB_ERR_MEMORY))
605 /* Unexpected error! Shouldn't get here */
606 log_error(LOG_LEVEL_ERROR,
607 "Unexpected CGI error %d in top-level handler. "
608 "Please file a bug report!", err);
609 err = cgi_error_unknown(csp, rsp, err);
614 rsp->crunch_reason = CGI_CALL;
615 return finish_http_response(csp, rsp);
619 /* Error in handler, probably out-of-memory */
620 free_http_response(rsp);
621 return cgi_error_memory();
629 /*********************************************************************
631 * Function : parse_cgi_parameters
633 * Description : Parse a URL-encoded argument string into name/value
634 * pairs and store them in a struct map list.
637 * 1 : argstring = string to be parsed. Will be trashed.
639 * Returns : pointer to param list, or NULL if out of memory.
641 *********************************************************************/
642 static struct map *parse_cgi_parameters(char *argstring)
647 struct map *cgi_params;
650 * XXX: This estimate is guaranteed to be high enough as we
651 * let ssplit() ignore empty fields, but also a bit wasteful.
652 * The same hack is used in get_last_url() so it looks like
653 * a real solution is needed.
655 size_t max_segments = strlen(argstring) / 2;
656 if (max_segments == 0)
659 * XXX: If the argstring is empty, there's really
660 * no point in creating a param list, but currently
661 * other parts of Privoxy depend on the list's existence.
665 vector = malloc_or_die(max_segments * sizeof(char *));
667 cgi_params = new_map();
670 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
671 * the fragment identifier along with the request, so we must
672 * cut it off here, so it won't pollute the CGI params:
674 if (NULL != (p = strchr(argstring, '#')))
679 pairs = ssplit(argstring, "&", vector, max_segments);
684 free_map(cgi_params);
688 for (i = 0; i < pairs; i++)
690 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
693 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
696 free_map(cgi_params);
709 /*********************************************************************
711 * Function : get_char_param
713 * Description : Get a single-character parameter passed to a CGI
717 * 1 : parameters = map of cgi parameters
718 * 2 : param_name = The name of the parameter to read
720 * Returns : Uppercase character on success, '\0' on error.
722 *********************************************************************/
723 char get_char_param(const struct map *parameters,
724 const char *param_name)
731 ch = *(lookup(parameters, param_name));
732 if ((ch >= 'a') && (ch <= 'z'))
734 ch = (char)(ch - 'a' + 'A');
741 /*********************************************************************
743 * Function : get_string_param
745 * Description : Get a string paramater, to be used as an
746 * ACTION_STRING or ACTION_MULTI paramater.
747 * Validates the input to prevent stupid/malicious
748 * users from corrupting their action file.
751 * 1 : parameters = map of cgi parameters
752 * 2 : param_name = The name of the parameter to read
753 * 3 : pparam = destination for paramater. Allocated as
754 * part of the map "parameters", so don't free it.
755 * Set to NULL if not specified.
757 * Returns : JB_ERR_OK on success, or if the paramater
759 * JB_ERR_MEMORY on out-of-memory.
760 * JB_ERR_CGI_PARAMS if the paramater is not valid.
762 *********************************************************************/
763 jb_err get_string_param(const struct map *parameters,
764 const char *param_name,
777 param = lookup(parameters, param_name);
783 if (strlen(param) >= CGI_PARAM_LEN_MAX)
788 * Note that the length limit is arbitrary, it just seems
789 * sensible to limit it to *something*. There's no
790 * technical reason for any limit at all.
792 return JB_ERR_CGI_PARAMS;
795 /* Check every character to see if it's legal */
797 while ((ch = *s++) != '\0')
799 if (((unsigned char)ch < (unsigned char)' ')
802 /* Probable hack attempt, or user accidentally used '}'. */
803 return JB_ERR_CGI_PARAMS;
814 /*********************************************************************
816 * Function : get_number_param
818 * Description : Get a non-negative integer from the parameters
819 * passed to a CGI function.
822 * 1 : csp = Current client state (buffers, headers, etc...)
823 * 2 : parameters = map of cgi parameters
824 * 3 : name = Name of CGI parameter to read
825 * 4 : pvalue = destination for value.
826 * Set to -1 on error.
828 * Returns : JB_ERR_OK on success
829 * JB_ERR_MEMORY on out-of-memory
830 * JB_ERR_CGI_PARAMS if the parameter was not specified
833 *********************************************************************/
834 jb_err get_number_param(struct client_state *csp,
835 const struct map *parameters,
849 param = lookup(parameters, name);
852 return JB_ERR_CGI_PARAMS;
855 *pvalue = (unsigned int)strtol(param, &endptr, 0);
858 return JB_ERR_CGI_PARAMS;
866 /*********************************************************************
868 * Function : error_response
870 * Description : returns an http_response that explains the reason
871 * why a request failed.
874 * 1 : csp = Current client state (buffers, headers, etc...)
875 * 2 : templatename = Which template should be used for the answer
877 * Returns : A http_response. If we run out of memory, this
878 * will be cgi_error_memory().
880 *********************************************************************/
881 struct http_response *error_response(struct client_state *csp,
882 const char *templatename)
885 struct http_response *rsp;
886 struct map *exports = default_exports(csp, NULL);
891 return cgi_error_memory();
894 if (NULL == (rsp = alloc_http_response()))
897 return cgi_error_memory();
900 #ifdef FEATURE_FORCE_LOAD
901 if (csp->flags & CSP_FLAG_FORCED)
903 path = strdup(FORCE_PREFIX);
906 #endif /* def FEATURE_FORCE_LOAD */
910 err = string_append(&path, csp->http->path);
912 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
913 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
914 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
915 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
918 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
921 /* Some failures, like "404 no such domain", don't have an IP address. */
922 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
930 free_http_response(rsp);
931 return cgi_error_memory();
934 if (!strcmp(templatename, "no-such-domain"))
936 rsp->status = strdup("404 No such domain");
937 rsp->crunch_reason = NO_SUCH_DOMAIN;
939 else if (!strcmp(templatename, "forwarding-failed"))
941 const struct forward_spec *fwd = forward_url(csp, csp->http);
942 char *socks_type = NULL;
945 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
946 /* Never get here - LOG_LEVEL_FATAL causes program exit */
950 * XXX: While the template is called forwarding-failed,
951 * it currently only handles socks forwarding failures.
954 assert(fwd->type != SOCKS_NONE);
957 * Map failure reason, forwarding type and forwarder.
959 if (NULL == csp->error_message)
962 * Either we forgot to record the failure reason,
963 * or the memory allocation failed.
965 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
966 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
968 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
971 * XXX: this is almost the same code as in cgi_show_url_info()
972 * and thus should be factored out and shared.
977 socks_type = "socks4-";
980 socks_type = "socks4a-";
983 socks_type = "socks5-";
986 socks_type = "socks5t-";
989 log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
992 if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
993 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
994 if ((NULL == csp->error_message) || err)
997 free_http_response(rsp);
998 return cgi_error_memory();
1001 rsp->status = strdup("503 Forwarding failure");
1002 rsp->crunch_reason = FORWARDING_FAILED;
1004 else if (!strcmp(templatename, "connect-failed"))
1006 rsp->status = strdup("503 Connect failed");
1007 rsp->crunch_reason = CONNECT_FAILED;
1009 else if (!strcmp(templatename, "connection-timeout"))
1011 rsp->status = strdup("504 Connection timeout");
1012 rsp->crunch_reason = CONNECTION_TIMEOUT;
1014 else if (!strcmp(templatename, "no-server-data"))
1016 rsp->status = strdup("502 No data received from server or forwarder");
1017 rsp->crunch_reason = NO_SERVER_DATA;
1020 if (rsp->status == NULL)
1023 free_http_response(rsp);
1024 return cgi_error_memory();
1027 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1030 free_http_response(rsp);
1031 return cgi_error_memory();
1034 return finish_http_response(csp, rsp);
1038 /*********************************************************************
1040 * Function : cgi_error_disabled
1042 * Description : CGI function that is called to generate an error
1043 * response if the actions editor or toggle CGI are
1044 * accessed despite having being disabled at compile-
1045 * or run-time, or if the user followed an untrusted link
1046 * to access a unsafe CGI feature that is only reachable
1047 * through Privoxy directly.
1050 * 1 : csp = Current client state (buffers, headers, etc...)
1051 * 2 : rsp = http_response data structure for output
1053 * CGI Parameters : none
1055 * Returns : JB_ERR_OK on success
1056 * JB_ERR_MEMORY on out-of-memory error.
1058 *********************************************************************/
1059 jb_err cgi_error_disabled(const struct client_state *csp,
1060 struct http_response *rsp)
1062 struct map *exports;
1067 rsp->status = strdup_or_die("403 Request not trusted or feature disabled");
1069 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1071 return JB_ERR_MEMORY;
1073 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1075 /* Not important enough to do anything */
1076 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1079 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1083 /*********************************************************************
1085 * Function : cgi_init_error_messages
1087 * Description : Call at the start of the program to initialize
1088 * the error message used by cgi_error_memory().
1094 *********************************************************************/
1095 void cgi_init_error_messages(void)
1097 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1098 cgi_error_memory_response->head =
1099 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1100 "Content-Type: text/html\r\n"
1102 cgi_error_memory_response->body =
1105 " <title>500 Internal Privoxy Error</title>\n"
1106 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1109 "<h1>500 Internal Privoxy Error</h1>\n"
1110 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\n"
1111 "<p>Please contact your proxy administrator, or try again later</p>\n"
1115 cgi_error_memory_response->head_length =
1116 strlen(cgi_error_memory_response->head);
1117 cgi_error_memory_response->content_length =
1118 strlen(cgi_error_memory_response->body);
1119 cgi_error_memory_response->crunch_reason = OUT_OF_MEMORY;
1123 /*********************************************************************
1125 * Function : cgi_error_memory
1127 * Description : Called if a CGI function runs out of memory.
1128 * Returns a statically-allocated error response.
1132 * Returns : http_response data structure for output. This is
1133 * statically allocated, for obvious reasons.
1135 *********************************************************************/
1136 struct http_response *cgi_error_memory(void)
1138 /* assert that it's been initialized. */
1139 assert(cgi_error_memory_response->head);
1141 return cgi_error_memory_response;
1145 /*********************************************************************
1147 * Function : cgi_error_no_template
1149 * Description : Almost-CGI function that is called if a template
1150 * cannot be loaded. Note this is not a true CGI,
1151 * it takes a template name rather than a map of
1155 * 1 : csp = Current client state (buffers, headers, etc...)
1156 * 2 : rsp = http_response data structure for output
1157 * 3 : template_name = Name of template that could not
1160 * Returns : JB_ERR_OK on success
1161 * JB_ERR_MEMORY on out-of-memory error.
1163 *********************************************************************/
1164 jb_err cgi_error_no_template(const struct client_state *csp,
1165 struct http_response *rsp,
1166 const char *template_name)
1168 static const char status[] =
1169 "500 Internal Privoxy Error";
1170 static const char body_prefix[] =
1173 " <title>500 Internal Privoxy Error</title>\n"
1174 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1177 "<h1>500 Internal Privoxy Error</h1>\n"
1178 "<p>Privoxy encountered an error while processing your request:</p>\n"
1179 "<p><b>Could not load template file <code>";
1180 static const char body_suffix[] =
1181 "</code> or one of its included components.</b></p>\n"
1182 "<p>Please contact your proxy administrator.</p>\n"
1183 "<p>If you are the proxy administrator, please put the required file(s)"
1184 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1185 "location of the <code><i>(confdir)</i></code> directory "
1186 "is specified in the main Privoxy <code>config</code> "
1187 "file. (It's typically the Privoxy install directory"
1189 ", or <code>/etc/privoxy/</code>"
1190 #endif /* ndef _WIN32 */
1194 const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1198 assert(template_name);
1200 /* Reset rsp, if needed */
1204 rsp->content_length = 0;
1205 rsp->head_length = 0;
1208 rsp->body = malloc_or_die(body_size);
1209 strlcpy(rsp->body, body_prefix, body_size);
1210 strlcat(rsp->body, template_name, body_size);
1211 strlcat(rsp->body, body_suffix, body_size);
1213 rsp->status = strdup(status);
1214 if (rsp->status == NULL)
1216 return JB_ERR_MEMORY;
1223 /*********************************************************************
1225 * Function : cgi_error_unknown
1227 * Description : Almost-CGI function that is called if an unexpected
1228 * error occurs in the top-level CGI dispatcher.
1229 * In this context, "unexpected" means "anything other
1230 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1231 * expected to handle all other errors internally,
1232 * since they can give more relavent error messages
1235 * Note this is not a true CGI, it takes an error
1236 * code rather than a map of parameters.
1239 * 1 : csp = Current client state (buffers, headers, etc...)
1240 * 2 : rsp = http_response data structure for output
1241 * 3 : error_to_report = Error code to report.
1243 * Returns : JB_ERR_OK on success
1244 * JB_ERR_MEMORY on out-of-memory error.
1246 *********************************************************************/
1247 jb_err cgi_error_unknown(const struct client_state *csp,
1248 struct http_response *rsp,
1249 jb_err error_to_report)
1251 static const char status[] =
1252 "500 Internal Privoxy Error";
1253 static const char body_prefix[] =
1256 " <title>500 Internal Privoxy Error</title>\n"
1257 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1260 "<h1>500 Internal Privoxy Error</h1>\n"
1261 "<p>Privoxy encountered an error while processing your request:</p>\n"
1262 "<p><b>Unexpected internal error: ";
1263 static const char body_suffix[] =
1266 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1267 "file a bug report</a>.</p>\n"
1270 /* Includes room for larger error numbers in the future. */
1271 const size_t body_size = sizeof(body_prefix) + sizeof(body_suffix) + 5;
1275 /* Reset rsp, if needed */
1279 rsp->content_length = 0;
1280 rsp->head_length = 0;
1282 rsp->crunch_reason = INTERNAL_ERROR;
1284 rsp->body = malloc_or_die(body_size);
1286 snprintf(rsp->body, body_size, "%s%d%s", body_prefix, error_to_report, body_suffix);
1288 rsp->status = strdup(status);
1289 if (rsp->status == NULL)
1291 return JB_ERR_MEMORY;
1298 /*********************************************************************
1300 * Function : cgi_error_bad_param
1302 * Description : CGI function that is called if the parameters
1303 * (query string) for a CGI were wrong.
1306 * 1 : csp = Current client state (buffers, headers, etc...)
1307 * 2 : rsp = http_response data structure for output
1309 * CGI Parameters : none
1311 * Returns : JB_ERR_OK on success
1312 * JB_ERR_MEMORY on out-of-memory error.
1314 *********************************************************************/
1315 jb_err cgi_error_bad_param(const struct client_state *csp,
1316 struct http_response *rsp)
1318 struct map *exports;
1323 if (NULL == (exports = default_exports(csp, NULL)))
1325 return JB_ERR_MEMORY;
1328 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1332 /*********************************************************************
1334 * Function : cgi_redirect
1336 * Description : CGI support function to generate a HTTP redirect
1340 * 1 : rsp = http_response data structure for output
1341 * 2 : target = string with the target URL
1343 * CGI Parameters : None
1345 * Returns : JB_ERR_OK on success
1346 * JB_ERR_MEMORY on out-of-memory error.
1348 *********************************************************************/
1349 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1356 err = enlist_unique_header(rsp->headers, "Location", target);
1358 rsp->status = strdup("302 Local Redirect from Privoxy");
1359 if (rsp->status == NULL)
1361 return JB_ERR_MEMORY;
1368 /*********************************************************************
1370 * Function : add_help_link
1372 * Description : Produce a copy of the string given as item,
1373 * embedded in an HTML link to its corresponding
1374 * section (item name in uppercase) in the actions
1375 * chapter of the user manual, (whose URL is given in
1376 * the config and defaults to our web site).
1378 * FIXME: I currently only work for actions, and would
1379 * like to be generalized for other topics.
1382 * 1 : item = item (will NOT be free()d.)
1383 * It is assumed to be HTML-safe.
1384 * 2 : config = The current configuration.
1386 * Returns : String with item embedded in link, or NULL on
1389 *********************************************************************/
1390 char *add_help_link(const char *item,
1391 struct configuration_spec *config)
1395 if (!item) return NULL;
1397 result = strdup("<a href=\"");
1398 if (!strncmpic(config->usermanual, "file://", 7) ||
1399 !strncmpic(config->usermanual, "http", 4))
1401 string_append(&result, config->usermanual);
1405 string_append(&result, "http://");
1406 string_append(&result, CGI_SITE_2_HOST);
1407 string_append(&result, "/user-manual/");
1409 string_append(&result, ACTIONS_HELP_PREFIX);
1410 string_join (&result, string_toupper(item));
1411 string_append(&result, "\">");
1412 string_append(&result, item);
1413 string_append(&result, "</a>");
1419 /*********************************************************************
1421 * Function : get_http_time
1423 * Description : Get the time in a format suitable for use in a
1424 * HTTP header - e.g.:
1425 * "Sun, 06 Nov 1994 08:49:37 GMT"
1428 * 1 : time_offset = Time returned will be current time
1429 * plus this number of seconds.
1430 * 2 : buf = Destination for result.
1431 * 3 : buffer_size = Size of the buffer above. Must be big
1432 * enough to hold 29 characters plus a
1437 *********************************************************************/
1438 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1441 time_t current_time;
1442 #if defined(HAVE_GMTIME_R)
1447 assert(buffer_size > (size_t)29);
1449 time(¤t_time);
1451 current_time += time_offset;
1453 /* get and save the gmt */
1455 t = gmtime_r(¤t_time, &dummy);
1456 #elif defined(MUTEX_LOCKS_AVAILABLE)
1457 privoxy_mutex_lock(&gmtime_mutex);
1458 t = gmtime(¤t_time);
1459 privoxy_mutex_unlock(&gmtime_mutex);
1461 t = gmtime(¤t_time);
1464 strftime(buf, buffer_size, "%a, %d %b %Y %H:%M:%S GMT", t);
1468 /*********************************************************************
1470 * Function : get_locale_time
1472 * Description : Get the time in a date(1)-like format
1473 * according to the current locale - e.g.:
1474 * "Fri Aug 29 19:37:12 CEST 2008"
1476 * XXX: Should we allow the user to change the format?
1479 * 1 : buf = Destination for result.
1480 * 2 : buffer_size = Size of the buffer above. Must be big
1481 * enough to hold 29 characters plus a
1486 *********************************************************************/
1487 static void get_locale_time(char *buf, size_t buffer_size)
1490 time_t current_time;
1491 #if defined(HAVE_LOCALTIME_R)
1496 assert(buffer_size > (size_t)29);
1498 time(¤t_time);
1500 #if HAVE_LOCALTIME_R
1501 timeptr = localtime_r(¤t_time, &dummy);
1502 #elif defined(MUTEX_LOCKS_AVAILABLE)
1503 privoxy_mutex_lock(&localtime_mutex);
1504 timeptr = localtime(¤t_time);
1505 privoxy_mutex_unlock(&localtime_mutex);
1507 timeptr = localtime(¤t_time);
1510 strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1515 #ifdef FEATURE_COMPRESSION
1516 /*********************************************************************
1518 * Function : compress_buffer
1520 * Description : Compresses the content of a buffer with zlib's deflate
1521 * Allocates a new buffer for the result, free'ing it is
1525 * 1 : buffer = buffer whose content should be compressed
1526 * 2 : buffer_length = length of the buffer
1527 * 3 : compression_level = compression level for compress2()
1529 * Returns : NULL on error, otherwise a pointer to the compressed
1530 * content of the input buffer.
1532 *********************************************************************/
1533 char *compress_buffer(char *buffer, size_t *buffer_length, int compression_level)
1535 char *compressed_buffer;
1537 assert(-1 <= compression_level && compression_level <= 9);
1539 /* Let zlib figure out the maximum length of the compressed data */
1540 new_length = compressBound((uLongf)*buffer_length);
1542 compressed_buffer = malloc_or_die(new_length);
1544 if (Z_OK != compress2((Bytef *)compressed_buffer, &new_length,
1545 (Bytef *)buffer, *buffer_length, compression_level))
1547 log_error(LOG_LEVEL_ERROR,
1548 "compress2() failed. Buffer size: %d, compression level: %d.",
1549 new_length, compression_level);
1550 freez(compressed_buffer);
1554 log_error(LOG_LEVEL_RE_FILTER,
1555 "Compressed content from %d to %d bytes. Compression level: %d",
1556 *buffer_length, new_length, compression_level);
1558 *buffer_length = (size_t)new_length;
1560 return compressed_buffer;
1566 /*********************************************************************
1568 * Function : finish_http_response
1570 * Description : Fill in the missing headers in an http response,
1571 * and flatten the headers to an http head.
1572 * For HEAD requests the body is freed once
1573 * the Content-Length header is set.
1576 * 1 : rsp = pointer to http_response to be processed
1578 * Returns : A http_response, usually the rsp parameter.
1579 * On error, free()s rsp and returns cgi_error_memory()
1581 *********************************************************************/
1582 struct http_response *finish_http_response(struct client_state *csp, struct http_response *rsp)
1584 char buf[BUFFER_SIZE];
1587 /* Special case - do NOT change this statically allocated response,
1588 * which is ready for output anyway.
1590 if (rsp == cgi_error_memory_response)
1596 * Fill in the HTTP Status, using HTTP/1.1
1597 * unless the client asked for HTTP/1.0.
1599 snprintf(buf, sizeof(buf), "%s %s",
1600 strcmpic(csp->http->ver, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1601 rsp->status ? rsp->status : "200 OK");
1602 err = enlist_first(rsp->headers, buf);
1605 * Set the Content-Length
1607 if (rsp->content_length == 0)
1609 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1612 #ifdef FEATURE_COMPRESSION
1613 if (!err && (csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
1614 && (rsp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
1616 char *compressed_content;
1618 compressed_content = compress_buffer(rsp->body, &rsp->content_length,
1619 csp->config->compression_level);
1620 if (NULL != compressed_content)
1623 rsp->body = compressed_content;
1624 err = enlist_unique_header(rsp->headers, "Content-Encoding", "deflate");
1631 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1633 * Signal serve() that the client will be able to figure out
1634 * the end of the response without having to close the connection.
1636 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1637 err = enlist(rsp->headers, buf);
1640 if (0 == strcmpic(csp->http->gpc, "head"))
1643 * The client only asked for the head. Dispose
1644 * the body and log an offensive message.
1646 * While it may seem to be a bit inefficient to
1647 * prepare the body if it isn't needed, it's the
1648 * only way to get the Content-Length right for
1649 * dynamic pages. We could have disposed the body
1650 * earlier, but not without duplicating the
1651 * Content-Length setting code above.
1653 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1655 rsp->content_length = 0;
1658 if (strncmpic(rsp->status, "302", 3))
1661 * If it's not a redirect without any content,
1662 * set the Content-Type to text/html if it's
1663 * not already specified.
1665 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1669 * Fill in the rest of the default headers:
1671 * Date: set to current date/time.
1672 * Last-Modified: set to date/time the page was last changed.
1673 * Expires: set to date/time page next needs reloading.
1674 * Cache-Control: set to "no-cache" if applicable.
1676 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1681 * Set Expires to about 10 min into the future so it'll get reloaded
1682 * occasionally, e.g. if Privoxy gets upgraded.
1687 get_http_time(0, buf, sizeof(buf));
1688 err = enlist_unique_header(rsp->headers, "Date", buf);
1691 /* Some date in the past. */
1692 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1696 get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1697 err = enlist_unique_header(rsp->headers, "Expires", buf);
1700 else if (!strncmpic(rsp->status, "302", 3))
1702 get_http_time(0, buf, sizeof(buf));
1703 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1708 * Setting "Cache-Control" to "no-cache" and "Expires" to
1709 * the current time doesn't exactly forbid caching, it just
1710 * requires the client to revalidate the cached copy.
1712 * If a temporary problem occurs and the user tries again after
1713 * getting Privoxy's error message, a compliant browser may set the
1714 * If-Modified-Since header with the content of the error page's
1715 * Last-Modified header. More often than not, the document on the server
1716 * is older than Privoxy's error message, the server would send status code
1717 * 304 and the browser would display the outdated error message again and again.
1719 * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1720 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1721 * and can be safely used to "revalidate" without getting a status code 304.
1723 * There is no need to let the useless If-Modified-Since header reach the
1724 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1726 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1728 get_http_time(0, buf, sizeof(buf));
1729 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1730 if (!strncmpic(rsp->status, "403", 3)
1731 || !strncmpic(rsp->status, "404", 3)
1732 || !strncmpic(rsp->status, "502", 3)
1733 || !strncmpic(rsp->status, "503", 3)
1734 || !strncmpic(rsp->status, "504", 3))
1736 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1740 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1742 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1743 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1746 if (!err && (!(csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1747 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)))
1749 err = enlist_unique_header(rsp->headers, "Connection", "close");
1755 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1757 free_http_response(rsp);
1758 return cgi_error_memory();
1760 rsp->head_length = strlen(rsp->head);
1767 /*********************************************************************
1769 * Function : alloc_http_response
1771 * Description : Allocates a new http_response structure.
1775 * Returns : pointer to a new http_response, or NULL.
1777 *********************************************************************/
1778 struct http_response *alloc_http_response(void)
1780 return (struct http_response *) zalloc(sizeof(struct http_response));
1785 /*********************************************************************
1787 * Function : free_http_response
1789 * Description : Free the memory occupied by an http_response
1790 * and its depandant structures.
1793 * 1 : rsp = pointer to http_response to be freed
1797 *********************************************************************/
1798 void free_http_response(struct http_response *rsp)
1801 * Must special case cgi_error_memory_response, which is never freed.
1803 if (rsp && (rsp != cgi_error_memory_response))
1808 destroy_list(rsp->headers);
1815 /*********************************************************************
1817 * Function : template_load
1819 * Description : CGI support function that loads a given HTML
1820 * template, ignoring comment lines and following
1821 * #include statements up to a depth of 1.
1824 * 1 : csp = Current client state (buffers, headers, etc...)
1825 * 2 : template_ptr = Destination for pointer to loaded
1827 * 3 : templatename = name of the HTML template to be used
1828 * 4 : recursive = Flag set if this function calls itself
1829 * following an #include statament
1831 * Returns : JB_ERR_OK on success
1832 * JB_ERR_MEMORY on out-of-memory error.
1833 * JB_ERR_FILE if the template file cannot be read
1835 *********************************************************************/
1836 jb_err template_load(const struct client_state *csp, char **template_ptr,
1837 const char *templatename, int recursive)
1840 char *templates_dir_path;
1843 char *included_module;
1846 char buf[BUFFER_SIZE];
1849 assert(template_ptr);
1850 assert(templatename);
1852 *template_ptr = NULL;
1854 /* Validate template name. Paranoia. */
1855 for (p = templatename; *p != 0; p++)
1857 if ( ((*p < 'a') || (*p > 'z'))
1858 && ((*p < 'A') || (*p > 'Z'))
1859 && ((*p < '0') || (*p > '9'))
1863 /* Illegal character */
1869 * Generate full path using either templdir
1870 * or confdir/templates as base directory.
1872 if (NULL != csp->config->templdir)
1874 templates_dir_path = strdup(csp->config->templdir);
1878 templates_dir_path = make_path(csp->config->confdir, "templates");
1881 if (templates_dir_path == NULL)
1883 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1885 return JB_ERR_MEMORY;
1888 full_path = make_path(templates_dir_path, templatename);
1889 free(templates_dir_path);
1890 if (full_path == NULL)
1892 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1894 return JB_ERR_MEMORY;
1897 /* Allocate buffer */
1899 file_buffer = strdup("");
1900 if (file_buffer == NULL)
1902 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1904 return JB_ERR_MEMORY;
1907 /* Open template file */
1909 if (NULL == (fp = fopen(full_path, "r")))
1911 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1919 * Read the file, ignoring comments, and honoring #include
1920 * statements, unless we're already called recursively.
1922 * XXX: The comment handling could break with lines lengths > sizeof(buf).
1923 * This is unlikely in practise.
1925 while (fgets(buf, sizeof(buf), fp))
1927 if (!recursive && !strncmp(buf, "#include ", 9))
1929 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1936 if (string_join(&file_buffer, included_module))
1939 return JB_ERR_MEMORY;
1945 /* skip lines starting with '#' */
1951 if (string_append(&file_buffer, buf))
1954 return JB_ERR_MEMORY;
1959 *template_ptr = file_buffer;
1965 /*********************************************************************
1967 * Function : template_fill
1969 * Description : CGI support function that fills in a pre-loaded
1970 * HTML template by replacing @name@ with value using
1971 * pcrs, for each item in the output map.
1973 * Note that a leading '$' character in the export map's
1974 * values will be stripped and toggle on backreference
1978 * 1 : template_ptr = IN: Template to be filled out.
1980 * OUT: Filled out template.
1981 * Caller must free().
1982 * 2 : exports = map with fill in symbol -> name pairs
1984 * Returns : JB_ERR_OK on success (and for uncritical errors)
1985 * JB_ERR_MEMORY on out-of-memory error
1987 *********************************************************************/
1988 jb_err template_fill(char **template_ptr, const struct map *exports)
1990 struct map_entry *m;
1992 char buf[BUFFER_SIZE];
1993 char *tmp_out_buffer;
1999 assert(template_ptr);
2000 assert(*template_ptr);
2003 file_buffer = *template_ptr;
2004 size = strlen(file_buffer) + 1;
2007 * Assemble pcrs joblist from exports map
2009 for (m = exports->first; m != NULL; m = m->next)
2011 if (*m->name == '$')
2014 * First character of name is '$', so remove this flag
2015 * character and allow backreferences ($1 etc) in the
2016 * "replace with" text.
2018 snprintf(buf, sizeof(buf), "%s", m->name + 1);
2024 * Treat the "replace with" text as a literal string -
2025 * no quoting needed, no backreferences allowed.
2026 * ("Trivial" ['T'] flag).
2030 /* Enclose name in @@ */
2031 snprintf(buf, sizeof(buf), "@%s@", m->name);
2034 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
2036 /* Make and run job. */
2037 job = pcrs_compile(buf, m->value, flags, &error);
2040 if (error == PCRS_ERR_NOMEM)
2043 *template_ptr = NULL;
2044 return JB_ERR_MEMORY;
2048 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2049 /* Hope it wasn't important and silently ignore the invalid job */
2054 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2057 if (NULL == tmp_out_buffer)
2059 *template_ptr = NULL;
2060 return JB_ERR_MEMORY;
2066 * Substitution failed, keep the original buffer,
2067 * log the problem and ignore it.
2069 * The user might see some unresolved @CGI_VARIABLES@,
2070 * but returning a special CGI error page seems unreasonable
2071 * and could mask more important error messages.
2073 free(tmp_out_buffer);
2074 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
2075 buf, m->value, flags, pcrs_strerror(error));
2079 /* Substitution succeeded, use modified buffer. */
2081 file_buffer = tmp_out_buffer;
2089 *template_ptr = file_buffer;
2094 /*********************************************************************
2096 * Function : template_fill_for_cgi
2098 * Description : CGI support function that loads a HTML template
2099 * and fills it in. Handles file-not-found errors
2100 * by sending a HTML error message. For convenience,
2101 * this function also frees the passed "exports" map.
2104 * 1 : csp = Client state
2105 * 2 : templatename = name of the HTML template to be used
2106 * 3 : exports = map with fill in symbol -> name pairs.
2107 * Will be freed by this function.
2108 * 4 : rsp = Response structure to fill in.
2110 * Returns : JB_ERR_OK on success
2111 * JB_ERR_MEMORY on out-of-memory error
2113 *********************************************************************/
2114 jb_err template_fill_for_cgi(const struct client_state *csp,
2115 const char *templatename,
2116 struct map *exports,
2117 struct http_response *rsp)
2122 assert(templatename);
2126 err = template_load(csp, &rsp->body, templatename, 0);
2127 if (err == JB_ERR_FILE)
2130 return cgi_error_no_template(csp, rsp, templatename);
2135 return err; /* JB_ERR_MEMORY */
2137 err = template_fill(&rsp->body, exports);
2143 /*********************************************************************
2145 * Function : default_exports
2147 * Description : returns a struct map list that contains exports
2148 * which are common to all CGI functions.
2151 * 1 : csp = Current client state (buffers, headers, etc...)
2152 * 2 : caller = name of CGI who calls us and which should
2153 * be excluded from the generated menu. May be
2155 * Returns : NULL if no memory, else a new map. Caller frees.
2157 *********************************************************************/
2158 struct map *default_exports(const struct client_state *csp, const char *caller)
2162 struct map * exports;
2163 int local_help_exists = 0;
2164 char *ip_address = NULL;
2166 char *hostname = NULL;
2170 exports = new_map();
2172 if (csp->config->hostname)
2174 get_host_information(csp->cfd, &ip_address, &port, NULL);
2175 hostname = strdup(csp->config->hostname);
2179 get_host_information(csp->cfd, &ip_address, &port, &hostname);
2182 err = map(exports, "version", 1, html_encode(VERSION), 0);
2183 get_locale_time(buf, sizeof(buf));
2184 if (!err) err = map(exports, "time", 1, html_encode(buf), 0);
2185 if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2187 if (!err) err = map(exports, "my-port", 1, html_encode(port ? port : "unknown"), 0);
2189 if (!err) err = map(exports, "my-hostname", 1, html_encode(hostname ? hostname : "unknown"), 0);
2191 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2192 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2193 if (!err) err = map(exports, "menu", 1, make_menu(caller, csp->config->feature_flags), 0);
2194 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2195 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2196 !strncmpic(csp->config->usermanual, "http", 4))
2198 /* Manual is located somewhere else, just link to it. */
2199 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2203 /* Manual is delivered by Privoxy. */
2204 if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2206 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2207 #ifdef FEATURE_TOGGLE
2208 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2210 if (!err) err = map_block_killer(exports, "can-toggle");
2213 if (!strcmp(CODE_STATUS, "stable"))
2215 if (!err) err = map_block_killer(exports, "unstable");
2218 if (csp->config->admin_address != NULL)
2220 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2221 local_help_exists = 1;
2225 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2228 if (csp->config->proxy_info_url != NULL)
2230 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2231 local_help_exists = 1;
2235 if (!err) err = map_block_killer(exports, "have-proxy-info");
2238 if (local_help_exists == 0)
2240 if (!err) err = map_block_killer(exports, "have-help-info");
2253 /*********************************************************************
2255 * Function : map_block_killer
2257 * Description : Convenience function.
2258 * Adds a "killer" for the conditional HTML-template
2259 * block <name>, i.e. a substitution of the regex
2260 * "if-<name>-start.*if-<name>-end" to the given
2264 * 1 : exports = map to extend
2265 * 2 : name = name of conditional block
2267 * Returns : JB_ERR_OK on success
2268 * JB_ERR_MEMORY on out-of-memory error.
2270 *********************************************************************/
2271 jb_err map_block_killer(struct map *exports, const char *name)
2273 char buf[1000]; /* Will do, since the names are hardwired */
2277 assert(strlen(name) < (size_t)490);
2279 snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2280 return map(exports, buf, 1, "", 1);
2284 /*********************************************************************
2286 * Function : map_block_keep
2288 * Description : Convenience function. Removes the markers used
2289 * by map-block-killer, to save a few bytes.
2290 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2293 * 1 : exports = map to extend
2294 * 2 : name = name of conditional block
2296 * Returns : JB_ERR_OK on success
2297 * JB_ERR_MEMORY on out-of-memory error.
2299 *********************************************************************/
2300 jb_err map_block_keep(struct map *exports, const char *name)
2303 char buf[500]; /* Will do, since the names are hardwired */
2307 assert(strlen(name) < (size_t)490);
2309 snprintf(buf, sizeof(buf), "if-%s-start", name);
2310 err = map(exports, buf, 1, "", 1);
2317 snprintf(buf, sizeof(buf), "if-%s-end", name);
2318 return map(exports, buf, 1, "", 1);
2322 /*********************************************************************
2324 * Function : map_conditional
2326 * Description : Convenience function.
2327 * Adds an "if-then-else" for the conditional HTML-template
2328 * block <name>, i.e. a substitution of the form:
2335 * The control structure and one of the alternatives
2339 * 1 : exports = map to extend
2340 * 2 : name = name of conditional block
2341 * 3 : choose_first = nonzero for first, zero for second.
2343 * Returns : JB_ERR_OK on success
2344 * JB_ERR_MEMORY on out-of-memory error.
2346 *********************************************************************/
2347 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2349 char buf[1000]; /* Will do, since the names are hardwired */
2354 assert(strlen(name) < (size_t)480);
2356 snprintf(buf, sizeof(buf), (choose_first
2357 ? "else-not-%s@.*@endif-%s"
2358 : "if-%s-then@.*@else-not-%s"),
2361 err = map(exports, buf, 1, "", 1);
2367 snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2368 return map(exports, buf, 1, "", 1);
2372 /*********************************************************************
2374 * Function : make_menu
2376 * Description : Returns an HTML-formatted menu of the available
2377 * unhidden CGIs, excluding the one given in <self>
2378 * and the toggle CGI if toggling is disabled.
2381 * 1 : self = name of CGI to leave out, can be NULL for
2383 * 2 : feature_flags = feature bitmap from csp->config
2386 * Returns : menu string, or NULL on out-of-memory error.
2388 *********************************************************************/
2389 char *make_menu(const char *self, const unsigned feature_flags)
2391 const struct cgi_dispatcher *d;
2392 char *result = strdup("");
2396 self = "NO-SUCH-CGI!";
2399 /* List available unhidden CGI's and export as "other-cgis" */
2400 for (d = cgi_dispatchers; d->name; d++)
2403 #ifdef FEATURE_TOGGLE
2404 if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2407 * Suppress the toggle link if remote toggling is disabled.
2411 #endif /* def FEATURE_TOGGLE */
2413 if (d->description && strcmp(d->name, self))
2415 char *html_encoded_prefix;
2418 * Line breaks would be great, but break
2419 * the "blocked" template's JavaScript.
2421 string_append(&result, "<li><a href=\"");
2422 html_encoded_prefix = html_encode(CGI_PREFIX);
2423 if (html_encoded_prefix == NULL)
2429 string_append(&result, html_encoded_prefix);
2430 free(html_encoded_prefix);
2432 string_append(&result, d->name);
2433 string_append(&result, "\">");
2434 string_append(&result, d->description);
2435 string_append(&result, "</a></li>");
2443 /*********************************************************************
2445 * Function : dump_map
2447 * Description : HTML-dump a map for debugging (as table)
2450 * 1 : the_map = map to dump
2452 * Returns : string with HTML
2454 *********************************************************************/
2455 char *dump_map(const struct map *the_map)
2457 struct map_entry *cur_entry;
2458 char *ret = strdup("");
2460 string_append(&ret, "<table>\n");
2462 for (cur_entry = the_map->first;
2463 (cur_entry != NULL) && (ret != NULL);
2464 cur_entry = cur_entry->next)
2466 string_append(&ret, "<tr><td><b>");
2467 string_join (&ret, html_encode(cur_entry->name));
2468 string_append(&ret, "</b></td><td>");
2469 string_join (&ret, html_encode(cur_entry->value));
2470 string_append(&ret, "</td></tr>\n");
2473 string_append(&ret, "</table>\n");