1 const char cgi_rcs[] = "$Id: cgi.c,v 1.126 2009/10/29 16:53:56 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/cgi.c,v $
6 * Purpose : Declares functions to intercept request, generate
7 * html or gif answers, and to compose HTTP resonses.
8 * This only contains the framework functions, the
9 * actual handler functions are declared elsewhere.
11 * Functions declared include:
14 * Copyright : Written by and Copyright (C) 2001-2004, 2006-2008
15 * the SourceForge Privoxy team. http://www.privoxy.org/
17 * Based on the Internet Junkbuster originally written
18 * by and Copyright (C) 1997 Anonymous Coders and
19 * Junkbusters Corporation. http://www.junkbusters.com
21 * This program is free software; you can redistribute it
22 * and/or modify it under the terms of the GNU General
23 * Public License as published by the Free Software
24 * Foundation; either version 2 of the License, or (at
25 * your option) any later version.
27 * This program is distributed in the hope that it will
28 * be useful, but WITHOUT ANY WARRANTY; without even the
29 * implied warranty of MERCHANTABILITY or FITNESS FOR A
30 * PARTICULAR PURPOSE. See the GNU General Public
31 * License for more details.
33 * The GNU General Public License should be included with
34 * this file. If not, you can view it at
35 * http://www.gnu.org/copyleft/gpl.html
36 * or write to the Free Software Foundation, Inc., 59
37 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39 **********************************************************************/
45 #include <sys/types.h>
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) */
66 /* loadcfg.h is for global_toggle_state only */
68 /* jcc.h is for mutex semaphore globals only */
71 const char cgi_h_rcs[] = CGI_H_VERSION;
74 * List of CGI functions: name, handler, description
75 * Note: Do NOT use single quotes in the description;
76 * this will break the dynamic "blocked" template!
78 static const struct cgi_dispatcher cgi_dispatchers[] = {
83 #ifdef FEATURE_GRACEFUL_TERMINATION
86 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
87 "this is a one click Denial Of Service attack!!!</em>",
92 #ifdef FEATURE_CGI_EDIT_ACTIONS
93 "View & change the current configuration",
95 "View the current configuration",
100 "View the source code version numbers",
104 "View the request headers",
108 "Look up which actions apply to a URL and why",
110 #ifdef FEATURE_TOGGLE
113 "Toggle Privoxy on or off",
115 #endif /* def FEATURE_TOGGLE */
116 #ifdef FEATURE_CGI_EDIT_ACTIONS
117 { "edit-actions", /* Edit the actions list */
120 { "eaa", /* Shortcut for edit-actions-add-url-form */
121 cgi_edit_actions_add_url_form,
123 { "eau", /* Shortcut for edit-actions-url-form */
124 cgi_edit_actions_url_form,
126 { "ear", /* Shortcut for edit-actions-remove-url-form */
127 cgi_edit_actions_remove_url_form,
129 { "eal", /* Shortcut for edit-actions-list */
130 cgi_edit_actions_list,
132 { "eafu", /* Shortcut for edit-actions-for-url */
133 cgi_edit_actions_for_url,
135 { "eas", /* Shortcut for edit-actions-submit */
136 cgi_edit_actions_submit,
138 { "easa", /* Shortcut for edit-actions-section-add */
139 cgi_edit_actions_section_add,
141 { "easr", /* Shortcut for edit-actions-section-remove */
142 cgi_edit_actions_section_remove,
144 { "eass", /* Shortcut for edit-actions-section-swap */
145 cgi_edit_actions_section_swap,
147 { "edit-actions-for-url",
148 cgi_edit_actions_for_url,
149 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
150 { "edit-actions-list",
151 cgi_edit_actions_list,
152 NULL, TRUE /* Edit the actions list */ },
153 { "edit-actions-submit",
154 cgi_edit_actions_submit,
155 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
156 { "edit-actions-url",
157 cgi_edit_actions_url,
158 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
159 { "edit-actions-url-form",
160 cgi_edit_actions_url_form,
161 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
162 { "edit-actions-add-url",
163 cgi_edit_actions_add_url,
164 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
165 { "edit-actions-add-url-form",
166 cgi_edit_actions_add_url_form,
167 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
168 { "edit-actions-remove-url",
169 cgi_edit_actions_remove_url,
170 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
171 { "edit-actions-remove-url-form",
172 cgi_edit_actions_remove_url_form,
173 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
174 { "edit-actions-section-add",
175 cgi_edit_actions_section_add,
176 NULL, FALSE /* Remove a section from the actionsfile */ },
177 { "edit-actions-section-remove",
178 cgi_edit_actions_section_remove,
179 NULL, FALSE /* Remove a section from the actionsfile */ },
180 { "edit-actions-section-swap",
181 cgi_edit_actions_section_swap,
182 NULL, FALSE /* Swap two sections in the actionsfile */ },
183 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
184 { "error-favicon.ico",
185 cgi_send_error_favicon,
186 NULL, TRUE /* Sends the favicon image for error pages. */ },
188 cgi_send_default_favicon,
189 NULL, TRUE /* Sends the default favicon image. */ },
192 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
195 NULL, TRUE /* Send a built-in image */ },
198 NULL, FALSE /* Send templates/cgi-style.css */ },
200 cgi_transparent_image,
201 NULL, TRUE /* Send a transparent image (short name) */ },
202 { "url-info-osd.xml",
203 cgi_send_url_info_osd,
204 NULL, TRUE /* Send templates/url-info-osd.xml */ },
206 cgi_send_user_manual,
207 NULL, TRUE /* Send user-manual */ },
208 { NULL, /* NULL Indicates end of list and default page */
210 NULL, TRUE /* Unknown CGI page */ }
215 * Built-in images for ad replacement
217 * Hint: You can encode your own images like this:
218 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
221 #ifdef FEATURE_NO_GIFS
224 * Checkerboard pattern, as a PNG.
226 const char image_pattern_data[] =
227 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
228 "\122\000\000\000\004\000\000\000\004\010\006\000\000\000\251"
229 "\361\236\176\000\000\000\006\142\113\107\104\000\000\000\000"
230 "\000\000\371\103\273\177\000\000\000\033\111\104\101\124\010"
231 "\327\143\140\140\140\060\377\377\377\077\003\234\106\341\060"
232 "\060\230\063\020\124\001\000\161\021\031\241\034\364\030\143"
233 "\000\000\000\000\111\105\116\104\256\102\140\202";
236 * 1x1 transparant PNG.
238 const char image_blank_data[] =
239 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
240 "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
241 "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
242 "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
243 "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
244 "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
245 "\000\000\000\000\111\105\116\104\256\102\140\202";
249 * Checkerboard pattern, as a GIF.
251 const char image_pattern_data[] =
252 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
253 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
254 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
255 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
259 * 1x1 transparant GIF.
261 const char image_blank_data[] =
262 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
263 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
264 "\000\001\000\000\002\002D\001\000;";
267 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
268 const size_t image_blank_length = sizeof(image_blank_data) - 1;
271 static struct http_response cgi_error_memory_response[1];
273 static struct http_response *dispatch_known_cgi(struct client_state * csp,
275 static struct map *parse_cgi_parameters(char *argstring);
278 /*********************************************************************
280 * Function : dispatch_cgi
282 * Description : Checks if a request URL has either the magical
283 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
284 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
285 * http://config.privoxy.org/). If so, it passes
286 * the (rest of the) path onto dispatch_known_cgi, which
287 * calls the relevant CGI handler function.
290 * 1 : csp = Current client state (buffers, headers, etc...)
292 * Returns : http_response if match, NULL if nonmatch or handler fail
294 *********************************************************************/
295 struct http_response *dispatch_cgi(struct client_state *csp)
297 const char *host = csp->http->host;
298 const char *path = csp->http->path;
301 * Should we intercept ?
304 /* Note: "example.com" and "example.com." are equivalent hostnames. */
306 /* Either the host matches CGI_SITE_1_HOST ..*/
307 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
308 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
309 && (path[0] == '/') )
311 /* ..then the path will all be for us. Remove leading '/' */
314 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
315 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
316 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
317 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
319 /* take everything following CGI_SITE_2_PATH */
320 path += strlen(CGI_SITE_2_PATH);
323 /* skip the forward slash after CGI_SITE_2_PATH */
326 else if (*path != '\0')
329 * weirdness: URL is /configXXX, where XXX is some string
330 * Do *NOT* intercept.
342 * This is a CGI call.
345 return dispatch_known_cgi(csp, path);
349 /*********************************************************************
351 * Function : grep_cgi_referrer
353 * Description : Ugly provisorical fix that greps the value of the
354 * referer HTTP header field out of a linked list of
355 * strings like found at csp->headers. Will disappear
358 * FIXME: csp->headers ought to be csp->http->headers
359 * FIXME: Parsing all client header lines should
360 * happen right after the request is received!
363 * 1 : csp = Current client state (buffers, headers, etc...)
365 * Returns : pointer to value (no copy!), or NULL if none found.
367 *********************************************************************/
368 static char *grep_cgi_referrer(const struct client_state *csp)
370 struct list_entry *p;
372 for (p = csp->headers->first; p != NULL; p = p->next)
374 if (p->str == NULL) continue;
375 if (strncmpic(p->str, "Referer: ", 9) == 0)
377 return ((p->str) + 9);
385 /*********************************************************************
387 * Function : referrer_is_safe
389 * Description : Decides whether we trust the Referer for
390 * CGI pages which are only meant to be reachable
391 * through Privoxy's web interface directly.
394 * 1 : csp = Current client state (buffers, headers, etc...)
396 * Returns : TRUE if the referrer is safe, or
397 * FALSE if the referrer is unsafe or not set.
399 *********************************************************************/
400 static int referrer_is_safe(const struct client_state *csp)
403 static const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
405 referrer = grep_cgi_referrer(csp);
407 if (NULL == referrer)
409 /* No referrer, no access */
410 log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
413 else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)
414 || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix)))))
416 /* Trustworthy referrer */
417 log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
418 csp->http->url, referrer);
424 /* Untrustworthy referrer */
425 log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
426 csp->http->url, referrer);
433 /*********************************************************************
435 * Function : dispatch_known_cgi
437 * Description : Processes a CGI once dispatch_cgi has determined that
438 * it matches one of the magic prefixes. Parses the path
439 * as a cgi name plus query string, prepares a map that
440 * maps CGI parameter names to their values, initializes
441 * the http_response struct, and calls the relevant CGI
445 * 1 : csp = Current client state (buffers, headers, etc...)
446 * 2 : path = Path of CGI, with the CGI prefix removed.
447 * Should not have a leading "/".
449 * Returns : http_response, or NULL on handler failure or out of
452 *********************************************************************/
453 static struct http_response *dispatch_known_cgi(struct client_state * csp,
456 const struct cgi_dispatcher *d;
457 struct map *param_list;
458 struct http_response *rsp;
459 char *query_args_start;
463 if (NULL == (path_copy = strdup(path)))
465 return cgi_error_memory();
467 query_args_start = path_copy;
468 while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
472 if (*query_args_start == '/')
474 *query_args_start++ = '\0';
475 if ((param_list = new_map()))
477 map(param_list, "file", 1, url_decode(query_args_start), 0);
482 if (*query_args_start == '?')
484 *query_args_start++ = '\0';
486 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
489 return cgi_error_memory();
495 * path_copy = CGI call name
496 * param_list = CGI params, as map
499 /* Get mem for response or fail*/
500 if (NULL == (rsp = alloc_http_response()))
503 free_map(param_list);
504 return cgi_error_memory();
508 * Find and start the right CGI function
513 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
516 * If the called CGI is either harmless, or referred
517 * from a trusted source, start it.
519 if (d->harmless || referrer_is_safe(csp))
521 err = (d->handler)(csp, rsp, param_list);
526 * Else, modify toggle calls so that they only display
527 * the status, and deny all other calls.
529 if (0 == strcmp(path_copy, "toggle"))
531 unmap(param_list, "set");
532 err = (d->handler)(csp, rsp, param_list);
536 err = cgi_error_disabled(csp, rsp);
541 free_map(param_list);
543 if (err == JB_ERR_CGI_PARAMS)
545 err = cgi_error_bad_param(csp, rsp);
547 if (err && (err != JB_ERR_MEMORY))
549 /* Unexpected error! Shouldn't get here */
550 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
551 err = cgi_error_unknown(csp, rsp, err);
556 rsp->reason = RSP_REASON_CGI_CALL;
557 return finish_http_response(csp, rsp);
561 /* Error in handler, probably out-of-memory */
562 free_http_response(rsp);
563 return cgi_error_memory();
571 /*********************************************************************
573 * Function : parse_cgi_parameters
575 * Description : Parse a URL-encoded argument string into name/value
576 * pairs and store them in a struct map list.
579 * 1 : argstring = string to be parsed. Will be trashed.
581 * Returns : pointer to param list, or NULL if out of memory.
583 *********************************************************************/
584 static struct map *parse_cgi_parameters(char *argstring)
587 char *vector[BUFFER_SIZE];
589 struct map *cgi_params;
591 if (NULL == (cgi_params = new_map()))
597 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
598 * the fragment identifier along with the request, so we must
599 * cut it off here, so it won't pollute the CGI params:
601 if (NULL != (p = strchr(argstring, '#')))
606 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
608 for (i = 0; i < pairs; i++)
610 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
613 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
615 free_map(cgi_params);
626 /*********************************************************************
628 * Function : get_char_param
630 * Description : Get a single-character parameter passed to a CGI
634 * 1 : parameters = map of cgi parameters
635 * 2 : param_name = The name of the parameter to read
637 * Returns : Uppercase character on success, '\0' on error.
639 *********************************************************************/
640 char get_char_param(const struct map *parameters,
641 const char *param_name)
648 ch = *(lookup(parameters, param_name));
649 if ((ch >= 'a') && (ch <= 'z'))
651 ch = (char)(ch - 'a' + 'A');
658 /*********************************************************************
660 * Function : get_string_param
662 * Description : Get a string paramater, to be used as an
663 * ACTION_STRING or ACTION_MULTI paramater.
664 * Validates the input to prevent stupid/malicious
665 * users from corrupting their action file.
668 * 1 : parameters = map of cgi parameters
669 * 2 : param_name = The name of the parameter to read
670 * 3 : pparam = destination for paramater. Allocated as
671 * part of the map "parameters", so don't free it.
672 * Set to NULL if not specified.
674 * Returns : JB_ERR_OK on success, or if the paramater
676 * JB_ERR_MEMORY on out-of-memory.
677 * JB_ERR_CGI_PARAMS if the paramater is not valid.
679 *********************************************************************/
680 jb_err get_string_param(const struct map *parameters,
681 const char *param_name,
694 param = lookup(parameters, param_name);
700 if (strlen(param) >= CGI_PARAM_LEN_MAX)
705 * Note that the length limit is arbitrary, it just seems
706 * sensible to limit it to *something*. There's no
707 * technical reason for any limit at all.
709 return JB_ERR_CGI_PARAMS;
712 /* Check every character to see if it's legal */
714 while ((ch = *s++) != '\0')
716 if ( ((unsigned char)ch < (unsigned char)' ')
719 /* Probable hack attempt, or user accidentally used '}'. */
720 return JB_ERR_CGI_PARAMS;
731 /*********************************************************************
733 * Function : get_number_param
735 * Description : Get a non-negative integer from the parameters
736 * passed to a CGI function.
739 * 1 : csp = Current client state (buffers, headers, etc...)
740 * 2 : parameters = map of cgi parameters
741 * 3 : name = Name of CGI parameter to read
742 * 4 : pvalue = destination for value.
743 * Set to -1 on error.
745 * Returns : JB_ERR_OK on success
746 * JB_ERR_MEMORY on out-of-memory
747 * JB_ERR_CGI_PARAMS if the parameter was not specified
750 *********************************************************************/
751 jb_err get_number_param(struct client_state *csp,
752 const struct map *parameters,
767 param = lookup(parameters, name);
770 return JB_ERR_CGI_PARAMS;
773 /* We don't use atoi because I want to check this carefully... */
776 while ((ch = *param++) != '\0')
778 if ((ch < '0') || (ch > '9'))
780 return JB_ERR_CGI_PARAMS;
783 ch = (char)(ch - '0');
787 * <limits.h> defines UINT_MAX
789 * (UINT_MAX - ch) / 10 is the largest number that
790 * can be safely multiplied by 10 then have ch added.
792 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
794 return JB_ERR_CGI_PARAMS;
797 value = value * 10 + (unsigned)ch;
808 /*********************************************************************
810 * Function : error_response
812 * Description : returns an http_response that explains the reason
813 * why a request failed.
816 * 1 : csp = Current client state (buffers, headers, etc...)
817 * 2 : templatename = Which template should be used for the answer
819 * Returns : A http_response. If we run out of memory, this
820 * will be cgi_error_memory().
822 *********************************************************************/
823 struct http_response *error_response(struct client_state *csp,
824 const char *templatename)
827 struct http_response *rsp;
828 struct map *exports = default_exports(csp, NULL);
833 return cgi_error_memory();
836 if (NULL == (rsp = alloc_http_response()))
839 return cgi_error_memory();
842 #ifdef FEATURE_FORCE_LOAD
843 if (csp->flags & CSP_FLAG_FORCED)
845 path = strdup(FORCE_PREFIX);
848 #endif /* def FEATURE_FORCE_LOAD */
852 err = string_append(&path, csp->http->path);
854 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
855 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
856 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
857 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
860 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
863 /* Some failures, like "404 no such domain", don't have an IP address. */
864 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
872 free_http_response(rsp);
873 return cgi_error_memory();
876 if (!strcmp(templatename, "no-such-domain"))
878 rsp->status = strdup("404 No such domain");
879 rsp->reason = RSP_REASON_NO_SUCH_DOMAIN;
881 else if (!strcmp(templatename, "forwarding-failed"))
883 const struct forward_spec *fwd = forward_url(csp, csp->http);
884 char *socks_type = NULL;
887 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
888 /* Never get here - LOG_LEVEL_FATAL causes program exit */
892 * XXX: While the template is called forwarding-failed,
893 * it currently only handles socks forwarding failures.
896 assert(fwd->type != SOCKS_NONE);
899 * Map failure reason, forwarding type and forwarder.
901 if (NULL == csp->error_message)
904 * Either we forgot to record the failure reason,
905 * or the memory allocation failed.
907 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
908 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
910 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
913 * XXX: this is almost the same code as in cgi_show_url_info()
914 * and thus should be factored out and shared.
919 socks_type = "socks4-";
922 socks_type = "socks4a-";
925 socks_type = "socks5-";
928 log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
931 if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
932 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
933 if ((NULL == csp->error_message) || err)
936 free_http_response(rsp);
937 return cgi_error_memory();
940 rsp->status = strdup("503 Forwarding failure");
941 rsp->reason = RSP_REASON_FORWARDING_FAILED;
943 else if (!strcmp(templatename, "connect-failed"))
945 rsp->status = strdup("503 Connect failed");
946 rsp->reason = RSP_REASON_CONNECT_FAILED;
948 else if (!strcmp(templatename, "connection-timeout"))
950 rsp->status = strdup("504 Connection timeout");
951 rsp->reason = RSP_REASON_CONNECTION_TIMEOUT;
953 else if (!strcmp(templatename, "no-server-data"))
955 rsp->status = strdup("502 No data received from server or forwarder");
956 rsp->reason = RSP_REASON_NO_SERVER_DATA;
959 if (rsp->status == NULL)
962 free_http_response(rsp);
963 return cgi_error_memory();
966 err = template_fill_for_cgi(csp, templatename, exports, rsp);
969 free_http_response(rsp);
970 return cgi_error_memory();
973 return finish_http_response(csp, rsp);
977 /*********************************************************************
979 * Function : cgi_error_disabled
981 * Description : CGI function that is called to generate an error
982 * response if the actions editor or toggle CGI are
983 * accessed despite having being disabled at compile-
984 * or run-time, or if the user followed an untrusted link
985 * to access a unsafe CGI feature that is only reachable
986 * through Privoxy directly.
989 * 1 : csp = Current client state (buffers, headers, etc...)
990 * 2 : rsp = http_response data structure for output
992 * CGI Parameters : none
994 * Returns : JB_ERR_OK on success
995 * JB_ERR_MEMORY on out-of-memory error.
997 *********************************************************************/
998 jb_err cgi_error_disabled(const struct client_state *csp,
999 struct http_response *rsp)
1001 struct map *exports;
1006 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1008 return JB_ERR_MEMORY;
1010 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1012 /* Not important enough to do anything */
1013 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1016 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1020 /*********************************************************************
1022 * Function : cgi_init_error_messages
1024 * Description : Call at the start of the program to initialize
1025 * the error message used by cgi_error_memory().
1031 *********************************************************************/
1032 void cgi_init_error_messages(void)
1034 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1035 cgi_error_memory_response->head =
1036 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1037 "Content-Type: text/html\r\n"
1039 cgi_error_memory_response->body =
1042 " <title>500 Internal Privoxy Error</title>\r\n"
1043 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1046 "<h1>500 Internal Privoxy Error</h1>\r\n"
1047 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1048 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1052 cgi_error_memory_response->head_length =
1053 strlen(cgi_error_memory_response->head);
1054 cgi_error_memory_response->content_length =
1055 strlen(cgi_error_memory_response->body);
1056 cgi_error_memory_response->reason = RSP_REASON_OUT_OF_MEMORY;
1060 /*********************************************************************
1062 * Function : cgi_error_memory
1064 * Description : Called if a CGI function runs out of memory.
1065 * Returns a statically-allocated error response.
1069 * Returns : http_response data structure for output. This is
1070 * statically allocated, for obvious reasons.
1072 *********************************************************************/
1073 struct http_response *cgi_error_memory(void)
1075 /* assert that it's been initialized. */
1076 assert(cgi_error_memory_response->head);
1078 return cgi_error_memory_response;
1082 /*********************************************************************
1084 * Function : cgi_error_no_template
1086 * Description : Almost-CGI function that is called if a template
1087 * cannot be loaded. Note this is not a true CGI,
1088 * it takes a template name rather than a map of
1092 * 1 : csp = Current client state (buffers, headers, etc...)
1093 * 2 : rsp = http_response data structure for output
1094 * 3 : template_name = Name of template that could not
1097 * Returns : JB_ERR_OK on success
1098 * JB_ERR_MEMORY on out-of-memory error.
1100 *********************************************************************/
1101 jb_err cgi_error_no_template(const struct client_state *csp,
1102 struct http_response *rsp,
1103 const char *template_name)
1105 static const char status[] =
1106 "500 Internal Privoxy Error";
1107 static const char body_prefix[] =
1110 " <title>500 Internal Privoxy Error</title>\r\n"
1111 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1114 "<h1>500 Internal Privoxy Error</h1>\r\n"
1115 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1116 "<p><b>Could not load template file <code>";
1117 static const char body_suffix[] =
1118 "</code> or one of its included components.</b></p>\r\n"
1119 "<p>Please contact your proxy administrator.</p>\r\n"
1120 "<p>If you are the proxy administrator, please put the required file(s)"
1121 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1122 "location of the <code><i>(confdir)</i></code> directory "
1123 "is specified in the main Privoxy <code>config</code> "
1124 "file. (It's typically the Privoxy install directory"
1126 ", or <code>/etc/privoxy/</code>"
1127 #endif /* ndef _WIN32 */
1131 const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1135 assert(template_name);
1137 /* Reset rsp, if needed */
1141 rsp->content_length = 0;
1142 rsp->head_length = 0;
1145 rsp->body = malloc(body_size);
1146 if (rsp->body == NULL)
1148 return JB_ERR_MEMORY;
1150 strlcpy(rsp->body, body_prefix, body_size);
1151 strlcat(rsp->body, template_name, body_size);
1152 strlcat(rsp->body, body_suffix, body_size);
1154 rsp->status = strdup(status);
1155 if (rsp->status == NULL)
1157 return JB_ERR_MEMORY;
1164 /*********************************************************************
1166 * Function : cgi_error_unknown
1168 * Description : Almost-CGI function that is called if an unexpected
1169 * error occurs in the top-level CGI dispatcher.
1170 * In this context, "unexpected" means "anything other
1171 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1172 * expected to handle all other errors internally,
1173 * since they can give more relavent error messages
1176 * Note this is not a true CGI, it takes an error
1177 * code rather than a map of parameters.
1180 * 1 : csp = Current client state (buffers, headers, etc...)
1181 * 2 : rsp = http_response data structure for output
1182 * 3 : error_to_report = Error code to report.
1184 * Returns : JB_ERR_OK on success
1185 * JB_ERR_MEMORY on out-of-memory error.
1187 *********************************************************************/
1188 jb_err cgi_error_unknown(const struct client_state *csp,
1189 struct http_response *rsp,
1190 jb_err error_to_report)
1192 static const char status[] =
1193 "500 Internal Privoxy Error";
1194 static const char body_prefix[] =
1197 " <title>500 Internal Privoxy Error</title>\r\n"
1198 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1201 "<h1>500 Internal Privoxy Error</h1>\r\n"
1202 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1203 "<p><b>Unexpected internal error: ";
1204 static const char body_suffix[] =
1207 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1208 "file a bug report</a>.</p>\r\n"
1213 * Due to sizeof(errnumbuf), body_size will be slightly
1214 * bigger than necessary but it doesn't really matter.
1216 const size_t body_size = strlen(body_prefix) + sizeof(errnumbuf) + strlen(body_suffix) + 1;
1220 /* Reset rsp, if needed */
1224 rsp->content_length = 0;
1225 rsp->head_length = 0;
1227 rsp->reason = RSP_REASON_INTERNAL_ERROR;
1229 snprintf(errnumbuf, sizeof(errnumbuf), "%d", error_to_report);
1231 rsp->body = malloc(body_size);
1232 if (rsp->body == NULL)
1234 return JB_ERR_MEMORY;
1236 strlcpy(rsp->body, body_prefix, body_size);
1237 strlcat(rsp->body, errnumbuf, body_size);
1238 strlcat(rsp->body, body_suffix, body_size);
1240 rsp->status = strdup(status);
1241 if (rsp->status == NULL)
1243 return JB_ERR_MEMORY;
1250 /*********************************************************************
1252 * Function : cgi_error_bad_param
1254 * Description : CGI function that is called if the parameters
1255 * (query string) for a CGI were wrong.
1258 * 1 : csp = Current client state (buffers, headers, etc...)
1259 * 2 : rsp = http_response data structure for output
1261 * CGI Parameters : none
1263 * Returns : JB_ERR_OK on success
1264 * JB_ERR_MEMORY on out-of-memory error.
1266 *********************************************************************/
1267 jb_err cgi_error_bad_param(const struct client_state *csp,
1268 struct http_response *rsp)
1270 struct map *exports;
1275 if (NULL == (exports = default_exports(csp, NULL)))
1277 return JB_ERR_MEMORY;
1280 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1284 /*********************************************************************
1286 * Function : cgi_redirect
1288 * Description : CGI support function to generate a HTTP redirect
1292 * 1 : rsp = http_response data structure for output
1293 * 2 : target = string with the target URL
1295 * CGI Parameters : None
1297 * Returns : JB_ERR_OK on success
1298 * JB_ERR_MEMORY on out-of-memory error.
1300 *********************************************************************/
1301 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1308 err = enlist_unique_header(rsp->headers, "Location", target);
1310 rsp->status = strdup("302 Local Redirect from Privoxy");
1311 if (rsp->status == NULL)
1313 return JB_ERR_MEMORY;
1320 /*********************************************************************
1322 * Function : add_help_link
1324 * Description : Produce a copy of the string given as item,
1325 * embedded in an HTML link to its corresponding
1326 * section (item name in uppercase) in the actions
1327 * chapter of the user manual, (whose URL is given in
1328 * the config and defaults to our web site).
1330 * FIXME: I currently only work for actions, and would
1331 * like to be generalized for other topics.
1334 * 1 : item = item (will NOT be free()d.)
1335 * It is assumed to be HTML-safe.
1336 * 2 : config = The current configuration.
1338 * Returns : String with item embedded in link, or NULL on
1341 *********************************************************************/
1342 char *add_help_link(const char *item,
1343 struct configuration_spec *config)
1347 if (!item) return NULL;
1349 result = strdup("<a href=\"");
1350 if (!strncmpic(config->usermanual, "file://", 7) ||
1351 !strncmpic(config->usermanual, "http", 4))
1353 string_append(&result, config->usermanual);
1357 string_append(&result, "http://");
1358 string_append(&result, CGI_SITE_2_HOST);
1359 string_append(&result, "/user-manual/");
1361 string_append(&result, ACTIONS_HELP_PREFIX);
1362 string_join (&result, string_toupper(item));
1363 string_append(&result, "\">");
1364 string_append(&result, item);
1365 string_append(&result, "</a>");
1371 /*********************************************************************
1373 * Function : get_http_time
1375 * Description : Get the time in a format suitable for use in a
1376 * HTTP header - e.g.:
1377 * "Sun, 06 Nov 1994 08:49:37 GMT"
1380 * 1 : time_offset = Time returned will be current time
1381 * plus this number of seconds.
1382 * 2 : buf = Destination for result.
1383 * 3 : buffer_size = Size of the buffer above. Must be big
1384 * enough to hold 29 characters plus a
1389 *********************************************************************/
1390 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1392 static const char day_names[7][4] =
1393 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1394 static const char month_names[12][4] =
1395 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1396 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1399 time_t current_time;
1400 #if defined(HAVE_GMTIME_R)
1405 assert(buffer_size > (size_t)29);
1407 time(¤t_time);
1409 current_time += time_offset;
1411 /* get and save the gmt */
1413 t = gmtime_r(¤t_time, &dummy);
1414 #elif defined(MUTEX_LOCKS_AVAILABLE)
1415 privoxy_mutex_lock(&gmtime_mutex);
1416 t = gmtime(¤t_time);
1417 privoxy_mutex_unlock(&gmtime_mutex);
1419 t = gmtime(¤t_time);
1422 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1423 snprintf(buf, buffer_size,
1424 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1425 day_names[t->tm_wday],
1427 month_names[t->tm_mon],
1436 /*********************************************************************
1438 * Function : get_locale_time
1440 * Description : Get the time in a date(1)-like format
1441 * according to the current locale - e.g.:
1442 * "Fri Aug 29 19:37:12 CEST 2008"
1444 * XXX: Should we allow the user to change the format?
1447 * 1 : buf = Destination for result.
1448 * 2 : buffer_size = Size of the buffer above. Must be big
1449 * enough to hold 29 characters plus a
1454 *********************************************************************/
1455 static void get_locale_time(char *buf, size_t buffer_size)
1458 time_t current_time;
1459 #if defined(HAVE_LOCALTIME_R)
1464 assert(buffer_size > (size_t)29);
1466 time(¤t_time);
1468 #if HAVE_LOCALTIME_R
1469 timeptr = localtime_r(¤t_time, &dummy);
1470 #elif defined(MUTEX_LOCKS_AVAILABLE)
1471 privoxy_mutex_lock(&localtime_mutex);
1472 timeptr = localtime(¤t_time);
1473 privoxy_mutex_unlock(&localtime_mutex);
1475 timeptr = localtime(¤t_time);
1478 strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1482 /*********************************************************************
1484 * Function : finish_http_response
1486 * Description : Fill in the missing headers in an http response,
1487 * and flatten the headers to an http head.
1488 * For HEAD requests the body is freed once
1489 * the Content-Length header is set.
1492 * 1 : rsp = pointer to http_response to be processed
1494 * Returns : A http_response, usually the rsp parameter.
1495 * On error, free()s rsp and returns cgi_error_memory()
1497 *********************************************************************/
1498 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1500 char buf[BUFFER_SIZE];
1503 /* Special case - do NOT change this statically allocated response,
1504 * which is ready for output anyway.
1506 if (rsp == cgi_error_memory_response)
1512 * Fill in the HTTP Status, using HTTP/1.1
1513 * unless the client asked for HTTP/1.0.
1515 snprintf(buf, sizeof(buf), "%s %s",
1516 strcmpic(csp->http->ver, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1517 rsp->status ? rsp->status : "200 OK");
1518 err = enlist_first(rsp->headers, buf);
1521 * Set the Content-Length
1523 if (rsp->content_length == 0)
1525 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1529 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1530 err = enlist(rsp->headers, buf);
1533 if (0 == strcmpic(csp->http->gpc, "head"))
1536 * The client only asked for the head. Dispose
1537 * the body and log an offensive message.
1539 * While it may seem to be a bit inefficient to
1540 * prepare the body if it isn't needed, it's the
1541 * only way to get the Content-Length right for
1542 * dynamic pages. We could have disposed the body
1543 * earlier, but not without duplicating the
1544 * Content-Length setting code above.
1546 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1548 rsp->content_length = 0;
1551 if (strncmpic(rsp->status, "302", 3))
1554 * If it's not a redirect without any content,
1555 * set the Content-Type to text/html if it's
1556 * not already specified.
1558 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1562 * Fill in the rest of the default headers:
1564 * Date: set to current date/time.
1565 * Last-Modified: set to date/time the page was last changed.
1566 * Expires: set to date/time page next needs reloading.
1567 * Cache-Control: set to "no-cache" if applicable.
1569 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1574 * Set Expires to about 10 min into the future so it'll get reloaded
1575 * occasionally, e.g. if Privoxy gets upgraded.
1580 get_http_time(0, buf, sizeof(buf));
1581 err = enlist_unique_header(rsp->headers, "Date", buf);
1584 /* Some date in the past. */
1585 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1589 get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1590 err = enlist_unique_header(rsp->headers, "Expires", buf);
1593 else if (!strncmpic(rsp->status, "302", 3))
1595 get_http_time(0, buf, sizeof(buf));
1596 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1601 * Setting "Cache-Control" to "no-cache" and "Expires" to
1602 * the current time doesn't exactly forbid caching, it just
1603 * requires the client to revalidate the cached copy.
1605 * If a temporary problem occurs and the user tries again after
1606 * getting Privoxy's error message, a compliant browser may set the
1607 * If-Modified-Since header with the content of the error page's
1608 * Last-Modified header. More often than not, the document on the server
1609 * is older than Privoxy's error message, the server would send status code
1610 * 304 and the browser would display the outdated error message again and again.
1612 * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1613 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1614 * and can be safely used to "revalidate" without getting a status code 304.
1616 * There is no need to let the useless If-Modified-Since header reach the
1617 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1619 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1621 get_http_time(0, buf, sizeof(buf));
1622 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1623 if (!strncmpic(rsp->status, "403", 3)
1624 || !strncmpic(rsp->status, "404", 3)
1625 || !strncmpic(rsp->status, "502", 3)
1626 || !strncmpic(rsp->status, "503", 3)
1627 || !strncmpic(rsp->status, "504", 3))
1629 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1633 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1635 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1636 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1642 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1644 free_http_response(rsp);
1645 return cgi_error_memory();
1647 rsp->head_length = strlen(rsp->head);
1654 /*********************************************************************
1656 * Function : alloc_http_response
1658 * Description : Allocates a new http_response structure.
1662 * Returns : pointer to a new http_response, or NULL.
1664 *********************************************************************/
1665 struct http_response *alloc_http_response(void)
1667 return (struct http_response *) zalloc(sizeof(struct http_response));
1672 /*********************************************************************
1674 * Function : free_http_response
1676 * Description : Free the memory occupied by an http_response
1677 * and its depandant structures.
1680 * 1 : rsp = pointer to http_response to be freed
1684 *********************************************************************/
1685 void free_http_response(struct http_response *rsp)
1688 * Must special case cgi_error_memory_response, which is never freed.
1690 if (rsp && (rsp != cgi_error_memory_response))
1695 destroy_list(rsp->headers);
1702 /*********************************************************************
1704 * Function : template_load
1706 * Description : CGI support function that loads a given HTML
1707 * template, ignoring comment lines and following
1708 * #include statements up to a depth of 1.
1711 * 1 : csp = Current client state (buffers, headers, etc...)
1712 * 2 : template_ptr = Destination for pointer to loaded
1714 * 3 : templatename = name of the HTML template to be used
1715 * 4 : recursive = Flag set if this function calls itself
1716 * following an #include statament
1718 * Returns : JB_ERR_OK on success
1719 * JB_ERR_MEMORY on out-of-memory error.
1720 * JB_ERR_FILE if the template file cannot be read
1722 *********************************************************************/
1723 jb_err template_load(const struct client_state *csp, char **template_ptr,
1724 const char *templatename, int recursive)
1727 char *templates_dir_path;
1730 char *included_module;
1733 char buf[BUFFER_SIZE];
1736 assert(template_ptr);
1737 assert(templatename);
1739 *template_ptr = NULL;
1741 /* Validate template name. Paranoia. */
1742 for (p = templatename; *p != 0; p++)
1744 if ( ((*p < 'a') || (*p > 'z'))
1745 && ((*p < 'A') || (*p > 'Z'))
1746 && ((*p < '0') || (*p > '9'))
1750 /* Illegal character */
1756 * Generate full path using either templdir
1757 * or confdir/templates as base directory.
1759 if (NULL != csp->config->templdir)
1761 templates_dir_path = strdup(csp->config->templdir);
1765 templates_dir_path = make_path(csp->config->confdir, "templates");
1768 if (templates_dir_path == NULL)
1770 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1772 return JB_ERR_MEMORY;
1775 full_path = make_path(templates_dir_path, templatename);
1776 free(templates_dir_path);
1777 if (full_path == NULL)
1779 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1781 return JB_ERR_MEMORY;
1784 /* Allocate buffer */
1786 file_buffer = strdup("");
1787 if (file_buffer == NULL)
1789 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1791 return JB_ERR_MEMORY;
1794 /* Open template file */
1796 if (NULL == (fp = fopen(full_path, "r")))
1798 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1806 * Read the file, ignoring comments, and honoring #include
1807 * statements, unless we're already called recursively.
1809 * XXX: The comment handling could break with lines lengths > sizeof(buf).
1810 * This is unlikely in practise.
1812 while (fgets(buf, sizeof(buf), fp))
1814 if (!recursive && !strncmp(buf, "#include ", 9))
1816 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1823 if (string_join(&file_buffer, included_module))
1826 return JB_ERR_MEMORY;
1832 /* skip lines starting with '#' */
1838 if (string_append(&file_buffer, buf))
1841 return JB_ERR_MEMORY;
1846 *template_ptr = file_buffer;
1852 /*********************************************************************
1854 * Function : template_fill
1856 * Description : CGI support function that fills in a pre-loaded
1857 * HTML template by replacing @name@ with value using
1858 * pcrs, for each item in the output map.
1860 * Note that a leading '$' charachter in the export map's
1861 * values will be stripped and toggle on backreference
1865 * 1 : template_ptr = IN: Template to be filled out.
1867 * OUT: Filled out template.
1868 * Caller must free().
1869 * 2 : exports = map with fill in symbol -> name pairs
1871 * Returns : JB_ERR_OK on success (and for uncritical errors)
1872 * JB_ERR_MEMORY on out-of-memory error
1874 *********************************************************************/
1875 jb_err template_fill(char **template_ptr, const struct map *exports)
1877 struct map_entry *m;
1879 char buf[BUFFER_SIZE];
1880 char *tmp_out_buffer;
1886 assert(template_ptr);
1887 assert(*template_ptr);
1890 file_buffer = *template_ptr;
1891 size = strlen(file_buffer) + 1;
1894 * Assemble pcrs joblist from exports map
1896 for (m = exports->first; m != NULL; m = m->next)
1898 if (*m->name == '$')
1901 * First character of name is '$', so remove this flag
1902 * character and allow backreferences ($1 etc) in the
1903 * "replace with" text.
1905 snprintf(buf, sizeof(buf), "%s", m->name + 1);
1911 * Treat the "replace with" text as a literal string -
1912 * no quoting needed, no backreferences allowed.
1913 * ("Trivial" ['T'] flag).
1917 /* Enclose name in @@ */
1918 snprintf(buf, sizeof(buf), "@%s@", m->name);
1921 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1923 /* Make and run job. */
1924 job = pcrs_compile(buf, m->value, flags, &error);
1927 if (error == PCRS_ERR_NOMEM)
1930 *template_ptr = NULL;
1931 return JB_ERR_MEMORY;
1935 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1936 /* Hope it wasn't important and silently ignore the invalid job */
1941 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1944 if (NULL == tmp_out_buffer)
1946 *template_ptr = NULL;
1947 return JB_ERR_MEMORY;
1953 * Substitution failed, keep the original buffer,
1954 * log the problem and ignore it.
1956 * The user might see some unresolved @CGI_VARIABLES@,
1957 * but returning a special CGI error page seems unreasonable
1958 * and could mask more important error messages.
1960 free(tmp_out_buffer);
1961 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
1962 buf, m->value, flags, pcrs_strerror(error));
1966 /* Substitution succeeded, use modified buffer. */
1968 file_buffer = tmp_out_buffer;
1976 *template_ptr = file_buffer;
1981 /*********************************************************************
1983 * Function : template_fill_for_cgi
1985 * Description : CGI support function that loads a HTML template
1986 * and fills it in. Handles file-not-found errors
1987 * by sending a HTML error message. For convenience,
1988 * this function also frees the passed "exports" map.
1991 * 1 : csp = Client state
1992 * 2 : templatename = name of the HTML template to be used
1993 * 3 : exports = map with fill in symbol -> name pairs.
1994 * Will be freed by this function.
1995 * 4 : rsp = Response structure to fill in.
1997 * Returns : JB_ERR_OK on success
1998 * JB_ERR_MEMORY on out-of-memory error
2000 *********************************************************************/
2001 jb_err template_fill_for_cgi(const struct client_state *csp,
2002 const char *templatename,
2003 struct map *exports,
2004 struct http_response *rsp)
2009 assert(templatename);
2013 err = template_load(csp, &rsp->body, templatename, 0);
2014 if (err == JB_ERR_FILE)
2017 return cgi_error_no_template(csp, rsp, templatename);
2022 return err; /* JB_ERR_MEMORY */
2024 err = template_fill(&rsp->body, exports);
2030 /*********************************************************************
2032 * Function : default_exports
2034 * Description : returns a struct map list that contains exports
2035 * which are common to all CGI functions.
2038 * 1 : csp = Current client state (buffers, headers, etc...)
2039 * 2 : caller = name of CGI who calls us and which should
2040 * be excluded from the generated menu. May be
2042 * Returns : NULL if no memory, else a new map. Caller frees.
2044 *********************************************************************/
2045 struct map *default_exports(const struct client_state *csp, const char *caller)
2049 struct map * exports;
2050 int local_help_exists = 0;
2051 char *ip_address = NULL;
2052 char *hostname = NULL;
2056 exports = new_map();
2057 if (exports == NULL)
2062 if (csp->config->hostname)
2064 get_host_information(csp->cfd, &ip_address, NULL);
2065 hostname = strdup(csp->config->hostname);
2069 get_host_information(csp->cfd, &ip_address, &hostname);
2072 err = map(exports, "version", 1, html_encode(VERSION), 0);
2073 get_locale_time(buf, sizeof(buf));
2074 if (!err) err = map(exports, "time", 1, html_encode(buf), 0);
2075 if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2077 if (!err) err = map(exports, "my-hostname", 1, html_encode(hostname ? hostname : "unknown"), 0);
2079 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2080 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2081 if (!err) err = map(exports, "menu", 1, make_menu(caller, csp->config->feature_flags), 0);
2082 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2083 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2084 !strncmpic(csp->config->usermanual, "http", 4))
2086 /* Manual is located somewhere else, just link to it. */
2087 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2091 /* Manual is delivered by Privoxy. */
2092 if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2094 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2095 #ifdef FEATURE_TOGGLE
2096 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2098 if (!err) err = map_block_killer(exports, "can-toggle");
2101 snprintf(buf, sizeof(buf), "%d", csp->config->hport);
2102 if (!err) err = map(exports, "my-port", 1, buf, 1);
2104 if(!strcmp(CODE_STATUS, "stable"))
2106 if (!err) err = map_block_killer(exports, "unstable");
2109 if (csp->config->admin_address != NULL)
2111 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2112 local_help_exists = 1;
2116 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2119 if (csp->config->proxy_info_url != NULL)
2121 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2122 local_help_exists = 1;
2126 if (!err) err = map_block_killer(exports, "have-proxy-info");
2129 if (local_help_exists == 0)
2131 if (!err) err = map_block_killer(exports, "have-help-info");
2144 /*********************************************************************
2146 * Function : map_block_killer
2148 * Description : Convenience function.
2149 * Adds a "killer" for the conditional HTML-template
2150 * block <name>, i.e. a substitution of the regex
2151 * "if-<name>-start.*if-<name>-end" to the given
2155 * 1 : exports = map to extend
2156 * 2 : name = name of conditional block
2158 * Returns : JB_ERR_OK on success
2159 * JB_ERR_MEMORY on out-of-memory error.
2161 *********************************************************************/
2162 jb_err map_block_killer(struct map *exports, const char *name)
2164 char buf[1000]; /* Will do, since the names are hardwired */
2168 assert(strlen(name) < (size_t)490);
2170 snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2171 return map(exports, buf, 1, "", 1);
2175 /*********************************************************************
2177 * Function : map_block_keep
2179 * Description : Convenience function. Removes the markers used
2180 * by map-block-killer, to save a few bytes.
2181 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2184 * 1 : exports = map to extend
2185 * 2 : name = name of conditional block
2187 * Returns : JB_ERR_OK on success
2188 * JB_ERR_MEMORY on out-of-memory error.
2190 *********************************************************************/
2191 jb_err map_block_keep(struct map *exports, const char *name)
2194 char buf[500]; /* Will do, since the names are hardwired */
2198 assert(strlen(name) < (size_t)490);
2200 snprintf(buf, sizeof(buf), "if-%s-start", name);
2201 err = map(exports, buf, 1, "", 1);
2208 snprintf(buf, sizeof(buf), "if-%s-end", name);
2209 return map(exports, buf, 1, "", 1);
2213 /*********************************************************************
2215 * Function : map_conditional
2217 * Description : Convenience function.
2218 * Adds an "if-then-else" for the conditional HTML-template
2219 * block <name>, i.e. a substitution of the form:
2226 * The control structure and one of the alternatives
2230 * 1 : exports = map to extend
2231 * 2 : name = name of conditional block
2232 * 3 : choose_first = nonzero for first, zero for second.
2234 * Returns : JB_ERR_OK on success
2235 * JB_ERR_MEMORY on out-of-memory error.
2237 *********************************************************************/
2238 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2240 char buf[1000]; /* Will do, since the names are hardwired */
2245 assert(strlen(name) < (size_t)480);
2247 snprintf(buf, sizeof(buf), (choose_first
2248 ? "else-not-%s@.*@endif-%s"
2249 : "if-%s-then@.*@else-not-%s"),
2252 err = map(exports, buf, 1, "", 1);
2258 snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2259 return map(exports, buf, 1, "", 1);
2263 /*********************************************************************
2265 * Function : make_menu
2267 * Description : Returns an HTML-formatted menu of the available
2268 * unhidden CGIs, excluding the one given in <self>
2269 * and the toggle CGI if toggling is disabled.
2272 * 1 : self = name of CGI to leave out, can be NULL for
2274 * 2 : feature_flags = feature bitmap from csp->config
2277 * Returns : menu string, or NULL on out-of-memory error.
2279 *********************************************************************/
2280 char *make_menu(const char *self, const unsigned feature_flags)
2282 const struct cgi_dispatcher *d;
2283 char *result = strdup("");
2287 self = "NO-SUCH-CGI!";
2290 /* List available unhidden CGI's and export as "other-cgis" */
2291 for (d = cgi_dispatchers; d->name; d++)
2294 #ifdef FEATURE_TOGGLE
2295 if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2298 * Suppress the toggle link if remote toggling is disabled.
2302 #endif /* def FEATURE_TOGGLE */
2304 if (d->description && strcmp(d->name, self))
2306 char *html_encoded_prefix;
2309 * Line breaks would be great, but break
2310 * the "blocked" template's JavaScript.
2312 string_append(&result, "<li><a href=\"");
2313 html_encoded_prefix = html_encode(CGI_PREFIX);
2314 if (html_encoded_prefix == NULL)
2320 string_append(&result, html_encoded_prefix);
2321 free(html_encoded_prefix);
2323 string_append(&result, d->name);
2324 string_append(&result, "\">");
2325 string_append(&result, d->description);
2326 string_append(&result, "</a></li>");
2334 /*********************************************************************
2336 * Function : dump_map
2338 * Description : HTML-dump a map for debugging (as table)
2341 * 1 : the_map = map to dump
2343 * Returns : string with HTML
2345 *********************************************************************/
2346 char *dump_map(const struct map *the_map)
2348 struct map_entry *cur_entry;
2349 char *ret = strdup("");
2351 string_append(&ret, "<table>\n");
2353 for (cur_entry = the_map->first;
2354 (cur_entry != NULL) && (ret != NULL);
2355 cur_entry = cur_entry->next)
2357 string_append(&ret, "<tr><td><b>");
2358 string_join (&ret, html_encode(cur_entry->name));
2359 string_append(&ret, "</b></td><td>");
2360 string_join (&ret, html_encode(cur_entry->value));
2361 string_append(&ret, "</td></tr>\n");
2364 string_append(&ret, "</table>\n");