1 const char cgi_rcs[] = "$Id: cgi.c,v 1.116 2009/03/15 14:59:34 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 */
67 #ifdef FEATURE_PTHREAD
69 /* jcc.h is for mutex semaphore globals only */
70 #endif /* def FEATURE_PTHREAD */
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
818 * 3 : sys_err = system error number
820 * Returns : A http_response. If we run out of memory, this
821 * will be cgi_error_memory().
823 *********************************************************************/
824 struct http_response *error_response(struct client_state *csp,
825 const char *templatename,
829 struct http_response *rsp;
830 struct map *exports = default_exports(csp, NULL);
835 return cgi_error_memory();
838 if (NULL == (rsp = alloc_http_response()))
841 return cgi_error_memory();
844 #ifdef FEATURE_FORCE_LOAD
845 if (csp->flags & CSP_FLAG_FORCED)
847 path = strdup(FORCE_PREFIX);
850 #endif /* def FEATURE_FORCE_LOAD */
854 err = string_append(&path, csp->http->path);
856 if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
857 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
858 if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
859 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
860 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
863 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
866 /* Some failures, like "404 no such domain", don't have an IP address. */
867 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
875 free_http_response(rsp);
876 return cgi_error_memory();
879 if (!strcmp(templatename, "no-such-domain"))
881 rsp->status = strdup("404 No such domain");
882 if (rsp->status == NULL)
885 free_http_response(rsp);
886 return cgi_error_memory();
888 rsp->reason = RSP_REASON_NO_SUCH_DOMAIN;
890 else if (!strcmp(templatename, "forwarding-failed"))
892 const struct forward_spec *fwd = forward_url(csp, csp->http);
893 char *socks_type = NULL;
896 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
897 /* Never get here - LOG_LEVEL_FATAL causes program exit */
901 * XXX: While the template is called forwarding-failed,
902 * it currently only handles socks forwarding failures.
905 assert(fwd->type != SOCKS_NONE);
908 * Map failure reason, forwarding type and forwarder.
910 if (NULL == csp->error_message)
913 * Either we forgot to record the failure reason,
914 * or the memory allocation failed.
916 log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
917 csp->error_message = strdup("Failure reason missing. Check the log file for details.");
919 if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
922 * XXX: this is almost the same code as in cgi_show_url_info()
923 * and thus should be factored out and shared.
928 socks_type = "socks4-";
931 socks_type = "socks4a-";
934 socks_type = "socks5-";
937 log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
940 if (!err) err = map(exports, "forwarding-type", 1, socks_type, 1);
941 if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
943 if (!err) rsp->status = strdup("503 Forwarding failure");
944 if ((rsp->status == NULL) || (NULL == csp->error_message) || err)
947 free_http_response(rsp);
948 return cgi_error_memory();
950 rsp->reason = RSP_REASON_FORWARDING_FAILED;
952 else if (!strcmp(templatename, "connect-failed"))
954 rsp->status = strdup("503 Connect failed");
955 if (rsp->status == NULL)
958 free_http_response(rsp);
959 return cgi_error_memory();
961 rsp->reason = RSP_REASON_CONNECT_FAILED;
964 err = template_fill_for_cgi(csp, templatename, exports, rsp);
967 free_http_response(rsp);
968 return cgi_error_memory();
971 return finish_http_response(csp, rsp);
975 /*********************************************************************
977 * Function : cgi_error_disabled
979 * Description : CGI function that is called to generate an error
980 * response if the actions editor or toggle CGI are
981 * accessed despite having being disabled at compile-
982 * or run-time, or if the user followed an untrusted link
983 * to access a unsafe CGI feature that is only reachable
984 * through Privoxy directly.
987 * 1 : csp = Current client state (buffers, headers, etc...)
988 * 2 : rsp = http_response data structure for output
990 * CGI Parameters : none
992 * Returns : JB_ERR_OK on success
993 * JB_ERR_MEMORY on out-of-memory error.
995 *********************************************************************/
996 jb_err cgi_error_disabled(const struct client_state *csp,
997 struct http_response *rsp)
1004 if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1006 return JB_ERR_MEMORY;
1008 if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1010 /* Not important enough to do anything */
1011 log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1014 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1018 /*********************************************************************
1020 * Function : cgi_init_error_messages
1022 * Description : Call at the start of the program to initialize
1023 * the error message used by cgi_error_memory().
1029 *********************************************************************/
1030 void cgi_init_error_messages(void)
1032 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1033 cgi_error_memory_response->head =
1034 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1035 "Content-Type: text/html\r\n"
1037 cgi_error_memory_response->body =
1040 " <title>500 Internal Privoxy Error</title>\r\n"
1041 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1044 "<h1>500 Internal Privoxy Error</h1>\r\n"
1045 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1046 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1050 cgi_error_memory_response->head_length =
1051 strlen(cgi_error_memory_response->head);
1052 cgi_error_memory_response->content_length =
1053 strlen(cgi_error_memory_response->body);
1054 cgi_error_memory_response->reason = RSP_REASON_OUT_OF_MEMORY;
1058 /*********************************************************************
1060 * Function : cgi_error_memory
1062 * Description : Called if a CGI function runs out of memory.
1063 * Returns a statically-allocated error response.
1067 * Returns : http_response data structure for output. This is
1068 * statically allocated, for obvious reasons.
1070 *********************************************************************/
1071 struct http_response *cgi_error_memory(void)
1073 /* assert that it's been initialized. */
1074 assert(cgi_error_memory_response->head);
1076 return cgi_error_memory_response;
1080 /*********************************************************************
1082 * Function : cgi_error_no_template
1084 * Description : Almost-CGI function that is called if a template
1085 * cannot be loaded. Note this is not a true CGI,
1086 * it takes a template name rather than a map of
1090 * 1 : csp = Current client state (buffers, headers, etc...)
1091 * 2 : rsp = http_response data structure for output
1092 * 3 : template_name = Name of template that could not
1095 * Returns : JB_ERR_OK on success
1096 * JB_ERR_MEMORY on out-of-memory error.
1098 *********************************************************************/
1099 jb_err cgi_error_no_template(const struct client_state *csp,
1100 struct http_response *rsp,
1101 const char *template_name)
1103 static const char status[] =
1104 "500 Internal Privoxy Error";
1105 static const char body_prefix[] =
1108 " <title>500 Internal Privoxy Error</title>\r\n"
1109 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1112 "<h1>500 Internal Privoxy Error</h1>\r\n"
1113 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1114 "<p><b>Could not load template file <code>";
1115 static const char body_suffix[] =
1116 "</code> or one of its included components.</b></p>\r\n"
1117 "<p>Please contact your proxy administrator.</p>\r\n"
1118 "<p>If you are the proxy administrator, please put the required file(s)"
1119 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1120 "location of the <code><i>(confdir)</i></code> directory "
1121 "is specified in the main Privoxy <code>config</code> "
1122 "file. (It's typically the Privoxy install directory"
1124 ", or <code>/etc/privoxy/</code>"
1125 #endif /* ndef _WIN32 */
1129 const size_t body_size = strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1;
1133 assert(template_name);
1135 /* Reset rsp, if needed */
1139 rsp->content_length = 0;
1140 rsp->head_length = 0;
1143 rsp->body = malloc(body_size);
1144 if (rsp->body == NULL)
1146 return JB_ERR_MEMORY;
1148 strlcpy(rsp->body, body_prefix, body_size);
1149 strlcat(rsp->body, template_name, body_size);
1150 strlcat(rsp->body, body_suffix, body_size);
1152 rsp->status = strdup(status);
1153 if (rsp->status == NULL)
1155 return JB_ERR_MEMORY;
1162 /*********************************************************************
1164 * Function : cgi_error_unknown
1166 * Description : Almost-CGI function that is called if an unexpected
1167 * error occurs in the top-level CGI dispatcher.
1168 * In this context, "unexpected" means "anything other
1169 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1170 * expected to handle all other errors internally,
1171 * since they can give more relavent error messages
1174 * Note this is not a true CGI, it takes an error
1175 * code rather than a map of parameters.
1178 * 1 : csp = Current client state (buffers, headers, etc...)
1179 * 2 : rsp = http_response data structure for output
1180 * 3 : error_to_report = Error code to report.
1182 * Returns : JB_ERR_OK on success
1183 * JB_ERR_MEMORY on out-of-memory error.
1185 *********************************************************************/
1186 jb_err cgi_error_unknown(const struct client_state *csp,
1187 struct http_response *rsp,
1188 jb_err error_to_report)
1190 static const char status[] =
1191 "500 Internal Privoxy Error";
1192 static const char body_prefix[] =
1195 " <title>500 Internal Privoxy Error</title>\r\n"
1196 " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1199 "<h1>500 Internal Privoxy Error</h1>\r\n"
1200 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1201 "<p><b>Unexpected internal error: ";
1202 static const char body_suffix[] =
1205 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1206 "file a bug report</a>.</p>\r\n"
1211 * Due to sizeof(errnumbuf), body_size will be slightly
1212 * bigger than necessary but it doesn't really matter.
1214 const size_t body_size = strlen(body_prefix) + sizeof(errnumbuf) + strlen(body_suffix) + 1;
1218 /* Reset rsp, if needed */
1222 rsp->content_length = 0;
1223 rsp->head_length = 0;
1225 rsp->reason = RSP_REASON_INTERNAL_ERROR;
1227 snprintf(errnumbuf, sizeof(errnumbuf), "%d", error_to_report);
1229 rsp->body = malloc(body_size);
1230 if (rsp->body == NULL)
1232 return JB_ERR_MEMORY;
1234 strlcpy(rsp->body, body_prefix, body_size);
1235 strlcat(rsp->body, errnumbuf, body_size);
1236 strlcat(rsp->body, body_suffix, body_size);
1238 rsp->status = strdup(status);
1239 if (rsp->status == NULL)
1241 return JB_ERR_MEMORY;
1248 /*********************************************************************
1250 * Function : cgi_error_bad_param
1252 * Description : CGI function that is called if the parameters
1253 * (query string) for a CGI were wrong.
1256 * 1 : csp = Current client state (buffers, headers, etc...)
1257 * 2 : rsp = http_response data structure for output
1259 * CGI Parameters : none
1261 * Returns : JB_ERR_OK on success
1262 * JB_ERR_MEMORY on out-of-memory error.
1264 *********************************************************************/
1265 jb_err cgi_error_bad_param(const struct client_state *csp,
1266 struct http_response *rsp)
1268 struct map *exports;
1273 if (NULL == (exports = default_exports(csp, NULL)))
1275 return JB_ERR_MEMORY;
1278 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1282 /*********************************************************************
1284 * Function : cgi_redirect
1286 * Description : CGI support function to generate a HTTP redirect
1290 * 1 : rsp = http_response data structure for output
1291 * 2 : target = string with the target URL
1293 * CGI Parameters : None
1295 * Returns : JB_ERR_OK on success
1296 * JB_ERR_MEMORY on out-of-memory error.
1298 *********************************************************************/
1299 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1306 err = enlist_unique_header(rsp->headers, "Location", target);
1308 rsp->status = strdup("302 Local Redirect from Privoxy");
1309 if (rsp->status == NULL)
1311 return JB_ERR_MEMORY;
1318 /*********************************************************************
1320 * Function : add_help_link
1322 * Description : Produce a copy of the string given as item,
1323 * embedded in an HTML link to its corresponding
1324 * section (item name in uppercase) in the actions
1325 * chapter of the user manual, (whose URL is given in
1326 * the config and defaults to our web site).
1328 * FIXME: I currently only work for actions, and would
1329 * like to be generalized for other topics.
1332 * 1 : item = item (will NOT be free()d.)
1333 * It is assumed to be HTML-safe.
1334 * 2 : config = The current configuration.
1336 * Returns : String with item embedded in link, or NULL on
1339 *********************************************************************/
1340 char *add_help_link(const char *item,
1341 struct configuration_spec *config)
1345 if (!item) return NULL;
1347 result = strdup("<a href=\"");
1348 if (!strncmpic(config->usermanual, "file://", 7) ||
1349 !strncmpic(config->usermanual, "http", 4))
1351 string_append(&result, config->usermanual);
1355 string_append(&result, "http://");
1356 string_append(&result, CGI_SITE_2_HOST);
1357 string_append(&result, "/user-manual/");
1359 string_append(&result, ACTIONS_HELP_PREFIX);
1360 string_join (&result, string_toupper(item));
1361 string_append(&result, "\">");
1362 string_append(&result, item);
1363 string_append(&result, "</a> ");
1369 /*********************************************************************
1371 * Function : get_http_time
1373 * Description : Get the time in a format suitable for use in a
1374 * HTTP header - e.g.:
1375 * "Sun, 06 Nov 1994 08:49:37 GMT"
1378 * 1 : time_offset = Time returned will be current time
1379 * plus this number of seconds.
1380 * 2 : buf = Destination for result.
1381 * 3 : buffer_size = Size of the buffer above. Must be big
1382 * enough to hold 29 characters plus a
1387 *********************************************************************/
1388 void get_http_time(int time_offset, char *buf, size_t buffer_size)
1390 static const char day_names[7][4] =
1391 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1392 static const char month_names[12][4] =
1393 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1394 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1397 time_t current_time;
1398 #if defined(HAVE_GMTIME_R)
1403 assert(buffer_size > (size_t)29);
1405 time(¤t_time);
1407 current_time += time_offset;
1409 /* get and save the gmt */
1411 t = gmtime_r(¤t_time, &dummy);
1412 #elif FEATURE_PTHREAD
1413 privoxy_mutex_lock(&gmtime_mutex);
1414 t = gmtime(¤t_time);
1415 privoxy_mutex_unlock(&gmtime_mutex);
1417 t = gmtime(¤t_time);
1420 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1421 snprintf(buf, buffer_size,
1422 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1423 day_names[t->tm_wday],
1425 month_names[t->tm_mon],
1434 /*********************************************************************
1436 * Function : get_locale_time
1438 * Description : Get the time in a date(1)-like format
1439 * according to the current locale - e.g.:
1440 * "Fri Aug 29 19:37:12 CEST 2008"
1442 * XXX: Should we allow the user to change the format?
1445 * 1 : buf = Destination for result.
1446 * 2 : buffer_size = Size of the buffer above. Must be big
1447 * enough to hold 29 characters plus a
1452 *********************************************************************/
1453 static void get_locale_time(char *buf, size_t buffer_size)
1456 time_t current_time;
1457 #if defined(HAVE_LOCALTIME_R)
1462 assert(buffer_size > (size_t)29);
1464 time(¤t_time);
1466 #if HAVE_LOCALTIME_R
1467 timeptr = localtime_r(¤t_time, &dummy);
1468 #elif FEATURE_PTHREAD
1469 privoxy_mutex_lock(&localtime_mutex);
1470 timeptr = localtime(¤t_time);
1471 privoxy_mutex_unlock(&localtime_mutex);
1473 timeptr = localtime(¤t_time);
1476 strftime(buf, buffer_size, "%a %b %d %X %Z %Y", timeptr);
1480 /*********************************************************************
1482 * Function : finish_http_response
1484 * Description : Fill in the missing headers in an http response,
1485 * and flatten the headers to an http head.
1486 * For HEAD requests the body is freed once
1487 * the Content-Length header is set.
1490 * 1 : rsp = pointer to http_response to be processed
1492 * Returns : A http_response, usually the rsp parameter.
1493 * On error, free()s rsp and returns cgi_error_memory()
1495 *********************************************************************/
1496 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1498 char buf[BUFFER_SIZE];
1501 /* Special case - do NOT change this statically allocated response,
1502 * which is ready for output anyway.
1504 if (rsp == cgi_error_memory_response)
1510 * Fill in the HTTP Status, using HTTP/1.1
1511 * unless the client asked for HTTP/1.0.
1513 snprintf(buf, sizeof(buf), "%s %s",
1514 strcmpic(csp->http->ver, "HTTP/1.0") ? "HTTP/1.1" : "HTTP/1.0",
1515 rsp->status ? rsp->status : "200 OK");
1516 err = enlist_first(rsp->headers, buf);
1519 * Set the Content-Length
1521 if (rsp->content_length == 0)
1523 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1527 snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1528 err = enlist(rsp->headers, buf);
1531 if (0 == strcmpic(csp->http->gpc, "head"))
1534 * The client only asked for the head. Dispose
1535 * the body and log an offensive message.
1537 * While it may seem to be a bit inefficient to
1538 * prepare the body if it isn't needed, it's the
1539 * only way to get the Content-Length right for
1540 * dynamic pages. We could have disposed the body
1541 * earlier, but not without duplicating the
1542 * Content-Length setting code above.
1544 log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1546 rsp->content_length = 0;
1549 if (strncmpic(rsp->status, "302", 3))
1552 * If it's not a redirect without any content,
1553 * set the Content-Type to text/html if it's
1554 * not already specified.
1556 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1560 * Fill in the rest of the default headers:
1562 * Date: set to current date/time.
1563 * Last-Modified: set to date/time the page was last changed.
1564 * Expires: set to date/time page next needs reloading.
1565 * Cache-Control: set to "no-cache" if applicable.
1567 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1572 * Set Expires to about 10 min into the future so it'll get reloaded
1573 * occasionally, e.g. if Privoxy gets upgraded.
1578 get_http_time(0, buf, sizeof(buf));
1579 err = enlist_unique_header(rsp->headers, "Date", buf);
1582 /* Some date in the past. */
1583 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1587 get_http_time(10 * 60, buf, sizeof(buf)); /* 10 * 60sec = 10 minutes */
1588 err = enlist_unique_header(rsp->headers, "Expires", buf);
1591 else if (!strncmpic(rsp->status, "302", 3))
1593 get_http_time(0, buf, sizeof(buf));
1594 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1599 * Setting "Cache-Control" to "no-cache" and "Expires" to
1600 * the current time doesn't exactly forbid caching, it just
1601 * requires the client to revalidate the cached copy.
1603 * If a temporary problem occurs and the user tries again after
1604 * getting Privoxy's error message, a compliant browser may set the
1605 * If-Modified-Since header with the content of the error page's
1606 * Last-Modified header. More often than not, the document on the server
1607 * is older than Privoxy's error message, the server would send status code
1608 * 304 and the browser would display the outdated error message again and again.
1610 * For documents delivered with status code 403, 404 and 503 we set "Last-Modified"
1611 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1612 * and can be safely used to "revalidate" without getting a status code 304.
1614 * There is no need to let the useless If-Modified-Since header reach the
1615 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1617 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1619 get_http_time(0, buf, sizeof(buf));
1620 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1621 if (!strncmpic(rsp->status, "403", 3)
1622 || !strncmpic(rsp->status, "404", 3)
1623 || !strncmpic(rsp->status, "503", 3))
1625 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1629 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1631 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1632 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1638 * HTTP/1.1 applications that do not support persistent connections MUST
1639 * include the "close" connection option in every message.
1641 if (!err) err = enlist_unique_header(rsp->headers, "Connection", "close");
1646 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1648 free_http_response(rsp);
1649 return cgi_error_memory();
1651 rsp->head_length = strlen(rsp->head);
1658 /*********************************************************************
1660 * Function : alloc_http_response
1662 * Description : Allocates a new http_response structure.
1666 * Returns : pointer to a new http_response, or NULL.
1668 *********************************************************************/
1669 struct http_response *alloc_http_response(void)
1671 return (struct http_response *) zalloc(sizeof(struct http_response));
1676 /*********************************************************************
1678 * Function : free_http_response
1680 * Description : Free the memory occupied by an http_response
1681 * and its depandant structures.
1684 * 1 : rsp = pointer to http_response to be freed
1688 *********************************************************************/
1689 void free_http_response(struct http_response *rsp)
1692 * Must special case cgi_error_memory_response, which is never freed.
1694 if (rsp && (rsp != cgi_error_memory_response))
1699 destroy_list(rsp->headers);
1706 /*********************************************************************
1708 * Function : template_load
1710 * Description : CGI support function that loads a given HTML
1711 * template, ignoring comment lines and following
1712 * #include statements up to a depth of 1.
1715 * 1 : csp = Current client state (buffers, headers, etc...)
1716 * 2 : template_ptr = Destination for pointer to loaded
1718 * 3 : templatename = name of the HTML template to be used
1719 * 4 : recursive = Flag set if this function calls itself
1720 * following an #include statament
1722 * Returns : JB_ERR_OK on success
1723 * JB_ERR_MEMORY on out-of-memory error.
1724 * JB_ERR_FILE if the template file cannot be read
1726 *********************************************************************/
1727 jb_err template_load(const struct client_state *csp, char **template_ptr,
1728 const char *templatename, int recursive)
1731 char *templates_dir_path;
1734 char *included_module;
1737 char buf[BUFFER_SIZE];
1740 assert(template_ptr);
1741 assert(templatename);
1743 *template_ptr = NULL;
1745 /* Validate template name. Paranoia. */
1746 for (p = templatename; *p != 0; p++)
1748 if ( ((*p < 'a') || (*p > 'z'))
1749 && ((*p < 'A') || (*p > 'Z'))
1750 && ((*p < '0') || (*p > '9'))
1754 /* Illegal character */
1760 * Generate full path using either templdir
1761 * or confdir/templates as base directory.
1763 if (NULL != csp->config->templdir)
1765 templates_dir_path = strdup(csp->config->templdir);
1769 templates_dir_path = make_path(csp->config->confdir, "templates");
1772 if (templates_dir_path == NULL)
1774 log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
1776 return JB_ERR_MEMORY;
1779 full_path = make_path(templates_dir_path, templatename);
1780 free(templates_dir_path);
1781 if (full_path == NULL)
1783 log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
1785 return JB_ERR_MEMORY;
1788 /* Allocate buffer */
1790 file_buffer = strdup("");
1791 if (file_buffer == NULL)
1793 log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
1795 return JB_ERR_MEMORY;
1798 /* Open template file */
1800 if (NULL == (fp = fopen(full_path, "r")))
1802 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1810 * Read the file, ignoring comments, and honoring #include
1811 * statements, unless we're already called recursively.
1813 * XXX: The comment handling could break with lines lengths > sizeof(buf).
1814 * This is unlikely in practise.
1816 while (fgets(buf, sizeof(buf), fp))
1818 if (!recursive && !strncmp(buf, "#include ", 9))
1820 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1827 if (string_join(&file_buffer, included_module))
1830 return JB_ERR_MEMORY;
1836 /* skip lines starting with '#' */
1842 if (string_append(&file_buffer, buf))
1845 return JB_ERR_MEMORY;
1850 *template_ptr = file_buffer;
1856 /*********************************************************************
1858 * Function : template_fill
1860 * Description : CGI support function that fills in a pre-loaded
1861 * HTML template by replacing @name@ with value using
1862 * pcrs, for each item in the output map.
1864 * Note that a leading '$' charachter in the export map's
1865 * values will be stripped and toggle on backreference
1869 * 1 : template_ptr = IN: Template to be filled out.
1871 * OUT: Filled out template.
1872 * Caller must free().
1873 * 2 : exports = map with fill in symbol -> name pairs
1875 * Returns : JB_ERR_OK on success (and for uncritical errors)
1876 * JB_ERR_MEMORY on out-of-memory error
1878 *********************************************************************/
1879 jb_err template_fill(char **template_ptr, const struct map *exports)
1881 struct map_entry *m;
1883 char buf[BUFFER_SIZE];
1884 char *tmp_out_buffer;
1890 assert(template_ptr);
1891 assert(*template_ptr);
1894 file_buffer = *template_ptr;
1895 size = strlen(file_buffer) + 1;
1898 * Assemble pcrs joblist from exports map
1900 for (m = exports->first; m != NULL; m = m->next)
1902 if (*m->name == '$')
1905 * First character of name is '$', so remove this flag
1906 * character and allow backreferences ($1 etc) in the
1907 * "replace with" text.
1909 snprintf(buf, sizeof(buf), "%s", m->name + 1);
1915 * Treat the "replace with" text as a literal string -
1916 * no quoting needed, no backreferences allowed.
1917 * ("Trivial" ['T'] flag).
1921 /* Enclose name in @@ */
1922 snprintf(buf, sizeof(buf), "@%s@", m->name);
1925 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1927 /* Make and run job. */
1928 job = pcrs_compile(buf, m->value, flags, &error);
1931 if (error == PCRS_ERR_NOMEM)
1934 *template_ptr = NULL;
1935 return JB_ERR_MEMORY;
1939 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1940 /* Hope it wasn't important and silently ignore the invalid job */
1945 error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1948 if (NULL == tmp_out_buffer)
1950 *template_ptr = NULL;
1951 return JB_ERR_MEMORY;
1957 * Substitution failed, keep the original buffer,
1958 * log the problem and ignore it.
1960 * The user might see some unresolved @CGI_VARIABLES@,
1961 * but returning a special CGI error page seems unreasonable
1962 * and could mask more important error messages.
1964 free(tmp_out_buffer);
1965 log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
1966 buf, m->value, flags, pcrs_strerror(error));
1970 /* Substitution succeeded, use modified buffer. */
1972 file_buffer = tmp_out_buffer;
1980 *template_ptr = file_buffer;
1985 /*********************************************************************
1987 * Function : template_fill_for_cgi
1989 * Description : CGI support function that loads a HTML template
1990 * and fills it in. Handles file-not-found errors
1991 * by sending a HTML error message. For convenience,
1992 * this function also frees the passed "exports" map.
1995 * 1 : csp = Client state
1996 * 2 : templatename = name of the HTML template to be used
1997 * 3 : exports = map with fill in symbol -> name pairs.
1998 * Will be freed by this function.
1999 * 4 : rsp = Response structure to fill in.
2001 * Returns : JB_ERR_OK on success
2002 * JB_ERR_MEMORY on out-of-memory error
2004 *********************************************************************/
2005 jb_err template_fill_for_cgi(const struct client_state *csp,
2006 const char *templatename,
2007 struct map *exports,
2008 struct http_response *rsp)
2013 assert(templatename);
2017 err = template_load(csp, &rsp->body, templatename, 0);
2018 if (err == JB_ERR_FILE)
2021 return cgi_error_no_template(csp, rsp, templatename);
2026 return err; /* JB_ERR_MEMORY */
2028 err = template_fill(&rsp->body, exports);
2034 /*********************************************************************
2036 * Function : default_exports
2038 * Description : returns a struct map list that contains exports
2039 * which are common to all CGI functions.
2042 * 1 : csp = Current client state (buffers, headers, etc...)
2043 * 2 : caller = name of CGI who calls us and which should
2044 * be excluded from the generated menu. May be
2046 * Returns : NULL if no memory, else a new map. Caller frees.
2048 *********************************************************************/
2049 struct map *default_exports(const struct client_state *csp, const char *caller)
2053 struct map * exports;
2054 int local_help_exists = 0;
2055 char *ip_address = NULL;
2056 char *hostname = NULL;
2060 exports = new_map();
2061 if (exports == NULL)
2066 if (csp->config->hostname)
2068 get_host_information(csp->cfd, &ip_address, NULL);
2069 hostname = strdup(csp->config->hostname);
2073 get_host_information(csp->cfd, &ip_address, &hostname);
2076 err = map(exports, "version", 1, html_encode(VERSION), 0);
2077 get_locale_time(buf, sizeof(buf));
2078 if (!err) err = map(exports, "time", 1, html_encode(buf), 0);
2079 if (!err) err = map(exports, "my-ip-address", 1, html_encode(ip_address ? ip_address : "unknown"), 0);
2081 if (!err) err = map(exports, "my-hostname", 1, html_encode(hostname ? hostname : "unknown"), 0);
2083 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2084 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2085 if (!err) err = map(exports, "menu", 1, make_menu(caller, csp->config->feature_flags), 0);
2086 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2087 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2088 !strncmpic(csp->config->usermanual, "http", 4))
2090 /* Manual is located somewhere else, just link to it. */
2091 if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2095 /* Manual is delivered by Privoxy. */
2096 if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2098 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2099 #ifdef FEATURE_TOGGLE
2100 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2102 if (!err) err = map_block_killer(exports, "can-toggle");
2105 snprintf(buf, sizeof(buf), "%d", csp->config->hport);
2106 if (!err) err = map(exports, "my-port", 1, buf, 1);
2108 if(!strcmp(CODE_STATUS, "stable"))
2110 if (!err) err = map_block_killer(exports, "unstable");
2113 if (csp->config->admin_address != NULL)
2115 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2116 local_help_exists = 1;
2120 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2123 if (csp->config->proxy_info_url != NULL)
2125 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2126 local_help_exists = 1;
2130 if (!err) err = map_block_killer(exports, "have-proxy-info");
2133 if (local_help_exists == 0)
2135 if (!err) err = map_block_killer(exports, "have-help-info");
2148 /*********************************************************************
2150 * Function : map_block_killer
2152 * Description : Convenience function.
2153 * Adds a "killer" for the conditional HTML-template
2154 * block <name>, i.e. a substitution of the regex
2155 * "if-<name>-start.*if-<name>-end" to the given
2159 * 1 : exports = map to extend
2160 * 2 : name = name of conditional block
2162 * Returns : JB_ERR_OK on success
2163 * JB_ERR_MEMORY on out-of-memory error.
2165 *********************************************************************/
2166 jb_err map_block_killer(struct map *exports, const char *name)
2168 char buf[1000]; /* Will do, since the names are hardwired */
2172 assert(strlen(name) < (size_t)490);
2174 snprintf(buf, sizeof(buf), "if-%s-start.*if-%s-end", name, name);
2175 return map(exports, buf, 1, "", 1);
2179 /*********************************************************************
2181 * Function : map_block_keep
2183 * Description : Convenience function. Removes the markers used
2184 * by map-block-killer, to save a few bytes.
2185 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2188 * 1 : exports = map to extend
2189 * 2 : name = name of conditional block
2191 * Returns : JB_ERR_OK on success
2192 * JB_ERR_MEMORY on out-of-memory error.
2194 *********************************************************************/
2195 jb_err map_block_keep(struct map *exports, const char *name)
2198 char buf[500]; /* Will do, since the names are hardwired */
2202 assert(strlen(name) < (size_t)490);
2204 snprintf(buf, sizeof(buf), "if-%s-start", name);
2205 err = map(exports, buf, 1, "", 1);
2212 snprintf(buf, sizeof(buf), "if-%s-end", name);
2213 return map(exports, buf, 1, "", 1);
2217 /*********************************************************************
2219 * Function : map_conditional
2221 * Description : Convenience function.
2222 * Adds an "if-then-else" for the conditional HTML-template
2223 * block <name>, i.e. a substitution of the form:
2230 * The control structure and one of the alternatives
2234 * 1 : exports = map to extend
2235 * 2 : name = name of conditional block
2236 * 3 : choose_first = nonzero for first, zero for second.
2238 * Returns : JB_ERR_OK on success
2239 * JB_ERR_MEMORY on out-of-memory error.
2241 *********************************************************************/
2242 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2244 char buf[1000]; /* Will do, since the names are hardwired */
2249 assert(strlen(name) < (size_t)480);
2251 snprintf(buf, sizeof(buf), (choose_first
2252 ? "else-not-%s@.*@endif-%s"
2253 : "if-%s-then@.*@else-not-%s"),
2256 err = map(exports, buf, 1, "", 1);
2262 snprintf(buf, sizeof(buf), (choose_first ? "if-%s-then" : "endif-%s"), name);
2263 return map(exports, buf, 1, "", 1);
2267 /*********************************************************************
2269 * Function : make_menu
2271 * Description : Returns an HTML-formatted menu of the available
2272 * unhidden CGIs, excluding the one given in <self>
2273 * and the toggle CGI if toggling is disabled.
2276 * 1 : self = name of CGI to leave out, can be NULL for
2278 * 2 : feature_flags = feature bitmap from csp->config
2281 * Returns : menu string, or NULL on out-of-memory error.
2283 *********************************************************************/
2284 char *make_menu(const char *self, const unsigned feature_flags)
2286 const struct cgi_dispatcher *d;
2287 char *result = strdup("");
2291 self = "NO-SUCH-CGI!";
2294 /* List available unhidden CGI's and export as "other-cgis" */
2295 for (d = cgi_dispatchers; d->name; d++)
2298 #ifdef FEATURE_TOGGLE
2299 if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2302 * Suppress the toggle link if remote toggling is disabled.
2306 #endif /* def FEATURE_TOGGLE */
2308 if (d->description && strcmp(d->name, self))
2310 char *html_encoded_prefix;
2313 * Line breaks would be great, but break
2314 * the "blocked" template's JavaScript.
2316 string_append(&result, "<li><a href=\"");
2317 html_encoded_prefix = html_encode(CGI_PREFIX);
2318 if (html_encoded_prefix == NULL)
2324 string_append(&result, html_encoded_prefix);
2325 free(html_encoded_prefix);
2327 string_append(&result, d->name);
2328 string_append(&result, "\">");
2329 string_append(&result, d->description);
2330 string_append(&result, "</a></li>");
2338 /*********************************************************************
2340 * Function : dump_map
2342 * Description : HTML-dump a map for debugging (as table)
2345 * 1 : the_map = map to dump
2347 * Returns : string with HTML
2349 *********************************************************************/
2350 char *dump_map(const struct map *the_map)
2352 struct map_entry *cur_entry;
2353 char *ret = strdup("");
2355 string_append(&ret, "<table>\n");
2357 for (cur_entry = the_map->first;
2358 (cur_entry != NULL) && (ret != NULL);
2359 cur_entry = cur_entry->next)
2361 string_append(&ret, "<tr><td><b>");
2362 string_join (&ret, html_encode(cur_entry->name));
2363 string_append(&ret, "</b></td><td>");
2364 string_join (&ret, html_encode(cur_entry->value));
2365 string_append(&ret, "</td></tr>\n");
2368 string_append(&ret, "</table>\n");