1 const char cgi_rcs[] = "$Id: cgi.c,v 1.77 2006/09/21 15:17:23 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 the SourceForge
15 * 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.
41 * Revision 1.77 2006/09/21 15:17:23 fabiankeil
42 * Adjusted headers for Privoxy's cgi responses:
43 * Don't set Last-Modified, Expires and Cache-Control
44 * headers for redirects; always set "Connection: close".
46 * Revision 1.76 2006/09/07 14:06:38 fabiankeil
47 * Only predate the Last-Modified header for cgi responses
48 * that are delivered with status code 404 or 503.
50 * Revision 1.75 2006/09/07 11:56:39 fabiankeil
51 * Mark cgi_send_user_manual as harmless,
52 * to fix the access denied problem Hal spotted.
53 * The manual has no secret content, therefore we
54 * don't have to care about "secure" referrers.
56 * Revision 1.74 2006/09/06 18:45:03 fabiankeil
57 * Incorporate modified version of Roland Rosenfeld's patch to
58 * optionally access the user-manual via Privoxy. Closes patch 679075.
60 * Formatting changed to Privoxy style, added call to
61 * cgi_error_no_template if the requested file doesn't
62 * exist and modified check whether or not Privoxy itself
63 * should serve the manual. Should work cross-platform now.
65 * Revision 1.73 2006/08/03 02:46:41 david__schmidt
66 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
68 * Revision 1.72 2006/07/18 14:48:45 david__schmidt
69 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
70 * with what was really the latest development (the v_3_0_branch branch)
72 * Revision 1.70.2.13 2004/02/17 13:30:23 oes
73 * Moved cgi_error_disabled() from cgiedit.c to
74 * cgi.c to re-enable build with --disable-editor.
75 * Fixes Bug #892744. Thanks to Matthew Fischer
78 * Revision 1.70.2.12 2003/12/17 16:33:16 oes
79 * - Added new function cgi_redirect to handle creation of
80 * HTTP redirect messages formerly repeated in the code.
81 * - Send cgi_error_disabled instead of cgi_error_404 when
82 * referrer check fails
83 * - Dynamic content now gets Expires header field with date
86 * Revision 1.70.2.11 2003/10/23 12:29:26 oes
87 * Bugfix: Transparent PNG was not transparent. Thanks to
88 * Dan Razzell of Starfish Systems for notice and new PNG.
90 * Revision 1.70.2.10 2003/06/06 07:54:25 oes
91 * Security fix: dspatch_known_cgi no longer considers an empty
92 * referrer safe for critical CGIs, since malicious links could
93 * reside on https:// locations which browsers don't advertize as
94 * referrers. Closes bug #749916, thanks to Jeff Epler for the
95 * hint. Goodbye One-Click[tm] toggling :-(
97 * Revision 1.70.2.9 2003/05/08 15:11:31 oes
100 * Revision 1.70.2.8 2003/04/29 13:33:51 oes
101 * Killed a compiler warning on OSX
103 * Revision 1.70.2.7 2003/04/03 13:50:58 oes
104 * - Don't call cgi_error_disabled ifndef FEATURE_CGI_EDIT_ACTIONS
105 * (fixes bug #710056)
106 * - Show toggle info only if we have it
108 * Revision 1.70.2.6 2003/03/12 01:26:25 david__schmidt
109 * Move declaration of struct tm dummy outside of a control block so it is
110 * accessible later on during snprintf in get_http_time.
112 * Revision 1.70.2.5 2003/03/11 11:53:58 oes
113 * Cosmetic: Renamed cryptic variable
115 * Revision 1.70.2.4 2003/03/07 03:41:03 david__schmidt
116 * Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX. Hopefully this will take care of all of those pesky crash reports.
118 * Revision 1.70.2.3 2002/11/28 18:14:32 oes
119 * Disable access to critical CGIs via untrusted referrers.
120 * This prevents users from being tricked by malicious websites
121 * into making unintentional configuration changes:
123 * - Added flag to each cgi_dispatcher that allows or denies
125 * - Introduced proviorical function that greps for the
126 * referrer header before regular header parsing happens
127 * - Added safety check to dispatch_known_cgi. CGI is called
128 * if (cgi harmless || no referrer || we are referrer).
129 * Else a) toggle calls are modified not to change status and
130 * b) all other calls are denied.
132 * Revision 1.70.2.2 2002/11/12 16:20:37 oes
133 * Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
135 * Revision 1.70.2.1 2002/08/05 11:17:46 oes
136 * Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
138 * Revision 1.70 2002/05/19 11:33:20 jongfoster
139 * If a CGI error was not handled, and propogated back to
140 * dispatch_known_cgi(), then it was assumed to be "out of memory".
141 * This gave a very misleading error message.
143 * Now other errors will cause a simple message giving the error
144 * number and asking the user to report a bug.
147 * http://sourceforge.net/tracker/index.php?func=detail
148 * &aid=557905&group_id=11118&atid=111118
150 * Revision 1.69 2002/05/14 21:28:40 oes
151 * - Fixed add_help_link to link to the (now split) actions
152 * part of the config chapter
153 * - Renamed helplink export to actions-help-prefix
155 * Revision 1.68 2002/05/12 21:36:29 jongfoster
156 * Correcting function comments
158 * Revision 1.67 2002/04/30 12:02:07 oes
159 * Nit: updated a comment
161 * Revision 1.66 2002/04/26 18:32:57 jongfoster
162 * Fixing a memory leak on error
164 * Revision 1.65 2002/04/26 12:53:51 oes
165 * - New function add_help_link
166 * - default_exports now exports links to the user manual
167 * and a prefix for links into the config chapter
169 * Revision 1.64 2002/04/24 02:17:21 oes
170 * - Better descriptions for CGIs
171 * - Hide edit-actions, more shortcuts
172 * - Moved get_char_param, get_string_param and get_number_param here
175 * Revision 1.63 2002/04/15 19:06:43 jongfoster
178 * Revision 1.62 2002/04/10 19:59:46 jongfoster
179 * Fixes to #include in templates:
180 * - Didn't close main file if loading an included template fails.
181 * - I'm paranoid and want to disallow "#include /etc/passwd".
183 * Revision 1.61 2002/04/10 13:37:48 oes
184 * Made templates modular: template_load now recursive with max depth 1
186 * Revision 1.60 2002/04/08 20:50:25 swa
189 * Revision 1.59 2002/04/05 15:51:51 oes
190 * - added send-stylesheet CGI
191 * - bugfix: error-pages now get correct request protocol
193 * - kludged CGI descriptions and menu not to break JS syntax
195 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
196 * Fix Mac OSX compiler warnings
198 * Revision 1.57 2002/03/26 22:29:54 swa
199 * we have a new homepage!
201 * Revision 1.56 2002/03/24 17:50:46 jongfoster
202 * Fixing compile error if actions file editor disabled
204 * Revision 1.55 2002/03/24 16:55:06 oes
205 * Making GIF checkerboard transparent
207 * Revision 1.54 2002/03/24 16:18:15 jongfoster
210 * Revision 1.53 2002/03/24 16:06:00 oes
211 * Correct transparency for checkerboard PNG. Thanks, Magnus!
213 * Revision 1.52 2002/03/24 15:23:33 jongfoster
216 * Revision 1.51 2002/03/24 13:25:43 swa
217 * name change related issues
219 * Revision 1.50 2002/03/16 23:54:06 jongfoster
220 * Adding graceful termination feature, to help look for memory leaks.
221 * If you enable this (which, by design, has to be done by hand
222 * editing config.h) and then go to http://i.j.b/die, then the program
223 * will exit cleanly after the *next* request. It should free all the
224 * memory that was used.
226 * Revision 1.49 2002/03/13 00:27:04 jongfoster
229 * Revision 1.48 2002/03/08 17:47:07 jongfoster
232 * Revision 1.47 2002/03/08 16:41:33 oes
233 * Added GIF images again
235 * Revision 1.46 2002/03/07 03:48:38 oes
236 * - Changed built-in images from GIF to PNG
237 * (with regard to Unisys patent issue)
238 * - Added a 4x4 pattern PNG which is less intrusive
239 * than the logo but also clearly marks the deleted banners
241 * Revision 1.45 2002/03/06 22:54:35 jongfoster
242 * Automated function-comment nitpicking.
244 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
245 * - Better error reporting on OS/2
246 * - Fix double-slash comment (oops)
248 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
249 * - Re-enable OS/2 building after new parms were added
250 * - Fix false out of memory report when resolving CGI templates when no IP
251 * address is available of failed attempt (a la no such domain)
253 * Revision 1.42 2002/01/21 00:33:20 jongfoster
254 * Replacing strsav() with the safer string_append() or string_join().
255 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
256 * Adding missing html_encode() to error message generators.
257 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
259 * Revision 1.41 2002/01/17 20:56:22 jongfoster
260 * Replacing hard references to the URL of the config interface
261 * with #defines from project.h
263 * Revision 1.40 2002/01/09 14:26:46 oes
264 * Added support for thread-safe gmtime_r call.
266 * Revision 1.39 2001/11/16 00:48:13 jongfoster
267 * Fixing a compiler warning
269 * Revision 1.38 2001/11/13 00:31:21 jongfoster
270 * - Adding new CGIs for use by non-JavaScript browsers:
271 * edit-actions-url-form
272 * edit-actions-add-url-form
273 * edit-actions-remove-url-form
274 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
277 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
278 * Show enablement/disablement status in almost all templates.
279 * There is a little trickiness here: apparent recursive resolution of
280 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
281 * the actual enablement status. So a similar construct,
282 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
285 * Revision 1.36 2001/10/26 17:33:27 oes
288 * Revision 1.35 2001/10/23 21:48:19 jongfoster
289 * Cleaning up error handling in CGI functions - they now send back
290 * a HTML error page and should never cause a FATAL error. (Fixes one
291 * potential source of "denial of service" attacks).
293 * CGI actions file editor that works and is actually useful.
295 * Ability to toggle Junkbuster remotely using a CGI call.
297 * You can turn off both the above features in the main configuration
298 * file, e.g. if you are running a multi-user proxy.
300 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
301 * Only show "Local support" on templates conditionally:
302 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
303 * - if not, no Local support section appears
305 * Revision 1.33 2001/10/14 22:28:41 jongfoster
306 * Fixing stupid typo.
308 * Revision 1.32 2001/10/14 22:20:18 jongfoster
309 * - Changes to CGI dispatching method to match CGI names exactly,
310 * rather than doing a prefix match.
311 * - No longer need to count the length of the CGI handler names by hand.
312 * - Adding new handler for 404 error when disptching a CGI, if none of
313 * the handlers match.
314 * - Adding new handlers for CGI actionsfile editor.
316 * Revision 1.31 2001/10/10 10:56:39 oes
317 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
319 * Revision 1.30 2001/10/02 15:30:57 oes
320 * Introduced show-request cgi
322 * Revision 1.29 2001/09/20 15:47:44 steudten
324 * Fix BUG: Modify int size to size_t size in fill_template()
325 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
327 * Revision 1.28 2001/09/19 18:00:37 oes
328 * - Deletef time() FIXME (Can't fail under Linux either, if
329 * the argument is guaranteed to be in out address space,
332 * - Pointer notation cosmetics
333 * - Fixed a minor bug in template_fill(): Failiure of
334 * pcrs_execute() now secure.
336 * Revision 1.27 2001/09/16 17:08:54 jongfoster
337 * Moving simple CGI functions from cgi.c to new file cgisimple.c
339 * Revision 1.26 2001/09/16 15:47:37 jongfoster
340 * First version of CGI-based edit interface. This is very much a
341 * work-in-progress, and you can't actually use it to edit anything
342 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
343 * to have any effect.
345 * Revision 1.25 2001/09/16 15:02:35 jongfoster
346 * Adding i.j.b/robots.txt.
347 * Inlining add_stats() since it's only ever called from one place.
349 * Revision 1.24 2001/09/16 11:38:01 jongfoster
350 * Splitting fill_template() into 2 functions:
351 * template_load() loads the file
352 * template_fill() performs the PCRS regexps.
353 * This is because the CGI edit interface has a "table row"
354 * template which is used many times in the page - this
355 * change means it's only loaded from disk once.
357 * Revision 1.23 2001/09/16 11:16:05 jongfoster
358 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
360 * Revision 1.22 2001/09/16 11:00:10 jongfoster
361 * New function alloc_http_response, for symmetry with free_http_response
363 * Revision 1.21 2001/09/13 23:53:03 jongfoster
364 * Support for both static and dynamically generated CGI pages.
365 * Correctly setting Last-Modified: and Expires: HTTP headers.
367 * Revision 1.20 2001/09/13 23:40:36 jongfoster
368 * (Cosmetic only) Indentation correction
370 * Revision 1.19 2001/09/13 23:31:25 jongfoster
371 * Moving image data to cgi.c rather than cgi.h.
373 * Revision 1.18 2001/08/05 16:06:20 jongfoster
374 * Modifiying "struct map" so that there are now separate header and
375 * "map_entry" structures. This means that functions which modify a
376 * map no longer need to return a pointer to the modified map.
377 * Also, it no longer reverses the order of the entries (which may be
378 * important with some advanced template substitutions).
380 * Revision 1.17 2001/08/05 15:57:38 oes
381 * Adapted finish_http_response to new list_to_text
383 * Revision 1.16 2001/08/01 21:33:18 jongfoster
384 * Changes to fill_template() that reduce memory usage without having
385 * an impact on performance. I also renamed some variables so as not
386 * to clash with the C++ keywords "new" and "template".
388 * Revision 1.15 2001/08/01 21:19:22 jongfoster
389 * Moving file version information to a separate CGI page.
391 * Revision 1.14 2001/08/01 00:19:03 jongfoster
392 * New function: map_conditional() for an if-then-else syntax.
393 * Changing to use new version of show_defines()
395 * Revision 1.13 2001/07/30 22:08:36 jongfoster
396 * Tidying up #defines:
397 * - All feature #defines are now of the form FEATURE_xxx
398 * - Permanently turned off WIN_GUI_EDIT
399 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
401 * Revision 1.12 2001/07/29 18:47:05 jongfoster
402 * Adding missing #include "loadcfg.h"
404 * Revision 1.11 2001/07/18 17:24:37 oes
405 * Changed to conform to new pcrs interface
407 * Revision 1.10 2001/07/13 13:53:13 oes
408 * Removed all #ifdef PCRS and related code
410 * Revision 1.9 2001/06/29 21:45:41 oes
411 * Indentation, CRLF->LF, Tab-> Space
413 * Revision 1.8 2001/06/29 13:21:46 oes
414 * - Cosmetics: renamed and reordered functions, variables,
415 * texts, improved comments etc
417 * - Removed ij_untrusted_url() The relevant
418 * info is now part of the "untrusted" page,
419 * which is generated by filters.c:trust_url()
421 * - Generators of content now call finish_http_response()
422 * themselves, making jcc.c:chat() a little less
425 * - Removed obsolete "Pragma: no-cache" from our headers
427 * - http_responses now know their head length
429 * - fill_template now uses the new interface to pcrs, so that
430 * - long jobs (like whole files) no longer have to be assembled
431 * in a fixed size buffer
432 * - the new T (trivial) option is used, and the replacement may
433 * contain Perl syntax backrefs without confusing pcrs
435 * - Introduced default_exports() which generates a set of exports
436 * common to all CGIs and other content generators
438 * - Introduced convenience function map_block_killer()
440 * - Introduced convenience function make_menu()
442 * - Introduced CGI-like function error_response() which generates
443 * the "No such domain" and "Connect failed" messages using the
446 * - cgi_show_url_info:
447 * - adapted to new CGI features
448 * - form and answers now generated from same template
449 * - http:// prefix in URL now OK
452 * - adapted to new CGI features
453 * - no longer uses csp->init_proxy_args
456 * - moved menu generation to make_menu()
458 * - add_stats now writes single export map entries instead
461 * - Moved redirect_url() to filters.c
463 * - Fixed mem leak in free_http_response(), map_block_killer(),
465 * - Removed logentry from cancelled commit
467 * Revision 1.7 2001/06/09 10:51:58 jongfoster
468 * Changing "show URL info" handler to new style.
469 * Changing BUFSIZ ==> BUFFER_SIZE
471 * Revision 1.6 2001/06/07 23:05:19 jongfoster
472 * Removing code related to old forward and ACL files.
474 * Revision 1.5 2001/06/05 19:59:16 jongfoster
475 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
477 * Revision 1.4 2001/06/04 10:41:52 swa
478 * show version string of cgi.h and cgi.c
480 * Revision 1.3 2001/06/03 19:12:16 oes
481 * introduced new cgi handling
483 * No revisions before 1.3
485 **********************************************************************/
491 #include <sys/types.h>
499 #define snprintf _snprintf
500 #endif /* def _WIN32 */
508 #include "miscutil.h"
509 #include "cgisimple.h"
510 #ifdef FEATURE_CGI_EDIT_ACTIONS
512 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
514 /* loadcfg.h is for global_toggle_state only */
515 #ifdef FEATURE_PTHREAD
518 /* jcc.h is for mutex semaphore globals only */
519 #endif /* def FEATURE_PTHREAD */
520 const char cgi_h_rcs[] = CGI_H_VERSION;
523 * List of CGI functions: name, handler, description
524 * Note: Do NOT use single quotes in the description;
525 * this will break the dynamic "blocked" template!
527 static const struct cgi_dispatcher cgi_dispatchers[] = {
532 #ifdef FEATURE_GRACEFUL_TERMINATION
535 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
536 "this is a one click Denial Of Service attack!!!</em>",
541 #ifdef FEATURE_CGI_EDIT_ACTIONS
542 "View & change the current configuration",
544 "View the current configuration",
549 "View the source code version numbers",
553 "View the request headers.",
557 "Look up which actions apply to a URL and why",
559 #ifdef FEATURE_CGI_EDIT_ACTIONS
562 "Toggle Privoxy on or off",
564 { "edit-actions", /* Edit the actions list */
567 { "eaa", /* Shortcut for edit-actions-add-url-form */
568 cgi_edit_actions_add_url_form,
570 { "eau", /* Shortcut for edit-actions-url-form */
571 cgi_edit_actions_url_form,
573 { "ear", /* Shortcut for edit-actions-remove-url-form */
574 cgi_edit_actions_remove_url_form,
576 { "eal", /* Shortcut for edit-actions-list */
577 cgi_edit_actions_list,
579 { "eafu", /* Shortcut for edit-actions-for-url */
580 cgi_edit_actions_for_url,
582 { "eas", /* Shortcut for edit-actions-submit */
583 cgi_edit_actions_submit,
585 { "easa", /* Shortcut for edit-actions-section-add */
586 cgi_edit_actions_section_add,
588 { "easr", /* Shortcut for edit-actions-section-remove */
589 cgi_edit_actions_section_remove,
591 { "eass", /* Shortcut for edit-actions-section-swap */
592 cgi_edit_actions_section_swap,
594 { "edit-actions-for-url",
595 cgi_edit_actions_for_url,
596 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
597 { "edit-actions-list",
598 cgi_edit_actions_list,
599 NULL, TRUE /* Edit the actions list */ },
600 { "edit-actions-submit",
601 cgi_edit_actions_submit,
602 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
603 { "edit-actions-url",
604 cgi_edit_actions_url,
605 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
606 { "edit-actions-url-form",
607 cgi_edit_actions_url_form,
608 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
609 { "edit-actions-add-url",
610 cgi_edit_actions_add_url,
611 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
612 { "edit-actions-add-url-form",
613 cgi_edit_actions_add_url_form,
614 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
615 { "edit-actions-remove-url",
616 cgi_edit_actions_remove_url,
617 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
618 { "edit-actions-remove-url-form",
619 cgi_edit_actions_remove_url_form,
620 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
621 { "edit-actions-section-add",
622 cgi_edit_actions_section_add,
623 NULL, FALSE /* Remove a section from the actionsfile */ },
624 { "edit-actions-section-remove",
625 cgi_edit_actions_section_remove,
626 NULL, FALSE /* Remove a section from the actionsfile */ },
627 { "edit-actions-section-swap",
628 cgi_edit_actions_section_swap,
629 NULL, FALSE /* Swap two sections in the actionsfile */ },
630 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
633 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
636 NULL, TRUE /* Send a built-in image */ },
639 NULL, TRUE /* Send templates/cgi-style.css */ },
641 cgi_transparent_image,
642 NULL, TRUE /* Send a transparent image (short name) */ },
644 cgi_send_user_manual,
645 NULL, TRUE /* Send user-manual */ },
646 { NULL, /* NULL Indicates end of list and default page */
648 NULL, TRUE /* Unknown CGI page */ }
653 * Built-in images for ad replacement
655 * Hint: You can encode your own images like this:
656 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
659 #ifdef FEATURE_NO_GIFS
662 * Checkerboard pattern, as a PNG.
664 const char image_pattern_data[] =
665 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
666 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
667 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
668 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
669 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
670 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
671 "\000\000\000\111\105\116\104\256\102\140\202";
674 * 1x1 transparant PNG.
676 const char image_blank_data[] =
677 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
678 "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
679 "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
680 "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
681 "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
682 "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
683 "\000\000\000\000\111\105\116\104\256\102\140\202";
687 * Checkerboard pattern, as a GIF.
689 const char image_pattern_data[] =
690 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
691 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
692 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
693 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
697 * 1x1 transparant GIF.
699 const char image_blank_data[] =
700 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
701 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
702 "\000\001\000\000\002\002D\001\000;";
705 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
706 const size_t image_blank_length = sizeof(image_blank_data) - 1;
709 static struct http_response cgi_error_memory_response[1];
711 static struct http_response *dispatch_known_cgi(struct client_state * csp,
713 static struct map *parse_cgi_parameters(char *argstring);
716 /*********************************************************************
718 * Function : dispatch_cgi
720 * Description : Checks if a request URL has either the magical
721 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
722 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
723 * http://config.privoxy.org/). If so, it passes
724 * the (rest of the) path onto dispatch_known_cgi, which
725 * calls the relevant CGI handler function.
728 * 1 : csp = Current client state (buffers, headers, etc...)
730 * Returns : http_response if match, NULL if nonmatch or handler fail
732 *********************************************************************/
733 struct http_response *dispatch_cgi(struct client_state *csp)
735 const char *host = csp->http->host;
736 const char *path = csp->http->path;
739 * Should we intercept ?
742 /* Note: "example.com" and "example.com." are equivalent hostnames. */
744 /* Either the host matches CGI_SITE_1_HOST ..*/
745 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
746 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
747 && (path[0] == '/') )
749 /* ..then the path will all be for us. Remove leading '/' */
752 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
753 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
754 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
755 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
757 /* take everything following CGI_SITE_2_PATH */
758 path += strlen(CGI_SITE_2_PATH);
761 /* skip the forward slash after CGI_SITE_2_PATH */
764 else if (*path != '\0')
767 * weirdness: URL is /configXXX, where XXX is some string
768 * Do *NOT* intercept.
780 * This is a CGI call.
783 return dispatch_known_cgi(csp, path);
787 /*********************************************************************
789 * Function : grep_cgi_referrer
791 * Description : Ugly provisorical fix that greps the value of the
792 * referer HTTP header field out of a linked list of
793 * strings like found at csp->headers. Will disappear
796 * FIXME: csp->headers ought to be csp->http->headers
797 * FIXME: Parsing all client header lines should
798 * happen right after the request is received!
801 * 1 : csp = Current client state (buffers, headers, etc...)
803 * Returns : pointer to value (no copy!), or NULL if none found.
805 *********************************************************************/
806 char *grep_cgi_referrer(struct client_state *csp)
808 struct list_entry *p;
810 for (p = csp->headers->first; p != NULL; p = p->next)
812 if (p->str == NULL) continue;
813 if (strncmpic(p->str, "Referer: ", 9) == 0)
815 return ((p->str) + 9);
823 /*********************************************************************
825 * Function : dispatch_known_cgi
827 * Description : Processes a CGI once dispatch_cgi has determined that
828 * it matches one of the magic prefixes. Parses the path
829 * as a cgi name plus query string, prepares a map that
830 * maps CGI parameter names to their values, initializes
831 * the http_response struct, and calls the relevant CGI
835 * 1 : csp = Current client state (buffers, headers, etc...)
836 * 2 : path = Path of CGI, with the CGI prefix removed.
837 * Should not have a leading "/".
839 * Returns : http_response, or NULL on handler failure or out of
842 *********************************************************************/
843 static struct http_response *dispatch_known_cgi(struct client_state * csp,
846 const struct cgi_dispatcher *d;
847 struct map *param_list;
848 struct http_response *rsp;
849 char *query_args_start;
854 if (NULL == (path_copy = strdup(path)))
856 return cgi_error_memory();
858 query_args_start = path_copy;
859 while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
863 if (*query_args_start == '/')
865 *query_args_start++ = '\0';
866 if ((param_list = new_map()))
868 map(param_list, "file", 1, url_decode(query_args_start), 0);
873 if (*query_args_start == '?')
875 *query_args_start++ = '\0';
877 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
880 return cgi_error_memory();
886 * path_copy = CGI call name
887 * param_list = CGI params, as map
890 /* Get mem for response or fail*/
891 if (NULL == (rsp = alloc_http_response()))
894 free_map(param_list);
895 return cgi_error_memory();
898 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
899 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
900 csp->ip_addr_str, csp->http->cmd);
903 * Find and start the right CGI function
908 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
911 * If the called CGI is either harmless, or referred
912 * from a trusted source, start it.
915 || ((NULL != (referrer = grep_cgi_referrer(csp)))
916 && (0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)))
919 err = (d->handler)(csp, rsp, param_list);
924 * Else, modify toggle calls so that they only display
925 * the status, and deny all other calls.
927 if (0 == strcmp(path_copy, "toggle"))
929 unmap(param_list, "set");
930 err = (d->handler)(csp, rsp, param_list);
934 err = cgi_error_disabled(csp, rsp);
939 free_map(param_list);
941 if (err == JB_ERR_CGI_PARAMS)
943 err = cgi_error_bad_param(csp, rsp);
945 if (err && (err != JB_ERR_MEMORY))
947 /* Unexpected error! Shouldn't get here */
948 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
949 err = cgi_error_unknown(csp, rsp, err);
954 return finish_http_response(rsp);
958 /* Error in handler, probably out-of-memory */
959 free_http_response(rsp);
960 return cgi_error_memory();
968 /*********************************************************************
970 * Function : parse_cgi_parameters
972 * Description : Parse a URL-encoded argument string into name/value
973 * pairs and store them in a struct map list.
976 * 1 : argstring = string to be parsed. Will be trashed.
978 * Returns : pointer to param list, or NULL if out of memory.
980 *********************************************************************/
981 static struct map *parse_cgi_parameters(char *argstring)
984 char *vector[BUFFER_SIZE];
986 struct map *cgi_params;
988 if (NULL == (cgi_params = new_map()))
994 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
995 * the fragment identifier along with the request, so we must
996 * cut it off here, so it won't pollute the CGI params:
998 if (NULL != (p = strchr(argstring, '#')))
1003 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
1005 for (i = 0; i < pairs; i++)
1007 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
1010 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
1012 free_map(cgi_params);
1023 /*********************************************************************
1025 * Function : get_char_param
1027 * Description : Get a single-character parameter passed to a CGI
1031 * 1 : parameters = map of cgi parameters
1032 * 2 : param_name = The name of the parameter to read
1034 * Returns : Uppercase character on success, '\0' on error.
1036 *********************************************************************/
1037 char get_char_param(const struct map *parameters,
1038 const char *param_name)
1045 ch = *(lookup(parameters, param_name));
1046 if ((ch >= 'a') && (ch <= 'z'))
1048 ch = ch - 'a' + 'A';
1055 /*********************************************************************
1057 * Function : get_string_param
1059 * Description : Get a string paramater, to be used as an
1060 * ACTION_STRING or ACTION_MULTI paramater.
1061 * Validates the input to prevent stupid/malicious
1062 * users from corrupting their action file.
1065 * 1 : parameters = map of cgi parameters
1066 * 2 : param_name = The name of the parameter to read
1067 * 3 : pparam = destination for paramater. Allocated as
1068 * part of the map "parameters", so don't free it.
1069 * Set to NULL if not specified.
1071 * Returns : JB_ERR_OK on success, or if the paramater
1072 * was not specified.
1073 * JB_ERR_MEMORY on out-of-memory.
1074 * JB_ERR_CGI_PARAMS if the paramater is not valid.
1076 *********************************************************************/
1077 jb_err get_string_param(const struct map *parameters,
1078 const char *param_name,
1079 const char **pparam)
1091 param = lookup(parameters, param_name);
1097 if (strlen(param) >= CGI_PARAM_LEN_MAX)
1102 * Note that the length limit is arbitrary, it just seems
1103 * sensible to limit it to *something*. There's no
1104 * technical reason for any limit at all.
1106 return JB_ERR_CGI_PARAMS;
1109 /* Check every character to see if it's legal */
1111 while ((ch = *s++) != '\0')
1113 if ( ((unsigned char)ch < (unsigned char)' ')
1116 /* Probable hack attempt, or user accidentally used '}'. */
1117 return JB_ERR_CGI_PARAMS;
1128 /*********************************************************************
1130 * Function : get_number_param
1132 * Description : Get a non-negative integer from the parameters
1133 * passed to a CGI function.
1136 * 1 : csp = Current client state (buffers, headers, etc...)
1137 * 2 : parameters = map of cgi parameters
1138 * 3 : name = Name of CGI parameter to read
1139 * 4 : pvalue = destination for value.
1140 * Set to -1 on error.
1142 * Returns : JB_ERR_OK on success
1143 * JB_ERR_MEMORY on out-of-memory
1144 * JB_ERR_CGI_PARAMS if the parameter was not specified
1147 *********************************************************************/
1148 jb_err get_number_param(struct client_state *csp,
1149 const struct map *parameters,
1164 param = lookup(parameters, name);
1167 return JB_ERR_CGI_PARAMS;
1170 /* We don't use atoi because I want to check this carefully... */
1173 while ((ch = *param++) != '\0')
1175 if ((ch < '0') || (ch > '9'))
1177 return JB_ERR_CGI_PARAMS;
1184 * <limits.h> defines UINT_MAX
1186 * (UINT_MAX - ch) / 10 is the largest number that
1187 * can be safely multiplied by 10 then have ch added.
1189 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1191 return JB_ERR_CGI_PARAMS;
1194 value = value * 10 + ch;
1205 /*********************************************************************
1207 * Function : error_response
1209 * Description : returns an http_response that explains the reason
1210 * why a request failed.
1213 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * 2 : templatename = Which template should be used for the answer
1215 * 3 : sys_err = system error number
1217 * Returns : A http_response. If we run out of memory, this
1218 * will be cgi_error_memory().
1220 *********************************************************************/
1221 struct http_response *error_response(struct client_state *csp,
1222 const char *templatename,
1226 struct http_response *rsp;
1227 struct map * exports = default_exports(csp, NULL);
1228 if (exports == NULL)
1230 return cgi_error_memory();
1233 if (NULL == (rsp = alloc_http_response()))
1236 return cgi_error_memory();
1239 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1240 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1241 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1242 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1243 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1246 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1249 /* Some failures, like "404 no such domain", don't have an IP address. */
1250 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1258 free_http_response(rsp);
1259 return cgi_error_memory();
1262 if (!strcmp(templatename, "no-such-domain"))
1264 rsp->status = strdup("404 No such domain");
1265 if (rsp->status == NULL)
1268 free_http_response(rsp);
1269 return cgi_error_memory();
1272 else if (!strcmp(templatename, "connect-failed"))
1274 rsp->status = strdup("503 Connect failed");
1275 if (rsp->status == NULL)
1278 free_http_response(rsp);
1279 return cgi_error_memory();
1283 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1286 free_http_response(rsp);
1287 return cgi_error_memory();
1290 return finish_http_response(rsp);
1294 /*********************************************************************
1296 * Function : cgi_error_disabled
1298 * Description : CGI function that is called to generate an error
1299 * response if the actions editor or toggle CGI are
1300 * accessed despite having being disabled at compile-
1304 * 1 : csp = Current client state (buffers, headers, etc...)
1305 * 2 : rsp = http_response data structure for output
1307 * CGI Parameters : none
1309 * Returns : JB_ERR_OK on success
1310 * JB_ERR_MEMORY on out-of-memory error.
1312 *********************************************************************/
1313 jb_err cgi_error_disabled(struct client_state *csp,
1314 struct http_response *rsp)
1316 struct map *exports;
1321 if (NULL == (exports = default_exports(csp, NULL)))
1323 return JB_ERR_MEMORY;
1326 return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1330 /*********************************************************************
1332 * Function : cgi_init_error_messages
1334 * Description : Call at the start of the program to initialize
1335 * the error message used by cgi_error_memory().
1341 *********************************************************************/
1342 void cgi_init_error_messages(void)
1344 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1345 cgi_error_memory_response->head =
1346 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1347 "Content-Type: text/html\r\n"
1349 cgi_error_memory_response->body =
1351 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1353 "<h1>500 Internal Privoxy Error</h1>\r\n"
1354 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1355 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1359 cgi_error_memory_response->head_length =
1360 strlen(cgi_error_memory_response->head);
1361 cgi_error_memory_response->content_length =
1362 strlen(cgi_error_memory_response->body);
1366 /*********************************************************************
1368 * Function : cgi_error_memory
1370 * Description : Called if a CGI function runs out of memory.
1371 * Returns a statically-allocated error response.
1375 * Returns : http_response data structure for output. This is
1376 * statically allocated, for obvious reasons.
1378 *********************************************************************/
1379 struct http_response *cgi_error_memory(void)
1381 /* assert that it's been initialized. */
1382 assert(cgi_error_memory_response->head);
1384 return cgi_error_memory_response;
1388 /*********************************************************************
1390 * Function : cgi_error_no_template
1392 * Description : Almost-CGI function that is called if a template
1393 * cannot be loaded. Note this is not a true CGI,
1394 * it takes a template name rather than a map of
1398 * 1 : csp = Current client state (buffers, headers, etc...)
1399 * 2 : rsp = http_response data structure for output
1400 * 3 : template_name = Name of template that could not
1403 * Returns : JB_ERR_OK on success
1404 * JB_ERR_MEMORY on out-of-memory error.
1406 *********************************************************************/
1407 jb_err cgi_error_no_template(struct client_state *csp,
1408 struct http_response *rsp,
1409 const char *template_name)
1411 static const char status[] =
1412 "500 Internal Privoxy Error";
1413 static const char body_prefix[] =
1415 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1417 "<h1>500 Internal Privoxy Error</h1>\r\n"
1418 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1419 "<p><b>Could not load template file <code>";
1420 static const char body_suffix[] =
1421 "</code> or one of it's included components.</b></p>\r\n"
1422 "<p>Please contact your proxy administrator.</p>\r\n"
1423 "<p>If you are the proxy administrator, please put the required file(s)"
1424 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1425 "location of the <code><i>(confdir)</i></code> directory "
1426 "is specified in the main Privoxy <code>config</code> "
1427 "file. (It's typically the Privoxy install directory"
1429 ", or <code>/etc/privoxy/</code>"
1430 #endif /* ndef _WIN32 */
1437 assert(template_name);
1439 /* Reset rsp, if needed */
1443 rsp->content_length = 0;
1444 rsp->head_length = 0;
1447 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1448 if (rsp->body == NULL)
1450 return JB_ERR_MEMORY;
1452 strcpy(rsp->body, body_prefix);
1453 strcat(rsp->body, template_name);
1454 strcat(rsp->body, body_suffix);
1456 rsp->status = strdup(status);
1457 if (rsp->body == NULL)
1459 return JB_ERR_MEMORY;
1466 /*********************************************************************
1468 * Function : cgi_error_unknown
1470 * Description : Almost-CGI function that is called if an unexpected
1471 * error occurs in the top-level CGI dispatcher.
1472 * In this context, "unexpected" means "anything other
1473 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1474 * expected to handle all other errors internally,
1475 * since they can give more relavent error messages
1478 * Note this is not a true CGI, it takes an error
1479 * code rather than a map of parameters.
1482 * 1 : csp = Current client state (buffers, headers, etc...)
1483 * 2 : rsp = http_response data structure for output
1484 * 3 : error_to_report = Error code to report.
1486 * Returns : JB_ERR_OK on success
1487 * JB_ERR_MEMORY on out-of-memory error.
1489 *********************************************************************/
1490 jb_err cgi_error_unknown(struct client_state *csp,
1491 struct http_response *rsp,
1492 jb_err error_to_report)
1494 static const char status[] =
1495 "500 Internal Privoxy Error";
1496 static const char body_prefix[] =
1498 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1500 "<h1>500 Internal Privoxy Error</h1>\r\n"
1501 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1502 "<p><b>Unexpected internal error: ";
1503 static const char body_suffix[] =
1506 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1507 "file a bug report</a>.</p>\r\n"
1514 /* Reset rsp, if needed */
1518 rsp->content_length = 0;
1519 rsp->head_length = 0;
1522 sprintf(errnumbuf, "%d", error_to_report);
1524 rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1525 if (rsp->body == NULL)
1527 return JB_ERR_MEMORY;
1529 strcpy(rsp->body, body_prefix);
1530 strcat(rsp->body, errnumbuf);
1531 strcat(rsp->body, body_suffix);
1533 rsp->status = strdup(status);
1534 if (rsp->body == NULL)
1536 return JB_ERR_MEMORY;
1543 /*********************************************************************
1545 * Function : cgi_error_bad_param
1547 * Description : CGI function that is called if the parameters
1548 * (query string) for a CGI were wrong.
1551 * 1 : csp = Current client state (buffers, headers, etc...)
1552 * 2 : rsp = http_response data structure for output
1554 * CGI Parameters : none
1556 * Returns : JB_ERR_OK on success
1557 * JB_ERR_MEMORY on out-of-memory error.
1559 *********************************************************************/
1560 jb_err cgi_error_bad_param(struct client_state *csp,
1561 struct http_response *rsp)
1563 struct map *exports;
1568 if (NULL == (exports = default_exports(csp, NULL)))
1570 return JB_ERR_MEMORY;
1573 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1577 /*********************************************************************
1579 * Function : cgi_redirect
1581 * Description : CGI support function to generate a HTTP redirect
1585 * 1 : rsp = http_response data structure for output
1586 * 2 : target = string with the target URL
1588 * CGI Parameters : None
1590 * Returns : JB_ERR_OK on success
1591 * JB_ERR_MEMORY on out-of-memory error.
1593 *********************************************************************/
1594 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1601 err = enlist_unique_header(rsp->headers, "Location", target);
1603 rsp->status = strdup("302 Local Redirect from Privoxy");
1604 if (rsp->status == NULL)
1606 return JB_ERR_MEMORY;
1613 /*********************************************************************
1615 * Function : add_help_link
1617 * Description : Produce a copy of the string given as item,
1618 * embedded in an HTML link to its corresponding
1619 * section (item name in uppercase) in the actions
1620 * chapter of the user manual, (whose URL is given in
1621 * the config and defaults to our web site).
1623 * FIXME: I currently only work for actions, and would
1624 * like to be generalized for other topics.
1627 * 1 : item = item (will NOT be free()d.)
1628 * It is assumed to be HTML-safe.
1629 * 2 : config = The current configuration.
1631 * Returns : String with item embedded in link, or NULL on
1634 *********************************************************************/
1635 char *add_help_link(const char *item,
1636 struct configuration_spec *config)
1640 if (!item) return NULL;
1642 result = strdup("<a href=\"");
1643 if (!strncmpic(config->usermanual, "file://", 7) ||
1644 !strncmpic(config->usermanual, "http", 4))
1646 string_append(&result, config->usermanual);
1650 string_append(&result, "http://");
1651 string_append(&result, CGI_SITE_2_HOST);
1652 string_append(&result, "/user-manual/");
1654 string_append(&result, ACTIONS_HELP_PREFIX);
1655 string_join (&result, string_toupper(item));
1656 string_append(&result, "\">");
1657 string_append(&result, item);
1658 string_append(&result, "</a> ");
1664 /*********************************************************************
1666 * Function : get_http_time
1668 * Description : Get the time in a format suitable for use in a
1669 * HTTP header - e.g.:
1670 * "Sun, 06 Nov 1994 08:49:37 GMT"
1673 * 1 : time_offset = Time returned will be current time
1674 * plus this number of seconds.
1675 * 2 : buf = Destination for result. Must be long enough
1676 * to hold 29 characters plus a trailing zero.
1680 *********************************************************************/
1681 void get_http_time(int time_offset, char *buf)
1683 static const char day_names[7][4] =
1684 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1685 static const char month_names[12][4] =
1686 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1687 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1690 time_t current_time;
1691 #if defined(HAVE_GMTIME_R) && !defined(OSX_DARWIN)
1693 * Declare dummy up here (instead of inside get/set gmt block) so it
1694 * doesn't go out of scope before it's potentially used in snprintf later.
1695 * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1696 * !defined HAVE_GMTIME_R.
1703 time(¤t_time); /* get current time */
1705 current_time += time_offset;
1707 /* get and save the gmt */
1710 pthread_mutex_lock(&gmtime_mutex);
1711 t = gmtime(¤t_time);
1712 pthread_mutex_unlock(&gmtime_mutex);
1714 t = gmtime_r(¤t_time, &dummy);
1716 t = gmtime(¤t_time);
1720 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1722 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1723 day_names[t->tm_wday],
1725 month_names[t->tm_mon],
1735 /*********************************************************************
1737 * Function : finish_http_response
1739 * Description : Fill in the missing headers in an http response,
1740 * and flatten the headers to an http head.
1743 * 1 : rsp = pointer to http_response to be processed
1745 * Returns : A http_response, usually the rsp parameter.
1746 * On error, free()s rsp and returns cgi_error_memory()
1748 *********************************************************************/
1749 struct http_response *finish_http_response(struct http_response *rsp)
1751 char buf[BUFFER_SIZE];
1754 /* Special case - do NOT change this statically allocated response,
1755 * which is ready for output anyway.
1757 if (rsp == cgi_error_memory_response)
1763 * Fill in the HTTP Status
1765 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1766 err = enlist_first(rsp->headers, buf);
1769 * Set the Content-Length
1771 if (rsp->content_length == 0)
1773 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1777 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1778 err = enlist(rsp->headers, buf);
1781 if (strncmpic(rsp->status, "302", 3))
1784 * If it's not a redirect without any content,
1785 * set the Content-Type to text/html if it's
1786 * not already specified.
1788 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1792 * Fill in the rest of the default headers:
1794 * Date: set to current date/time.
1795 * Last-Modified: set to date/time the page was last changed.
1796 * Expires: set to date/time page next needs reloading.
1797 * Cache-Control: set to "no-cache" if applicable.
1799 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1804 * Set Expires to about 10 min into the future so it'll get reloaded
1805 * occasionally, e.g. if Privoxy gets upgraded.
1810 get_http_time(0, buf);
1811 err = enlist_unique_header(rsp->headers, "Date", buf);
1814 /* Some date in the past. */
1815 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1819 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1820 err = enlist_unique_header(rsp->headers, "Expires", buf);
1823 else if (!strncmpic(rsp->status, "302", 3))
1825 get_http_time(0, buf);
1826 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1831 * Setting "Cache-Control" to "no-cache" and "Expires" to
1832 * the current time doesn't exactly forbid caching, it just
1833 * requires the client to revalidate the cached copy.
1835 * If a temporary problem occurs and the user tries again after
1836 * getting Privoxy's error message, a compliant browser may set the
1837 * If-Modified-Since header with the content of the error page's
1838 * Last-Modified header. More often than not, the document on the server
1839 * is older than Privoxy's error message, the server would send status code
1840 * 304 and the browser would display the outdated error message again and again.
1842 * For documents delivered with status code 404 or 503 we set "Last-Modified"
1843 * to Tim Berners-Lee's birthday, which predates the age of any page on the web
1844 * and can be safely used to "revalidate" without getting a status code 304.
1846 * There is no need to let the useless If-Modified-Since header reach the
1847 * server, it is therefore stripped by client_if_modified_since in parsers.c.
1849 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1851 get_http_time(0, buf);
1852 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1853 if (!strncmpic(rsp->status, "404", 3) || !strncmpic(rsp->status, "503", 3))
1855 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
1859 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1861 if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
1862 if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
1868 * HTTP/1.1 applications that do not support persistent connections MUST
1869 * include the "close" connection option in every message.
1871 if (!err) err = enlist_unique_header(rsp->headers, "Connection", "close");
1876 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1878 free_http_response(rsp);
1879 return cgi_error_memory();
1881 rsp->head_length = strlen(rsp->head);
1888 /*********************************************************************
1890 * Function : alloc_http_response
1892 * Description : Allocates a new http_response structure.
1896 * Returns : pointer to a new http_response, or NULL.
1898 *********************************************************************/
1899 struct http_response *alloc_http_response(void)
1901 return (struct http_response *) zalloc(sizeof(struct http_response));
1906 /*********************************************************************
1908 * Function : free_http_response
1910 * Description : Free the memory occupied by an http_response
1911 * and its depandant structures.
1914 * 1 : rsp = pointer to http_response to be freed
1918 *********************************************************************/
1919 void free_http_response(struct http_response *rsp)
1922 * Must special case cgi_error_memory_response, which is never freed.
1924 if (rsp && (rsp != cgi_error_memory_response))
1929 destroy_list(rsp->headers);
1936 /*********************************************************************
1938 * Function : template_load
1940 * Description : CGI support function that loads a given HTML
1941 * template from the confdir, ignoring comment
1942 * lines and following #include statements up to
1946 * 1 : csp = Current client state (buffers, headers, etc...)
1947 * 2 : template_ptr = Destination for pointer to loaded
1949 * 3 : templatename = name of the HTML template to be used
1950 * 4 : recursive = Flag set if this function calls itself
1951 * following an #include statament
1953 * Returns : JB_ERR_OK on success
1954 * JB_ERR_MEMORY on out-of-memory error.
1955 * JB_ERR_FILE if the template file cannot be read
1957 *********************************************************************/
1958 jb_err template_load(struct client_state *csp, char **template_ptr,
1959 const char *templatename, int recursive)
1962 char *templates_dir_path;
1965 char *included_module;
1968 char buf[BUFFER_SIZE];
1971 assert(template_ptr);
1972 assert(templatename);
1974 *template_ptr = NULL;
1976 /* Validate template name. Paranoia. */
1977 for (p = templatename; *p != 0; p++)
1979 if ( ((*p < 'a') || (*p > 'z'))
1980 && ((*p < 'A') || (*p > 'Z'))
1981 && ((*p < '0') || (*p > '9'))
1985 /* Illegal character */
1990 /* Generate full path */
1992 templates_dir_path = make_path(csp->config->confdir, "templates");
1993 if (templates_dir_path == NULL)
1995 return JB_ERR_MEMORY;
1998 full_path = make_path(templates_dir_path, templatename);
1999 free(templates_dir_path);
2000 if (full_path == NULL)
2002 return JB_ERR_MEMORY;
2005 /* Allocate buffer */
2007 file_buffer = strdup("");
2008 if (file_buffer == NULL)
2011 return JB_ERR_MEMORY;
2014 /* Open template file */
2016 if (NULL == (fp = fopen(full_path, "r")))
2018 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
2026 * Read the file, ignoring comments, and honoring #include
2027 * statements, unless we're already called recursively.
2029 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
2030 * This is unlikely in practise.
2032 while (fgets(buf, BUFFER_SIZE, fp))
2034 if (!recursive && !strncmp(buf, "#include ", 9))
2036 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
2043 if (string_join(&file_buffer, included_module))
2046 return JB_ERR_MEMORY;
2052 /* skip lines starting with '#' */
2058 if (string_append(&file_buffer, buf))
2061 return JB_ERR_MEMORY;
2066 *template_ptr = file_buffer;
2072 /*********************************************************************
2074 * Function : template_fill
2076 * Description : CGI support function that fills in a pre-loaded
2077 * HTML template by replacing @name@ with value using
2078 * pcrs, for each item in the output map.
2080 * Note that a leading '$' charachter in the export map's
2081 * values will be stripped and toggle on backreference
2085 * 1 : template_ptr = IN: Template to be filled out.
2087 * OUT: Filled out template.
2088 * Caller must free().
2089 * 2 : exports = map with fill in symbol -> name pairs
2091 * Returns : JB_ERR_OK on success
2092 * JB_ERR_MEMORY on out-of-memory error
2094 *********************************************************************/
2095 jb_err template_fill(char **template_ptr, const struct map *exports)
2097 struct map_entry *m;
2099 char buf[BUFFER_SIZE];
2100 char *tmp_out_buffer;
2106 assert(template_ptr);
2107 assert(*template_ptr);
2110 file_buffer = *template_ptr;
2111 size = strlen(file_buffer) + 1;
2114 * Assemble pcrs joblist from exports map
2116 for (m = exports->first; m != NULL; m = m->next)
2118 if (*m->name == '$')
2121 * First character of name is '$', so remove this flag
2122 * character and allow backreferences ($1 etc) in the
2123 * "replace with" text.
2125 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
2131 * Treat the "replace with" text as a literal string -
2132 * no quoting needed, no backreferences allowed.
2133 * ("Trivial" ['T'] flag).
2137 /* Enclose name in @@ */
2138 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
2142 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
2144 /* Make and run job. */
2145 job = pcrs_compile(buf, m->value, flags, &error);
2148 if (error == PCRS_ERR_NOMEM)
2151 *template_ptr = NULL;
2152 return JB_ERR_MEMORY;
2156 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2157 /* Hope it wasn't important and silently ignore the invalid job */
2162 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2165 if (NULL == tmp_out_buffer)
2167 *template_ptr = NULL;
2168 return JB_ERR_MEMORY;
2170 file_buffer = tmp_out_buffer;
2177 *template_ptr = file_buffer;
2182 /*********************************************************************
2184 * Function : template_fill_for_cgi
2186 * Description : CGI support function that loads a HTML template
2187 * and fills it in. Handles file-not-found errors
2188 * by sending a HTML error message. For convenience,
2189 * this function also frees the passed "exports" map.
2192 * 1 : csp = Client state
2193 * 2 : templatename = name of the HTML template to be used
2194 * 3 : exports = map with fill in symbol -> name pairs.
2195 * Will be freed by this function.
2196 * 4 : rsp = Response structure to fill in.
2198 * Returns : JB_ERR_OK on success
2199 * JB_ERR_MEMORY on out-of-memory error
2201 *********************************************************************/
2202 jb_err template_fill_for_cgi(struct client_state *csp,
2203 const char *templatename,
2204 struct map *exports,
2205 struct http_response *rsp)
2210 assert(templatename);
2214 err = template_load(csp, &rsp->body, templatename, 0);
2215 if (err == JB_ERR_FILE)
2218 return cgi_error_no_template(csp, rsp, templatename);
2223 return err; /* JB_ERR_MEMORY */
2225 err = template_fill(&rsp->body, exports);
2231 /*********************************************************************
2233 * Function : default_exports
2235 * Description : returns a struct map list that contains exports
2236 * which are common to all CGI functions.
2239 * 1 : csp = Current client state (buffers, headers, etc...)
2240 * 2 : caller = name of CGI who calls us and which should
2241 * be excluded from the generated menu. May be
2243 * Returns : NULL if no memory, else a new map. Caller frees.
2245 *********************************************************************/
2246 struct map *default_exports(const struct client_state *csp, const char *caller)
2250 struct map * exports;
2251 int local_help_exists = 0;
2255 exports = new_map();
2256 if (exports == NULL)
2261 err = map(exports, "version", 1, html_encode(VERSION), 0);
2262 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2263 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2264 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2265 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2266 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
2267 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2268 if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2269 !strncmpic(csp->config->usermanual, "http", 4))
2271 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
2275 if (!err) err = map(exports, "user-manual", 1, "http://"CGI_SITE_2_HOST"/user-manual/" ,1);
2277 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2278 #ifdef FEATURE_TOGGLE
2279 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2281 if (!err) err = map_block_killer(exports, "can-toggle");
2284 snprintf(buf, 20, "%d", csp->config->hport);
2285 if (!err) err = map(exports, "my-port", 1, buf, 1);
2287 if(!strcmp(CODE_STATUS, "stable"))
2289 if (!err) err = map_block_killer(exports, "unstable");
2292 if (csp->config->admin_address != NULL)
2294 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2295 local_help_exists = 1;
2299 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2302 if (csp->config->proxy_info_url != NULL)
2304 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2305 local_help_exists = 1;
2309 if (!err) err = map_block_killer(exports, "have-proxy-info");
2312 if (local_help_exists == 0)
2314 if (!err) err = map_block_killer(exports, "have-help-info");
2327 /*********************************************************************
2329 * Function : map_block_killer
2331 * Description : Convenience function.
2332 * Adds a "killer" for the conditional HTML-template
2333 * block <name>, i.e. a substitution of the regex
2334 * "if-<name>-start.*if-<name>-end" to the given
2338 * 1 : exports = map to extend
2339 * 2 : name = name of conditional block
2341 * Returns : JB_ERR_OK on success
2342 * JB_ERR_MEMORY on out-of-memory error.
2344 *********************************************************************/
2345 jb_err map_block_killer(struct map *exports, const char *name)
2347 char buf[1000]; /* Will do, since the names are hardwired */
2351 assert(strlen(name) < 490);
2353 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2354 return map(exports, buf, 1, "", 1);
2358 /*********************************************************************
2360 * Function : map_block_keep
2362 * Description : Convenience function. Removes the markers used
2363 * by map-block-killer, to save a few bytes.
2364 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2367 * 1 : exports = map to extend
2368 * 2 : name = name of conditional block
2370 * Returns : JB_ERR_OK on success
2371 * JB_ERR_MEMORY on out-of-memory error.
2373 *********************************************************************/
2374 jb_err map_block_keep(struct map *exports, const char *name)
2377 char buf[500]; /* Will do, since the names are hardwired */
2381 assert(strlen(name) < 490);
2383 snprintf(buf, 500, "if-%s-start", name);
2384 err = map(exports, buf, 1, "", 1);
2391 snprintf(buf, 500, "if-%s-end", name);
2392 return map(exports, buf, 1, "", 1);
2396 /*********************************************************************
2398 * Function : map_conditional
2400 * Description : Convenience function.
2401 * Adds an "if-then-else" for the conditional HTML-template
2402 * block <name>, i.e. a substitution of the form:
2409 * The control structure and one of the alternatives
2413 * 1 : exports = map to extend
2414 * 2 : name = name of conditional block
2415 * 3 : choose_first = nonzero for first, zero for second.
2417 * Returns : JB_ERR_OK on success
2418 * JB_ERR_MEMORY on out-of-memory error.
2420 *********************************************************************/
2421 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2423 char buf[1000]; /* Will do, since the names are hardwired */
2428 assert(strlen(name) < 480);
2430 snprintf(buf, 1000, (choose_first
2431 ? "else-not-%s@.*@endif-%s"
2432 : "if-%s-then@.*@else-not-%s"),
2435 err = map(exports, buf, 1, "", 1);
2441 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2442 return map(exports, buf, 1, "", 1);
2446 /*********************************************************************
2448 * Function : make_menu
2450 * Description : Returns an HTML-formatted menu of the available
2451 * unhidden CGIs, excluding the one given in <self>
2453 * Parameters : self = name of CGI to leave out, can be NULL for
2456 * Returns : menu string, or NULL on out-of-memory error.
2458 *********************************************************************/
2459 char *make_menu(const char *self)
2461 const struct cgi_dispatcher *d;
2462 char *result = strdup("");
2466 self = "NO-SUCH-CGI!";
2469 /* List available unhidden CGI's and export as "other-cgis" */
2470 for (d = cgi_dispatchers; d->name; d++)
2472 if (d->description && strcmp(d->name, self))
2474 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2475 string_append(&result, d->name);
2476 string_append(&result, "\">");
2477 string_append(&result, d->description);
2478 string_append(&result, "</a></li>");
2486 /*********************************************************************
2488 * Function : dump_map
2490 * Description : HTML-dump a map for debugging (as table)
2493 * 1 : the_map = map to dump
2495 * Returns : string with HTML
2497 *********************************************************************/
2498 char *dump_map(const struct map *the_map)
2500 struct map_entry *cur_entry;
2501 char *ret = strdup("");
2503 string_append(&ret, "<table>\n");
2505 for (cur_entry = the_map->first;
2506 (cur_entry != NULL) && (ret != NULL);
2507 cur_entry = cur_entry->next)
2509 string_append(&ret, "<tr><td><b>");
2510 string_join (&ret, html_encode(cur_entry->name));
2511 string_append(&ret, "</b></td><td>");
2512 string_join (&ret, html_encode(cur_entry->value));
2513 string_append(&ret, "</td></tr>\n");
2516 string_append(&ret, "</table>\n");