1 const char cgi_rcs[] = "$Id: cgi.c,v 1.70.2.7 2003/04/03 13:50:58 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.7 2003/04/03 13:50:58 oes
42 * - Don't call cgi_error_disabled ifndef FEATURE_CGI_EDIT_ACTIONS
44 * - Show toggle info only if we have it
46 * Revision 1.70.2.6 2003/03/12 01:26:25 david__schmidt
47 * Move declaration of struct tm dummy outside of a control block so it is
48 * accessible later on during snprintf in get_http_time.
50 * Revision 1.70.2.5 2003/03/11 11:53:58 oes
51 * Cosmetic: Renamed cryptic variable
53 * Revision 1.70.2.4 2003/03/07 03:41:03 david__schmidt
54 * 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.
56 * Revision 1.70.2.3 2002/11/28 18:14:32 oes
57 * Disable access to critical CGIs via untrusted referrers.
58 * This prevents users from being tricked by malicious websites
59 * into making unintentional configuration changes:
61 * - Added flag to each cgi_dispatcher that allows or denies
63 * - Introduced proviorical function that greps for the
64 * referrer header before regular header parsing happens
65 * - Added safety check to dispatch_known_cgi. CGI is called
66 * if (cgi harmless || no referrer || we are referrer).
67 * Else a) toggle calls are modified not to change status and
68 * b) all other calls are denied.
70 * Revision 1.70.2.2 2002/11/12 16:20:37 oes
71 * Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
73 * Revision 1.70.2.1 2002/08/05 11:17:46 oes
74 * Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
76 * Revision 1.70 2002/05/19 11:33:20 jongfoster
77 * If a CGI error was not handled, and propogated back to
78 * dispatch_known_cgi(), then it was assumed to be "out of memory".
79 * This gave a very misleading error message.
81 * Now other errors will cause a simple message giving the error
82 * number and asking the user to report a bug.
85 * http://sourceforge.net/tracker/index.php?func=detail
86 * &aid=557905&group_id=11118&atid=111118
88 * Revision 1.69 2002/05/14 21:28:40 oes
89 * - Fixed add_help_link to link to the (now split) actions
90 * part of the config chapter
91 * - Renamed helplink export to actions-help-prefix
93 * Revision 1.68 2002/05/12 21:36:29 jongfoster
94 * Correcting function comments
96 * Revision 1.67 2002/04/30 12:02:07 oes
97 * Nit: updated a comment
99 * Revision 1.66 2002/04/26 18:32:57 jongfoster
100 * Fixing a memory leak on error
102 * Revision 1.65 2002/04/26 12:53:51 oes
103 * - New function add_help_link
104 * - default_exports now exports links to the user manual
105 * and a prefix for links into the config chapter
107 * Revision 1.64 2002/04/24 02:17:21 oes
108 * - Better descriptions for CGIs
109 * - Hide edit-actions, more shortcuts
110 * - Moved get_char_param, get_string_param and get_number_param here
113 * Revision 1.63 2002/04/15 19:06:43 jongfoster
116 * Revision 1.62 2002/04/10 19:59:46 jongfoster
117 * Fixes to #include in templates:
118 * - Didn't close main file if loading an included template fails.
119 * - I'm paranoid and want to disallow "#include /etc/passwd".
121 * Revision 1.61 2002/04/10 13:37:48 oes
122 * Made templates modular: template_load now recursive with max depth 1
124 * Revision 1.60 2002/04/08 20:50:25 swa
127 * Revision 1.59 2002/04/05 15:51:51 oes
128 * - added send-stylesheet CGI
129 * - bugfix: error-pages now get correct request protocol
131 * - kludged CGI descriptions and menu not to break JS syntax
133 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
134 * Fix Mac OSX compiler warnings
136 * Revision 1.57 2002/03/26 22:29:54 swa
137 * we have a new homepage!
139 * Revision 1.56 2002/03/24 17:50:46 jongfoster
140 * Fixing compile error if actions file editor disabled
142 * Revision 1.55 2002/03/24 16:55:06 oes
143 * Making GIF checkerboard transparent
145 * Revision 1.54 2002/03/24 16:18:15 jongfoster
148 * Revision 1.53 2002/03/24 16:06:00 oes
149 * Correct transparency for checkerboard PNG. Thanks, Magnus!
151 * Revision 1.52 2002/03/24 15:23:33 jongfoster
154 * Revision 1.51 2002/03/24 13:25:43 swa
155 * name change related issues
157 * Revision 1.50 2002/03/16 23:54:06 jongfoster
158 * Adding graceful termination feature, to help look for memory leaks.
159 * If you enable this (which, by design, has to be done by hand
160 * editing config.h) and then go to http://i.j.b/die, then the program
161 * will exit cleanly after the *next* request. It should free all the
162 * memory that was used.
164 * Revision 1.49 2002/03/13 00:27:04 jongfoster
167 * Revision 1.48 2002/03/08 17:47:07 jongfoster
170 * Revision 1.47 2002/03/08 16:41:33 oes
171 * Added GIF images again
173 * Revision 1.46 2002/03/07 03:48:38 oes
174 * - Changed built-in images from GIF to PNG
175 * (with regard to Unisys patent issue)
176 * - Added a 4x4 pattern PNG which is less intrusive
177 * than the logo but also clearly marks the deleted banners
179 * Revision 1.45 2002/03/06 22:54:35 jongfoster
180 * Automated function-comment nitpicking.
182 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
183 * - Better error reporting on OS/2
184 * - Fix double-slash comment (oops)
186 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
187 * - Re-enable OS/2 building after new parms were added
188 * - Fix false out of memory report when resolving CGI templates when no IP
189 * address is available of failed attempt (a la no such domain)
191 * Revision 1.42 2002/01/21 00:33:20 jongfoster
192 * Replacing strsav() with the safer string_append() or string_join().
193 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
194 * Adding missing html_encode() to error message generators.
195 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
197 * Revision 1.41 2002/01/17 20:56:22 jongfoster
198 * Replacing hard references to the URL of the config interface
199 * with #defines from project.h
201 * Revision 1.40 2002/01/09 14:26:46 oes
202 * Added support for thread-safe gmtime_r call.
204 * Revision 1.39 2001/11/16 00:48:13 jongfoster
205 * Fixing a compiler warning
207 * Revision 1.38 2001/11/13 00:31:21 jongfoster
208 * - Adding new CGIs for use by non-JavaScript browsers:
209 * edit-actions-url-form
210 * edit-actions-add-url-form
211 * edit-actions-remove-url-form
212 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
215 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
216 * Show enablement/disablement status in almost all templates.
217 * There is a little trickiness here: apparent recursive resolution of
218 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
219 * the actual enablement status. So a similar construct,
220 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
223 * Revision 1.36 2001/10/26 17:33:27 oes
226 * Revision 1.35 2001/10/23 21:48:19 jongfoster
227 * Cleaning up error handling in CGI functions - they now send back
228 * a HTML error page and should never cause a FATAL error. (Fixes one
229 * potential source of "denial of service" attacks).
231 * CGI actions file editor that works and is actually useful.
233 * Ability to toggle Junkbuster remotely using a CGI call.
235 * You can turn off both the above features in the main configuration
236 * file, e.g. if you are running a multi-user proxy.
238 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
239 * Only show "Local support" on templates conditionally:
240 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
241 * - if not, no Local support section appears
243 * Revision 1.33 2001/10/14 22:28:41 jongfoster
244 * Fixing stupid typo.
246 * Revision 1.32 2001/10/14 22:20:18 jongfoster
247 * - Changes to CGI dispatching method to match CGI names exactly,
248 * rather than doing a prefix match.
249 * - No longer need to count the length of the CGI handler names by hand.
250 * - Adding new handler for 404 error when disptching a CGI, if none of
251 * the handlers match.
252 * - Adding new handlers for CGI actionsfile editor.
254 * Revision 1.31 2001/10/10 10:56:39 oes
255 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
257 * Revision 1.30 2001/10/02 15:30:57 oes
258 * Introduced show-request cgi
260 * Revision 1.29 2001/09/20 15:47:44 steudten
262 * Fix BUG: Modify int size to size_t size in fill_template()
263 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
265 * Revision 1.28 2001/09/19 18:00:37 oes
266 * - Deletef time() FIXME (Can't fail under Linux either, if
267 * the argument is guaranteed to be in out address space,
270 * - Pointer notation cosmetics
271 * - Fixed a minor bug in template_fill(): Failiure of
272 * pcrs_execute() now secure.
274 * Revision 1.27 2001/09/16 17:08:54 jongfoster
275 * Moving simple CGI functions from cgi.c to new file cgisimple.c
277 * Revision 1.26 2001/09/16 15:47:37 jongfoster
278 * First version of CGI-based edit interface. This is very much a
279 * work-in-progress, and you can't actually use it to edit anything
280 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
281 * to have any effect.
283 * Revision 1.25 2001/09/16 15:02:35 jongfoster
284 * Adding i.j.b/robots.txt.
285 * Inlining add_stats() since it's only ever called from one place.
287 * Revision 1.24 2001/09/16 11:38:01 jongfoster
288 * Splitting fill_template() into 2 functions:
289 * template_load() loads the file
290 * template_fill() performs the PCRS regexps.
291 * This is because the CGI edit interface has a "table row"
292 * template which is used many times in the page - this
293 * change means it's only loaded from disk once.
295 * Revision 1.23 2001/09/16 11:16:05 jongfoster
296 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
298 * Revision 1.22 2001/09/16 11:00:10 jongfoster
299 * New function alloc_http_response, for symmetry with free_http_response
301 * Revision 1.21 2001/09/13 23:53:03 jongfoster
302 * Support for both static and dynamically generated CGI pages.
303 * Correctly setting Last-Modified: and Expires: HTTP headers.
305 * Revision 1.20 2001/09/13 23:40:36 jongfoster
306 * (Cosmetic only) Indentation correction
308 * Revision 1.19 2001/09/13 23:31:25 jongfoster
309 * Moving image data to cgi.c rather than cgi.h.
311 * Revision 1.18 2001/08/05 16:06:20 jongfoster
312 * Modifiying "struct map" so that there are now separate header and
313 * "map_entry" structures. This means that functions which modify a
314 * map no longer need to return a pointer to the modified map.
315 * Also, it no longer reverses the order of the entries (which may be
316 * important with some advanced template substitutions).
318 * Revision 1.17 2001/08/05 15:57:38 oes
319 * Adapted finish_http_response to new list_to_text
321 * Revision 1.16 2001/08/01 21:33:18 jongfoster
322 * Changes to fill_template() that reduce memory usage without having
323 * an impact on performance. I also renamed some variables so as not
324 * to clash with the C++ keywords "new" and "template".
326 * Revision 1.15 2001/08/01 21:19:22 jongfoster
327 * Moving file version information to a separate CGI page.
329 * Revision 1.14 2001/08/01 00:19:03 jongfoster
330 * New function: map_conditional() for an if-then-else syntax.
331 * Changing to use new version of show_defines()
333 * Revision 1.13 2001/07/30 22:08:36 jongfoster
334 * Tidying up #defines:
335 * - All feature #defines are now of the form FEATURE_xxx
336 * - Permanently turned off WIN_GUI_EDIT
337 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
339 * Revision 1.12 2001/07/29 18:47:05 jongfoster
340 * Adding missing #include "loadcfg.h"
342 * Revision 1.11 2001/07/18 17:24:37 oes
343 * Changed to conform to new pcrs interface
345 * Revision 1.10 2001/07/13 13:53:13 oes
346 * Removed all #ifdef PCRS and related code
348 * Revision 1.9 2001/06/29 21:45:41 oes
349 * Indentation, CRLF->LF, Tab-> Space
351 * Revision 1.8 2001/06/29 13:21:46 oes
352 * - Cosmetics: renamed and reordered functions, variables,
353 * texts, improved comments etc
355 * - Removed ij_untrusted_url() The relevant
356 * info is now part of the "untrusted" page,
357 * which is generated by filters.c:trust_url()
359 * - Generators of content now call finish_http_response()
360 * themselves, making jcc.c:chat() a little less
363 * - Removed obsolete "Pragma: no-cache" from our headers
365 * - http_responses now know their head length
367 * - fill_template now uses the new interface to pcrs, so that
368 * - long jobs (like whole files) no longer have to be assembled
369 * in a fixed size buffer
370 * - the new T (trivial) option is used, and the replacement may
371 * contain Perl syntax backrefs without confusing pcrs
373 * - Introduced default_exports() which generates a set of exports
374 * common to all CGIs and other content generators
376 * - Introduced convenience function map_block_killer()
378 * - Introduced convenience function make_menu()
380 * - Introduced CGI-like function error_response() which generates
381 * the "No such domain" and "Connect failed" messages using the
384 * - cgi_show_url_info:
385 * - adapted to new CGI features
386 * - form and answers now generated from same template
387 * - http:// prefix in URL now OK
390 * - adapted to new CGI features
391 * - no longer uses csp->init_proxy_args
394 * - moved menu generation to make_menu()
396 * - add_stats now writes single export map entries instead
399 * - Moved redirect_url() to filters.c
401 * - Fixed mem leak in free_http_response(), map_block_killer(),
403 * - Removed logentry from cancelled commit
405 * Revision 1.7 2001/06/09 10:51:58 jongfoster
406 * Changing "show URL info" handler to new style.
407 * Changing BUFSIZ ==> BUFFER_SIZE
409 * Revision 1.6 2001/06/07 23:05:19 jongfoster
410 * Removing code related to old forward and ACL files.
412 * Revision 1.5 2001/06/05 19:59:16 jongfoster
413 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
415 * Revision 1.4 2001/06/04 10:41:52 swa
416 * show version string of cgi.h and cgi.c
418 * Revision 1.3 2001/06/03 19:12:16 oes
419 * introduced new cgi handling
421 * No revisions before 1.3
423 **********************************************************************/
429 #include <sys/types.h>
437 #define snprintf _snprintf
438 #endif /* def _WIN32 */
446 #include "miscutil.h"
447 #include "cgisimple.h"
448 #ifdef FEATURE_CGI_EDIT_ACTIONS
450 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
452 /* loadcfg.h is for global_toggle_state only */
453 #ifdef FEATURE_PTHREAD
456 /* jcc.h is for mutex semaphore globals only */
457 #endif /* def FEATURE_PTHREAD */
458 const char cgi_h_rcs[] = CGI_H_VERSION;
461 * List of CGI functions: name, handler, description
462 * Note: Do NOT use single quotes in the description;
463 * this will break the dynamic "blocked" template!
465 static const struct cgi_dispatcher cgi_dispatchers[] = {
470 #ifdef FEATURE_GRACEFUL_TERMINATION
473 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
474 "this is a one click Denial Of Service attack!!!</em>",
479 #ifdef FEATURE_CGI_EDIT_ACTIONS
480 "View & change the current configuration",
482 "View the current configuration",
487 "View the source code version numbers",
491 "View the request headers.",
495 "Look up which actions apply to a URL and why",
497 #ifdef FEATURE_CGI_EDIT_ACTIONS
500 "Toggle Privoxy on or off",
502 { "edit-actions", /* Edit the actions list */
505 { "eaa", /* Shortcut for edit-actions-add-url-form */
506 cgi_edit_actions_add_url_form,
508 { "eau", /* Shortcut for edit-actions-url-form */
509 cgi_edit_actions_url_form,
511 { "ear", /* Shortcut for edit-actions-remove-url-form */
512 cgi_edit_actions_remove_url_form,
514 { "eafu", /* Shortcut for edit-actions-for-url */
515 cgi_edit_actions_for_url,
517 { "eas", /* Shortcut for edit-actions-submit */
518 cgi_edit_actions_submit,
520 { "easa", /* Shortcut for edit-actions-section-add */
521 cgi_edit_actions_section_add,
523 { "easr", /* Shortcut for edit-actions-section-remove */
524 cgi_edit_actions_section_remove,
526 { "eass", /* Shortcut for edit-actions-section-swap */
527 cgi_edit_actions_section_swap,
529 { "edit-actions-for-url",
530 cgi_edit_actions_for_url,
531 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
532 { "edit-actions-list",
533 cgi_edit_actions_list,
534 NULL, TRUE /* Edit the actions list */ },
535 { "edit-actions-submit",
536 cgi_edit_actions_submit,
537 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
538 { "edit-actions-url",
539 cgi_edit_actions_url,
540 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
541 { "edit-actions-url-form",
542 cgi_edit_actions_url_form,
543 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
544 { "edit-actions-add-url",
545 cgi_edit_actions_add_url,
546 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
547 { "edit-actions-add-url-form",
548 cgi_edit_actions_add_url_form,
549 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
550 { "edit-actions-remove-url",
551 cgi_edit_actions_remove_url,
552 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
553 { "edit-actions-remove-url-form",
554 cgi_edit_actions_remove_url_form,
555 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
556 { "edit-actions-section-add",
557 cgi_edit_actions_section_add,
558 NULL, FALSE /* Remove a section from the actionsfile */ },
559 { "edit-actions-section-remove",
560 cgi_edit_actions_section_remove,
561 NULL, FALSE /* Remove a section from the actionsfile */ },
562 { "edit-actions-section-swap",
563 cgi_edit_actions_section_swap,
564 NULL, FALSE /* Swap two sections in the actionsfile */ },
565 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
568 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
571 NULL, TRUE /* Send a built-in image */ },
574 NULL, TRUE /* Send templates/cgi-style.css */ },
576 cgi_transparent_image,
577 NULL, TRUE /* Send a transparent image (short name) */ },
578 { NULL, /* NULL Indicates end of list and default page */
580 NULL, TRUE /* Unknown CGI page */ }
585 * Bulit-in images for ad replacement
587 * Hint: You can encode your own images like this:
588 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
591 #ifdef FEATURE_NO_GIFS
594 * Checkerboard pattern, as a PNG.
596 const char image_pattern_data[] =
597 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
598 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
599 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
600 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
601 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
602 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
603 "\000\000\000\111\105\116\104\256\102\140\202";
606 * 1x1 transparant PNG.
608 const char image_blank_data[] =
609 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
610 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
611 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
612 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
613 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
614 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
615 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
616 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
617 "\000\000\000\000\111\105\116\104\256\102\140\202";
621 * Checkerboard pattern, as a GIF.
623 const char image_pattern_data[] =
624 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
625 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
626 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
627 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
631 * 1x1 transparant GIF.
633 const char image_blank_data[] =
634 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
635 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
636 "\000\001\000\000\002\002D\001\000;";
639 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
640 const size_t image_blank_length = sizeof(image_blank_data) - 1;
643 static struct http_response cgi_error_memory_response[1];
645 static struct http_response *dispatch_known_cgi(struct client_state * csp,
647 static struct map *parse_cgi_parameters(char *argstring);
650 /*********************************************************************
652 * Function : dispatch_cgi
654 * Description : Checks if a request URL has either the magical
655 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
656 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
657 * http://config.privoxy.org/). If so, it passes
658 * the (rest of the) path onto dispatch_known_cgi, which
659 * calls the relevant CGI handler function.
662 * 1 : csp = Current client state (buffers, headers, etc...)
664 * Returns : http_response if match, NULL if nonmatch or handler fail
666 *********************************************************************/
667 struct http_response *dispatch_cgi(struct client_state *csp)
669 const char *host = csp->http->host;
670 const char *path = csp->http->path;
673 * Should we intercept ?
676 /* Note: "example.com" and "example.com." are equivalent hostnames. */
678 /* Either the host matches CGI_SITE_1_HOST ..*/
679 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
680 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
681 && (path[0] == '/') )
683 /* ..then the path will all be for us. Remove leading '/' */
686 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
687 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
688 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
689 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
691 /* take everything following CGI_SITE_2_PATH */
692 path += strlen(CGI_SITE_2_PATH);
695 /* skip the forward slash after CGI_SITE_2_PATH */
698 else if (*path != '\0')
701 * wierdness: URL is /configXXX, where XXX is some string
702 * Do *NOT* intercept.
714 * This is a CGI call.
717 return dispatch_known_cgi(csp, path);
721 /*********************************************************************
723 * Function : grep_cgi_referrer
725 * Description : Ugly provisorical fix that greps the value of the
726 * referer HTTP header field out of a linked list of
727 * strings like found at csp->headers. Will disappear
730 * FIXME: csp->headers ought to be csp->http->headers
731 * FIXME: Parsing all client header lines should
732 * happen right after the request is received!
735 * 1 : csp = Current client state (buffers, headers, etc...)
737 * Returns : pointer to value (no copy!), or NULL if none found.
739 *********************************************************************/
740 char *grep_cgi_referrer(struct client_state *csp)
742 struct list_entry *p;
744 for (p = csp->headers->first; p != NULL; p = p->next)
746 if (p->str == NULL) continue;
747 if (strncmpic(p->str, "Referer: ", 9) == 0)
749 return ((p->str) + 9);
757 /*********************************************************************
759 * Function : dispatch_known_cgi
761 * Description : Processes a CGI once dispatch_cgi has determined that
762 * it matches one of the magic prefixes. Parses the path
763 * as a cgi name plus query string, prepares a map that
764 * maps CGI parameter names to their values, initializes
765 * the http_response struct, and calls the relevant CGI
769 * 1 : csp = Current client state (buffers, headers, etc...)
770 * 2 : path = Path of CGI, with the CGI prefix removed.
771 * Should not have a leading "/".
773 * Returns : http_response, or NULL on handler failure or out of
776 *********************************************************************/
777 static struct http_response *dispatch_known_cgi(struct client_state * csp,
780 const struct cgi_dispatcher *d;
781 struct map *param_list;
782 struct http_response *rsp;
783 char *query_args_start;
788 if (NULL == (path_copy = strdup(path)))
790 return cgi_error_memory();
793 query_args_start = path_copy;
794 while (*query_args_start && *query_args_start != '?')
798 if (*query_args_start == '?')
800 *query_args_start++ = '\0';
803 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
806 return cgi_error_memory();
811 * path_copy = CGI call name
812 * param_list = CGI params, as map
815 /* Get mem for response or fail*/
816 if (NULL == (rsp = alloc_http_response()))
819 free_map(param_list);
820 return cgi_error_memory();
823 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
824 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
825 csp->ip_addr_str, csp->http->cmd);
828 * Find and start the right CGI function
833 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
836 * If the called CGI is either harmless, or not referred
837 * from an untrusted source, start it.
840 || (NULL == (referrer = grep_cgi_referrer(csp)))
841 || (0 == strncmp(referrer, "http://config.privoxy.org/", 26))
844 err = (d->handler)(csp, rsp, param_list);
849 * Else, modify toggle calls so that they only display
850 * the status, and deny all other calls.
852 if (0 == strcmp(path_copy, "toggle"))
854 unmap(param_list, "set");
855 err = (d->handler)(csp, rsp, param_list);
859 err = cgi_error_404(csp, rsp, param_list);
864 free_map(param_list);
866 if (err == JB_ERR_CGI_PARAMS)
868 err = cgi_error_bad_param(csp, rsp);
870 if (err && (err != JB_ERR_MEMORY))
872 /* Unexpected error! Shouldn't get here */
873 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
874 err = cgi_error_unknown(csp, rsp, err);
879 return finish_http_response(rsp);
883 /* Error in handler, probably out-of-memory */
884 free_http_response(rsp);
885 return cgi_error_memory();
893 /*********************************************************************
895 * Function : parse_cgi_parameters
897 * Description : Parse a URL-encoded argument string into name/value
898 * pairs and store them in a struct map list.
901 * 1 : argstring = string to be parsed. Will be trashed.
903 * Returns : pointer to param list, or NULL if out of memory.
905 *********************************************************************/
906 static struct map *parse_cgi_parameters(char *argstring)
909 char *vector[BUFFER_SIZE];
911 struct map *cgi_params;
913 if (NULL == (cgi_params = new_map()))
919 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
920 * the fragment identifier along with the request, so we must
921 * cut it off here, so it won't pollute the CGI params:
923 if (NULL != (p = strchr(argstring, '#')))
928 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
930 for (i = 0; i < pairs; i++)
932 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
935 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
937 free_map(cgi_params);
948 /*********************************************************************
950 * Function : get_char_param
952 * Description : Get a single-character parameter passed to a CGI
956 * 1 : parameters = map of cgi parameters
957 * 2 : param_name = The name of the parameter to read
959 * Returns : Uppercase character on success, '\0' on error.
961 *********************************************************************/
962 char get_char_param(const struct map *parameters,
963 const char *param_name)
970 ch = *(lookup(parameters, param_name));
971 if ((ch >= 'a') && (ch <= 'z'))
980 /*********************************************************************
982 * Function : get_string_param
984 * Description : Get a string paramater, to be used as an
985 * ACTION_STRING or ACTION_MULTI paramater.
986 * Validates the input to prevent stupid/malicious
987 * users from corrupting their action file.
990 * 1 : parameters = map of cgi parameters
991 * 2 : param_name = The name of the parameter to read
992 * 3 : pparam = destination for paramater. Allocated as
993 * part of the map "parameters", so don't free it.
994 * Set to NULL if not specified.
996 * Returns : JB_ERR_OK on success, or if the paramater
998 * JB_ERR_MEMORY on out-of-memory.
999 * JB_ERR_CGI_PARAMS if the paramater is not valid.
1001 *********************************************************************/
1002 jb_err get_string_param(const struct map *parameters,
1003 const char *param_name,
1004 const char **pparam)
1016 param = lookup(parameters, param_name);
1022 if (strlen(param) >= CGI_PARAM_LEN_MAX)
1027 * Note that the length limit is arbitrary, it just seems
1028 * sensible to limit it to *something*. There's no
1029 * technical reason for any limit at all.
1031 return JB_ERR_CGI_PARAMS;
1034 /* Check every character to see if it's legal */
1036 while ((ch = *s++) != '\0')
1038 if ( ((unsigned char)ch < (unsigned char)' ')
1041 /* Probable hack attempt, or user accidentally used '}'. */
1042 return JB_ERR_CGI_PARAMS;
1053 /*********************************************************************
1055 * Function : get_number_param
1057 * Description : Get a non-negative integer from the parameters
1058 * passed to a CGI function.
1061 * 1 : csp = Current client state (buffers, headers, etc...)
1062 * 2 : parameters = map of cgi parameters
1063 * 3 : name = Name of CGI parameter to read
1064 * 4 : pvalue = destination for value.
1065 * Set to -1 on error.
1067 * Returns : JB_ERR_OK on success
1068 * JB_ERR_MEMORY on out-of-memory
1069 * JB_ERR_CGI_PARAMS if the parameter was not specified
1072 *********************************************************************/
1073 jb_err get_number_param(struct client_state *csp,
1074 const struct map *parameters,
1089 param = lookup(parameters, name);
1092 return JB_ERR_CGI_PARAMS;
1095 /* We don't use atoi because I want to check this carefully... */
1098 while ((ch = *param++) != '\0')
1100 if ((ch < '0') || (ch > '9'))
1102 return JB_ERR_CGI_PARAMS;
1109 * <limits.h> defines UINT_MAX
1111 * (UINT_MAX - ch) / 10 is the largest number that
1112 * can be safely multiplied by 10 then have ch added.
1114 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1116 return JB_ERR_CGI_PARAMS;
1119 value = value * 10 + ch;
1130 /*********************************************************************
1132 * Function : error_response
1134 * Description : returns an http_response that explains the reason
1135 * why a request failed.
1138 * 1 : csp = Current client state (buffers, headers, etc...)
1139 * 2 : templatename = Which template should be used for the answer
1140 * 3 : sys_err = system error number
1142 * Returns : A http_response. If we run out of memory, this
1143 * will be cgi_error_memory().
1145 *********************************************************************/
1146 struct http_response *error_response(struct client_state *csp,
1147 const char *templatename,
1151 struct http_response *rsp;
1152 struct map * exports = default_exports(csp, NULL);
1153 if (exports == NULL)
1155 return cgi_error_memory();
1158 if (NULL == (rsp = alloc_http_response()))
1161 return cgi_error_memory();
1164 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1165 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1166 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1167 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1168 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1171 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1174 /* Some failures, like "404 no such domain", don't have an IP address. */
1175 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1183 free_http_response(rsp);
1184 return cgi_error_memory();
1187 if (!strcmp(templatename, "no-such-domain"))
1189 rsp->status = strdup("404 No such domain");
1190 if (rsp->status == NULL)
1193 free_http_response(rsp);
1194 return cgi_error_memory();
1197 else if (!strcmp(templatename, "connect-failed"))
1199 rsp->status = strdup("503 Connect failed");
1200 if (rsp->status == NULL)
1203 free_http_response(rsp);
1204 return cgi_error_memory();
1208 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1211 free_http_response(rsp);
1212 return cgi_error_memory();
1215 return finish_http_response(rsp);
1219 /*********************************************************************
1221 * Function : cgi_init_error_messages
1223 * Description : Call at the start of the program to initialize
1224 * the error message used by cgi_error_memory().
1230 *********************************************************************/
1231 void cgi_init_error_messages(void)
1233 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1234 cgi_error_memory_response->head =
1235 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1236 "Content-Type: text/html\r\n"
1238 cgi_error_memory_response->body =
1240 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1242 "<h1>500 Internal Privoxy Error</h1>\r\n"
1243 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1244 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1248 cgi_error_memory_response->head_length =
1249 strlen(cgi_error_memory_response->head);
1250 cgi_error_memory_response->content_length =
1251 strlen(cgi_error_memory_response->body);
1255 /*********************************************************************
1257 * Function : cgi_error_memory
1259 * Description : Called if a CGI function runs out of memory.
1260 * Returns a statically-allocated error response.
1264 * Returns : http_response data structure for output. This is
1265 * statically allocated, for obvious reasons.
1267 *********************************************************************/
1268 struct http_response *cgi_error_memory(void)
1270 /* assert that it's been initialized. */
1271 assert(cgi_error_memory_response->head);
1273 return cgi_error_memory_response;
1277 /*********************************************************************
1279 * Function : cgi_error_no_template
1281 * Description : Almost-CGI function that is called if a template
1282 * cannot be loaded. Note this is not a true CGI,
1283 * it takes a template name rather than a map of
1287 * 1 : csp = Current client state (buffers, headers, etc...)
1288 * 2 : rsp = http_response data structure for output
1289 * 3 : template_name = Name of template that could not
1292 * Returns : JB_ERR_OK on success
1293 * JB_ERR_MEMORY on out-of-memory error.
1295 *********************************************************************/
1296 jb_err cgi_error_no_template(struct client_state *csp,
1297 struct http_response *rsp,
1298 const char *template_name)
1300 static const char status[] =
1301 "500 Internal Privoxy Error";
1302 static const char body_prefix[] =
1304 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1306 "<h1>500 Internal Privoxy Error</h1>\r\n"
1307 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1308 "<p><b>Could not load template file <code>";
1309 static const char body_suffix[] =
1310 "</code> or one of it's included components.</b></p>\r\n"
1311 "<p>Please contact your proxy administrator.</p>\r\n"
1312 "<p>If you are the proxy administrator, please put the required file(s)"
1313 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1314 "location of the <code><i>(confdir)</i></code> directory "
1315 "is specified in the main Privoxy <code>config</code> "
1316 "file. (It's typically the Privoxy install directory"
1318 ", or <code>/etc/privoxy/</code>"
1319 #endif /* ndef _WIN32 */
1326 assert(template_name);
1328 /* Reset rsp, if needed */
1332 rsp->content_length = 0;
1333 rsp->head_length = 0;
1336 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1337 if (rsp->body == NULL)
1339 return JB_ERR_MEMORY;
1341 strcpy(rsp->body, body_prefix);
1342 strcat(rsp->body, template_name);
1343 strcat(rsp->body, body_suffix);
1345 rsp->status = strdup(status);
1346 if (rsp->body == NULL)
1348 return JB_ERR_MEMORY;
1355 /*********************************************************************
1357 * Function : cgi_error_unknown
1359 * Description : Almost-CGI function that is called if an unexpected
1360 * error occurs in the top-level CGI dispatcher.
1361 * In this context, "unexpected" means "anything other
1362 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1363 * expected to handle all other errors internally,
1364 * since they can give more relavent error messages
1367 * Note this is not a true CGI, it takes an error
1368 * code rather than a map of parameters.
1371 * 1 : csp = Current client state (buffers, headers, etc...)
1372 * 2 : rsp = http_response data structure for output
1373 * 3 : error_to_report = Error code to report.
1375 * Returns : JB_ERR_OK on success
1376 * JB_ERR_MEMORY on out-of-memory error.
1378 *********************************************************************/
1379 jb_err cgi_error_unknown(struct client_state *csp,
1380 struct http_response *rsp,
1381 jb_err error_to_report)
1383 static const char status[] =
1384 "500 Internal Privoxy Error";
1385 static const char body_prefix[] =
1387 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1389 "<h1>500 Internal Privoxy Error</h1>\r\n"
1390 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1391 "<p><b>Unexpected internal error: ";
1392 static const char body_suffix[] =
1395 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1396 "file a bug report</a>.</p>\r\n"
1403 /* Reset rsp, if needed */
1407 rsp->content_length = 0;
1408 rsp->head_length = 0;
1411 sprintf(errnumbuf, "%d", error_to_report);
1413 rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1414 if (rsp->body == NULL)
1416 return JB_ERR_MEMORY;
1418 strcpy(rsp->body, body_prefix);
1419 strcat(rsp->body, errnumbuf);
1420 strcat(rsp->body, body_suffix);
1422 rsp->status = strdup(status);
1423 if (rsp->body == NULL)
1425 return JB_ERR_MEMORY;
1432 /*********************************************************************
1434 * Function : cgi_error_bad_param
1436 * Description : CGI function that is called if the parameters
1437 * (query string) for a CGI were wrong.
1440 * 1 : csp = Current client state (buffers, headers, etc...)
1441 * 2 : rsp = http_response data structure for output
1443 * CGI Parameters : none
1445 * Returns : JB_ERR_OK on success
1446 * JB_ERR_MEMORY on out-of-memory error.
1448 *********************************************************************/
1449 jb_err cgi_error_bad_param(struct client_state *csp,
1450 struct http_response *rsp)
1452 struct map *exports;
1457 if (NULL == (exports = default_exports(csp, NULL)))
1459 return JB_ERR_MEMORY;
1462 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1466 /*********************************************************************
1468 * Function : add_help_link
1470 * Description : Produce a copy of the string given as item,
1471 * embedded in an HTML link to its corresponding
1472 * section (item name in uppercase) in the actions
1473 * chapter of the user manual, (whose URL is given in
1474 * the config and defaults to our web site).
1476 * FIXME: I currently only work for actions, and would
1477 * like to be generalized for other topics.
1480 * 1 : item = item (will NOT be free()d.)
1481 * It is assumed to be HTML-safe.
1482 * 2 : config = The current configuration.
1484 * Returns : String with item embedded in link, or NULL on
1487 *********************************************************************/
1488 char *add_help_link(const char *item,
1489 struct configuration_spec *config)
1493 if (!item) return NULL;
1495 result = strdup("<a href=\"");
1496 string_append(&result, config->usermanual);
1497 string_append(&result, ACTIONS_HELP_PREFIX);
1498 string_join (&result, string_toupper(item));
1499 string_append(&result, "\">");
1500 string_append(&result, item);
1501 string_append(&result, "</a> ");
1507 /*********************************************************************
1509 * Function : get_http_time
1511 * Description : Get the time in a format suitable for use in a
1512 * HTTP header - e.g.:
1513 * "Sun, 06 Nov 1994 08:49:37 GMT"
1516 * 1 : time_offset = Time returned will be current time
1517 * plus this number of seconds.
1518 * 2 : buf = Destination for result. Must be long enough
1519 * to hold 29 characters plus a trailing zero.
1523 *********************************************************************/
1524 void get_http_time(int time_offset, char *buf)
1526 static const char day_names[7][4] =
1527 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1528 static const char month_names[12][4] =
1529 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1530 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1533 time_t current_time;
1534 #if defined(HAVE_GMTIME_R) && !defined(OSX_DARWIN)
1536 * Declare dummy up here (instead of inside get/set gmt block) so it
1537 * doesn't go out of scope before it's potentially used in snprintf later.
1538 * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1539 * !defined HAVE_GMTIME_R.
1546 time(¤t_time); /* get current time */
1548 current_time += time_offset;
1550 /* get and save the gmt */
1553 pthread_mutex_lock(&gmtime_mutex);
1554 t = gmtime(¤t_time);
1555 pthread_mutex_unlock(&gmtime_mutex);
1557 t = gmtime_r(¤t_time, &dummy);
1559 t = gmtime(¤t_time);
1563 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1565 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1566 day_names[t->tm_wday],
1568 month_names[t->tm_mon],
1578 /*********************************************************************
1580 * Function : finish_http_response
1582 * Description : Fill in the missing headers in an http response,
1583 * and flatten the headers to an http head.
1586 * 1 : rsp = pointer to http_response to be processed
1588 * Returns : A http_response, usually the rsp parameter.
1589 * On error, free()s rsp and returns cgi_error_memory()
1591 *********************************************************************/
1592 struct http_response *finish_http_response(struct http_response *rsp)
1594 char buf[BUFFER_SIZE];
1597 /* Special case - do NOT change this statically allocated response,
1598 * which is ready for output anyway.
1600 if (rsp == cgi_error_memory_response)
1606 * Fill in the HTTP Status
1608 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1609 err = enlist_first(rsp->headers, buf);
1612 * Set the Content-Length
1614 if (rsp->content_length == 0)
1616 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1620 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1621 err = enlist(rsp->headers, buf);
1625 * Fill in the default headers:
1627 * Content-Type: default to text/html if not already specified.
1628 * Date: set to current date/time.
1629 * Last-Modified: set to date/time the page was last changed.
1630 * Expires: set to date/time page next needs reloading.
1631 * Cache-Control: set to "no-cache" if applicable.
1633 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1635 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1640 * Set Expires to about 10 min into the future so it'll get reloaded
1641 * occasionally, e.g. if Privoxy gets upgraded.
1646 get_http_time(0, buf);
1647 err = enlist_unique_header(rsp->headers, "Date", buf);
1650 /* Some date in the past. */
1651 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1655 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1656 err = enlist_unique_header(rsp->headers, "Expires", buf);
1662 * Compliant browsers should not cache this due to the "Cache-Control"
1663 * setting. However, to be certain, we also set both "Last-Modified"
1664 * and "Expires" to the current time.
1666 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1668 get_http_time(0, buf);
1669 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1670 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1671 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1678 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1680 free_http_response(rsp);
1681 return cgi_error_memory();
1683 rsp->head_length = strlen(rsp->head);
1690 /*********************************************************************
1692 * Function : alloc_http_response
1694 * Description : Allocates a new http_response structure.
1698 * Returns : pointer to a new http_response, or NULL.
1700 *********************************************************************/
1701 struct http_response *alloc_http_response(void)
1703 return (struct http_response *) zalloc(sizeof(struct http_response));
1708 /*********************************************************************
1710 * Function : free_http_response
1712 * Description : Free the memory occupied by an http_response
1713 * and its depandant structures.
1716 * 1 : rsp = pointer to http_response to be freed
1720 *********************************************************************/
1721 void free_http_response(struct http_response *rsp)
1724 * Must special case cgi_error_memory_response, which is never freed.
1726 if (rsp && (rsp != cgi_error_memory_response))
1731 destroy_list(rsp->headers);
1738 /*********************************************************************
1740 * Function : template_load
1742 * Description : CGI support function that loads a given HTML
1743 * template from the confdir, ignoring comment
1744 * lines and following #include statements up to
1748 * 1 : csp = Current client state (buffers, headers, etc...)
1749 * 2 : template_ptr = Destination for pointer to loaded
1751 * 3 : templatename = name of the HTML template to be used
1752 * 4 : recursive = Flag set if this function calls itself
1753 * following an #include statament
1755 * Returns : JB_ERR_OK on success
1756 * JB_ERR_MEMORY on out-of-memory error.
1757 * JB_ERR_FILE if the template file cannot be read
1759 *********************************************************************/
1760 jb_err template_load(struct client_state *csp, char **template_ptr,
1761 const char *templatename, int recursive)
1764 char *templates_dir_path;
1767 char *included_module;
1770 char buf[BUFFER_SIZE];
1773 assert(template_ptr);
1774 assert(templatename);
1776 *template_ptr = NULL;
1778 /* Validate template name. Paranoia. */
1779 for (p = templatename; *p != 0; p++)
1781 if ( ((*p < 'a') || (*p > 'z'))
1782 && ((*p < 'A') || (*p > 'Z'))
1783 && ((*p < '0') || (*p > '9'))
1787 /* Illegal character */
1792 /* Generate full path */
1794 templates_dir_path = make_path(csp->config->confdir, "templates");
1795 if (templates_dir_path == NULL)
1797 return JB_ERR_MEMORY;
1800 full_path = make_path(templates_dir_path, templatename);
1801 free(templates_dir_path);
1802 if (full_path == NULL)
1804 return JB_ERR_MEMORY;
1807 /* Allocate buffer */
1809 file_buffer = strdup("");
1810 if (file_buffer == NULL)
1813 return JB_ERR_MEMORY;
1816 /* Open template file */
1818 if (NULL == (fp = fopen(full_path, "r")))
1820 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1828 * Read the file, ignoring comments, and honoring #include
1829 * statements, unless we're already called recursively.
1831 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1832 * This is unlikely in practise.
1834 while (fgets(buf, BUFFER_SIZE, fp))
1836 if (!recursive && !strncmp(buf, "#include ", 9))
1838 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1845 if (string_join(&file_buffer, included_module))
1848 return JB_ERR_MEMORY;
1854 /* skip lines starting with '#' */
1860 if (string_append(&file_buffer, buf))
1863 return JB_ERR_MEMORY;
1868 *template_ptr = file_buffer;
1874 /*********************************************************************
1876 * Function : template_fill
1878 * Description : CGI support function that fills in a pre-loaded
1879 * HTML template by replacing @name@ with value using
1880 * pcrs, for each item in the output map.
1882 * Note that a leading '$' charachter in the export map's
1883 * values will be stripped and toggle on backreference
1887 * 1 : template_ptr = IN: Template to be filled out.
1889 * OUT: Filled out template.
1890 * Caller must free().
1891 * 2 : exports = map with fill in symbol -> name pairs
1893 * Returns : JB_ERR_OK on success
1894 * JB_ERR_MEMORY on out-of-memory error
1896 *********************************************************************/
1897 jb_err template_fill(char **template_ptr, const struct map *exports)
1899 struct map_entry *m;
1901 char buf[BUFFER_SIZE];
1902 char *tmp_out_buffer;
1908 assert(template_ptr);
1909 assert(*template_ptr);
1912 file_buffer = *template_ptr;
1913 size = strlen(file_buffer) + 1;
1916 * Assemble pcrs joblist from exports map
1918 for (m = exports->first; m != NULL; m = m->next)
1920 if (*m->name == '$')
1923 * First character of name is '$', so remove this flag
1924 * character and allow backreferences ($1 etc) in the
1925 * "replace with" text.
1927 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1933 * Treat the "replace with" text as a literal string -
1934 * no quoting needed, no backreferences allowed.
1935 * ("Trivial" ['T'] flag).
1939 /* Enclose name in @@ */
1940 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1944 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1946 /* Make and run job. */
1947 job = pcrs_compile(buf, m->value, flags, &error);
1950 if (error == PCRS_ERR_NOMEM)
1953 *template_ptr = NULL;
1954 return JB_ERR_MEMORY;
1958 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1959 /* Hope it wasn't important and silently ignore the invalid job */
1964 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1967 if (NULL == tmp_out_buffer)
1969 *template_ptr = NULL;
1970 return JB_ERR_MEMORY;
1972 file_buffer = tmp_out_buffer;
1979 *template_ptr = file_buffer;
1984 /*********************************************************************
1986 * Function : template_fill_for_cgi
1988 * Description : CGI support function that loads a HTML template
1989 * and fills it in. Handles file-not-found errors
1990 * by sending a HTML error message. For convenience,
1991 * this function also frees the passed "exports" map.
1994 * 1 : csp = Client state
1995 * 2 : templatename = name of the HTML template to be used
1996 * 3 : exports = map with fill in symbol -> name pairs.
1997 * Will be freed by this function.
1998 * 4 : rsp = Response structure to fill in.
2000 * Returns : JB_ERR_OK on success
2001 * JB_ERR_MEMORY on out-of-memory error
2003 *********************************************************************/
2004 jb_err template_fill_for_cgi(struct client_state *csp,
2005 const char *templatename,
2006 struct map *exports,
2007 struct http_response *rsp)
2012 assert(templatename);
2016 err = template_load(csp, &rsp->body, templatename, 0);
2017 if (err == JB_ERR_FILE)
2020 return cgi_error_no_template(csp, rsp, templatename);
2025 return err; /* JB_ERR_MEMORY */
2027 err = template_fill(&rsp->body, exports);
2033 /*********************************************************************
2035 * Function : default_exports
2037 * Description : returns a struct map list that contains exports
2038 * which are common to all CGI functions.
2041 * 1 : csp = Current client state (buffers, headers, etc...)
2042 * 2 : caller = name of CGI who calls us and which should
2043 * be excluded from the generated menu. May be
2045 * Returns : NULL if no memory, else a new map. Caller frees.
2047 *********************************************************************/
2048 struct map *default_exports(const struct client_state *csp, const char *caller)
2052 struct map * exports;
2053 int local_help_exists = 0;
2057 exports = new_map();
2058 if (exports == NULL)
2063 err = map(exports, "version", 1, html_encode(VERSION), 0);
2064 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2065 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2066 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2067 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2068 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
2069 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2070 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
2071 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2072 #ifdef FEATURE_TOGGLE
2073 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2075 if (!err) err = map_block_killer(exports, "can-toggle");
2078 snprintf(buf, 20, "%d", csp->config->hport);
2079 if (!err) err = map(exports, "my-port", 1, buf, 1);
2081 if(!strcmp(CODE_STATUS, "stable"))
2083 if (!err) err = map_block_killer(exports, "unstable");
2086 if (csp->config->admin_address != NULL)
2088 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2089 local_help_exists = 1;
2093 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2096 if (csp->config->proxy_info_url != NULL)
2098 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2099 local_help_exists = 1;
2103 if (!err) err = map_block_killer(exports, "have-proxy-info");
2106 if (local_help_exists == 0)
2108 if (!err) err = map_block_killer(exports, "have-help-info");
2121 /*********************************************************************
2123 * Function : map_block_killer
2125 * Description : Convenience function.
2126 * Adds a "killer" for the conditional HTML-template
2127 * block <name>, i.e. a substitution of the regex
2128 * "if-<name>-start.*if-<name>-end" to the given
2132 * 1 : exports = map to extend
2133 * 2 : name = name of conditional block
2135 * Returns : JB_ERR_OK on success
2136 * JB_ERR_MEMORY on out-of-memory error.
2138 *********************************************************************/
2139 jb_err map_block_killer(struct map *exports, const char *name)
2141 char buf[1000]; /* Will do, since the names are hardwired */
2145 assert(strlen(name) < 490);
2147 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2148 return map(exports, buf, 1, "", 1);
2152 /*********************************************************************
2154 * Function : map_block_keep
2156 * Description : Convenience function. Removes the markers used
2157 * by map-block-killer, to save a few bytes.
2158 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2161 * 1 : exports = map to extend
2162 * 2 : name = name of conditional block
2164 * Returns : JB_ERR_OK on success
2165 * JB_ERR_MEMORY on out-of-memory error.
2167 *********************************************************************/
2168 jb_err map_block_keep(struct map *exports, const char *name)
2171 char buf[500]; /* Will do, since the names are hardwired */
2175 assert(strlen(name) < 490);
2177 snprintf(buf, 500, "if-%s-start", name);
2178 err = map(exports, buf, 1, "", 1);
2185 snprintf(buf, 500, "if-%s-end", name);
2186 return map(exports, buf, 1, "", 1);
2190 /*********************************************************************
2192 * Function : map_conditional
2194 * Description : Convenience function.
2195 * Adds an "if-then-else" for the conditional HTML-template
2196 * block <name>, i.e. a substitution of the form:
2203 * The control structure and one of the alternatives
2207 * 1 : exports = map to extend
2208 * 2 : name = name of conditional block
2209 * 3 : choose_first = nonzero for first, zero for second.
2211 * Returns : JB_ERR_OK on success
2212 * JB_ERR_MEMORY on out-of-memory error.
2214 *********************************************************************/
2215 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2217 char buf[1000]; /* Will do, since the names are hardwired */
2222 assert(strlen(name) < 480);
2224 snprintf(buf, 1000, (choose_first
2225 ? "else-not-%s@.*@endif-%s"
2226 : "if-%s-then@.*@else-not-%s"),
2229 err = map(exports, buf, 1, "", 1);
2235 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2236 return map(exports, buf, 1, "", 1);
2240 /*********************************************************************
2242 * Function : make_menu
2244 * Description : Returns an HTML-formatted menu of the available
2245 * unhidden CGIs, excluding the one given in <self>
2247 * Parameters : self = name of CGI to leave out, can be NULL for
2250 * Returns : menu string, or NULL on out-of-memory error.
2252 *********************************************************************/
2253 char *make_menu(const char *self)
2255 const struct cgi_dispatcher *d;
2256 char *result = strdup("");
2260 self = "NO-SUCH-CGI!";
2263 /* List available unhidden CGI's and export as "other-cgis" */
2264 for (d = cgi_dispatchers; d->name; d++)
2266 if (d->description && strcmp(d->name, self))
2268 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2269 string_append(&result, d->name);
2270 string_append(&result, "\">");
2271 string_append(&result, d->description);
2272 string_append(&result, "</a></li>");
2280 /*********************************************************************
2282 * Function : dump_map
2284 * Description : HTML-dump a map for debugging (as table)
2287 * 1 : the_map = map to dump
2289 * Returns : string with HTML
2291 *********************************************************************/
2292 char *dump_map(const struct map *the_map)
2294 struct map_entry *cur_entry;
2295 char *ret = strdup("");
2297 string_append(&ret, "<table>\n");
2299 for (cur_entry = the_map->first;
2300 (cur_entry != NULL) && (ret != NULL);
2301 cur_entry = cur_entry->next)
2303 string_append(&ret, "<tr><td><b>");
2304 string_join (&ret, html_encode(cur_entry->name));
2305 string_append(&ret, "</b></td><td>");
2306 string_join (&ret, html_encode(cur_entry->value));
2307 string_append(&ret, "</td></tr>\n");
2310 string_append(&ret, "</table>\n");