1 const char cgi_rcs[] = "$Id: cgi.c,v 1.54 2002/03/24 16:18:15 jongfoster 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 the SourceForge
15 * Privoxy team. http://ijbswa.sourceforge.net
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.
41 * Revision 1.54 2002/03/24 16:18:15 jongfoster
44 * Revision 1.53 2002/03/24 16:06:00 oes
45 * Correct transparency for checkerboard PNG. Thanks, Magnus!
47 * Revision 1.52 2002/03/24 15:23:33 jongfoster
50 * Revision 1.51 2002/03/24 13:25:43 swa
51 * name change related issues
53 * Revision 1.50 2002/03/16 23:54:06 jongfoster
54 * Adding graceful termination feature, to help look for memory leaks.
55 * If you enable this (which, by design, has to be done by hand
56 * editing config.h) and then go to http://i.j.b/die, then the program
57 * will exit cleanly after the *next* request. It should free all the
58 * memory that was used.
60 * Revision 1.49 2002/03/13 00:27:04 jongfoster
63 * Revision 1.48 2002/03/08 17:47:07 jongfoster
66 * Revision 1.47 2002/03/08 16:41:33 oes
67 * Added GIF images again
69 * Revision 1.46 2002/03/07 03:48:38 oes
70 * - Changed built-in images from GIF to PNG
71 * (with regard to Unisys patent issue)
72 * - Added a 4x4 pattern PNG which is less intrusive
73 * than the logo but also clearly marks the deleted banners
75 * Revision 1.45 2002/03/06 22:54:35 jongfoster
76 * Automated function-comment nitpicking.
78 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
79 * - Better error reporting on OS/2
80 * - Fix double-slash comment (oops)
82 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
83 * - Re-enable OS/2 building after new parms were added
84 * - Fix false out of memory report when resolving CGI templates when no IP
85 * address is available of failed attempt (a la no such domain)
87 * Revision 1.42 2002/01/21 00:33:20 jongfoster
88 * Replacing strsav() with the safer string_append() or string_join().
89 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
90 * Adding missing html_encode() to error message generators.
91 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
93 * Revision 1.41 2002/01/17 20:56:22 jongfoster
94 * Replacing hard references to the URL of the config interface
95 * with #defines from project.h
97 * Revision 1.40 2002/01/09 14:26:46 oes
98 * Added support for thread-safe gmtime_r call.
100 * Revision 1.39 2001/11/16 00:48:13 jongfoster
101 * Fixing a compiler warning
103 * Revision 1.38 2001/11/13 00:31:21 jongfoster
104 * - Adding new CGIs for use by non-JavaScript browsers:
105 * edit-actions-url-form
106 * edit-actions-add-url-form
107 * edit-actions-remove-url-form
108 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
111 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
112 * Show enablement/disablement status in almost all templates.
113 * There is a little trickiness here: apparent recursive resolution of
114 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
115 * the actual enablement status. So a similar construct,
116 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
119 * Revision 1.36 2001/10/26 17:33:27 oes
122 * Revision 1.35 2001/10/23 21:48:19 jongfoster
123 * Cleaning up error handling in CGI functions - they now send back
124 * a HTML error page and should never cause a FATAL error. (Fixes one
125 * potential source of "denial of service" attacks).
127 * CGI actions file editor that works and is actually useful.
129 * Ability to toggle JunkBuster remotely using a CGI call.
131 * You can turn off both the above features in the main configuration
132 * file, e.g. if you are running a multi-user proxy.
134 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
135 * Only show "Local support" on templates conditionally:
136 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
137 * - if not, no Local support section appears
139 * Revision 1.33 2001/10/14 22:28:41 jongfoster
140 * Fixing stupid typo.
142 * Revision 1.32 2001/10/14 22:20:18 jongfoster
143 * - Changes to CGI dispatching method to match CGI names exactly,
144 * rather than doing a prefix match.
145 * - No longer need to count the length of the CGI handler names by hand.
146 * - Adding new handler for 404 error when disptching a CGI, if none of
147 * the handlers match.
148 * - Adding new handlers for CGI actionsfile editor.
150 * Revision 1.31 2001/10/10 10:56:39 oes
151 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
153 * Revision 1.30 2001/10/02 15:30:57 oes
154 * Introduced show-request cgi
156 * Revision 1.29 2001/09/20 15:47:44 steudten
158 * Fix BUG: Modify int size to size_t size in fill_template()
159 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
161 * Revision 1.28 2001/09/19 18:00:37 oes
162 * - Deletef time() FIXME (Can't fail under Linux either, if
163 * the argument is guaranteed to be in out address space,
166 * - Pointer notation cosmetics
167 * - Fixed a minor bug in template_fill(): Failiure of
168 * pcrs_execute() now secure.
170 * Revision 1.27 2001/09/16 17:08:54 jongfoster
171 * Moving simple CGI functions from cgi.c to new file cgisimple.c
173 * Revision 1.26 2001/09/16 15:47:37 jongfoster
174 * First version of CGI-based edit interface. This is very much a
175 * work-in-progress, and you can't actually use it to edit anything
176 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
177 * to have any effect.
179 * Revision 1.25 2001/09/16 15:02:35 jongfoster
180 * Adding i.j.b/robots.txt.
181 * Inlining add_stats() since it's only ever called from one place.
183 * Revision 1.24 2001/09/16 11:38:01 jongfoster
184 * Splitting fill_template() into 2 functions:
185 * template_load() loads the file
186 * template_fill() performs the PCRS regexps.
187 * This is because the CGI edit interface has a "table row"
188 * template which is used many times in the page - this
189 * change means it's only loaded from disk once.
191 * Revision 1.23 2001/09/16 11:16:05 jongfoster
192 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
194 * Revision 1.22 2001/09/16 11:00:10 jongfoster
195 * New function alloc_http_response, for symmetry with free_http_response
197 * Revision 1.21 2001/09/13 23:53:03 jongfoster
198 * Support for both static and dynamically generated CGI pages.
199 * Correctly setting Last-Modified: and Expires: HTTP headers.
201 * Revision 1.20 2001/09/13 23:40:36 jongfoster
202 * (Cosmetic only) Indentation correction
204 * Revision 1.19 2001/09/13 23:31:25 jongfoster
205 * Moving image data to cgi.c rather than cgi.h.
207 * Revision 1.18 2001/08/05 16:06:20 jongfoster
208 * Modifiying "struct map" so that there are now separate header and
209 * "map_entry" structures. This means that functions which modify a
210 * map no longer need to return a pointer to the modified map.
211 * Also, it no longer reverses the order of the entries (which may be
212 * important with some advanced template substitutions).
214 * Revision 1.17 2001/08/05 15:57:38 oes
215 * Adapted finish_http_response to new list_to_text
217 * Revision 1.16 2001/08/01 21:33:18 jongfoster
218 * Changes to fill_template() that reduce memory usage without having
219 * an impact on performance. I also renamed some variables so as not
220 * to clash with the C++ keywords "new" and "template".
222 * Revision 1.15 2001/08/01 21:19:22 jongfoster
223 * Moving file version information to a separate CGI page.
225 * Revision 1.14 2001/08/01 00:19:03 jongfoster
226 * New function: map_conditional() for an if-then-else syntax.
227 * Changing to use new version of show_defines()
229 * Revision 1.13 2001/07/30 22:08:36 jongfoster
230 * Tidying up #defines:
231 * - All feature #defines are now of the form FEATURE_xxx
232 * - Permanently turned off WIN_GUI_EDIT
233 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
235 * Revision 1.12 2001/07/29 18:47:05 jongfoster
236 * Adding missing #include "loadcfg.h"
238 * Revision 1.11 2001/07/18 17:24:37 oes
239 * Changed to conform to new pcrs interface
241 * Revision 1.10 2001/07/13 13:53:13 oes
242 * Removed all #ifdef PCRS and related code
244 * Revision 1.9 2001/06/29 21:45:41 oes
245 * Indentation, CRLF->LF, Tab-> Space
247 * Revision 1.8 2001/06/29 13:21:46 oes
248 * - Cosmetics: renamed and reordered functions, variables,
249 * texts, improved comments etc
251 * - Removed ij_untrusted_url() The relevant
252 * info is now part of the "untrusted" page,
253 * which is generated by filters.c:trust_url()
255 * - Generators of content now call finish_http_response()
256 * themselves, making jcc.c:chat() a little less
259 * - Removed obsolete "Pragma: no-cache" from our headers
261 * - http_responses now know their head length
263 * - fill_template now uses the new interface to pcrs, so that
264 * - long jobs (like whole files) no longer have to be assembled
265 * in a fixed size buffer
266 * - the new T (trivial) option is used, and the replacement may
267 * contain Perl syntax backrefs without confusing pcrs
269 * - Introduced default_exports() which generates a set of exports
270 * common to all CGIs and other content generators
272 * - Introduced convenience function map_block_killer()
274 * - Introduced convenience function make_menu()
276 * - Introduced CGI-like function error_response() which generates
277 * the "No such domain" and "Connect failed" messages using the
280 * - cgi_show_url_info:
281 * - adapted to new CGI features
282 * - form and answers now generated from same template
283 * - http:// prefix in URL now OK
286 * - adapted to new CGI features
287 * - no longer uses csp->init_proxy_args
290 * - moved menu generation to make_menu()
292 * - add_stats now writes single export map entries instead
295 * - Moved redirect_url() to filters.c
297 * - Fixed mem leak in free_http_response(), map_block_killer(),
299 * - Removed logentry from cancelled commit
301 * Revision 1.7 2001/06/09 10:51:58 jongfoster
302 * Changing "show URL info" handler to new style.
303 * Changing BUFSIZ ==> BUFFER_SIZE
305 * Revision 1.6 2001/06/07 23:05:19 jongfoster
306 * Removing code related to old forward and ACL files.
308 * Revision 1.5 2001/06/05 19:59:16 jongfoster
309 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
311 * Revision 1.4 2001/06/04 10:41:52 swa
312 * show version string of cgi.h and cgi.c
314 * Revision 1.3 2001/06/03 19:12:16 oes
315 * introduced new cgi handling
317 * No revisions before 1.3
319 **********************************************************************/
325 #include <sys/types.h>
332 #define snprintf _snprintf
333 #endif /* def _WIN32 */
341 #include "miscutil.h"
342 #include "cgisimple.h"
343 #ifdef FEATURE_CGI_EDIT_ACTIONS
345 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
347 /* loadcfg.h is for g_bToggleIJB only */
349 const char cgi_h_rcs[] = CGI_H_VERSION;
351 static const struct cgi_dispatcher cgi_dispatchers[] = {
354 "Privoxy main page" },
355 #ifdef FEATURE_GRACEFUL_TERMINATION
358 "<b>Shut down</b> - <font color=red size='+1'>Do not deploy this build in a production environment, this is a one click Denial Of Service attack!!!</font>" },
362 "Show information about the current configuration" },
365 "Show the source code version numbers" },
368 "Show the client's request headers." },
371 "Show which actions apply to a URL and why" },
374 "Toggle Privoxy on or off" },
375 #ifdef FEATURE_CGI_EDIT_ACTIONS
378 "Edit the actions list" },
381 { "eaa", /* Shortcut for edit-actions-add-url-form */
382 cgi_edit_actions_add_url_form,
384 { "eau", /* Shortcut for edit-actions-url-form */
385 cgi_edit_actions_url_form,
387 { "ear", /* Shortcut for edit-actions-remove-url-form */
388 cgi_edit_actions_remove_url_form,
390 { "eas", /* Shortcut for edit-actions-for-url */
391 cgi_edit_actions_for_url,
393 { "easa", /* Shortcut for edit-actions-section-add */
394 cgi_edit_actions_section_add,
396 { "easr", /* Shortcut for edit-actions-section-remove */
397 cgi_edit_actions_section_remove,
399 { "eass", /* Shortcut for edit-actions-section-swap */
400 cgi_edit_actions_section_swap,
402 { "edit-actions-for-url",
403 cgi_edit_actions_for_url,
404 NULL /* Edit the actions for (a) specified URL(s) */ },
405 { "edit-actions-list",
406 cgi_edit_actions_list,
407 NULL /* Edit the actions list */ },
408 { "edit-actions-submit",
409 cgi_edit_actions_submit,
410 NULL /* Change the actions for (a) specified URL(s) */ },
411 { "edit-actions-url",
412 cgi_edit_actions_url,
413 NULL /* Change a URL pattern in the actionsfile */ },
414 { "edit-actions-url-form",
415 cgi_edit_actions_url_form,
416 NULL /* Form to change a URL pattern in the actionsfile */ },
417 { "edit-actions-add-url",
418 cgi_edit_actions_add_url,
419 NULL /* Add a URL pattern to the actionsfile */ },
420 { "edit-actions-add-url-form",
421 cgi_edit_actions_add_url_form,
422 NULL /* Form to add a URL pattern to the actionsfile */ },
423 { "edit-actions-remove-url",
424 cgi_edit_actions_remove_url,
425 NULL /* Remove a URL pattern from the actionsfile */ },
426 { "edit-actions-remove-url-form",
427 cgi_edit_actions_remove_url_form,
428 NULL /* Form to remove a URL pattern from the actionsfile */ },
429 { "edit-actions-section-add",
430 cgi_edit_actions_section_add,
431 NULL /* Remove a section from the actionsfile */ },
432 { "edit-actions-section-remove",
433 cgi_edit_actions_section_remove,
434 NULL /* Remove a section from the actionsfile */ },
435 { "edit-actions-section-swap",
436 cgi_edit_actions_section_swap,
437 NULL /* Swap two sections in the actionsfile */ },
438 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
441 NULL /* Sends a robots.txt file to tell robots to go away. */ },
444 NULL /* Send a built-in image */ },
446 cgi_transparent_image,
447 NULL /* Send a transparent image (short name) */ },
448 { NULL, /* NULL Indicates end of list and default page */
450 NULL /* Unknown CGI page */ }
455 * Bulit-in images for ad replacement
457 * Hint: You can encode your own images like this:
458 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
461 #ifdef FEATURE_NO_GIFS
464 * Checkerboard pattern, as a PNG.
466 const char image_pattern_data[] =
467 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
468 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
469 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
470 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
471 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
472 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
473 "\000\000\000\111\105\116\104\256\102\140\202";
476 * 1x1 transparant PNG.
478 const char image_blank_data[] =
479 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
480 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
481 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
482 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
483 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
484 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
485 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
486 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
487 "\000\000\000\000\111\105\116\104\256\102\140\202";
491 * Checkerboard pattern, as a GIF.
493 const char image_pattern_data[] =
494 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
495 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
496 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
497 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
501 * 1x1 transparant GIF.
503 const char image_blank_data[] =
504 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
505 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
506 "\000\001\000\000\002\002D\001\000;";
509 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
510 const size_t image_blank_length = sizeof(image_blank_data) - 1;
513 static struct http_response cgi_error_memory_response[1];
515 static struct http_response *dispatch_known_cgi(struct client_state * csp,
517 static struct map *parse_cgi_parameters(char *argstring);
520 /*********************************************************************
522 * Function : dispatch_cgi
524 * Description : Checks if a request URL has either the magical
525 * hostname CGI_SITE_1_HOST (usully http://i.j.b/) or
526 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
527 * http://ijbswa.sourceforge.net/config). If so, it passes
528 * the (rest of the) path onto dispatch_known_cgi, which
529 * calls the relevant CGI handler function.
532 * 1 : csp = Current client state (buffers, headers, etc...)
534 * Returns : http_response if match, NULL if nonmatch or handler fail
536 *********************************************************************/
537 struct http_response *dispatch_cgi(struct client_state *csp)
539 const char *host = csp->http->host;
540 const char *path = csp->http->path;
543 * Should we intercept ?
546 /* Note: "example.com" and "example.com." are equivalent hostnames. */
548 /* Either the host matches CGI_SITE_1_HOST ..*/
549 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
550 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
551 && (path[0] == '/') )
553 /* ..then the path will all be for us. Remove leading '/' */
556 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
557 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
558 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
559 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
561 /* take everything following CGI_SITE_2_PATH */
562 path += strlen(CGI_SITE_2_PATH);
565 /* skip the forward slash after CGI_SITE_2_PATH */
568 else if (*path != '\0')
571 * wierdness: URL is /configXXX, where XXX is some string
572 * Do *NOT* intercept.
584 * This is a CGI call.
587 return dispatch_known_cgi(csp, path);
591 /*********************************************************************
593 * Function : dispatch_known_cgi
595 * Description : Processes a CGI once dispatch_cgi has determined that
596 * it matches one of the magic prefixes. Parses the path
597 * as a cgi name plus query string, prepares a map that
598 * maps CGI parameter names to their values, initializes
599 * the http_response struct, and calls the relevant CGI
603 * 1 : csp = Current client state (buffers, headers, etc...)
604 * 2 : path = Path of CGI, with the CGI prefix removed.
605 * Should not have a leading "/".
607 * Returns : http_response, or NULL on handler failure or out of
610 *********************************************************************/
611 static struct http_response *dispatch_known_cgi(struct client_state * csp,
614 const struct cgi_dispatcher *d;
615 struct map *param_list;
616 struct http_response *rsp;
617 char *query_args_start;
621 if (NULL == (path_copy = strdup(path)))
623 return cgi_error_memory();
626 query_args_start = path_copy;
627 while (*query_args_start && *query_args_start != '?')
631 if (*query_args_start == '?')
633 *query_args_start++ = '\0';
636 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
639 return cgi_error_memory();
645 * path_copy = CGI call name
646 * param_list = CGI params, as map
649 /* Get mem for response or fail*/
650 if (NULL == (rsp = alloc_http_response()))
653 free_map(param_list);
654 return cgi_error_memory();
657 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
658 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
659 csp->ip_addr_str, csp->http->cmd);
661 /* Find and start the right CGI function*/
665 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
667 err = (d->handler)(csp, rsp, param_list);
669 free_map(param_list);
670 if (err == JB_ERR_CGI_PARAMS)
672 err = cgi_error_bad_param(csp, rsp);
677 return finish_http_response(rsp);
681 /* Error in handler, probably out-of-memory */
682 free_http_response(rsp);
683 return cgi_error_memory();
691 /*********************************************************************
693 * Function : parse_cgi_parameters
695 * Description : Parse a URL-encoded argument string into name/value
696 * pairs and store them in a struct map list.
699 * 1 : string = string to be parsed. Will be trashed.
701 * Returns : pointer to param list, or NULL if out of memory.
703 *********************************************************************/
704 static struct map *parse_cgi_parameters(char *argstring)
707 char *vector[BUFFER_SIZE];
709 struct map *cgi_params;
711 if (NULL == (cgi_params = new_map()))
716 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
718 for (i = 0; i < pairs; i++)
720 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
723 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
725 free_map(cgi_params);
736 /*********************************************************************
738 * Function : error_response
740 * Description : returns an http_response that explains the reason
741 * why a request failed.
744 * 1 : csp = Current client state (buffers, headers, etc...)
745 * 2 : templatename = Which template should be used for the answer
746 * 3 : sys_err = system error number
748 * Returns : A http_response. If we run out of memory, this
749 * will be cgi_error_memory().
751 *********************************************************************/
752 struct http_response *error_response(struct client_state *csp,
753 const char *templatename,
757 struct http_response *rsp;
758 struct map * exports = default_exports(csp, NULL);
761 return cgi_error_memory();
764 if (NULL == (rsp = alloc_http_response()))
767 return cgi_error_memory();
770 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
771 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
772 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
773 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
776 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
779 /* Some failures, like "404 no such domain", don't have an IP address. */
780 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
788 free_http_response(rsp);
789 return cgi_error_memory();
792 if (!strcmp(templatename, "no-such-domain"))
794 rsp->status = strdup("404 No such domain");
795 if (rsp->status == NULL)
798 free_http_response(rsp);
799 return cgi_error_memory();
802 else if (!strcmp(templatename, "connect-failed"))
804 rsp->status = strdup("503 Connect failed");
805 if (rsp->status == NULL)
808 free_http_response(rsp);
809 return cgi_error_memory();
813 err = template_fill_for_cgi(csp, templatename, exports, rsp);
816 free_http_response(rsp);
817 return cgi_error_memory();
820 return finish_http_response(rsp);
824 /*********************************************************************
826 * Function : cgi_init_error_messages
828 * Description : Call at the start of the program to initialize
829 * the error message used by cgi_error_memory().
835 *********************************************************************/
836 void cgi_init_error_messages(void)
838 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
839 cgi_error_memory_response->head =
840 "HTTP/1.0 500 Internal Privoxy Error\r\n"
841 "Content-Type: text/html\r\n"
843 cgi_error_memory_response->body =
845 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
847 "<h1>500 Internal Privoxy Error</h1>\r\n"
848 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
849 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
853 cgi_error_memory_response->head_length =
854 strlen(cgi_error_memory_response->head);
855 cgi_error_memory_response->content_length =
856 strlen(cgi_error_memory_response->body);
860 /*********************************************************************
862 * Function : cgi_error_memory
864 * Description : Called if a CGI function runs out of memory.
865 * Returns a statically-allocated error response.
868 * 1 : csp = Current client state (buffers, headers, etc...)
869 * 2 : rsp = http_response data structure for output
870 * 3 : template_name = Name of template that could not
873 * Returns : JB_ERR_OK on success
874 * JB_ERR_MEMORY on out-of-memory error.
876 *********************************************************************/
877 struct http_response *cgi_error_memory(void)
879 /* assert that it's been initialized. */
880 assert(cgi_error_memory_response->head);
882 return cgi_error_memory_response;
886 /*********************************************************************
888 * Function : cgi_error_no_template
890 * Description : Almost-CGI function that is called if a templae
891 * cannot be loaded. Note this is not a true CGI,
892 * it takes a template name rather than a map of
896 * 1 : csp = Current client state (buffers, headers, etc...)
897 * 2 : rsp = http_response data structure for output
898 * 3 : template_name = Name of template that could not
901 * Returns : JB_ERR_OK on success
902 * JB_ERR_MEMORY on out-of-memory error.
904 *********************************************************************/
905 jb_err cgi_error_no_template(struct client_state *csp,
906 struct http_response *rsp,
907 const char *template_name)
909 static const char status[] =
910 "500 Internal Privoxy Error";
911 static const char body_prefix[] =
913 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
915 "<h1>500 Internal Privoxy Error</h1>\r\n"
916 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
917 "<p><b>Could not load template file <code>";
918 static const char body_suffix[] =
919 "</code></b></p>\r\n"
920 "<p>Please contact your proxy administrator.</p>\r\n"
921 "<p>If you are the proxy administrator, please put the required file "
922 "in the <code><i>(confdir)</i>/templates</code> directory. The "
923 "location of the <code><i>(confdir)</i></code> directory "
924 "is specified in the main Privoxy <code>config</code> "
925 "file. (It's typically the Privoxy install directory"
927 ", or <code>/etc/privoxy/</code>"
928 #endif /* ndef _WIN32 */
935 assert(template_name);
937 /* Reset rsp, if needed */
941 rsp->content_length = 0;
942 rsp->head_length = 0;
945 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
946 if (rsp->body == NULL)
948 return JB_ERR_MEMORY;
950 strcpy(rsp->body, body_prefix);
951 strcat(rsp->body, template_name);
952 strcat(rsp->body, body_suffix);
954 rsp->status = strdup(status);
955 if (rsp->body == NULL)
957 return JB_ERR_MEMORY;
964 /*********************************************************************
966 * Function : cgi_error_bad_param
968 * Description : CGI function that is called if the parameters
969 * (query string) for a CGI were wrong.
972 * 1 : csp = Current client state (buffers, headers, etc...)
973 * 2 : rsp = http_response data structure for output
975 * CGI Parameters : none
977 * Returns : JB_ERR_OK on success
978 * JB_ERR_MEMORY on out-of-memory error.
980 *********************************************************************/
981 jb_err cgi_error_bad_param(struct client_state *csp,
982 struct http_response *rsp)
989 if (NULL == (exports = default_exports(csp, NULL)))
991 return JB_ERR_MEMORY;
994 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
998 /*********************************************************************
1000 * Function : get_http_time
1002 * Description : Get the time in a format suitable for use in a
1003 * HTTP header - e.g.:
1004 * "Sun, 06 Nov 1994 08:49:37 GMT"
1007 * 1 : time_offset = Time returned will be current time
1008 * plus this number of seconds.
1009 * 2 : buf = Destination for result. Must be long enough
1010 * to hold 29 characters plus a trailing zero.
1014 *********************************************************************/
1015 void get_http_time(int time_offset, char *buf)
1017 static const char day_names[7][4] =
1018 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1019 static const char month_names[12][4] =
1020 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1021 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1024 time_t current_time;
1028 time(¤t_time); /* get current time */
1030 current_time += time_offset;
1032 /* get and save the gmt */
1034 #ifdef HAVE_GMTIME_R
1036 t = gmtime_r(¤t_time, &dummy);
1038 t = gmtime(¤t_time);
1042 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1044 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1045 day_names[t->tm_wday],
1047 month_names[t->tm_mon],
1057 /*********************************************************************
1059 * Function : finish_http_response
1061 * Description : Fill in the missing headers in an http response,
1062 * and flatten the headers to an http head.
1065 * 1 : rsp = pointer to http_response to be processed
1067 * Returns : A http_response, usually the rsp parameter.
1068 * On error, free()s rsp and returns cgi_error_memory()
1070 *********************************************************************/
1071 struct http_response *finish_http_response(struct http_response *rsp)
1073 char buf[BUFFER_SIZE];
1076 /* Special case - do NOT change this statically allocated response,
1077 * which is ready for output anyway.
1079 if (rsp == cgi_error_memory_response)
1085 * Fill in the HTTP Status
1087 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1088 err = enlist_first(rsp->headers, buf);
1091 * Set the Content-Length
1093 if (rsp->content_length == 0)
1095 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1099 sprintf(buf, "Content-Length: %d", rsp->content_length);
1100 err = enlist(rsp->headers, buf);
1104 * Fill in the default headers:
1106 * Content-Type: default to text/html if not already specified.
1107 * Date: set to current date/time.
1108 * Last-Modified: set to date/time the page was last changed.
1109 * Expires: set to date/time page next needs reloading.
1110 * Cache-Control: set to "no-cache" if applicable.
1112 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1114 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1119 * Set Expires to about 10 min into the future so it'll get reloaded
1120 * occasionally, e.g. if Privoxy gets upgraded.
1125 get_http_time(0, buf);
1126 err = enlist_unique_header(rsp->headers, "Date", buf);
1129 /* Some date in the past. */
1130 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1134 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1135 err = enlist_unique_header(rsp->headers, "Expires", buf);
1141 * Compliant browsers should not cache this due to the "Cache-Control"
1142 * setting. However, to be certain, we also set both "Last-Modified"
1143 * and "Expires" to the current time.
1145 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1147 get_http_time(0, buf);
1148 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1149 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1150 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1157 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1159 free_http_response(rsp);
1160 return cgi_error_memory();
1162 rsp->head_length = strlen(rsp->head);
1169 /*********************************************************************
1171 * Function : alloc_http_response
1173 * Description : Allocates a new http_response structure.
1177 * Returns : pointer to a new http_response, or NULL.
1179 *********************************************************************/
1180 struct http_response *alloc_http_response(void)
1182 return (struct http_response *) zalloc(sizeof(struct http_response));
1187 /*********************************************************************
1189 * Function : free_http_response
1191 * Description : Free the memory occupied by an http_response
1192 * and its depandant structures.
1195 * 1 : rsp = pointer to http_response to be freed
1199 *********************************************************************/
1200 void free_http_response(struct http_response *rsp)
1203 * Must special case cgi_error_memory_response, which is never freed.
1205 if (rsp && (rsp != cgi_error_memory_response))
1210 destroy_list(rsp->headers);
1217 /*********************************************************************
1219 * Function : template_load
1221 * Description : CGI support function that loads a given HTML
1222 * template from the confdir, ignoring comment
1226 * 1 : csp = Current client state (buffers, headers, etc...)
1227 * 2 : template_ptr = Destination for pointer to loaded
1229 * 3 : template = name of the HTML template to be used
1231 * Returns : JB_ERR_OK on success
1232 * JB_ERR_MEMORY on out-of-memory error.
1233 * JB_ERR_FILE if the template file cannot be read
1235 *********************************************************************/
1236 jb_err template_load(struct client_state *csp, char ** template_ptr,
1237 const char *templatename)
1239 char *templates_dir_path;
1243 char buf[BUFFER_SIZE];
1246 assert(template_ptr);
1247 assert(templatename);
1249 *template_ptr = NULL;
1252 * Open template file or fail
1255 templates_dir_path = make_path(csp->config->confdir, "templates");
1256 if (templates_dir_path == NULL)
1258 return JB_ERR_MEMORY;
1261 full_path = make_path(templates_dir_path, templatename);
1262 free(templates_dir_path);
1263 if (full_path == NULL)
1265 return JB_ERR_MEMORY;
1268 file_buffer = strdup("");
1269 if (file_buffer == NULL)
1272 return JB_ERR_MEMORY;
1275 if (NULL == (fp = fopen(full_path, "r")))
1277 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1285 * Read the file, ignoring comments.
1287 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1288 * This is unlikely in practise.
1290 while (fgets(buf, BUFFER_SIZE, fp))
1292 /* skip lines starting with '#' */
1298 if (string_append(&file_buffer, buf))
1301 return JB_ERR_MEMORY;
1306 *template_ptr = file_buffer;
1312 /*********************************************************************
1314 * Function : template_fill
1316 * Description : CGI support function that fills in a pre-loaded
1317 * HTML template by replacing @name@ with value using
1318 * pcrs, for each item in the output map.
1320 * Note that a leading '$' charachter in the export map's
1321 * values will be stripped and toggle on backreference
1325 * 1 : template_ptr = IN: Template to be filled out.
1327 * OUT: Filled out template.
1328 * Caller must free().
1329 * 2 : exports = map with fill in symbol -> name pairs
1331 * Returns : JB_ERR_OK on success
1332 * JB_ERR_MEMORY on out-of-memory error
1334 *********************************************************************/
1335 jb_err template_fill(char **template_ptr, const struct map *exports)
1337 struct map_entry *m;
1339 char buf[BUFFER_SIZE];
1340 char *tmp_out_buffer;
1346 assert(template_ptr);
1347 assert(*template_ptr);
1350 file_buffer = *template_ptr;
1351 size = strlen(file_buffer) + 1;
1354 * Assemble pcrs joblist from exports map
1356 for (m = exports->first; m != NULL; m = m->next)
1358 if (*m->name == '$')
1361 * First character of name is '$', so remove this flag
1362 * character and allow backreferences ($1 etc) in the
1363 * "replace with" text.
1365 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1371 * Treat the "replace with" text as a literal string -
1372 * no quoting needed, no backreferences allowed.
1373 * ("Trivial" ['T'] flag).
1377 /* Enclose name in @@ */
1378 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1382 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1384 /* Make and run job. */
1385 job = pcrs_compile(buf, m->value, flags, &error);
1388 if (error == PCRS_ERR_NOMEM)
1391 *template_ptr = NULL;
1392 return JB_ERR_MEMORY;
1396 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1397 /* Hope it wasn't important and silently ignore the invalid job */
1402 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1405 if (NULL == tmp_out_buffer)
1407 *template_ptr = NULL;
1408 return JB_ERR_MEMORY;
1410 file_buffer = tmp_out_buffer;
1417 *template_ptr = file_buffer;
1422 /*********************************************************************
1424 * Function : template_fill_for_cgi
1426 * Description : CGI support function that loads a HTML template
1427 * and fills it in. Handles file-not-found errors
1428 * by sending a HTML error message. For convenience,
1429 * this function also frees the passed "exports" map.
1432 * 1 : csp = Client state
1433 * 2 : templatename = name of the HTML template to be used
1434 * 3 : exports = map with fill in symbol -> name pairs.
1435 * Will be freed by this function.
1437 * Returns : JB_ERR_OK on success
1438 * JB_ERR_MEMORY on out-of-memory error
1440 *********************************************************************/
1441 jb_err template_fill_for_cgi(struct client_state *csp,
1442 const char *templatename,
1443 struct map *exports,
1444 struct http_response *rsp)
1449 assert(templatename);
1453 err = template_load(csp, &rsp->body, templatename);
1454 if (err == JB_ERR_FILE)
1457 return cgi_error_no_template(csp, rsp, templatename);
1462 return err; /* JB_ERR_MEMORY */
1464 err = template_fill(&rsp->body, exports);
1470 /*********************************************************************
1472 * Function : default_exports
1474 * Description : returns a struct map list that contains exports
1475 * which are common to all CGI functions.
1478 * 1 : csp = Current client state (buffers, headers, etc...)
1479 * 2 : caller = name of CGI who calls us and which should
1480 * be excluded from the generated menu. May be
1482 * Returns : NULL if no memory, else a new map. Caller frees.
1484 *********************************************************************/
1485 struct map *default_exports(const struct client_state *csp, const char *caller)
1489 struct map * exports;
1490 int local_help_exists = 0;
1494 exports = new_map();
1495 if (exports == NULL)
1500 err = map(exports, "version", 1, html_encode(VERSION), 0);
1501 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1502 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1503 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
1504 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
1505 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
1506 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
1507 if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1509 snprintf(buf, 20, "%d", csp->config->hport);
1510 if (!err) err = map(exports, "my-port", 1, buf, 1);
1512 if(!strcmp(CODE_STATUS, "stable"))
1514 if (!err) err = map_block_killer(exports, "unstable");
1517 if (csp->config->admin_address != NULL)
1519 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1520 local_help_exists = 1;
1524 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1527 if (csp->config->proxy_info_url != NULL)
1529 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1530 local_help_exists = 1;
1534 if (!err) err = map_block_killer(exports, "have-proxy-info");
1537 if (local_help_exists == 0)
1539 if (!err) err = map_block_killer(exports, "have-help-info");
1552 /*********************************************************************
1554 * Function : map_block_killer
1556 * Description : Convenience function.
1557 * Adds a "killer" for the conditional HTML-template
1558 * block <name>, i.e. a substitution of the regex
1559 * "if-<name>-start.*if-<name>-end" to the given
1563 * 1 : exports = map to extend
1564 * 2 : name = name of conditional block
1566 * Returns : JB_ERR_OK on success
1567 * JB_ERR_MEMORY on out-of-memory error.
1569 *********************************************************************/
1570 jb_err map_block_killer(struct map *exports, const char *name)
1572 char buf[1000]; /* Will do, since the names are hardwired */
1576 assert(strlen(name) < 490);
1578 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1579 return map(exports, buf, 1, "", 1);
1583 /*********************************************************************
1585 * Function : map_block_keep
1587 * Description : Convenience function. Removes the markers used
1588 * by map-block-killer, to save a few bytes.
1589 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1592 * 1 : exports = map to extend
1593 * 2 : name = name of conditional block
1595 * Returns : JB_ERR_OK on success
1596 * JB_ERR_MEMORY on out-of-memory error.
1598 *********************************************************************/
1599 jb_err map_block_keep(struct map *exports, const char *name)
1602 char buf[500]; /* Will do, since the names are hardwired */
1606 assert(strlen(name) < 490);
1608 snprintf(buf, 500, "if-%s-start", name);
1609 err = map(exports, buf, 1, "", 1);
1616 snprintf(buf, 500, "if-%s-end", name);
1617 return map(exports, buf, 1, "", 1);
1621 /*********************************************************************
1623 * Function : map_conditional
1625 * Description : Convenience function.
1626 * Adds an "if-then-else" for the conditional HTML-template
1627 * block <name>, i.e. a substitution of the form:
1634 * The control structure and one of the alternatives
1638 * 1 : exports = map to extend
1639 * 2 : name = name of conditional block
1640 * 3 : choose_first = nonzero for first, zero for second.
1642 * Returns : JB_ERR_OK on success
1643 * JB_ERR_MEMORY on out-of-memory error.
1645 *********************************************************************/
1646 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1648 char buf[1000]; /* Will do, since the names are hardwired */
1653 assert(strlen(name) < 480);
1655 snprintf(buf, 1000, (choose_first
1656 ? "else-not-%s@.*@endif-%s"
1657 : "if-%s-then@.*@else-not-%s"),
1660 err = map(exports, buf, 1, "", 1);
1666 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1667 return map(exports, buf, 1, "", 1);
1671 /*********************************************************************
1673 * Function : make_menu
1675 * Description : Returns an HTML-formatted menu of the available
1676 * unhidden CGIs, excluding the one given in <self>.
1678 * Parameters : self = name of CGI to leave out, can be NULL
1680 * Returns : menu string, or NULL on out-of-memory error.
1682 *********************************************************************/
1683 char *make_menu(const char *self)
1685 const struct cgi_dispatcher *d;
1686 char *result = strdup("");
1690 self = "NO-SUCH-CGI!";
1693 /* List available unhidden CGI's and export as "other-cgis" */
1694 for (d = cgi_dispatchers; d->name; d++)
1696 if (d->description && strcmp(d->name, self))
1698 string_append(&result, "<li><a href=\"" CGI_PREFIX);
1699 string_append(&result, d->name);
1700 string_append(&result, "\">");
1701 string_append(&result, d->description);
1702 string_append(&result, "</a></li>\n");
1710 /*********************************************************************
1712 * Function : dump_map
1714 * Description : HTML-dump a map for debugging
1717 * 1 : the_map = map to dump
1719 * Returns : string with HTML
1721 *********************************************************************/
1722 char *dump_map(const struct map *the_map)
1724 struct map_entry *cur_entry;
1725 char *ret = strdup("");
1727 string_append(&ret, "<table>\n");
1729 for (cur_entry = the_map->first;
1730 (cur_entry != NULL) && (ret != NULL);
1731 cur_entry = cur_entry->next)
1733 string_append(&ret, "<tr><td><b>");
1734 string_join (&ret, html_encode(cur_entry->name));
1735 string_append(&ret, "</b></td><td>");
1736 string_join (&ret, html_encode(cur_entry->value));
1737 string_append(&ret, "</td></tr>\n");
1740 string_append(&ret, "</table>\n");