1 const char cgi_rcs[] = "$Id: cgi.c,v 1.70.2.10 2003/06/06 07:54:25 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/Attic/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.70.2.10 2003/06/06 07:54:25 oes
42 * Security fix: dspatch_known_cgi no longer considers an empty
43 * referrer safe for critical CGIs, since malicious links could
44 * reside on https:// locations which browsers don't advertize as
45 * referrers. Closes bug #749916, thanks to Jeff Epler for the
46 * hint. Goodbye One-Click[tm] toggling :-(
48 * Revision 1.70.2.9 2003/05/08 15:11:31 oes
51 * Revision 1.70.2.8 2003/04/29 13:33:51 oes
52 * Killed a compiler warning on OSX
54 * Revision 1.70.2.7 2003/04/03 13:50:58 oes
55 * - Don't call cgi_error_disabled ifndef FEATURE_CGI_EDIT_ACTIONS
57 * - Show toggle info only if we have it
59 * Revision 1.70.2.6 2003/03/12 01:26:25 david__schmidt
60 * Move declaration of struct tm dummy outside of a control block so it is
61 * accessible later on during snprintf in get_http_time.
63 * Revision 1.70.2.5 2003/03/11 11:53:58 oes
64 * Cosmetic: Renamed cryptic variable
66 * Revision 1.70.2.4 2003/03/07 03:41:03 david__schmidt
67 * 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.
69 * Revision 1.70.2.3 2002/11/28 18:14:32 oes
70 * Disable access to critical CGIs via untrusted referrers.
71 * This prevents users from being tricked by malicious websites
72 * into making unintentional configuration changes:
74 * - Added flag to each cgi_dispatcher that allows or denies
76 * - Introduced proviorical function that greps for the
77 * referrer header before regular header parsing happens
78 * - Added safety check to dispatch_known_cgi. CGI is called
79 * if (cgi harmless || no referrer || we are referrer).
80 * Else a) toggle calls are modified not to change status and
81 * b) all other calls are denied.
83 * Revision 1.70.2.2 2002/11/12 16:20:37 oes
84 * Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
86 * Revision 1.70.2.1 2002/08/05 11:17:46 oes
87 * Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
89 * Revision 1.70 2002/05/19 11:33:20 jongfoster
90 * If a CGI error was not handled, and propogated back to
91 * dispatch_known_cgi(), then it was assumed to be "out of memory".
92 * This gave a very misleading error message.
94 * Now other errors will cause a simple message giving the error
95 * number and asking the user to report a bug.
98 * http://sourceforge.net/tracker/index.php?func=detail
99 * &aid=557905&group_id=11118&atid=111118
101 * Revision 1.69 2002/05/14 21:28:40 oes
102 * - Fixed add_help_link to link to the (now split) actions
103 * part of the config chapter
104 * - Renamed helplink export to actions-help-prefix
106 * Revision 1.68 2002/05/12 21:36:29 jongfoster
107 * Correcting function comments
109 * Revision 1.67 2002/04/30 12:02:07 oes
110 * Nit: updated a comment
112 * Revision 1.66 2002/04/26 18:32:57 jongfoster
113 * Fixing a memory leak on error
115 * Revision 1.65 2002/04/26 12:53:51 oes
116 * - New function add_help_link
117 * - default_exports now exports links to the user manual
118 * and a prefix for links into the config chapter
120 * Revision 1.64 2002/04/24 02:17:21 oes
121 * - Better descriptions for CGIs
122 * - Hide edit-actions, more shortcuts
123 * - Moved get_char_param, get_string_param and get_number_param here
126 * Revision 1.63 2002/04/15 19:06:43 jongfoster
129 * Revision 1.62 2002/04/10 19:59:46 jongfoster
130 * Fixes to #include in templates:
131 * - Didn't close main file if loading an included template fails.
132 * - I'm paranoid and want to disallow "#include /etc/passwd".
134 * Revision 1.61 2002/04/10 13:37:48 oes
135 * Made templates modular: template_load now recursive with max depth 1
137 * Revision 1.60 2002/04/08 20:50:25 swa
140 * Revision 1.59 2002/04/05 15:51:51 oes
141 * - added send-stylesheet CGI
142 * - bugfix: error-pages now get correct request protocol
144 * - kludged CGI descriptions and menu not to break JS syntax
146 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
147 * Fix Mac OSX compiler warnings
149 * Revision 1.57 2002/03/26 22:29:54 swa
150 * we have a new homepage!
152 * Revision 1.56 2002/03/24 17:50:46 jongfoster
153 * Fixing compile error if actions file editor disabled
155 * Revision 1.55 2002/03/24 16:55:06 oes
156 * Making GIF checkerboard transparent
158 * Revision 1.54 2002/03/24 16:18:15 jongfoster
161 * Revision 1.53 2002/03/24 16:06:00 oes
162 * Correct transparency for checkerboard PNG. Thanks, Magnus!
164 * Revision 1.52 2002/03/24 15:23:33 jongfoster
167 * Revision 1.51 2002/03/24 13:25:43 swa
168 * name change related issues
170 * Revision 1.50 2002/03/16 23:54:06 jongfoster
171 * Adding graceful termination feature, to help look for memory leaks.
172 * If you enable this (which, by design, has to be done by hand
173 * editing config.h) and then go to http://i.j.b/die, then the program
174 * will exit cleanly after the *next* request. It should free all the
175 * memory that was used.
177 * Revision 1.49 2002/03/13 00:27:04 jongfoster
180 * Revision 1.48 2002/03/08 17:47:07 jongfoster
183 * Revision 1.47 2002/03/08 16:41:33 oes
184 * Added GIF images again
186 * Revision 1.46 2002/03/07 03:48:38 oes
187 * - Changed built-in images from GIF to PNG
188 * (with regard to Unisys patent issue)
189 * - Added a 4x4 pattern PNG which is less intrusive
190 * than the logo but also clearly marks the deleted banners
192 * Revision 1.45 2002/03/06 22:54:35 jongfoster
193 * Automated function-comment nitpicking.
195 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
196 * - Better error reporting on OS/2
197 * - Fix double-slash comment (oops)
199 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
200 * - Re-enable OS/2 building after new parms were added
201 * - Fix false out of memory report when resolving CGI templates when no IP
202 * address is available of failed attempt (a la no such domain)
204 * Revision 1.42 2002/01/21 00:33:20 jongfoster
205 * Replacing strsav() with the safer string_append() or string_join().
206 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
207 * Adding missing html_encode() to error message generators.
208 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
210 * Revision 1.41 2002/01/17 20:56:22 jongfoster
211 * Replacing hard references to the URL of the config interface
212 * with #defines from project.h
214 * Revision 1.40 2002/01/09 14:26:46 oes
215 * Added support for thread-safe gmtime_r call.
217 * Revision 1.39 2001/11/16 00:48:13 jongfoster
218 * Fixing a compiler warning
220 * Revision 1.38 2001/11/13 00:31:21 jongfoster
221 * - Adding new CGIs for use by non-JavaScript browsers:
222 * edit-actions-url-form
223 * edit-actions-add-url-form
224 * edit-actions-remove-url-form
225 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
228 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
229 * Show enablement/disablement status in almost all templates.
230 * There is a little trickiness here: apparent recursive resolution of
231 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
232 * the actual enablement status. So a similar construct,
233 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
236 * Revision 1.36 2001/10/26 17:33:27 oes
239 * Revision 1.35 2001/10/23 21:48:19 jongfoster
240 * Cleaning up error handling in CGI functions - they now send back
241 * a HTML error page and should never cause a FATAL error. (Fixes one
242 * potential source of "denial of service" attacks).
244 * CGI actions file editor that works and is actually useful.
246 * Ability to toggle Junkbuster remotely using a CGI call.
248 * You can turn off both the above features in the main configuration
249 * file, e.g. if you are running a multi-user proxy.
251 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
252 * Only show "Local support" on templates conditionally:
253 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
254 * - if not, no Local support section appears
256 * Revision 1.33 2001/10/14 22:28:41 jongfoster
257 * Fixing stupid typo.
259 * Revision 1.32 2001/10/14 22:20:18 jongfoster
260 * - Changes to CGI dispatching method to match CGI names exactly,
261 * rather than doing a prefix match.
262 * - No longer need to count the length of the CGI handler names by hand.
263 * - Adding new handler for 404 error when disptching a CGI, if none of
264 * the handlers match.
265 * - Adding new handlers for CGI actionsfile editor.
267 * Revision 1.31 2001/10/10 10:56:39 oes
268 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
270 * Revision 1.30 2001/10/02 15:30:57 oes
271 * Introduced show-request cgi
273 * Revision 1.29 2001/09/20 15:47:44 steudten
275 * Fix BUG: Modify int size to size_t size in fill_template()
276 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
278 * Revision 1.28 2001/09/19 18:00:37 oes
279 * - Deletef time() FIXME (Can't fail under Linux either, if
280 * the argument is guaranteed to be in out address space,
283 * - Pointer notation cosmetics
284 * - Fixed a minor bug in template_fill(): Failiure of
285 * pcrs_execute() now secure.
287 * Revision 1.27 2001/09/16 17:08:54 jongfoster
288 * Moving simple CGI functions from cgi.c to new file cgisimple.c
290 * Revision 1.26 2001/09/16 15:47:37 jongfoster
291 * First version of CGI-based edit interface. This is very much a
292 * work-in-progress, and you can't actually use it to edit anything
293 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
294 * to have any effect.
296 * Revision 1.25 2001/09/16 15:02:35 jongfoster
297 * Adding i.j.b/robots.txt.
298 * Inlining add_stats() since it's only ever called from one place.
300 * Revision 1.24 2001/09/16 11:38:01 jongfoster
301 * Splitting fill_template() into 2 functions:
302 * template_load() loads the file
303 * template_fill() performs the PCRS regexps.
304 * This is because the CGI edit interface has a "table row"
305 * template which is used many times in the page - this
306 * change means it's only loaded from disk once.
308 * Revision 1.23 2001/09/16 11:16:05 jongfoster
309 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
311 * Revision 1.22 2001/09/16 11:00:10 jongfoster
312 * New function alloc_http_response, for symmetry with free_http_response
314 * Revision 1.21 2001/09/13 23:53:03 jongfoster
315 * Support for both static and dynamically generated CGI pages.
316 * Correctly setting Last-Modified: and Expires: HTTP headers.
318 * Revision 1.20 2001/09/13 23:40:36 jongfoster
319 * (Cosmetic only) Indentation correction
321 * Revision 1.19 2001/09/13 23:31:25 jongfoster
322 * Moving image data to cgi.c rather than cgi.h.
324 * Revision 1.18 2001/08/05 16:06:20 jongfoster
325 * Modifiying "struct map" so that there are now separate header and
326 * "map_entry" structures. This means that functions which modify a
327 * map no longer need to return a pointer to the modified map.
328 * Also, it no longer reverses the order of the entries (which may be
329 * important with some advanced template substitutions).
331 * Revision 1.17 2001/08/05 15:57:38 oes
332 * Adapted finish_http_response to new list_to_text
334 * Revision 1.16 2001/08/01 21:33:18 jongfoster
335 * Changes to fill_template() that reduce memory usage without having
336 * an impact on performance. I also renamed some variables so as not
337 * to clash with the C++ keywords "new" and "template".
339 * Revision 1.15 2001/08/01 21:19:22 jongfoster
340 * Moving file version information to a separate CGI page.
342 * Revision 1.14 2001/08/01 00:19:03 jongfoster
343 * New function: map_conditional() for an if-then-else syntax.
344 * Changing to use new version of show_defines()
346 * Revision 1.13 2001/07/30 22:08:36 jongfoster
347 * Tidying up #defines:
348 * - All feature #defines are now of the form FEATURE_xxx
349 * - Permanently turned off WIN_GUI_EDIT
350 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
352 * Revision 1.12 2001/07/29 18:47:05 jongfoster
353 * Adding missing #include "loadcfg.h"
355 * Revision 1.11 2001/07/18 17:24:37 oes
356 * Changed to conform to new pcrs interface
358 * Revision 1.10 2001/07/13 13:53:13 oes
359 * Removed all #ifdef PCRS and related code
361 * Revision 1.9 2001/06/29 21:45:41 oes
362 * Indentation, CRLF->LF, Tab-> Space
364 * Revision 1.8 2001/06/29 13:21:46 oes
365 * - Cosmetics: renamed and reordered functions, variables,
366 * texts, improved comments etc
368 * - Removed ij_untrusted_url() The relevant
369 * info is now part of the "untrusted" page,
370 * which is generated by filters.c:trust_url()
372 * - Generators of content now call finish_http_response()
373 * themselves, making jcc.c:chat() a little less
376 * - Removed obsolete "Pragma: no-cache" from our headers
378 * - http_responses now know their head length
380 * - fill_template now uses the new interface to pcrs, so that
381 * - long jobs (like whole files) no longer have to be assembled
382 * in a fixed size buffer
383 * - the new T (trivial) option is used, and the replacement may
384 * contain Perl syntax backrefs without confusing pcrs
386 * - Introduced default_exports() which generates a set of exports
387 * common to all CGIs and other content generators
389 * - Introduced convenience function map_block_killer()
391 * - Introduced convenience function make_menu()
393 * - Introduced CGI-like function error_response() which generates
394 * the "No such domain" and "Connect failed" messages using the
397 * - cgi_show_url_info:
398 * - adapted to new CGI features
399 * - form and answers now generated from same template
400 * - http:// prefix in URL now OK
403 * - adapted to new CGI features
404 * - no longer uses csp->init_proxy_args
407 * - moved menu generation to make_menu()
409 * - add_stats now writes single export map entries instead
412 * - Moved redirect_url() to filters.c
414 * - Fixed mem leak in free_http_response(), map_block_killer(),
416 * - Removed logentry from cancelled commit
418 * Revision 1.7 2001/06/09 10:51:58 jongfoster
419 * Changing "show URL info" handler to new style.
420 * Changing BUFSIZ ==> BUFFER_SIZE
422 * Revision 1.6 2001/06/07 23:05:19 jongfoster
423 * Removing code related to old forward and ACL files.
425 * Revision 1.5 2001/06/05 19:59:16 jongfoster
426 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
428 * Revision 1.4 2001/06/04 10:41:52 swa
429 * show version string of cgi.h and cgi.c
431 * Revision 1.3 2001/06/03 19:12:16 oes
432 * introduced new cgi handling
434 * No revisions before 1.3
436 **********************************************************************/
442 #include <sys/types.h>
450 #define snprintf _snprintf
451 #endif /* def _WIN32 */
459 #include "miscutil.h"
460 #include "cgisimple.h"
461 #ifdef FEATURE_CGI_EDIT_ACTIONS
463 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
465 /* loadcfg.h is for global_toggle_state only */
466 #ifdef FEATURE_PTHREAD
469 /* jcc.h is for mutex semaphore globals only */
470 #endif /* def FEATURE_PTHREAD */
471 const char cgi_h_rcs[] = CGI_H_VERSION;
474 * List of CGI functions: name, handler, description
475 * Note: Do NOT use single quotes in the description;
476 * this will break the dynamic "blocked" template!
478 static const struct cgi_dispatcher cgi_dispatchers[] = {
483 #ifdef FEATURE_GRACEFUL_TERMINATION
486 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
487 "this is a one click Denial Of Service attack!!!</em>",
492 #ifdef FEATURE_CGI_EDIT_ACTIONS
493 "View & change the current configuration",
495 "View the current configuration",
500 "View the source code version numbers",
504 "View the request headers.",
508 "Look up which actions apply to a URL and why",
510 #ifdef FEATURE_CGI_EDIT_ACTIONS
513 "Toggle Privoxy on or off",
515 { "edit-actions", /* Edit the actions list */
518 { "eaa", /* Shortcut for edit-actions-add-url-form */
519 cgi_edit_actions_add_url_form,
521 { "eau", /* Shortcut for edit-actions-url-form */
522 cgi_edit_actions_url_form,
524 { "ear", /* Shortcut for edit-actions-remove-url-form */
525 cgi_edit_actions_remove_url_form,
527 { "eafu", /* Shortcut for edit-actions-for-url */
528 cgi_edit_actions_for_url,
530 { "eas", /* Shortcut for edit-actions-submit */
531 cgi_edit_actions_submit,
533 { "easa", /* Shortcut for edit-actions-section-add */
534 cgi_edit_actions_section_add,
536 { "easr", /* Shortcut for edit-actions-section-remove */
537 cgi_edit_actions_section_remove,
539 { "eass", /* Shortcut for edit-actions-section-swap */
540 cgi_edit_actions_section_swap,
542 { "edit-actions-for-url",
543 cgi_edit_actions_for_url,
544 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
545 { "edit-actions-list",
546 cgi_edit_actions_list,
547 NULL, TRUE /* Edit the actions list */ },
548 { "edit-actions-submit",
549 cgi_edit_actions_submit,
550 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
551 { "edit-actions-url",
552 cgi_edit_actions_url,
553 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
554 { "edit-actions-url-form",
555 cgi_edit_actions_url_form,
556 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
557 { "edit-actions-add-url",
558 cgi_edit_actions_add_url,
559 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
560 { "edit-actions-add-url-form",
561 cgi_edit_actions_add_url_form,
562 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
563 { "edit-actions-remove-url",
564 cgi_edit_actions_remove_url,
565 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
566 { "edit-actions-remove-url-form",
567 cgi_edit_actions_remove_url_form,
568 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
569 { "edit-actions-section-add",
570 cgi_edit_actions_section_add,
571 NULL, FALSE /* Remove a section from the actionsfile */ },
572 { "edit-actions-section-remove",
573 cgi_edit_actions_section_remove,
574 NULL, FALSE /* Remove a section from the actionsfile */ },
575 { "edit-actions-section-swap",
576 cgi_edit_actions_section_swap,
577 NULL, FALSE /* Swap two sections in the actionsfile */ },
578 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
581 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
584 NULL, TRUE /* Send a built-in image */ },
587 NULL, TRUE /* Send templates/cgi-style.css */ },
589 cgi_transparent_image,
590 NULL, TRUE /* Send a transparent image (short name) */ },
591 { NULL, /* NULL Indicates end of list and default page */
593 NULL, TRUE /* Unknown CGI page */ }
598 * Built-in images for ad replacement
600 * Hint: You can encode your own images like this:
601 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
604 #ifdef FEATURE_NO_GIFS
607 * Checkerboard pattern, as a PNG.
609 const char image_pattern_data[] =
610 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
611 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
612 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
613 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
614 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
615 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
616 "\000\000\000\111\105\116\104\256\102\140\202";
619 * 1x1 transparant PNG.
621 const char image_blank_data[] =
622 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
623 "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
624 "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
625 "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
626 "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
627 "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
628 "\000\000\000\000\111\105\116\104\256\102\140\202";
632 * Checkerboard pattern, as a GIF.
634 const char image_pattern_data[] =
635 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
636 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
637 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
638 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
642 * 1x1 transparant GIF.
644 const char image_blank_data[] =
645 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
646 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
647 "\000\001\000\000\002\002D\001\000;";
650 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
651 const size_t image_blank_length = sizeof(image_blank_data) - 1;
654 static struct http_response cgi_error_memory_response[1];
656 static struct http_response *dispatch_known_cgi(struct client_state * csp,
658 static struct map *parse_cgi_parameters(char *argstring);
661 /*********************************************************************
663 * Function : dispatch_cgi
665 * Description : Checks if a request URL has either the magical
666 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
667 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
668 * http://config.privoxy.org/). If so, it passes
669 * the (rest of the) path onto dispatch_known_cgi, which
670 * calls the relevant CGI handler function.
673 * 1 : csp = Current client state (buffers, headers, etc...)
675 * Returns : http_response if match, NULL if nonmatch or handler fail
677 *********************************************************************/
678 struct http_response *dispatch_cgi(struct client_state *csp)
680 const char *host = csp->http->host;
681 const char *path = csp->http->path;
684 * Should we intercept ?
687 /* Note: "example.com" and "example.com." are equivalent hostnames. */
689 /* Either the host matches CGI_SITE_1_HOST ..*/
690 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
691 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
692 && (path[0] == '/') )
694 /* ..then the path will all be for us. Remove leading '/' */
697 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
698 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
699 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
700 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
702 /* take everything following CGI_SITE_2_PATH */
703 path += strlen(CGI_SITE_2_PATH);
706 /* skip the forward slash after CGI_SITE_2_PATH */
709 else if (*path != '\0')
712 * wierdness: URL is /configXXX, where XXX is some string
713 * Do *NOT* intercept.
725 * This is a CGI call.
728 return dispatch_known_cgi(csp, path);
732 /*********************************************************************
734 * Function : grep_cgi_referrer
736 * Description : Ugly provisorical fix that greps the value of the
737 * referer HTTP header field out of a linked list of
738 * strings like found at csp->headers. Will disappear
741 * FIXME: csp->headers ought to be csp->http->headers
742 * FIXME: Parsing all client header lines should
743 * happen right after the request is received!
746 * 1 : csp = Current client state (buffers, headers, etc...)
748 * Returns : pointer to value (no copy!), or NULL if none found.
750 *********************************************************************/
751 char *grep_cgi_referrer(struct client_state *csp)
753 struct list_entry *p;
755 for (p = csp->headers->first; p != NULL; p = p->next)
757 if (p->str == NULL) continue;
758 if (strncmpic(p->str, "Referer: ", 9) == 0)
760 return ((p->str) + 9);
768 /*********************************************************************
770 * Function : dispatch_known_cgi
772 * Description : Processes a CGI once dispatch_cgi has determined that
773 * it matches one of the magic prefixes. Parses the path
774 * as a cgi name plus query string, prepares a map that
775 * maps CGI parameter names to their values, initializes
776 * the http_response struct, and calls the relevant CGI
780 * 1 : csp = Current client state (buffers, headers, etc...)
781 * 2 : path = Path of CGI, with the CGI prefix removed.
782 * Should not have a leading "/".
784 * Returns : http_response, or NULL on handler failure or out of
787 *********************************************************************/
788 static struct http_response *dispatch_known_cgi(struct client_state * csp,
791 const struct cgi_dispatcher *d;
792 struct map *param_list;
793 struct http_response *rsp;
794 char *query_args_start;
799 if (NULL == (path_copy = strdup(path)))
801 return cgi_error_memory();
804 query_args_start = path_copy;
805 while (*query_args_start && *query_args_start != '?')
809 if (*query_args_start == '?')
811 *query_args_start++ = '\0';
814 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
817 return cgi_error_memory();
822 * path_copy = CGI call name
823 * param_list = CGI params, as map
826 /* Get mem for response or fail*/
827 if (NULL == (rsp = alloc_http_response()))
830 free_map(param_list);
831 return cgi_error_memory();
834 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
835 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
836 csp->ip_addr_str, csp->http->cmd);
839 * Find and start the right CGI function
844 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
847 * If the called CGI is either harmless, or referred
848 * from a trusted source, start it.
851 || ((NULL != (referrer = grep_cgi_referrer(csp)))
852 && (0 == strncmp(referrer, "http://config.privoxy.org/", 26)))
855 err = (d->handler)(csp, rsp, param_list);
860 * Else, modify toggle calls so that they only display
861 * the status, and deny all other calls.
863 if (0 == strcmp(path_copy, "toggle"))
865 unmap(param_list, "set");
866 err = (d->handler)(csp, rsp, param_list);
870 err = cgi_error_404(csp, rsp, param_list);
875 free_map(param_list);
877 if (err == JB_ERR_CGI_PARAMS)
879 err = cgi_error_bad_param(csp, rsp);
881 if (err && (err != JB_ERR_MEMORY))
883 /* Unexpected error! Shouldn't get here */
884 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
885 err = cgi_error_unknown(csp, rsp, err);
890 return finish_http_response(rsp);
894 /* Error in handler, probably out-of-memory */
895 free_http_response(rsp);
896 return cgi_error_memory();
904 /*********************************************************************
906 * Function : parse_cgi_parameters
908 * Description : Parse a URL-encoded argument string into name/value
909 * pairs and store them in a struct map list.
912 * 1 : argstring = string to be parsed. Will be trashed.
914 * Returns : pointer to param list, or NULL if out of memory.
916 *********************************************************************/
917 static struct map *parse_cgi_parameters(char *argstring)
920 char *vector[BUFFER_SIZE];
922 struct map *cgi_params;
924 if (NULL == (cgi_params = new_map()))
930 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
931 * the fragment identifier along with the request, so we must
932 * cut it off here, so it won't pollute the CGI params:
934 if (NULL != (p = strchr(argstring, '#')))
939 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
941 for (i = 0; i < pairs; i++)
943 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
946 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
948 free_map(cgi_params);
959 /*********************************************************************
961 * Function : get_char_param
963 * Description : Get a single-character parameter passed to a CGI
967 * 1 : parameters = map of cgi parameters
968 * 2 : param_name = The name of the parameter to read
970 * Returns : Uppercase character on success, '\0' on error.
972 *********************************************************************/
973 char get_char_param(const struct map *parameters,
974 const char *param_name)
981 ch = *(lookup(parameters, param_name));
982 if ((ch >= 'a') && (ch <= 'z'))
991 /*********************************************************************
993 * Function : get_string_param
995 * Description : Get a string paramater, to be used as an
996 * ACTION_STRING or ACTION_MULTI paramater.
997 * Validates the input to prevent stupid/malicious
998 * users from corrupting their action file.
1001 * 1 : parameters = map of cgi parameters
1002 * 2 : param_name = The name of the parameter to read
1003 * 3 : pparam = destination for paramater. Allocated as
1004 * part of the map "parameters", so don't free it.
1005 * Set to NULL if not specified.
1007 * Returns : JB_ERR_OK on success, or if the paramater
1008 * was not specified.
1009 * JB_ERR_MEMORY on out-of-memory.
1010 * JB_ERR_CGI_PARAMS if the paramater is not valid.
1012 *********************************************************************/
1013 jb_err get_string_param(const struct map *parameters,
1014 const char *param_name,
1015 const char **pparam)
1027 param = lookup(parameters, param_name);
1033 if (strlen(param) >= CGI_PARAM_LEN_MAX)
1038 * Note that the length limit is arbitrary, it just seems
1039 * sensible to limit it to *something*. There's no
1040 * technical reason for any limit at all.
1042 return JB_ERR_CGI_PARAMS;
1045 /* Check every character to see if it's legal */
1047 while ((ch = *s++) != '\0')
1049 if ( ((unsigned char)ch < (unsigned char)' ')
1052 /* Probable hack attempt, or user accidentally used '}'. */
1053 return JB_ERR_CGI_PARAMS;
1064 /*********************************************************************
1066 * Function : get_number_param
1068 * Description : Get a non-negative integer from the parameters
1069 * passed to a CGI function.
1072 * 1 : csp = Current client state (buffers, headers, etc...)
1073 * 2 : parameters = map of cgi parameters
1074 * 3 : name = Name of CGI parameter to read
1075 * 4 : pvalue = destination for value.
1076 * Set to -1 on error.
1078 * Returns : JB_ERR_OK on success
1079 * JB_ERR_MEMORY on out-of-memory
1080 * JB_ERR_CGI_PARAMS if the parameter was not specified
1083 *********************************************************************/
1084 jb_err get_number_param(struct client_state *csp,
1085 const struct map *parameters,
1100 param = lookup(parameters, name);
1103 return JB_ERR_CGI_PARAMS;
1106 /* We don't use atoi because I want to check this carefully... */
1109 while ((ch = *param++) != '\0')
1111 if ((ch < '0') || (ch > '9'))
1113 return JB_ERR_CGI_PARAMS;
1120 * <limits.h> defines UINT_MAX
1122 * (UINT_MAX - ch) / 10 is the largest number that
1123 * can be safely multiplied by 10 then have ch added.
1125 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1127 return JB_ERR_CGI_PARAMS;
1130 value = value * 10 + ch;
1141 /*********************************************************************
1143 * Function : error_response
1145 * Description : returns an http_response that explains the reason
1146 * why a request failed.
1149 * 1 : csp = Current client state (buffers, headers, etc...)
1150 * 2 : templatename = Which template should be used for the answer
1151 * 3 : sys_err = system error number
1153 * Returns : A http_response. If we run out of memory, this
1154 * will be cgi_error_memory().
1156 *********************************************************************/
1157 struct http_response *error_response(struct client_state *csp,
1158 const char *templatename,
1162 struct http_response *rsp;
1163 struct map * exports = default_exports(csp, NULL);
1164 if (exports == NULL)
1166 return cgi_error_memory();
1169 if (NULL == (rsp = alloc_http_response()))
1172 return cgi_error_memory();
1175 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1176 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1177 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1178 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1179 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1182 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1185 /* Some failures, like "404 no such domain", don't have an IP address. */
1186 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1194 free_http_response(rsp);
1195 return cgi_error_memory();
1198 if (!strcmp(templatename, "no-such-domain"))
1200 rsp->status = strdup("404 No such domain");
1201 if (rsp->status == NULL)
1204 free_http_response(rsp);
1205 return cgi_error_memory();
1208 else if (!strcmp(templatename, "connect-failed"))
1210 rsp->status = strdup("503 Connect failed");
1211 if (rsp->status == NULL)
1214 free_http_response(rsp);
1215 return cgi_error_memory();
1219 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1222 free_http_response(rsp);
1223 return cgi_error_memory();
1226 return finish_http_response(rsp);
1230 /*********************************************************************
1232 * Function : cgi_init_error_messages
1234 * Description : Call at the start of the program to initialize
1235 * the error message used by cgi_error_memory().
1241 *********************************************************************/
1242 void cgi_init_error_messages(void)
1244 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1245 cgi_error_memory_response->head =
1246 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1247 "Content-Type: text/html\r\n"
1249 cgi_error_memory_response->body =
1251 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1253 "<h1>500 Internal Privoxy Error</h1>\r\n"
1254 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1255 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1259 cgi_error_memory_response->head_length =
1260 strlen(cgi_error_memory_response->head);
1261 cgi_error_memory_response->content_length =
1262 strlen(cgi_error_memory_response->body);
1266 /*********************************************************************
1268 * Function : cgi_error_memory
1270 * Description : Called if a CGI function runs out of memory.
1271 * Returns a statically-allocated error response.
1275 * Returns : http_response data structure for output. This is
1276 * statically allocated, for obvious reasons.
1278 *********************************************************************/
1279 struct http_response *cgi_error_memory(void)
1281 /* assert that it's been initialized. */
1282 assert(cgi_error_memory_response->head);
1284 return cgi_error_memory_response;
1288 /*********************************************************************
1290 * Function : cgi_error_no_template
1292 * Description : Almost-CGI function that is called if a template
1293 * cannot be loaded. Note this is not a true CGI,
1294 * it takes a template name rather than a map of
1298 * 1 : csp = Current client state (buffers, headers, etc...)
1299 * 2 : rsp = http_response data structure for output
1300 * 3 : template_name = Name of template that could not
1303 * Returns : JB_ERR_OK on success
1304 * JB_ERR_MEMORY on out-of-memory error.
1306 *********************************************************************/
1307 jb_err cgi_error_no_template(struct client_state *csp,
1308 struct http_response *rsp,
1309 const char *template_name)
1311 static const char status[] =
1312 "500 Internal Privoxy Error";
1313 static const char body_prefix[] =
1315 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1317 "<h1>500 Internal Privoxy Error</h1>\r\n"
1318 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1319 "<p><b>Could not load template file <code>";
1320 static const char body_suffix[] =
1321 "</code> or one of it's included components.</b></p>\r\n"
1322 "<p>Please contact your proxy administrator.</p>\r\n"
1323 "<p>If you are the proxy administrator, please put the required file(s)"
1324 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1325 "location of the <code><i>(confdir)</i></code> directory "
1326 "is specified in the main Privoxy <code>config</code> "
1327 "file. (It's typically the Privoxy install directory"
1329 ", or <code>/etc/privoxy/</code>"
1330 #endif /* ndef _WIN32 */
1337 assert(template_name);
1339 /* Reset rsp, if needed */
1343 rsp->content_length = 0;
1344 rsp->head_length = 0;
1347 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1348 if (rsp->body == NULL)
1350 return JB_ERR_MEMORY;
1352 strcpy(rsp->body, body_prefix);
1353 strcat(rsp->body, template_name);
1354 strcat(rsp->body, body_suffix);
1356 rsp->status = strdup(status);
1357 if (rsp->body == NULL)
1359 return JB_ERR_MEMORY;
1366 /*********************************************************************
1368 * Function : cgi_error_unknown
1370 * Description : Almost-CGI function that is called if an unexpected
1371 * error occurs in the top-level CGI dispatcher.
1372 * In this context, "unexpected" means "anything other
1373 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1374 * expected to handle all other errors internally,
1375 * since they can give more relavent error messages
1378 * Note this is not a true CGI, it takes an error
1379 * code rather than a map of parameters.
1382 * 1 : csp = Current client state (buffers, headers, etc...)
1383 * 2 : rsp = http_response data structure for output
1384 * 3 : error_to_report = Error code to report.
1386 * Returns : JB_ERR_OK on success
1387 * JB_ERR_MEMORY on out-of-memory error.
1389 *********************************************************************/
1390 jb_err cgi_error_unknown(struct client_state *csp,
1391 struct http_response *rsp,
1392 jb_err error_to_report)
1394 static const char status[] =
1395 "500 Internal Privoxy Error";
1396 static const char body_prefix[] =
1398 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1400 "<h1>500 Internal Privoxy Error</h1>\r\n"
1401 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1402 "<p><b>Unexpected internal error: ";
1403 static const char body_suffix[] =
1406 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1407 "file a bug report</a>.</p>\r\n"
1414 /* Reset rsp, if needed */
1418 rsp->content_length = 0;
1419 rsp->head_length = 0;
1422 sprintf(errnumbuf, "%d", error_to_report);
1424 rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1425 if (rsp->body == NULL)
1427 return JB_ERR_MEMORY;
1429 strcpy(rsp->body, body_prefix);
1430 strcat(rsp->body, errnumbuf);
1431 strcat(rsp->body, body_suffix);
1433 rsp->status = strdup(status);
1434 if (rsp->body == NULL)
1436 return JB_ERR_MEMORY;
1443 /*********************************************************************
1445 * Function : cgi_error_bad_param
1447 * Description : CGI function that is called if the parameters
1448 * (query string) for a CGI were wrong.
1451 * 1 : csp = Current client state (buffers, headers, etc...)
1452 * 2 : rsp = http_response data structure for output
1454 * CGI Parameters : none
1456 * Returns : JB_ERR_OK on success
1457 * JB_ERR_MEMORY on out-of-memory error.
1459 *********************************************************************/
1460 jb_err cgi_error_bad_param(struct client_state *csp,
1461 struct http_response *rsp)
1463 struct map *exports;
1468 if (NULL == (exports = default_exports(csp, NULL)))
1470 return JB_ERR_MEMORY;
1473 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1477 /*********************************************************************
1479 * Function : add_help_link
1481 * Description : Produce a copy of the string given as item,
1482 * embedded in an HTML link to its corresponding
1483 * section (item name in uppercase) in the actions
1484 * chapter of the user manual, (whose URL is given in
1485 * the config and defaults to our web site).
1487 * FIXME: I currently only work for actions, and would
1488 * like to be generalized for other topics.
1491 * 1 : item = item (will NOT be free()d.)
1492 * It is assumed to be HTML-safe.
1493 * 2 : config = The current configuration.
1495 * Returns : String with item embedded in link, or NULL on
1498 *********************************************************************/
1499 char *add_help_link(const char *item,
1500 struct configuration_spec *config)
1504 if (!item) return NULL;
1506 result = strdup("<a href=\"");
1507 string_append(&result, config->usermanual);
1508 string_append(&result, ACTIONS_HELP_PREFIX);
1509 string_join (&result, string_toupper(item));
1510 string_append(&result, "\">");
1511 string_append(&result, item);
1512 string_append(&result, "</a> ");
1518 /*********************************************************************
1520 * Function : get_http_time
1522 * Description : Get the time in a format suitable for use in a
1523 * HTTP header - e.g.:
1524 * "Sun, 06 Nov 1994 08:49:37 GMT"
1527 * 1 : time_offset = Time returned will be current time
1528 * plus this number of seconds.
1529 * 2 : buf = Destination for result. Must be long enough
1530 * to hold 29 characters plus a trailing zero.
1534 *********************************************************************/
1535 void get_http_time(int time_offset, char *buf)
1537 static const char day_names[7][4] =
1538 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1539 static const char month_names[12][4] =
1540 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1541 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1544 time_t current_time;
1545 #if defined(HAVE_GMTIME_R) && !defined(OSX_DARWIN)
1547 * Declare dummy up here (instead of inside get/set gmt block) so it
1548 * doesn't go out of scope before it's potentially used in snprintf later.
1549 * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1550 * !defined HAVE_GMTIME_R.
1557 time(¤t_time); /* get current time */
1559 current_time += time_offset;
1561 /* get and save the gmt */
1564 pthread_mutex_lock(&gmtime_mutex);
1565 t = gmtime(¤t_time);
1566 pthread_mutex_unlock(&gmtime_mutex);
1568 t = gmtime_r(¤t_time, &dummy);
1570 t = gmtime(¤t_time);
1574 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1576 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1577 day_names[t->tm_wday],
1579 month_names[t->tm_mon],
1589 /*********************************************************************
1591 * Function : finish_http_response
1593 * Description : Fill in the missing headers in an http response,
1594 * and flatten the headers to an http head.
1597 * 1 : rsp = pointer to http_response to be processed
1599 * Returns : A http_response, usually the rsp parameter.
1600 * On error, free()s rsp and returns cgi_error_memory()
1602 *********************************************************************/
1603 struct http_response *finish_http_response(struct http_response *rsp)
1605 char buf[BUFFER_SIZE];
1608 /* Special case - do NOT change this statically allocated response,
1609 * which is ready for output anyway.
1611 if (rsp == cgi_error_memory_response)
1617 * Fill in the HTTP Status
1619 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1620 err = enlist_first(rsp->headers, buf);
1623 * Set the Content-Length
1625 if (rsp->content_length == 0)
1627 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1631 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1632 err = enlist(rsp->headers, buf);
1636 * Fill in the default headers:
1638 * Content-Type: default to text/html if not already specified.
1639 * Date: set to current date/time.
1640 * Last-Modified: set to date/time the page was last changed.
1641 * Expires: set to date/time page next needs reloading.
1642 * Cache-Control: set to "no-cache" if applicable.
1644 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1646 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1651 * Set Expires to about 10 min into the future so it'll get reloaded
1652 * occasionally, e.g. if Privoxy gets upgraded.
1657 get_http_time(0, buf);
1658 err = enlist_unique_header(rsp->headers, "Date", buf);
1661 /* Some date in the past. */
1662 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1666 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1667 err = enlist_unique_header(rsp->headers, "Expires", buf);
1673 * Compliant browsers should not cache this due to the "Cache-Control"
1674 * setting. However, to be certain, we also set both "Last-Modified"
1675 * and "Expires" to the current time.
1677 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1679 get_http_time(0, buf);
1680 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1681 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1682 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1689 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1691 free_http_response(rsp);
1692 return cgi_error_memory();
1694 rsp->head_length = strlen(rsp->head);
1701 /*********************************************************************
1703 * Function : alloc_http_response
1705 * Description : Allocates a new http_response structure.
1709 * Returns : pointer to a new http_response, or NULL.
1711 *********************************************************************/
1712 struct http_response *alloc_http_response(void)
1714 return (struct http_response *) zalloc(sizeof(struct http_response));
1719 /*********************************************************************
1721 * Function : free_http_response
1723 * Description : Free the memory occupied by an http_response
1724 * and its depandant structures.
1727 * 1 : rsp = pointer to http_response to be freed
1731 *********************************************************************/
1732 void free_http_response(struct http_response *rsp)
1735 * Must special case cgi_error_memory_response, which is never freed.
1737 if (rsp && (rsp != cgi_error_memory_response))
1742 destroy_list(rsp->headers);
1749 /*********************************************************************
1751 * Function : template_load
1753 * Description : CGI support function that loads a given HTML
1754 * template from the confdir, ignoring comment
1755 * lines and following #include statements up to
1759 * 1 : csp = Current client state (buffers, headers, etc...)
1760 * 2 : template_ptr = Destination for pointer to loaded
1762 * 3 : templatename = name of the HTML template to be used
1763 * 4 : recursive = Flag set if this function calls itself
1764 * following an #include statament
1766 * Returns : JB_ERR_OK on success
1767 * JB_ERR_MEMORY on out-of-memory error.
1768 * JB_ERR_FILE if the template file cannot be read
1770 *********************************************************************/
1771 jb_err template_load(struct client_state *csp, char **template_ptr,
1772 const char *templatename, int recursive)
1775 char *templates_dir_path;
1778 char *included_module;
1781 char buf[BUFFER_SIZE];
1784 assert(template_ptr);
1785 assert(templatename);
1787 *template_ptr = NULL;
1789 /* Validate template name. Paranoia. */
1790 for (p = templatename; *p != 0; p++)
1792 if ( ((*p < 'a') || (*p > 'z'))
1793 && ((*p < 'A') || (*p > 'Z'))
1794 && ((*p < '0') || (*p > '9'))
1798 /* Illegal character */
1803 /* Generate full path */
1805 templates_dir_path = make_path(csp->config->confdir, "templates");
1806 if (templates_dir_path == NULL)
1808 return JB_ERR_MEMORY;
1811 full_path = make_path(templates_dir_path, templatename);
1812 free(templates_dir_path);
1813 if (full_path == NULL)
1815 return JB_ERR_MEMORY;
1818 /* Allocate buffer */
1820 file_buffer = strdup("");
1821 if (file_buffer == NULL)
1824 return JB_ERR_MEMORY;
1827 /* Open template file */
1829 if (NULL == (fp = fopen(full_path, "r")))
1831 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1839 * Read the file, ignoring comments, and honoring #include
1840 * statements, unless we're already called recursively.
1842 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1843 * This is unlikely in practise.
1845 while (fgets(buf, BUFFER_SIZE, fp))
1847 if (!recursive && !strncmp(buf, "#include ", 9))
1849 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1856 if (string_join(&file_buffer, included_module))
1859 return JB_ERR_MEMORY;
1865 /* skip lines starting with '#' */
1871 if (string_append(&file_buffer, buf))
1874 return JB_ERR_MEMORY;
1879 *template_ptr = file_buffer;
1885 /*********************************************************************
1887 * Function : template_fill
1889 * Description : CGI support function that fills in a pre-loaded
1890 * HTML template by replacing @name@ with value using
1891 * pcrs, for each item in the output map.
1893 * Note that a leading '$' charachter in the export map's
1894 * values will be stripped and toggle on backreference
1898 * 1 : template_ptr = IN: Template to be filled out.
1900 * OUT: Filled out template.
1901 * Caller must free().
1902 * 2 : exports = map with fill in symbol -> name pairs
1904 * Returns : JB_ERR_OK on success
1905 * JB_ERR_MEMORY on out-of-memory error
1907 *********************************************************************/
1908 jb_err template_fill(char **template_ptr, const struct map *exports)
1910 struct map_entry *m;
1912 char buf[BUFFER_SIZE];
1913 char *tmp_out_buffer;
1919 assert(template_ptr);
1920 assert(*template_ptr);
1923 file_buffer = *template_ptr;
1924 size = strlen(file_buffer) + 1;
1927 * Assemble pcrs joblist from exports map
1929 for (m = exports->first; m != NULL; m = m->next)
1931 if (*m->name == '$')
1934 * First character of name is '$', so remove this flag
1935 * character and allow backreferences ($1 etc) in the
1936 * "replace with" text.
1938 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1944 * Treat the "replace with" text as a literal string -
1945 * no quoting needed, no backreferences allowed.
1946 * ("Trivial" ['T'] flag).
1950 /* Enclose name in @@ */
1951 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1955 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1957 /* Make and run job. */
1958 job = pcrs_compile(buf, m->value, flags, &error);
1961 if (error == PCRS_ERR_NOMEM)
1964 *template_ptr = NULL;
1965 return JB_ERR_MEMORY;
1969 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1970 /* Hope it wasn't important and silently ignore the invalid job */
1975 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1978 if (NULL == tmp_out_buffer)
1980 *template_ptr = NULL;
1981 return JB_ERR_MEMORY;
1983 file_buffer = tmp_out_buffer;
1990 *template_ptr = file_buffer;
1995 /*********************************************************************
1997 * Function : template_fill_for_cgi
1999 * Description : CGI support function that loads a HTML template
2000 * and fills it in. Handles file-not-found errors
2001 * by sending a HTML error message. For convenience,
2002 * this function also frees the passed "exports" map.
2005 * 1 : csp = Client state
2006 * 2 : templatename = name of the HTML template to be used
2007 * 3 : exports = map with fill in symbol -> name pairs.
2008 * Will be freed by this function.
2009 * 4 : rsp = Response structure to fill in.
2011 * Returns : JB_ERR_OK on success
2012 * JB_ERR_MEMORY on out-of-memory error
2014 *********************************************************************/
2015 jb_err template_fill_for_cgi(struct client_state *csp,
2016 const char *templatename,
2017 struct map *exports,
2018 struct http_response *rsp)
2023 assert(templatename);
2027 err = template_load(csp, &rsp->body, templatename, 0);
2028 if (err == JB_ERR_FILE)
2031 return cgi_error_no_template(csp, rsp, templatename);
2036 return err; /* JB_ERR_MEMORY */
2038 err = template_fill(&rsp->body, exports);
2044 /*********************************************************************
2046 * Function : default_exports
2048 * Description : returns a struct map list that contains exports
2049 * which are common to all CGI functions.
2052 * 1 : csp = Current client state (buffers, headers, etc...)
2053 * 2 : caller = name of CGI who calls us and which should
2054 * be excluded from the generated menu. May be
2056 * Returns : NULL if no memory, else a new map. Caller frees.
2058 *********************************************************************/
2059 struct map *default_exports(const struct client_state *csp, const char *caller)
2063 struct map * exports;
2064 int local_help_exists = 0;
2068 exports = new_map();
2069 if (exports == NULL)
2074 err = map(exports, "version", 1, html_encode(VERSION), 0);
2075 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2076 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2077 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2078 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2079 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
2080 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2081 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
2082 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2083 #ifdef FEATURE_TOGGLE
2084 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2086 if (!err) err = map_block_killer(exports, "can-toggle");
2089 snprintf(buf, 20, "%d", csp->config->hport);
2090 if (!err) err = map(exports, "my-port", 1, buf, 1);
2092 if(!strcmp(CODE_STATUS, "stable"))
2094 if (!err) err = map_block_killer(exports, "unstable");
2097 if (csp->config->admin_address != NULL)
2099 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2100 local_help_exists = 1;
2104 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2107 if (csp->config->proxy_info_url != NULL)
2109 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2110 local_help_exists = 1;
2114 if (!err) err = map_block_killer(exports, "have-proxy-info");
2117 if (local_help_exists == 0)
2119 if (!err) err = map_block_killer(exports, "have-help-info");
2132 /*********************************************************************
2134 * Function : map_block_killer
2136 * Description : Convenience function.
2137 * Adds a "killer" for the conditional HTML-template
2138 * block <name>, i.e. a substitution of the regex
2139 * "if-<name>-start.*if-<name>-end" to the given
2143 * 1 : exports = map to extend
2144 * 2 : name = name of conditional block
2146 * Returns : JB_ERR_OK on success
2147 * JB_ERR_MEMORY on out-of-memory error.
2149 *********************************************************************/
2150 jb_err map_block_killer(struct map *exports, const char *name)
2152 char buf[1000]; /* Will do, since the names are hardwired */
2156 assert(strlen(name) < 490);
2158 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2159 return map(exports, buf, 1, "", 1);
2163 /*********************************************************************
2165 * Function : map_block_keep
2167 * Description : Convenience function. Removes the markers used
2168 * by map-block-killer, to save a few bytes.
2169 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2172 * 1 : exports = map to extend
2173 * 2 : name = name of conditional block
2175 * Returns : JB_ERR_OK on success
2176 * JB_ERR_MEMORY on out-of-memory error.
2178 *********************************************************************/
2179 jb_err map_block_keep(struct map *exports, const char *name)
2182 char buf[500]; /* Will do, since the names are hardwired */
2186 assert(strlen(name) < 490);
2188 snprintf(buf, 500, "if-%s-start", name);
2189 err = map(exports, buf, 1, "", 1);
2196 snprintf(buf, 500, "if-%s-end", name);
2197 return map(exports, buf, 1, "", 1);
2201 /*********************************************************************
2203 * Function : map_conditional
2205 * Description : Convenience function.
2206 * Adds an "if-then-else" for the conditional HTML-template
2207 * block <name>, i.e. a substitution of the form:
2214 * The control structure and one of the alternatives
2218 * 1 : exports = map to extend
2219 * 2 : name = name of conditional block
2220 * 3 : choose_first = nonzero for first, zero for second.
2222 * Returns : JB_ERR_OK on success
2223 * JB_ERR_MEMORY on out-of-memory error.
2225 *********************************************************************/
2226 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2228 char buf[1000]; /* Will do, since the names are hardwired */
2233 assert(strlen(name) < 480);
2235 snprintf(buf, 1000, (choose_first
2236 ? "else-not-%s@.*@endif-%s"
2237 : "if-%s-then@.*@else-not-%s"),
2240 err = map(exports, buf, 1, "", 1);
2246 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2247 return map(exports, buf, 1, "", 1);
2251 /*********************************************************************
2253 * Function : make_menu
2255 * Description : Returns an HTML-formatted menu of the available
2256 * unhidden CGIs, excluding the one given in <self>
2258 * Parameters : self = name of CGI to leave out, can be NULL for
2261 * Returns : menu string, or NULL on out-of-memory error.
2263 *********************************************************************/
2264 char *make_menu(const char *self)
2266 const struct cgi_dispatcher *d;
2267 char *result = strdup("");
2271 self = "NO-SUCH-CGI!";
2274 /* List available unhidden CGI's and export as "other-cgis" */
2275 for (d = cgi_dispatchers; d->name; d++)
2277 if (d->description && strcmp(d->name, self))
2279 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2280 string_append(&result, d->name);
2281 string_append(&result, "\">");
2282 string_append(&result, d->description);
2283 string_append(&result, "</a></li>");
2291 /*********************************************************************
2293 * Function : dump_map
2295 * Description : HTML-dump a map for debugging (as table)
2298 * 1 : the_map = map to dump
2300 * Returns : string with HTML
2302 *********************************************************************/
2303 char *dump_map(const struct map *the_map)
2305 struct map_entry *cur_entry;
2306 char *ret = strdup("");
2308 string_append(&ret, "<table>\n");
2310 for (cur_entry = the_map->first;
2311 (cur_entry != NULL) && (ret != NULL);
2312 cur_entry = cur_entry->next)
2314 string_append(&ret, "<tr><td><b>");
2315 string_join (&ret, html_encode(cur_entry->name));
2316 string_append(&ret, "</b></td><td>");
2317 string_join (&ret, html_encode(cur_entry->value));
2318 string_append(&ret, "</td></tr>\n");
2321 string_append(&ret, "</table>\n");